
    קgw                     `   U d dl Z d dlZd dlZd dlmZ d dlmZmZmZm	Z	m
Z
mZmZmZmZmZmZ d dlZd dlmZmZmZ d dlmZ ddlmZmZ eeeee         f                  Z ej        e          Z ed          	 dddd	d
edee         deee	e         f         dedee         defd            Z G d d          Z i Z!eedf         e"d<    ej#                    Z$ej#        e"d<   ded
eddfdZ%	 ddee         deeef         de&de
e         fdZ'dee ej(        ef         dee          fdZ)dS )     N)contextmanager)AnyCallableDictIterableIteratorListOptionalSequenceSetTupleUnion)_C_opsTensor)
exposed_in   )autogradutilsztorch.library)device_typesschemanamefnmutates_argsr   r   returnc               8      fd}||S  ||          S )a  Wraps a function into custom operator.

    Reasons why you may want to create a custom op include:
    - Wrapping a third-party library or custom kernel to work with PyTorch
    subsystems like Autograd.
    - Preventing torch.compile/export/FX tracing from peeking inside your function.

    This API is used as a decorator around a function (please see examples).
    The provided function must have type hints; these are needed to interface
    with PyTorch's various subsystems.

    Args:
        name (str): A name for the custom op that looks like "{namespace}::{name}",
            e.g. "mylib::my_linear". The name is used as the op's stable identifier
            in PyTorch subsystems (e.g. torch.export, FX graphs).
            To avoid name collisions, please use your project name as the namespace;
            e.g. all custom ops in pytorch/fbgemm use "fbgemm" as the namespace.
        mutates_args (Iterable[str] or "unknown"): The names of args that the function mutates.
            This MUST be accurate, otherwise, the behavior is undefined. If "unknown",
            it pessimistically assumes that all inputs to the operator are being mutated.
        device_types (None | str | Sequence[str]): The device type(s) the function
            is valid for. If no device type is provided, then the function
            is used as the default implementation for all device types.
            Examples: "cpu", "cuda".
            When registering a device-specific implementation for an operator that accepts no Tensors,
            we require the operator to have a "device: torch.device argument".
        schema (None | str): A schema string for the operator. If None
            (recommended) we'll infer a schema for the operator from its type
            annotations. We recommend letting us infer a schema unless you
            have a specific reason not to.
            Example: "(Tensor x, int y) -> (Tensor, Tensor)".

    .. note::
        We recommend not passing in a ``schema`` arg and instead letting us infer
        it from the type annotations. It is error-prone to write your own schema.
        You may wish to provide your own schema if our interpretation of
        the type annotation is not what you want.
        For more info on how to write a schema string, see
        `here <https://github.com/pytorch/pytorch/blob/main/aten/src/ATen/native/README.md#func>`_

    Examples::
        >>> import torch
        >>> from torch import Tensor
        >>> from torch.library import custom_op
        >>> import numpy as np
        >>>
        >>> @custom_op("mylib::numpy_sin", mutates_args=())
        >>> def numpy_sin(x: Tensor) -> Tensor:
        >>>     x_np = x.cpu().numpy()
        >>>     y_np = np.sin(x_np)
        >>>     return torch.from_numpy(y_np).to(device=x.device)
        >>>
        >>> x = torch.randn(3)
        >>> y = numpy_sin(x)
        >>> assert torch.allclose(y, x.sin())
        >>>
        >>> # Example of a custom op that only works for one device type.
        >>> @custom_op("mylib::numpy_sin_cpu", mutates_args=(), device_types="cpu")
        >>> def numpy_sin_cpu(x: Tensor) -> Tensor:
        >>>     x_np = x.numpy()
        >>>     y_np = np.sin(x_np)
        >>>     return torch.from_numpy(y_np)
        >>>
        >>> x = torch.randn(3)
        >>> y = numpy_sin_cpu(x)
        >>> assert torch.allclose(y, x.sin())
        >>>
        >>> # Example of a custom op that mutates an input
        >>> @custom_op("mylib::numpy_sin_inplace", mutates_args={"x"}, device_types="cpu")
        >>> def numpy_sin_inplace(x: Tensor) -> None:
        >>>     x_np = x.numpy()
        >>>     np.sin(x_np, out=x_np)
        >>>
        >>> x = torch.randn(3)
        >>> expected = x.sin()
        >>> numpy_sin_inplace(x)
        >>> assert torch.allclose(x, expected)
        >>>
        >>> # Example of a factory function
        >>> @torch.library.custom_op("mylib::bar", mutates_args={}, device_types="cpu")
        >>> def bar(device: torch.device) -> Tensor:
        >>>     return torch.ones(3)
        >>>
        >>> bar("cpu")

    c           	         dd l }|j                            | 	          }n}
                    d          \  }}t	          ||||           }{t                      }|j        j        j        D ]/}|j	        &|j	        j
        r|                    |j                   0|t          	          k    rt          d	 d d| d           |                              |            |S )Nr   )r   ::z3Attempted to create a custom op with `mutates_args=z` and `schema=z*. The schema suggests that the op mutates z`which is different from what was provided to us in `mutates_args`. Please make these consistent.)torchlibraryinfer_schemasplitCustomOpDefset_opoverload_schema	arguments
