U
    dD                     @   sJ  d 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 ddlmZ ddlmZmZ ddlmZmZ dd	lmZmZmZmZ dd
lmZmZ ddlmZmZm Z  ddl!m"Z" ddl!m#Z# ddl!m$Z$ ddl!m%Z% ddddgZ&e	ej' Z(e
ej' e
e( e)ee(df dddZ*e	e e+ee(df dddZ,d-ee	e e	e) e)e	e e	e ddddZ-d.eee	e e	e) e)e)e)e)eej'df d 	d!d"Z.d#d$ Z/d%d& Zee_ej01 se2d'dd(l3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;m<Z<m=Z=m>Z>m?Z?m@Z@mAZAmBZBmCZCmDZDmEZE dd)l3mFZFmGZGmHZHmIZImJZJmKZK dd*l!mLZL d+d, ZMdS )/a  
``torch.autograd`` provides classes and functions implementing automatic
differentiation of arbitrary scalar valued functions. It requires minimal
changes to the existing code - you only need to declare :class:`Tensor` s
for which gradients should be computed with the ``requires_grad=True`` keyword.
As of now, we only support autograd for floating point :class:`Tensor` types (
half, float, double and bfloat16) and complex :class:`Tensor` types (cfloat, cdouble).
    N)_TensorOrTensors)AnyCallableListOptionalSequenceTupleUnioncast   )Variable)FunctionNestedIOFunction)	gradcheckgradgradcheck)no_gradenable_gradset_grad_enabledinference_mode)detect_anomalyset_detect_anomaly   )has_torch_functionhandle_torch_functionis_tensor_like)
functional)
forward_ad)graph)_vmap_internalsr   r   backward	grad_mode.)outputsgradsis_grads_batchedreturnc                 C   s  g }t | |D ]\}}t|tjrD|s0|jn|jdd  }|j|ks|rtdt|| d t|j d t| | d t|j d nHtdt|| d t|j d t| | d t|j d |jj	|jj	kr8tdt|| d	 t|j d t| | d	 t|j d |
| q|d kr|jr| dkrltd
|
tj|tjd n
|
d  qtdt|j qt|S )Nr   zIf `is_grads_batched=True`, we interpret the first dimension of each grad_output as the batch dimension. The sizes of the remaining dimensions are expected to match the shape of corresponding output, but a mismatch was detected: grad_output[z] has a shape of z and output[z_. If you only want some tensors in `grad_output` to be considered batched, consider using vmap.zMismatch in shape: grad_output[.zuFor complex Tensors, both grad_output and output are required to have the same dtype. Mismatch in dtype: grad_output[z] has a dtype of z6grad can be implicitly created only for scalar outputs)Zmemory_formatz1gradients can be either Tensors or None, but got )zip
isinstancetorchTensorshapeRuntimeErrorstrindexZdtypeZ
is_complexappendZrequires_gradZnumelZ	ones_likeZpreserve_format	TypeErrortype__name__tuple)r!   r"   r#   Z	new_gradsoutgradZ
grad_shape r5   ;/tmp/pip-unpacked-wheel-ua33x9lu/torch/autograd/__init__.py_make_grads   s    

r7   )tensorslengthr$   c                 C   s*   | d krd| S t | tjr"| fS t| S )NN)r'   r(   r)   r2   )r8   r9   r5   r5   r6   _tensor_or_tensors_to_tupleM   s
    r;   F)r8   grad_tensorsretain_graphcreate_graphgrad_variablesinputsr$   c              	   C   s   |dk	r(t d |dkr |}ntd|dk	rDt|dkrDtdt| tjrV| fnt| } t|tjrp|fn|dk	rt|nt }t|t| }t	| |dd}|dkr|}t
