� J��gQ����UddlmZddlmZmZmZmZmZmZm Z m Z m Z ddl m Z ddlZddlZddlZddlZddlZddlZddlZddlZddlmZmZmZmZddlmZgd�Ze��aee e!d<e��Z"ee e!d <d gZ#d �Z$Gd �d ��Z%d�Z&ej'd���Z(gZ)ee%e!d<ej*d��Z+ej,ddd�d���Z-e-j.d:de%fd���Z/ej,d;dd�d���Z0de de fd�Z1e0j.d:de%fd���Z/e de2���d;ddd �d!���Z3ee d"d#fZ4 d;dd�d$e4d%ed&eedee%fd'�Z5 d;ddd �d$e4d&eedee%d(e6fd)�Z7ddd*�d$e4d+ed,eeddfd-�Z8d.�Z9d<d0�Z:d1Z; d;e;d2d3�d$eejjejj<efd4e ed5fd6ee e efd7ee e e fd8e=de e e ff d9�Z>dS)=�)� OpOverload�) �Any�Optional�Set�List�Union�Callable�Tuple�Dict�Sequence)� deprecatedN)� custom_op�_maybe_get_opdef�device_types_t� CustomOpDef)�Library�impl�define�fallthrough_kernel� impl_abstract� register_fake�get_ctxr�_impls�_defs�primc� �td���)zZ A dummy function to pass to ``Library.impl`` in order to register a fallthrough. z,fallthrough_kernel() should never be called.)�NotImplementedError���]/home/asafur/pinokio/api/open-webui.git/app/env/lib/python3.11/site-packages/torch/library.pyrr&s�� �L� M� M�Mr c�R�eZdZdZdd�Zd�Zddd�d�Zdd �Zdd �Zdd d �d �Z d�Z dS)raC A class to create libraries that can be used to register new operators or override operators in existing libraries from Python. A user can optionally pass in a dispatch keyname if they only want to register kernels corresponding to only one specific dispatch key. To create a library to override operators in an existing library (with name ns), set the kind to "IMPL". To create a new library (with name ns) to register new operators, set the kind to "DEF". To create a fragment of a possibly existing library to register operators (and bypass the limitation that there is only one library for a given namespace), set the kind to "FRAGMENT". Args: ns: library name kind: "DEF", "IMPL" (default: "IMPL"), "FRAGMENT" dispatch_key: PyTorch dispatch key (default: "") �c ��|dvrtd|���|tvr|dks|dkrt|d���tjd���d}|j|j}}t j�|||||��|_ ||_ t��|_ t��|_ g|_||_||_t#j|t&t(|j t*|j |j��dS) N)�IMPL�DEF�FRAGMENTzUnsupported kind: r&r'zJ is a reserved namespace. Please try creating a library with another name.�)�limitr)� ValueError�_reserved_namespaces� traceback� extract_stack�filename�lineno�torch�_C�_dispatch_library�m�ns�set�_op_defs� _op_impls�_registration_handles�kind� dispatch_key�weakref�finalize� _del_libraryrr)�selfr4r9r:�framer.r/s r!�__init__zLibrary.__init__>s��� �2� 2� 2��1�4�8�8� 8� �%� %� %�4�5�=�=�D�J�<N�<N��R�!m�n�n� n��'�a�0�0�0��3�� �>�5�<�&�� %�� :� :�4��\�S[�]c� d� d������"%�%�%�� �#&�5�5���TV��"��� �(��� ���|�V�T�^�U�D�M�[_�[u�v�v�v�v�vr c�8�d|j�d|j�d|j�d�S)Nz Library(kind=z, ns=z, dispatch_key=z)>)r9r4r:)r>s r!�__repr__zLibrary.__repr__Ts*��\�t�y�\�\�t�w�\�\�t�GX�\�\�\�\r r)�tagsc�8�|dvrtd|�����|j�J�t|tj��r|f}|�d��d}d|vr|�d��dn|}t tj|j��o,t ttj|j��|��}|j� ||t|����}|�d��d}|jdz|z}|rNttj|j��} t| |��} tj � | ��|j�|��t �|��|S)a�Defines a new operator and its semantics in the ns namespace. Args: schema: function schema to define a new operator. alias_analysis (optional): Indicates if the aliasing properties of the operator arguments can be inferred from the schema (default behavior) or not ("CONSERVATIVE"). tags (Tag | Sequence[Tag]): one or more torch.Tag to apply to this operator. Tagging an operator changes the operator's behavior under various PyTorch subsystems; please read the docs for the torch.Tag carefully before applying it. Returns: name of the operator as inferred from the schema. Example:: >>> my_lib = Library("mylib", "DEF") >>> my_lib.define("sum(Tensor self) -> Tensor") )r#� FROM_SCHEMA� CONSERVATIVEzInvalid alias_analysis type N�(r�.�::)� RuntimeErrorr3� isinstancer0�Tag�split�hasattr�opsr4�getattrr�tuple�_ops�_refresh_packetr6�addr) r>�schema�alias_analysisrC�name� packet_name�has_preexisting_packet�result�qualnamer4�packets r!rzLibrary.defineWso��* �!D� D� D��N�n�N�N�O�O� O��v�!�!�!� �d�E�I� &� &� ��7�D��|�|�C� � ��#��,/�4�K�K�d�j�j��o�o�a�(�(�T� �!(���D�G�!<�!<�!r���QV�QZ�\`�\c�Id�Id�fq�Ar�Ar������v�~�u�T�{�{�C�C���|�|�C� � ��#���7�T�>�D�(�� "� /����D�G�,�,�B��R��-�-�F� �J� &� &�v� .� .� .� � ���(�#�#�#� � � �(����� r rc���tjj�|dz��}t j|��}t j|��}|�dn|j}|�|� d��rd}|j �d|��}tjj j � |��} |�t|||��} n|} | j�| |��} |j�| ��dS)z?Registers the fake impl for an operator defined in the library.rNz torchvision.rI)r0�_library�utils� get_source�sys� _getframe�inspect� getmodule�__name__� startswithr4�simple_registry� singleton�find�_check_pystubs_once� abstract_impl�registerr8�append) r>�op_name�fn� _stacklevel�sourcer?� caller_module�caller_module_namer[�entry�func_to_register�handles r!�_register_fakezLibrary._register_fake�s�����%�0�0��q��A�A��� �k�*�*���)�%�0�0� �&3�%:�T�T� �@V�� � )�.@�.K�.K�N�.[�.[� )�!%� ��g�*�*��*�*����.�8�=�=�h�G�G�� � )�2�2�x�AS�T�T� � �!� ��$�-�-�.>��G�G�� �"�)�)�&�1�1�1�1�1r c�6�|dkr|j}tj|���tjjj��sJ�t|t��r|}nKt|t��r'|j j }|j j }|dkr|dz|z}ntd���|jdz|�d��dzdz|z}|t vrBtd�|�d��d||j�����|j�J�|jj}||j|�d��d|��t �|��|j�|��dS) a�Register the operator to use the AOTI-compiled implementation. Args: op_name: operator name (along with the overload) or OpOverload object. dispatch_key: dispatch key that the input function should be registered for. By default, it uses the dispatch key that the library was created with. Example:: >>> my_lib = Library("aten", "IMPL") >>> my_lib._impl_with_aoti_compile("div.Tensor", "CPU") r#rHzd_impl_with_aoti_compile should be passed either a name or an OpOverload object as the first argument�/rI�������This is not allowed since there's already a kernel registered from python overriding {}'s behavior for {} dispatch key and {} namespace.N)r:r0�DispatchKeySet�hasr1� DispatchKey�DenserK�strr�_schemarW� overload_namerJr4rMr�formatr3�impl_with_aoti_compilerTr7)r>rnr:rWr��key�impl_fns r!�_impl_with_aoti_compilezLibrary._impl_with_aoti_compile�s��� �2� � ��,�L��#�L�1�1�5�5�e�h�6J�6P�Q�Q�Q�Q�Q� �g�s� #� #� 8��D�D� ��� ,� ,� 8��?�'�D�#�O�9�M���"�"��c�z�M�1���� 7�8�8� 8��g��m�d�j�j��.�.�r�2�2�S�8�<�G�� �&�=�=�� S�%�v�d�j�j��&6�&6�r�&:�L�$�'�R�R�T�T� T��v�!�!�!� �F�9���������D�)�)�"�-�|�<�<�<�� � �3���� ����3�����r F�� with_keysetc��t|��stdt|�������|dkr|j}t |t ��r|}nKt |t ��r'|jj}|jj }|dkr|dz|z}ntd���|j dz|� d��dzdz|z}|tvrBtd�|� d��d||j �����|d krE|}d|vr |j �d|��}tj�|d ��rtd |�d ����|j�J�|j�||dkr|nd ||��t�|��|j�|��d S)a�Registers the function implementation for an operator defined in the library. Args: op_name: operator name (along with the overload) or OpOverload object. fn: function that's the operator implementation for the input dispatch key or :func:`~fallthrough_kernel` to register a fallthrough. dispatch_key: dispatch key that the input function should be registered for. By default, it uses the dispatch key that the library was created with. Example:: >>> my_lib = Library("aten", "IMPL") >>> def div_cpu(self, other): >>> return self * (1 / other) >>> my_lib.impl("div.Tensor", div_cpu, "CPU") z;Input function is required to be a callable but found type r#rHzQimpl should be passed either a name or an OpOverload object as the first argumentryrIrzr{�Meta�CompositeImplicitAutogradz?We should not register a meta kernel directly to the operator 'z�', because it has a CompositeImplicitAutograd kernel in core. Instead we should let the operator decompose, and ensure that we have meta kernels for the base ops that it decomposes into.N)�callable� TypeError�typer:rKr�rr�rWr�rJr4rMrr�r0r1�%_dispatch_has_kernel_for_dispatch_keyr3rrTr7) r>rnror:r�rWr�r��dispatcher_op_names r!rz Library.impl�s�� ��|�|� f��d�Z^�_a�Zb�Zb�d�d�e�e� e� �2� � ��,�L� �g�s� #� #� t��D�D� ��� ,� ,� t��?�'�D�#�O�9�M���"�"��c�z�M�1����r�s�s� s��g��m�d�j�j��.�.�r�2�2�S�8�<�G�� �&�=�=�� S�%�v�d�j�j��&6�&6�r�&:�L�$�'�R�R�T�T� T� �6� !� !�!%� ��-�-�-�(,��%G�%G�3E�%G�%G�"� �x�=�=�>P�Rm�n�n� B�"�A�VZ�A�A�A�B�B�B� �v�!�!�!� �� � �D�,�"�*<�*<�,�,�B]�_a�cn�o�o�o�� � �3���� ����3�����r c��|j�|j���d|_|jD]}|����|j���t |jza|jD]�}|�d��\}}|�d��d}ttj |��s�Pttj |��}t||��s�{t||����dS)NrIrHr)r3�resetr8�destroy�clearrr7r6rMrNr0rOrP�delattr)r>rvrWr4�name_with_overload� namespaces r!�_destroyzLibrary._destroys�� �6� � �F�L�L�N�N�N�����0� � �F� �N�N� � � � � �"�(�(�*�*�*��$�.� ���M� %� %�D�&*�Z�Z��%5�%5� "�B�"�%�+�+�C�0�0��3�D��5�9�b�)�)� ���� �2�.�.�I��9�d�+�+� �� �I�t� $� $� $� $� %� %r N�r#)r) re� __module__� __qualname__�__doc__r@rBrrwr�rr�rr r!rr,s���������"w�w�w�w�,]�]�]�,��,�,�,�,�,�\2�2�2�2�0( �( �( �( �T; ��; �; �; �; �; �z%�%�%�%�%r rc�L�||z}||z}|D]}|����dS�N)r�)�captured_impls�op_impls� captured_defs�op_defs�registration_handlesrvs r!r=r=sB���h��N��W��M�&������������r c/�K� t|i|��}|V�|���dS#|���wxYwr�)rr�)�args�kwargs�libs r!�_scoped_libraryr�%sI������t�&�v�&�&��� � � � � � �������� � �������s �*�A� _keep_alivez \(.*\) -> .*r)r�rCc��t|t��stdt|�������tjj�|��\}}|�*t|d��}t� |��t� |��std|�d����|� ||zd|���dS)a�Defines a new 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, like :func:`torch.library.impl` or :func:`torch.library.register_fake`. Args: qualname (str): The qualified name for the operator. Should be a string that looks like "namespace::name", e.g. "aten::sin". 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. schema (str): The schema of the operator. E.g. "(Tensor x) -> Tensor" for an op that accepts one Tensor and returns one Tensor. It does not contain the operator name (that is passed in ``qualname``). lib (Optional[Library]): If provided, the lifetime of this operator will be tied to the lifetime of the Library object. tags (Tag | Sequence[Tag]): one or more torch.Tag to apply to this operator. Tagging an operator changes the operator's behavior under various PyTorch subsystems; please read the docs for the torch.Tag carefully before applying it. Example:: >>> import torch >>> import numpy as np >>> >>> # Define the operator >>> torch.library.define("mylib::sin", "(Tensor x) -> Tensor") >>> >>> # Add implementations for the operator >>> @torch.library.impl("mylib::sin", "cpu") >>> def f(x): >>> return torch.from_numpy(np.sin(x.numpy())) >>> >>> # Call the new operator from torch.ops. >>> x = torch.randn(3) >>> y = torch.ops.mylib.sin(x) >>> assert torch.allclose(y, x.sin()) zGdefine(qualname, schema): expected qualname to be instance of str, got Nr'zadefine(qualname, schema, ...): expected schema to look like e.g. "(Tensor x) -> Tensor" but got "�"r#)rVrC)rKr�r*r�r0r^r_�parse_namespacerr�rm�NAMELESS_SCHEMA� fullmatchr)r[rUr�rCr�rWs r!rr4s���b �h�� $� $�<�� ;�*.�x�.�.� ;� ;�<�<� <��n�*�:�:�8�D�D�O�I�t� �{��i��,�,�����3���� � $� $�V� ,� ,��� �� � � ��� ��J�J�t�f�}�R�d�J�;�;�;�;�;r r#r�c��������fd�}|S)zOThe old torch.library.define. We're keeping this around for BC reasons c�`��������}��||��|Sr�)rr)�frWrVr�rUs ���r!�wrapz_.<locals>.wrapzs/����z�z�&�.�1�1�� ����q�����r r)r�rUrVr�s``` r!�_r�us/����� ������� �Kr �r�c�B����t|t��r|f}ti���|D][}tj�|��}|r��|���9��t|�����\���fd�}|�|S||��dS)a�Register an implementation for a device type for this operator. You may pass "default" for ``types`` to register this implementation as the default implementation for ALL device types. Please only use this if the implementation truly supports all device types; for example, this is true if it is a composition of built-in PyTorch operators. Some valid types are: "cpu", "cuda", "xla", "mps", "ipu", "xpu". Args: qualname (str): Should be a string that looks like "namespace::operator_name". types (str | Sequence[str]): The device types to register an impl to. lib (Optional[Library]): If provided, the lifetime of this registration will be tied to the lifetime of the Library object. Examples: >>> import torch >>> import numpy as np >>> >>> # Define the operator >>> torch.library.define("mylib::mysin", "(Tensor x) -> Tensor") >>> >>> # Add implementations for the cpu device >>> @torch.library.impl("mylib::mysin", "cpu") >>> def f(x): >>> return torch.from_numpy(np.sin(x.numpy())) >>> >>> x = torch.randn(3) >>> y = torch.ops.mylib.mysin(x) >>> assert torch.allclose(y, x.sin()) c����tjj����\}}��+t |d��}t �|��n�}�D]}|��||���dS)Nr')r0r^r_r�rr�rmr)�funcr�r��use_libr��keysr�r[s ���r!rlzimpl.<locals>.register�s�����~�+�;�;�H�E�E� � �1� �;��i��4�4�G� � � �w� '� '� '� '��G�� .� .�C� �L�L��4�� -� -� -� -� .� .r N)rKr�r5r0r1�_parse_dispatch_keyrT�_device_type_to_key)r[�typesr�r��typ�is_dispatch_keyrlr�s` ` @r!rr�s������B�%�������� �r�7�7�D�� /� /���(�6�6�s�;�;�� � /� �H�H�S�M�M�M�M� �H�H�(��-�-� .� .� .� .�.�.�.�.�.�.�.� �|����������r � device_type�returnc�P�|dkrdStj�|��S)N�default�CompositeExplicitAutograd)r0r1�_dispatch_key_for_device)r�s r!r�r��s+���i��� +�*� �8� ,� ,�[� 9� 9�9r c��������fd�}|S)z1Legacy torch.library.impl API. Kept around for BCc�6�����|���|Sr�)r)r�r:r�rWs ���r!r�z_.<locals>.wrap�s��� ����q�,�'�'�'��r r)r�rWr:r�s``` r!r�r��s/������������ �Kr z�`torch.library.impl_abstract` was renamed to `torch.library.register_fake`. Please use that instead; we will remove `torch.library.impl_abstract` in a future version of PyTorch.)�category�r�rpc�6�|�|dz}t||||���S)zmThis API was renamed to :func:`torch.library.register_fake` in PyTorch 2.4. Please use that instead. Nrr�)r)r[r�r�rps r!rr�s*�� ��!�A�o� � ��4�S�k� J� J� J�Jr ztorch._ops.OpOverloadz%torch._library.custom_ops.CustomOpDef�op� device_typesr�c��t|ttjjtjjjf��std���t|tjj��r|j }t|��}|�|� ||��St|t��sJ�|�d}t||||���S)a5Register 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 (None | str | Sequence[str]): The device_types to register an impl to. If None, we will register to all device types -- please only use this option if your implementation is truly device-type-agnostic. 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 >>> @torch.library.register_kernel("mylib::numpy_sin", "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()) z;register_kernel(op): got unexpected type for op: {type(op)}Nr�r�) rKr�r0rRrr^� custom_opsrr*�_namer�register_kernelr)r�r�r�r��opdefs r!r�r��s���^ �b�3�� � 5�u�~�7P�7\�]� ^� ^�X��V�W�W�W��"�e�j�+�,�,�� �X�� �R� � �E� ���$�$�\�4�8�8�8� �b�#� � ��� ���2� � ��L�$�C� 0� 0� 0�0r rpc�����t�ttjjtjjjf��std���t�tjj��r�j �t���}|�|�|j S|� |��St�t��sJ�|����fd�}|�|S�dz �||��S)aRegister a FakeTensor implementation ("fake impl") for this operator. Also sometimes known as a "meta kernel", "abstract impl". An "FakeTensor implementation" specifies the behavior of this operator on Tensors that carry no data ("FakeTensor"). Given some input Tensors with certain properties (sizes/strides/storage_offset/device), it specifies what the properties of the output Tensors are. The FakeTensor implementation has the same signature as the operator. It is run for both FakeTensors and meta tensors. To write a FakeTensor 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 FakeTensor 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://pytorch.org/tutorials/advanced/custom_ops_landing_page.html 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::custom_linear", mutates_args=()) >>> def custom_linear(x: Tensor, weight: Tensor, bias: Tensor) -> Tensor: >>> raise NotImplementedError("Implementation goes here") >>> >>> @torch.library.register_fake("mylib::custom_linear") >>> 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 @ weight.t()) + bias >>> >>> with torch._subclasses.fake_tensor.FakeTensorMode(): >>> x = torch.randn(2, 3) >>> w = torch.randn(3, 3) >>> b = torch.randn(3) >>> y = torch.ops.mylib.custom_linear(x, w, b) >>> >>> assert y.shape == (2, 3) >>> >>> # Example 2: an operator with data-dependent output shape >>> @torch.library.custom_op("mylib::custom_nonzero", mutates_args=()) >>> def custom_nonzero(x: Tensor) -> Tensor: >>> x_np = x.numpy(force=True) >>> res = np.stack(np.nonzero(x_np), axis=1) >>> return torch.tensor(res, device=x.device) >>> >>> @torch.library.register_fake("mylib::custom_nonzero") >>> def _(x): >>> # Number of nonzero-elements is data-dependent. >>> # Since we cannot peek at the data in an fake 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 >>> >>> from torch.fx.experimental.proxy_tensor import make_fx >>> >>> x = torch.tensor([0, 1, 2, 3, 4, 0]) >>> trace = make_fx(torch.ops.mylib.custom_nonzero, tracing_mode="symbolic")(x) >>> trace.print_readable() >>> >>> assert torch.allclose(trace(x), torch.ops.mylib.custom_nonzero(x)) z9register_fake(op): got unexpected type for op: {type(op)}Nc����tjj����\}}��+t |d��}t �|��n�}|�||�dz���|S)Nr'r)rp)r0r^r_r�rr�rmrw)r�r�rnr�r�r�� stacklevels ���r!rlzregister_fake.<locals>.register�st���"�^�1�A�A�"�E�E�� �7� �;��i��4�4�G� � � �w� '� '� '� '��G����w��*�q�.��I�I�I�� r r) rKr�r0rRrr^r�rr*r�rr)r�r�r�rpr�rlr�s` ` @r!rr"s������n �b�3�� � 5�u�~�7P�7\�]� ^� ^�V��T�U�U�U��"�e�j�+�,�,�� �X�� �R� � �E� �� �<��&� &��&�&�t�,�,� ,� �b�#� � ��� ��J�������� �|����a�� ��x��~�~�r )� setup_contextr��backwardr�c��t|ttjjtjjjf��stdt|�������t|tjj��r|j }t|��}|�|� ||���dSt|t��sJ�|}tjj �|��}|j}t j �|��st#d|�d|�d����t j �|��rt'd|�����t j�||��}t j�||��}tjj �|��\} } |�*t1| d��}t2�|��|�| |d d � ��dS) a� 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`` 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() >>> >>> torch.library.register_autograd("mylib::numpy_sin", 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 >>> >>> torch.library.register_autograd("mylib::numpy_mul", 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)) z3register_autograd(op): got unexpected type for op: N)r�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.z�register_autograd with kwarg-only Tensor args. In the original definition of the op, please make your tensors not kwarg-only. Got: r'�AutogradTr�)rKr�r0rRrr^r�rr*r�r�r�register_autogradr_� lookup_opr��is_functional_schemarJ�has_kwarg_only_tensorsr�autograd�Info�make_autograd_implr�rr�rmr) r�r�r�r�r�r[rU�info�autograd_kernelr��opnames r!r�r��s���X �b�3�� � 5�u�~�7P�7\�]� ^� ^�[��Y�t�TV�x�x�Y�Y�Z�Z�Z��"�e�j�+�,�,�� �X�� �R� � �E� �� ���� ��F�F�F��� �b�#� � ��� ��H� �� � '� '�� 1� 1�B� �Z�F� �>� .� .�v� 6� 6� �� P�� P� P� &� P� P� P� � � � �~�,�,�V�4�4��!� �� � ��� � � � !� !�(�M� :� :�D��'�:�:�2�t�D�D�O���,�<�<�X�F�F��I�v� �{��i��,�,�����3�����H�H�V�_�j�d�H�C�C�C�C�Cr c�"�����d�����fd�}|S)NFc �H���r� |i|��Stjj�� ��}|jr d�� |i|��Stj�|jj|jj ��}|�`tjj� ��r<|j }|j � ��}td� �d��d|�d|�d� ���nC|d}�|kr5|j � ��}td� �d|�d ��d |�d� ���d�� |i|��S) NTz Operator 'z�' was defined in C++ and has a Python fake impl. In this situation, we require there to also be a companion C++ `m.set_python_module("z\")` call, but we could not find one. Please add that to to the top of the C++ TORCH_LIBRARY(z-, ...) block the operator was registered in (�)rz?' specified that its python fake impl is in the Python module 'z ' but it was actually found in 'zM'. Please either move the fake impl or correct the m.set_python_module call ()r0r^r_r��_defined_in_pythonr1�_dispatch_pystubr�rWr��requires_set_python_moduler��_handle�debugrJ) r�r�r�� maybe_pystubr�� cpp_filename� pystub_module�actual_module_name�checkedr�r[s ����r!�innerz"_check_pystubs_once.<locals>.inner s���� � )��4��(��(�(� (� �^� !� +� +�H� 5� 5�� � � )��G��4��(��(�(� (��x�0�0� �J�O� �J� $�&�&� � � ��~�#�>�>�@�@� D��L� �!�z�/�/�1�1� �"�C��C�C�;M�C�C�<E� C�C� 4@� C�C�C�D�D�D� D�)��O�M�!�]�2�2�!�z�/�/�1�1� �"�P��P�P�0=�P�P�-�P�P�AM�P�P�P�Q�Q�Q� ���t�T�$�V�$�$�$r r)r�r[r�r�r�s``` @r!rjrj s;�������G�"%�"%�"%�"%�"%�"%�"%�"%�F �Lr �,torch._library.abstract_impl.AbstractImplCtxc�H�tjj���S)z�get_ctx() returns the current AbstractImplCtx object. Calling ``get_ctx()`` is only valid inside of an fake impl (see :func:`torch.library.register_fake` for more usage details. )r0r^rk�global_ctx_getterrr r!rr9s�� �>� '� 9� 9� ;� ;�;r )� test_schema�test_autograd_registration�test_faketensor�test_aot_dispatch_dynamicT�� test_utils�raise_exceptionr�.r�r�r�c�N�ddlmcmcm}|�|||||���S)aAGiven an operator and some sample arguments, tests if the operator is registered correctly. That is, when you use the torch.library/TORCH_LIBRARY APIs to create a custom op, you specified metadata (e.g. mutability info) about the custom op and these APIs require that the functions you pass them satisfy certain properties (e.g. no data pointer access in the fake/meta/abstract kernel) ``opcheck`` tests these metadata and properties. Concretely, we test the following: - test_schema: if the operator's schema is correct. - test_autograd_registration: if autograd was registered correctly. - test_faketensor: If the operator has a FakeTensor kernel (and if it is correct). The FakeTensor kernel is necessary ( but not sufficient) for the operator to work with PyTorch compilation APIs (torch.compile/export/FX). - test_aot_dispatch_dynamic: If the operator has correct behavior with PyTorch compilation APIs (torch.compile/export/FX). This checks that the outputs (and gradients, if applicable) are the same under eager-mode PyTorch and torch.compile. This test is a superset of ``test_faketensor``. For best results, please call ``opcheck`` multiple times with a representative set of inputs. If your operator supports autograd, please use ``opcheck`` with inputs with ``requires_grad = True``; if your operator supports multiple devices (e.g. CPU and CUDA), please use ``opcheck`` with inputs on all supported devices. Args: op: The operator. Must either be a function decorated with :func:`torch.library.custom_op` or an OpOverload/OpOverloadPacket found in torch.ops.* (e.g. torch.ops.aten.sin, torch.ops.mylib.foo) args: The args to the operator kwargs: The kwargs to the operator test_utils: Tests that we should run. Default: all of them. Example: ("test_schema", "test_faketensor") raise_exception: If we should raise an exception on the first error. If False, we will return a dict with information on if each test passed or not. .. warning:: opcheck and :func:`torch.autograd.gradcheck` test different things; opcheck tests if your usage of torch.library APIs is correct while :func:`torch.autograd.gradcheck` tests if your autograd formula is mathematically correct. Use both to test custom ops that support gradient computation. Example: >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA) >>> @torch.library.custom_op("mylib::numpy_mul", mutates_args=()) >>> def numpy_add(x: Tensor, y: float) -> Tensor: >>> x_np = x.numpy(force=True) >>> z_np = x_np + y >>> return torch.from_numpy(z_np).to(x.device) >>> >>> @numpy_sin.register_fake >>> def _(x, y): >>> return torch.empty_like(x) >>> >>> def setup_context(ctx, inputs, output): >>> y, = inputs >>> ctx.y = y >>> >>> def backward(ctx, grad): >>> return grad * ctx.y, None >>> >>> numpy_sin.register_autograd(backward, setup_context=setup_context) >>> >>> sample_inputs = [ >>> (torch.randn(3), 3.14), >>> (torch.randn(2, 3, device='cuda'), 2.718), >>> (torch.randn(1, 10, requires_grad=True), 1.234), >>> (torch.randn(64, 64, device='cuda', requires_grad=True), 90.18), >>> ] >>> >>> for args in sample_inputs: >>> torch.library.opcheck(foo, args) rNr�)�torch.testing._internal.optests�testing� _internal�optests�opcheck)r�r�r�r�r�r�s r!rrJsF��r6�5�5�5�5�5�5�5�5�5�5�5� �?�?�2�t�V� �Tc�?� d� d�dr r�r�)r�r�)?rRr�typingrrrrr r r r r �typing_extensionsrr,r0r;� functoolsrc�re� contextlibra�torch._library.custom_opsrrrr�torch._libraryr^�__all__r5rr��__annotations__rr+rrr=�contextmanagerr�r��compiler��singledispatchrrlr�rr�� FutureWarningr�_op_identifierr��intrr�rjr�_OPCHECK_DEFAULT_UTILS�OpOverloadPacket�boolrrr r!�<module>rsI���������S�S�S�S�S�S�S�S�S�S�S�S�S�S�S�S�S�S�S�S�S�S�(�(�(�(�(�(����� � � � ������������� � � � ����� � � � �^�^�^�^�^�^�^�^�^�^�^�^�!�!�!�!�!�!� � � ���3�5�5���C������#�%�%��s�3�x�����x��N�N�N� o%�o%�o%�o%�o%�o%�o%�o%�d��� ������� � �T�'�]�����"�*�_�-�-�� ��$(�r�=<�=<�=<�=<���=<�@����7������� ��=�D�=�=�=�=���=�@:�S�:�S�:�:�:�:�����7������� ��\� ���� K�d��K�K�K�K� �� K��s�3�5\�\�]�� $(�91� "&� 91�91�91� �91�$�91��x� �91� �g� � 91�91�91�91�|$(�s� "&�� s�s�s� �s��x� �s� �g� � s� � s�s�s�s�lim�rv�kD�kD�kD�.�kD�H�kD�S[�\d�Se�kD�{�kD�kD�kD�kD�b&�&�&�`<�<�<�<���(,�Ze� -C� � Ze�Ze�Ze� �e�j�#�U�Z�%@�+�M�N�Ze� ��S��/�Ze� �T�#�s�(�^� $�Ze� �c�8�C�=�(�)� Ze� � Ze� �#�s�(�^�Ze�Ze�Ze�Ze�Ze�Zer
Memory