alias_infois_writeaddr   
ValueErrorregister_kernel)r   r   
schema_str	namespaceopnameresultexpectedargr   r   r   r   s           U/var/www/html/ai-engine/env/lib/python3.11/site-packages/torch/_library/custom_ops.pyinnerzcustom_op.<locals>.inner   s#   >33B\3RRJJJ JJt,,	6Y
B??uuH)1; + +>-#.2I-LL***3|,,,, 5, 5 5#)5 5U]5 5 5   	-|,,R000     )r   r   r   r   r   r4   s   ` ``` r3   	custom_opr7       sI    B       4 
z599r5   c            
       ,   e Zd ZdZdededededdf
dZedefd	            Zdefd
Z	e
ddedefd            Z	 ddedee         defdZdedefdZ	 ddedee         defdZdddedee         ddfdZd dZdefdZd Z	 ddee         fdZdS )!r#   a  CustomOpDef is a wrapper around a function that turns it into a custom op.

    It has various methods for registering additional behavior for this
    custom op.

    You should not instantiate CustomOpDef directly; instead, use the
    :func:`torch.library.custom_op` API.
    r.   r   r   r   r   Nc                 <   || _         || _        || _        || _        i | _        d | _        d | _        d | _        i | _        d | _	        t          | j         | j                  | _        |                                  t                      | _        | t          | j        <   d S N)