jj| ||||ddd	 dS )
a   Computes the sum of gradients of given tensors with respect to graph
    leaves.

    The graph is differentiated using the chain rule. If any of ``tensors``
    are non-scalar (i.e. their data has more than one element) and require
    gradient, then the Jacobian-vector product would be computed, in this
    case the function additionally requires specifying ``grad_tensors``.
    It should be a sequence of matching length, that contains the "vector"
    in the Jacobian-vector product, usually the gradient of the differentiated
    function w.r.t. corresponding tensors (``None`` is an acceptable value for
    all tensors that don't need gradient tensors).

    This function accumulates gradients in the leaves - you might need to zero
    ``.grad`` attributes or set them to ``None`` before calling it.
    See :ref:`Default gradient layouts<default-grad-layouts>`
    for details on the memory layout of accumulated gradients.

    .. note::
        Using this method with ``create_graph=True`` will create a reference cycle
        between the parameter and its gradient which can cause a memory leak.
        We recommend using ``autograd.grad`` when creating the graph to avoid this.
        If you have to use this function, make sure to reset the ``.grad`` fields of your
        parameters to ``None`` after use to break the cycle and avoid the leak.

    .. note::

        If you run any forward ops, create ``grad_tensors``, and/or call ``backward``
        in a user-specified CUDA stream context, see
        :ref:`Stream semantics of backward passes<bwd-cuda-stream-semantics>`.

    .. note::

        When ``inputs`` are provided and a given input is not a leaf,
        the current implementation will call its grad_fn (even though it is not strictly needed to get this gradients).
        It is an implementation detail on which the user should not rely.
        See https://github.com/pytorch/pytorch/pull/60521#issuecomment-867061780 for more details.

    Args:
        tensors (Sequence[Tensor] or Tensor): Tensors of which the derivative will be
            computed.
        grad_tensors (Sequence[Tensor or None] or Tensor, optional): The "vector" in
            the Jacobian-vector product, usually gradients w.r.t. each element of
            corresponding tensors. None values can be specified for scalar Tensors or
            ones that don't require grad. If a None value would be acceptable for all
            grad_tensors, then this argument is optional.
        retain_graph (bool, optional): If ``False``, the graph used to compute the grad
            will be freed. Note that in nearly all cases setting this option to ``True``
            is not needed and often can be worked around in a much more efficient
            way. Defaults to the value of ``create_graph``.
        create_graph (bool, optional): If ``True``, graph of the derivative will
            be constructed, allowing to compute higher order derivative products.
            Defaults to ``False``.
        inputs (Sequence[Tensor] or Tensor, optional): Inputs w.r.t. which the gradient
            be will accumulated into ``.grad``. All other Tensors will be ignored. If
            not provided, the gradient is accumulated into all the leaf Tensors that
            were used to compute the attr::tensors.
    Nz;'grad_variables' is deprecated. Use 'grad_tensors' instead.zu'grad_tensors' and 'grad_variables' (deprecated) arguments both passed to backward(). Please only use 'grad_tensors'.r   z0'inputs' argument to backward() cannot be empty.Fr#   T)Zallow_unreachableaccumulate_grad)warningswarnr+   lenr'   r(   r)   r2   r;   r7   r   _execution_enginerun_backward)r8   r<   r=   r>   r?   r@   Zgrad_tensors_r5   r5   r6   r   U   s0    A
     T)	r!   r@   grad_outputsr=   r>   only_inputsallow_unusedr#   r$   c                    s   t ttjdf t| r| fnt| t ttjdf t|rB|fnt| }t|rxtt||| |d