_namespace_namer&   _init_fn_backend_fns_abstract_fn_setup_context_fn_backward_fn_torch_dispatch_fns_vmap_fnget_library_allowing_overwrite_lib_register_to_dispatcherr$   _disabled_kernelOPDEFS	_qualname)selfr.   r   r   r   s        r3   __init__zCustomOpDef.__init__   s    #
>@0459049; ,024?DJOO	$$&&&%(UU!%t~r5   c                 $    | j          d| j         S )Nr   )r;   r<   rJ   s    r3   rI   zCustomOpDef._qualname   s    /11TZ111r5   c                     d| j          dS )Nz<CustomOpDef(z)>)rI   rM   s    r3   __repr__zCustomOpDef.__repr__   s    1t~1111r5   Tdevice_typeenabledc              #   J  K   |rdnd}|| j         v }|| j        vrt                              d||           |s9|rt                              d|           nS| j                             |           n8|st                              d|           n| j                             |           	 dV  |r| j                             |           dS | j                             |           dS # |r| j                             |           w | j                             |           w xY w)a  
        Disable or re-enable an already registered kernel for this custom operator.

        If the kernel is already disabled/enabled, this is a no-op.

        Note:
            If a kernel is first disabled and then registered, it is disabled until enabled again.

        Args:
            device_type (str): The device type to disable/enable the kernel for.
            disable (bool): Whether to disable or enable the kernel.

        Example:
            >>> inp = torch.randn(1)
            >>>
            >>> # define custom op `f`.
            >>> @custom_op("mylib::f", mutates_args=())
            >>> def f(x: Tensor) -> Tensor:
            >>>     return torch.zeros(1)
            >>>
            >>> print(f(inp))  # tensor([0.]), default kernel
            >>>
            >>> @f.register_kernel("cpu")
            >>> def _(x):
            >>>     return torch.ones(1)
            >>>
            >>> print(f(inp))  # tensor([1.]), CPU kernel
            >>>
            >>> # temporarily disable the CPU kernel
            >>> with f.set_kernel_enabled("cpu", enabled = False):
            >>>     print(f(inp))  # tensor([0.]) with CPU kernel disabled

        enabledisablezPAttempted to %s kernel for %s but no kernel was registered for this device type.z?Attempted to disable kernel for %s but it was already disabled.z>Attempted to enable kernel for  %s but it was already enabled.N)rG   r>   logwarningr*   removediscard)rJ   rP   rQ   actionoriginally_disableds        r3   set_kernel_enabledzCustomOpDef.set_kernel_enabled   sw     F %3))T-BBd///KKb    	:" 7U   
 %))+6666& :T   
 %,,[999	;EEE # ;%))+66666%--k::::: # ;%))+6666%--k::::s   +C) )9D"r   c                      fd}bt          j         j        j                  sDt          j         j        j                  }|t          d                               |           ||S  ||          S )a  Register an implementation for a device type for this operator.

        Some valid device_types are: "cpu", "cuda", "xla", "mps", "ipu", "xpu".
        This API may be used as a decorator.

        Args:
            fn (Callable): The function to register as the implementation for
                the given device types.
            device_types (str | Sequence[str]): The device device_types to register an impl to.

        Examples::
            >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA)
            >>> import torch
            >>> from torch import Tensor
            >>> from torch.library import custom_op
            >>> import numpy as np
            >>>
            >>> # Create a custom op that works on cpu
            >>> @custom_op("mylib::numpy_sin", mutates_args=(), device_types="cpu")
            >>> def numpy_sin(x: Tensor) -> Tensor:
            >>>     x_np = x.numpy()
            >>>     y_np = np.sin(x_np)
            >>>     return torch.from_numpy(y_np)
            >>>
            >>> # Add implementations for the cuda device
            >>> @numpy_sin.register_kernel("cuda")
            >>> def _(x):
            >>>     x_np = x.cpu().numpy()
            >>>     y_np = np.sin(x_np)
            >>>     return torch.from_numpy(y_np).to(device=x.device)
            >>>
            >>> x_cpu = torch.randn(3)
            >>> x_cuda = x_cpu.cuda()
            >>> assert torch.allclose(numpy_sin(x_cpu), x_cpu.sin())
            >>> assert torch.allclose(numpy_sin(x_cuda), x_cuda.sin())

        c                 |    t          t                    rg}nt                    }|D ]j        vr]fd}"j                            j        |d           n3j                            j        |t          j                             t          j
         fd            }|j        <    S )Nc                     d t          | |          D             } 
j        	         | i |}|}t          |t                    s|f}t          |i           D ]}t	          |                                          }t	          |                                          |v r;
j        	         }t          j        |          }t          
j	         d| d          |
                    |           |S )Nc                 P    h | ]#}t          |                                          $S r6   )iduntyped_storage).0tensors     r3   	<setcomp>zSCustomOpDef.register_kernel.<locals>.inner.<locals>.backend_impl.<locals>.<setcomp>?  s<     $ $ $ & v557788$ $ $r5   z (with implementation in a  ): The output of this custom operator (1) must not also be an input to this custom operator and (2) may not alias any inputs to this custom operator or other returns. The most common way to trigger this error is if we have y = custom_op(x) and y and x are the same Tensor. Please instead return a clone of the offending output tensor(s) (e.g. return x.clone()) or refactor the custom operator to not return y.)iter_tensorsr>   
isinstancetupler`   ra   inspect	getmoduleRuntimeErrorr<   r*   )argskwargsstoragesr0   tuple_resultrc   keyr   modulerP   rJ   s            r3   backend_implz@CustomOpDef.register_kernel.<locals>.inner.<locals>.backend_impl<  s)   $ $*6tV*D*D$ $ $
 "@!2;!?!P!P!P'-)&%88 5,29L&2<&D&D . .F"$V%;%;%=%=">">C!&"8"8":":;;xGG%)%6{%C)0):2)>)>&2'+z 	%A 	%AF 	%A 	%A 	%A'" '" !" %LL----%r5   CompositeExplicitAutogradc                  @    j         v r j        | i |S  | i |S r:   )rG   r=   )rk   rl   rP   r   rJ   s     r3   
wrapped_fnz>CustomOpDef.register_kernel.<locals>.inner.<locals>.wrapped_fnj  s=    "d&;;;,t}d=f===!r426222r5   )rf   strlistr>   rE   implr<   r   _dispatch_key_for_devicer   _disable_dynamo)r   dtypesrq   rt   rP   r   rJ   s   `   @r3   r4   z*CustomOpDef.register_kernel.<locals>.inner4  s   #z,'D'D#2>l++% 8< 8<d&777& & & & & &B #*	 J6Q    	 J(7DD   &3 3 3 3 3 3 '&3 2<!+..Ir5   NzVFunctions without tensor inputs are required to have a `device: torch.device` argument)r   has_tensor_argr%   r&   get_device_arg_indexr+   #_register_backend_select_dispatcher)rJ   r   r   r4   device_arg_indexs   ``   r3   r,   zCustomOpDef.register_kernel  s    R>	 >	 >	 >	 >	 >	@ #E,@$-
 -