S |st	
d t|t}	t|	|d}	dkr|r܇ fdd}
tj|
ddd	d
|	S tjj|	 ddS dS )a  Computes and returns the sum of gradients of outputs with respect to
    the inputs.

    ``grad_outputs`` should be a sequence of length matching ``output``
    containing the "vector" in vector-Jacobian product, usually the pre-computed
    gradients w.r.t. each of the outputs. If an output doesn't require_grad,
    then the gradient can be ``None``).

    .. note::

        If you run any forward ops, create ``grad_outputs``, and/or call ``grad``
        in a user-specified CUDA stream context, see
        :ref:`Stream semantics of backward passes<bwd-cuda-stream-semantics>`.

    .. note::

        ``only_inputs`` argument is deprecated and is ignored now (defaults to ``True``).
        To accumulate gradient for other parts of the graph, please use
        ``torch.autograd.backward``.

    Args:
        outputs (sequence of Tensor): outputs of the differentiated function.
        inputs (sequence of Tensor): Inputs w.r.t. which the gradient will be
            returned (and not accumulated into ``.grad``).
        grad_outputs (sequence of Tensor): The "vector" in the vector-Jacobian product.
            Usually gradients w.r.t. each output. None values can be specified for scalar
            Tensors or ones that don't require grad. If a None value would be acceptable
            for all grad_tensors, then this argument is optional. Default: None.
        retain_graph (bool, optional): If ``False``, the graph used to compute the grad
            will be freed. Note that in nearly all cases setting this option to ``True``
            is not needed and often can be worked around in a much more efficient
            way. Defaults to the value of ``create_graph``.
        create_graph (bool, optional): If ``True``, graph of the derivative will
            be constructed, allowing to compute higher order derivative products.
            Default: ``False``.
        allow_unused (bool, optional): If ``False``, specifying inputs that were not
            used when computing outputs (and therefore their grad is always zero)
            is an error. Defaults to ``False``.
        is_grads_batched (bool, optional): If ``True``, the first dimension of each
            tensor in ``grad_outputs`` will be interpreted as the batch dimension.
            Instead of computing a single vector-Jacobian product, we compute a
            batch of vector-Jacobian products for each "vector" in the batch.
            We use the vmap prototype feature as the backend to vectorize calls
            to the autograd engine so that this computation can be performed in a
            single call. This should lead to performance improvements when compared
            to manually looping and performing backward multiple times. Note that
            due to this feature being experimental, there may be performance
            cliffs. Please use ``torch._C._debug_only_display_vmap_fallback_warnings(True)``
            to show any performance warnings and file an issue on github if warnings exist
            for your use case. Defaults to ``False``.
    .)rH   r=   r>   rI   rJ   r#   zonly_inputs argument is deprecated and is ignored now (defaults to True). To accumulate gradient for other parts of the graph, please use torch.autograd.backward.rA   Nc              	      s   t jj|  ddS )NFrB   )r   rF   rG   )ZgOrJ   r>   r=   Zt_inputsZ	t_outputsr5   r6   vjp  s         zgrad.<locals>.vjpr   T)Zallow_none_pass_throughFrK   )r
   r   r(   r)   r   r2   r   r   r4   rC   rD   r;   rE   r7   r   Z_vmapr   rF   rG   )r!   r@   rH   r=   r>   rI   rJ   r#   Zoverridable_argsZgrad_outputs_rM   r5   rL   r6   r4      sD    =&&
     r4   c                   C   s
   t j S r:   )r   rF   Zis_checkpoint_validr5   r5   r5   r6   _is_checkpoint_valid&  s    rN   c                  O   s   t dd S )NzItorch.autograd.variable(...) is deprecated, use torch.tensor(...) instead)r+   )argskwargsr5   r5   r6   variable*  s    rQ   zautograd initialization failed)
DeviceTypeProfilerActivityProfilerStateProfilerConfigProfilerEvent_enable_profiler_legacy_disable_profiler_legacy_profiler_enabled_enable_record_function_set_empty_test_observerkineto_available _record_function_with_args_enter_record_function_with_args_exit_supported_activities_add_metadata_jsonSavedTensor!_push_saved_tensors_default_hooks _pop_saved_tensors_default_hooks)_ProfilerResult_KinetoEvent_kineto_step_prepare_profiler_enable_profiler_disable_profiler)profilerc                 C   s$   t |tstdtj| | d S )Nzcls isn't a typeinfo object)r'   r0   r+   r(   _CZ_register_py_class_for_device)Zdeviceclsr5   r5   r6   $_register_py_tensor_class_for_deviceC  s    
rm   )NNFNN)NNFTFF)N__doc__r(   rC   Ztorch.typesr   typingr   r   r   r   r   r   r	   r
   rQ   r   functionr   r   r   r   r    r   r   r   r   Zanomaly_moder   r   Z	overridesr   r   r    r   r   r   r   __all__r)   Z_OptionalTensorboolr7   intr;   r   r4   rN   rk   Z_autograd_initr+   Ztorch._C._autogradrR   rS   rT   rU   rV   rW   rX   rY   rZ   r[   r\   r]   r^   r_   r`   ra   rb   rc   rd   re   rf   rg   rh   ri   rj   rm   r5   r5   r5   r6   <module>   sz   (
 
/
     _      uP 