#  %9$:J:RSS' l   445EFFF :LuRyyr5   c                    || _         |S )a  Register a FakeTensor implementation for this custom op.

        This is necessary to get the operator to work efficiently with torch.compile.

        The Fake impl (sometimes also known as a meta kernel or abstract impl)
        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.

        Please see :func:`torch.library.impl_abstract` for more details.

        Args:
            fn (Callable): The function to register as the FakeTensor
                implementation.

        Examples:
            >>> import torch
            >>> import numpy as np
            >>> from torch import Tensor
            >>>
            >>> # Example 1: an operator without data-dependent output shape
            >>> @torch.library.custom_op("mylib::linear", mutates_args=())
            >>> def linear(x: Tensor, weight: Tensor, bias: Tensor) -> Tensor:
            >>>     return (x @ weight.t()) + bias
            >>>
            >>> @linear.register_fake
            >>> def _(x, weight, bias):
            >>>     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.new_empty(x.size(0), weight.size(0))
            >>>
            >>> x = torch.randn(2, 2)
            >>> weight = torch.randn(2, 2)
            >>> bias = torch.randn(2)
            >>> # xdoctest: +SKIP("Requires Python <= 3.11")
            >>> out = torch.compile(linear, fullgraph=True)(x, weight, bias)
            >>> # xdoctest: +SKIP("Requires Python <= 3.11")
            >>> assert torch.allclose(out, torch.nn.functional.linear(x, weight, bias))
            >>>
            >>> # Example 2: an operator with data-dependent output shape
            >>> @torch.library.custom_op("mylib::nonzero", mutates_args=())
            >>> def nonzero(x: Tensor) -> Tensor:
            >>>     x_np = x.cpu().numpy()
            >>>     res = np.stack(np.nonzero(x_np), axis=1)
            >>>     return torch.tensor(res, device=x.device)
            >>>
            >>> @nonzero.register_fake
            >>> def _(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.library.get_ctx()
            >>>     nnz = ctx.new_dynamic_size()
            >>>     shape = [nnz, x.dim()]
            >>>     result = x.new_empty(shape, dtype=torch.int64)
            >>>     return result
            >>>
            >>> x = torch.tensor([0, 1, 2, 0, 0, 1])
            >>> # xdoctest: +SKIP("Requires Python <= 3.11")
            >>> out = torch.compile(nonzero, fullgraph=True)(x)
            >>> # xdoctest: +SKIP("Requires Python <= 3.11")
            >>> assert torch.allclose(out, x.nonzero())

        )r?   )rJ   r   s     r3   register_fakezCustomOpDef.register_fake  s    N 	r5   torch_dispatch_classc                0      fd}||S  ||          S )a  Registers a torch_dispatch rule for the given operator and ``torch_dispatch_class``.

        This allows for open registration to specify the behavior between the operator
        and the ``torch_dispatch_class`` without needing to modify the ``torch_dispatch_class``
        or the operator directly.

        Please see :func:`torch.library.register_torch_dispatch` for examples and more details.
        c                 |    j         vr'fd}j                            j        |           | j         <   | S )Nc                  *     j                  | i |S r:   )rB   )rk   rl   rJ   r   s     r3   r4   zDCustomOpDef.register_torch_dispatch.<locals>.register.<locals>.inner  s+    I434HI!'  r5   )rB   rE   _register_torch_dispatch_ruler<   )r   r4   rJ   r   s     r3   registerz5CustomOpDef.register_torch_dispatch.<locals>.register  sk    #4+CCC     
 	77J 4e   >@D$%9:Ir5   r6   )rJ   r   r   r   s   ``  r3   register_torch_dispatchz#CustomOpDef.register_torch_dispatch  s<    	 	 	 	 	 	 :O8B<<r5   )setup_contextbackwardr   c                   | j         j        }t          j        |          st	          d|  d| d          || _        || _        dS )ad  Register a backward formula for this custom op.

        In order for an operator to work with autograd, you need to register
        a backward formula:
        1. You must tell us how to compute gradients during the backward pass
        by providing us a "backward" function.
        2. If you need any values from the forward to compute gradients, you can
        use `setup_context` to save values for backward.

        ``backward_fn`` runs during the backward pass. It accepts ``(ctx, *grads)``:
        - ``grads`` is one or more gradients. The number of gradients matches
        the number of outputs of the operator.
        The ``ctx`` object is `the same ctx object <context_method_mixins>`_ used by
        :class:`torch.autograd.Function`. The semantics of ``backward_fn`` are the
        same as :meth:`torch.autograd.Function.backward`.

        ``setup_context(ctx, inputs, output)`` runs during the forward pass.
        Please save quantities needed for backward onto the ``ctx`` object via
        either :meth:`torch.autograd.function.FunctionCtx.save_for_backward`
        or assigning them as attributes of ``ctx``. If your custom op has
        kwarg-only arguments, we expect the signature of ``setup_context``
        to be ``setup_context(ctx, inputs, keyword_only_inputs, output)``.

        Both ``setup_context_fn`` and ``backward_fn`` must be traceable. That is,
        they may not directly access :meth:`torch.Tensor.data_ptr` and they must
        not depend on or mutate global state. If you need a non-traceable backward,
        you can make it a separate custom_op that you call inside ``backward_fn``.

        Examples:
            >>> import torch
            >>> import numpy as np
            >>> from torch import Tensor
            >>>
            >>> @torch.library.custom_op("mylib::numpy_sin", mutates_args=())
            >>> def numpy_sin(x: Tensor) -> Tensor:
            >>>     x_np = x.cpu().numpy()
            >>>     y_np = np.sin(x_np)
            >>>     return torch.from_numpy(y_np).to(device=x.device)
            >>>
            >>> def setup_context(ctx, inputs, output) -> Tensor:
            >>>     x, = inputs
            >>>     ctx.save_for_backward(x)
            >>>
            >>> def backward(ctx, grad):
            >>>     x, = ctx.saved_tensors
            >>>     return grad * x.cos()
            >>>
            >>> numpy_sin.register_autograd(backward, setup_context=setup_context)
            >>>
            >>> x = torch.randn(3, requires_grad=True)
            >>> y = numpy_sin(x)
            >>> grad_x, = torch.autograd.grad(y, x, torch.ones_like(y))
            >>> assert torch.allclose(grad_x, x.cos())
            >>>
            >>> # Example with a keyword-only arg
            >>> @torch.library.custom_op("mylib::numpy_mul", mutates_args=())
            >>> def numpy_mul(x: Tensor, *, val: float) -> Tensor:
            >>>     x_np = x.cpu().numpy()
            >>>     y_np = x_np * val
            >>>     return torch.from_numpy(y_np).to(device=x.device)
            >>>
            >>> def setup_context(ctx, inputs, keyword_only_inputs, output) -> Tensor:
            >>>     ctx.val = keyword_only_inputs["val"]
            >>>
            >>> def backward(ctx, grad):
            >>>     return grad * ctx.val
            >>>
            >>> numpy_mul.register_autograd(backward, setup_context=setup_context)
            >>>
            >>> x = torch.randn(3, requires_grad=True)
            >>> y = numpy_mul(x, val=3.14)
            >>> grad_x, = torch.autograd.grad(y, x, torch.ones_like(y))
            >>> assert torch.allclose(grad_x, torch.full_like(x, 3.14))

        z=Cannot register autograd formula for non-functional operator z with schema zP. Please create a functional operator and register an autograd formula for that.N)r%   r&   r   is_functional_schemarj   rA   r@   )rJ   r   r   r   s       r3   register_autogradzCustomOpDef.register_autograd  sw    d !))&11 	TT T&,T T T   %!.r5   c                 z     j         } j         j        z   }t          j        |          }t          j        |          rt          d|           |                    |t          j	        j
        t          j	        j        g           t          j         j                   _         fd}|                     j        |d           t!          j         j                   }|                     j        |dd            j        j        j        r& fd	}|                     j        |d
d           d S d S )NzUcustom_op with kwarg-only Tensor args. Please make your tensors not kwarg-only. Got: )tagsc                      j         ;t          j        j                  rd S t	          d dj        j         d           j         | i |S )Nz&There was no fake impl registered for zM. This is necessary for torch.compile/export/fx tracing to work. Please use `z$.register_fake` to add an fake impl.)r?   r   can_generate_trivial_fake_implr%   rj   r=   __name__)rk   rl   rJ   s     r3   	fake_implz6CustomOpDef._register_to_dispatcher.<locals>.fake_impl\  s{     (78HII  4""T " "#'=#9" " "   %4$d5f555r5      )_stacklevelAutogradTwith_keysetc                 .   t          j        ||          D ]\  }}|j        s|j        j        st	          |t
                    r%t          j        j        	                    |           Tt	          |t          t          f          r>|D ];}t	          |t
                    r$t          j        j        	                    |           <t          j                    5   j        j        | t          j        z  g|R i |cd d d            S # 1 swxY w Y   d S r:   )r   
zip_schemar(   r)   rf   r   r   r   graphincrement_versionrg   rv   r   !_AutoDispatchBelowADInplaceOrViewr%   
redispatch_after_ADInplaceOrView_keyset)keysetrk   rl   r2   valvr   rJ   s         r3   adinplaceorview_implzACustomOpDef._register_to_dispatcher.<locals>.adinplaceorview_implp  sv    % 0v F F 
J 
JHC> ! >2 ! !#v.. J,>>sCCCC#C%77 J!$ J JA)!V44 J % 4 F Fq I I I9;;  64+6!AADH  LR                  s   #D

DDADInplaceOrView)rE   r<   r&   r   parse_schemar   has_kwarg_only_tensorsNotImplementedErrordefineTagpt2_compliant_tagneeds_fixed_stride_order	lookup_oprI   r%   _register_faker   make_autograd_implrw   
is_mutable)rJ   libr-   
cpp_schemar   autograd_implr   r   s   `      @r3   rF   z#CustomOpDef._register_to_dispatcherI  s   iZ$,.
_Z00
'
33 	 &=0:= =  
 	

&*BF,KL 	 	
 	
 	
 !?4>::
	6 
	6 
	6 
	6 
	6 	4:ya@@@ 3D4DdKK]JDIII!) 	     " HH
$! 	      '	 	r5   r~   c                 \      fd} j                              j        |dd           dS )z]
        Switch on the device argument to select the correct backend to dispatch to.
        c                    |         j         }|j        vrt          j         d| d          t	          j        |          }t          t          j        |          } j        j	        t	          j
        |          g|R i |S )Nz' does not have a kernel registered for z&. Please use register_kernel to do so.)typer>   rj   r<   r   rx   getattrDispatchKeyr%   r   DispatchKeySet)r   rk   rl   devicedispatch_keyr~   rJ   s        r3   backend_selectzGCustomOpDef._register_backend_select_dispatcher.<locals>.backend_select  s    *+0FT..."z ; ;& ; ; ;   6v>>L"2><@@L.4#.!,//26  :@  r5   BackendSelectTr   N)rE   rw   r<   )rJ   r~   r   s   `` r3   r}   z/CustomOpDef._register_backend_select_dispatcher  sI    
	 	 	 	 	 	 		tz>?PTUUUUUr5   c                      | j         |i |S r:   )r%   )rJ   rk   rl   s      r3   __call__zCustomOpDef.__call__  s    t0000r5   funcc                 L     ddl m ddlm  fd}||S  ||          S )a  Register a vmap implementation to support :func:`torch.vmap` for this custom op.

        This API may be used as a decorator.

        In order for an operator to work with :func:`torch.vmap`, you may need to register a
        vmap implementation in the following signature:

            ``vmap_func(info, in_dims: Tuple[Optional[int]], *args, **kwargs)``,

        where ``*args`` and ``**kwargs`` are the arguments and kwargs for ``op``.

        It specifies how do we compute the batched version of ``op`` given inputs with an additional
        dimension (specified by ``in_dims``).

        For each arg in ``args``, ``in_dims`` has a corresponding ``Optional[int]``. It is ``None``
        if the arg is not a Tensor or if the arg is not being vmapped over, otherwise, it is an integer
        specifying what dimension of the Tensor is being vmapped over.

        ``info`` is a collection of additional metadata that may be helpful:
        ``info.batch_size`` specifies the size of the dimension being vmapped over, while
        ``info.randomness`` is the ``randomness`` option that was passed to :func:`torch.vmap`.

        The return of the function ``func`` is a tuple of ``(output, out_dims)``. Similar to ``in_dims``,
        ``out_dims`` should be of the same structure as ``output`` and contain one ``out_dim``
        per output that specifies if the output has the vmapped dimension and what index it is in.

        Examples:
            >>> import torch
            >>> import numpy as np
            >>> from torch import Tensor
            >>> from typing import Tuple
            >>>
            >>> def to_numpy(tensor):
            >>>     return tensor.cpu().numpy()
            >>>
            >>> lib = torch.library.Library("mylib", "FRAGMENT")
            >>> @torch.library.custom_op("mylib::numpy_cube", mutates_args=())
            >>> def numpy_cube(x: Tensor) -> Tuple[Tensor, Tensor]:
            >>>     x_np = to_numpy(x)
            >>>     dx = torch.tensor(3 * x_np ** 2, device=x.device)
            >>>     return torch.tensor(x_np ** 3, device=x.device), dx
            >>>
            >>> def numpy_cube_vmap(info, in_dims, x):
            >>>     result = numpy_cube(x)
            >>>     return result, (in_dims[0], in_dims[0])
            >>>
            >>> numpy_cube.register_vmap(numpy_cube_vmap)
            >>>
            >>> x = torch.randn(3)
            >>> torch.vmap(numpy_cube)(x)
            >>>
            >>> @torch.library.custom_op("mylib::numpy_mul", mutates_args=())
            >>> def numpy_mul(x: Tensor, y: Tensor) -> Tensor:
            >>>     return torch.tensor(to_numpy(x) * to_numpy(y), device=x.device)
            >>>
            >>> @numpy_mul.register_vmap
            >>> def numpy_mul_vmap(info, in_dims, x, y):
            >>>     x_bdim, y_bdim = in_dims
            >>>     x = x.movedim(x_bdim, -1) if x_bdim is not None else x.unsqueeze(-1)
            >>>     y = y.movedim(y_bdim, -1) if y_bdim is not None else y.unsqueeze(-1)
            >>>     result = x * y
            >>>     result = result.movedim(-1, 0)
            >>>     return result, 0
            >>>
            >>>
            >>> x = torch.randn(3)
            >>> y = torch.randn(3)
            >>> torch.vmap(numpy_mul)(x, y)
        r   ) custom_function_call_vmap_helper)&retrieve_current_functorch_interpreterc                     j         d u }| _         |r,fd}j                            j        |dd           d S d S )Nc                 H                 } |j         j        g|R i |S r:   )rC   r%   )r   rk   rl   interpreterr   r   rJ   s       r3   wrapped_funczACustomOpDef.register_vmap.<locals>.register.<locals>.wrapped_func  sL    "H"H"J"JK;;#T]D4DGK  OU  r5   FuncTorchBatchedTr   )rC   rE   rw   r<   )r   need_registerr   r   r   rJ   s      r3   r   z+CustomOpDef.register_vmap.<locals>.register  s     MT1M DM 
       	J.@d      
 
r5   )"torch._functorch.autograd_functionr   torch._functorch.pyfunctorchr   )rJ   r   r   r   r   s   `  @@r3   register_vmapzCustomOpDef.register_vmap  sj    R 	XWWWWWWWWWWW	 	 	 	 	 	 	  <O8D>>!r5   )Tr:   )r   N)r   
__module____qualname____doc__ru   r   rK   propertyrI   rO   r   boolr[   device_types_tr
   r,   r   r   r   r   rF   intr}   r   r   r6   r5   r3   r#   r#      sE        &# &S &# &8 &PT & & & &( 23 2 2 2 X22# 2 2 2 2 C; C;c C;D C; C; C; ^C;L FJv v*v080Bv	v v v vpH H H H H HV CG   $' -5h-? 	       H -1[/ [/ [/[/
  )[/ 
[/ [/ [/ [/z= = = =~VC V V V V(1 1 1
 $(_" _"x _" _" _" _" _" _"r5   r#   ztorch.library.LibraryOPDEF_TO_LIBrH   r.   c                     |  d| }|t           v r't           |                                          t           |= t          j                            | d          }|t           |<   |S )Nr   FRAGMENT)r   _destroyr   r    Library)r.   r   qualnamer   s       r3   rD   rD     sg     %%t%%H<X'')))"
-

	:
6
6C LJr5   rk   rl   allowed_nestingc              #      K   fd}| D ]} ||          E d {V  |                                 D ]} ||          E d {V  d S )Nc              3      K   t          | t                    r| V  d S dk    rEt          | t          t          f          r+t	          t          |           i dz
            E d {V  d S d S d S )Nr   r   )rf   r   rg   rv   re   )r2   r   s    r3   checkziter_tensors.<locals>.check-  s      c6"" 	IIIIIIq  ZeT]%C%C #E#JJOa4GHHHHHHHHHHH !   r5   )values)rk   rl   r   r   r2   kwargs     `   r3   re   re   *  s      I I I I I   5::    5<<   r5   opc                     t          | t                    r| S t          | t          j                  r| j        } t          | t
                    sJ | t          v rt          |          S d S r:   )rf   r#   r   
OpOverloadr<   ru   rH   )r   s    r3   _maybe_get_opdefr   9  sd     "k"" 	"do&& Xb#	V||bz4r5   r:   )r   )*rh   loggingweakref
contextlibr   typingr   r   r   r   r   r	   r
   r   r   r   r   r   r   r   r   torch.utils._exposed_inr    r   r   ru   r   	getLoggerr   rU   r7   r#   r   __annotations__WeakValueDictionaryrH   rD   r   re   r   r   r6   r5   r3   <module>r      s      % % % % % %                           " " " " " " " " " " . . . . . .         %Xc] 234g!! O "| $( | | |
||
 Xc]*+| !| SM| | | | |~^	" ^	" ^	" ^	" ^	" ^	" ^	" ^	"p 46d3//0 5 5 5&Ag&A&C&C# C C C    FG   
* "38n ?B f       
k4?C/0
k
 
 
 
 
 
r5   