a
    Þñhþ2  ã                   @   sz  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 d dl	Z	ee
eee
 df f Zee
ee
df f Zeee
 df ee
dœdd„Zeee
 df eeeddœd	d
„Zeeeedf f e
dœdd„Zee
eg ef edœdd„Zeee
eeee
f dœdd„Zeeeedf f ee
e
eedœdd„Zeeddœdd„Zeeddœdd„Zedœdd„Zd#eeeed œd!d"„ZdS )$é    N)ÚTensor)ÚAnyÚCallableÚOptionalÚTupleÚUnion.)Úin_dims_as_tupleÚargsÚreturnc                    sF   dd„ t | |ƒD ƒ‰ ˆ r>t‡ fdd„ˆ D ƒƒr>tdˆ › d�ƒ‚ˆ d S )Nc                 S   s"   g | ]\}}|d ur|  |¡‘qS ©N)Úsize©Ú.0Úin_dimÚarg© r   úU/home/yuhw/wc/uboone-dl-vtx/venv/lib/python3.9/site-packages/torch/_vmap_internals.pyÚ
<listcomp>   s   ÿz0_validate_and_get_batch_size.<locals>.<listcomp>c                    s   g | ]}|ˆ d  k‘qS )r   r   )r   r   ©Zbatch_sizesr   r   r      ó    zTvmap: Expected all tensors to have the same size in the mapped dimension, got sizes z for the mapped dimensionr   )ÚzipÚanyÚ
ValueError)r   r	   r   r   r   Ú_validate_and_get_batch_size   s    ÿÿr   )r   r	   ÚfuncÚin_dimsr
   c                 C   sê   t t| |ƒƒD ]Ö\}\}}|d u r$qt|tƒsHtdt|ƒ› d|› d�ƒ‚t|tƒsŽtdt|ƒ› d|› d|› d|› d|› dt|ƒ› d|› d	�ƒ‚|d
kr¤|| ¡ k r¤qtdt|ƒ› d|› d|› d|› d|› d| ¡ › d| ¡ › d	�ƒ‚qd S )Núvmap(ú
, in_dims=z¹, ...)(<inputs>): in_dims must be a flat tuple containing ints and/or Nones. If you were trying to vmap over a Tensor inside a Python collection in `inputs`, we do not yet support that.z, ...)(<inputs>): Got in_dim=z for input z, but input z is not a Tensor (got zÄ) so it cannot be vmap'ed over. If you were trying to vmap over a Tensor inside a Python collection in `inputs`, we do not yet support that; otherwise, use None as the respective in_dim for input Ú.r   z is a Tensor of dimensionality z- so expected in_dim to satisfy 0 <= in_dim < )	Ú	enumerater   Ú
isinstanceÚintr   Ú	_get_namer   ÚtypeZdim)r   r	   r   r   Úidxr   r   r   r   r   Ú&_check_args_can_be_mapped_with_in_dims   sD    
ÿ
ÿÿÿþûÿ	ÿÿþþÿr%   )Úbatched_outputsr
   c                 C   s   t | tƒrt| ƒS dS )Né   )r    ÚtupleÚlen)r&   r   r   r   Ú_num_outputs8   s    
r*   )ÚvalueÚnum_elementsÚerror_message_lambdar
   c                 C   s.   t | tƒs| f| S t| ƒ|kr*t|ƒ ƒ‚| S r   )r    r(   r)   r   )r+   r,   r-   r   r   r   Ú	_as_tuple?   s
    


r.   )r   r	   Ú
vmap_levelr   r
   c                    s°   t ˆtƒs8t ˆtƒs8tdtˆƒ› dˆ› dtˆƒ› d�ƒ‚tˆtˆ ƒ‡ ‡‡fdd„ƒ}tˆ ƒdkrttdtˆƒ› d�ƒ‚t|ˆ ˆˆƒ t	|ˆ ƒ}t‡fd	d
„t
|ˆ ƒD ƒƒ}||fS )Nr   r   z4, ...): expected `in_dims` to be int or tuple, got: r   c                	      s(   dt ˆƒ› dˆ› dtˆ ƒ› dt ˆƒ› �S )Nr   r   z7, ...)(<inputs>): expected one `in_dim` per input (got z inputs) of )r"   r)   r   )r	   r   r   r   r   Ú<lambda>R   s   ÿÿz(_create_batched_inputs.<locals>.<lambda>r   z�)(<inputs>): got no inputs. Maybe you forgot to add inputs, or you are trying to vmap over a function with no inputs. The latter is unsupported.c                 3   s,   | ]$\}}|d u r|nt  ||ˆ ¡V  qd S r   )ÚtorchZ_add_batch_dimr   )r/   r   r   Ú	<genexpr>^   s   þz)_create_batched_inputs.<locals>.<genexpr>)r    r!   r(   r   r"   r#   r.   r)   r%   r   r   )r   r	   r/   r   r   Ú
batch_sizeÚbatched_inputsr   )r	   r   r   r/   r   Ú_create_batched_inputsH   s(    ÿÿþÿ
þr5   )r&   Úout_dimsr/   r3   r   r
   c                    s`   t | ƒ‰tˆˆ‡‡‡fdd„ƒ}t| tƒrB|d }t | ˆˆ |¡S t‡ ‡fdd„t| |ƒD ƒƒS )Nc                	      s&   dt ˆ ƒ› dˆ› dˆ› dt ˆ ƒ› d�	S )Nr   ú, ..., out_dims=z0): `out_dims` must have one dim per output (got z outputs) of r   )r"   r   )r   Únum_outputsr6   r   r   r0   k   s   ÿÿz!_unwrap_batched.<locals>.<lambda>r   c                 3   s"   | ]\}}t  |ˆˆ |¡V  qd S r   )r1   Ú_remove_batch_dim)r   ÚoutÚout_dim)r3   r/   r   r   r2   t   s   ÿz"_unwrap_batched.<locals>.<genexpr>)r*   r.   r    r   r1   r9   r(   r   )r&   r6   r/   r3   r   Zout_dims_as_tupler;   r   )r3   r   r8   r6   r/   r   Ú_unwrap_batchedd   s    þ
ÿr<   )Úoutputsr   r
   c                 C   s�   t | tƒrd S t | tƒs@tdt|ƒ› dt|ƒ› dt| ƒ› d�ƒ‚t| ƒD ]B\}}t |tƒr\qHtdt|ƒ› dt|ƒ› dt|ƒ› d|› d�	ƒ‚qHd S )Nr   z	, ...): `z%` must only return Tensors, got type z as the return.z for return r   )r    r   r(   r   r"   r#   r   )r=   r   r$   Úoutputr   r   r   Ú_validate_outputs{   s    

ÿ

ÿÿr?   )r6   r   r
   c                 C   sH   t | tƒrd S t | tƒr*tdd„ | D ƒƒsDtdt|ƒ› d| › d�ƒ‚d S )Nc                 S   s   g | ]}t |tƒ‘qS r   )r    r!   )r   r;   r   r   r   r   ‹   r   z7_check_out_dims_is_int_or_int_tuple.<locals>.<listcomp>r   r7   zu): `out_dims` must be an int or a tuple of int representing where in the outputs the vmapped dimension should appear.)r    r!   r(   Úallr   r"   )r6   r   r   r   r   Ú#_check_out_dims_is_int_or_int_tuple‡   s    

ÿÿrA   )r   c                 C   s   t | dƒr| jS t| ƒ}d S )NÚ__name__)ÚhasattrrB   Úrepr)r   Úfn_namer   r   r   r"   ‘   s    
r"   )r   r   r6   r
   c                    s(   t  d¡ t ˆ ¡‡ ‡‡fdd„ƒ}|S )a  
    vmap is the vectorizing map. 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.

    .. warning::
        torch.vmap is an experimental prototype that is subject to
        change and/or deletion. Please use at your own risk.

    .. note::
        If you're interested in using vmap for your use case, please
        `contact us! <https://github.com/pytorch/pytorch/issues/42368>`_
        We're interested in gathering feedback from early adopters to inform
        the design.

    Args:
        func (function): A Python function that takes one or more arguments.
            Must return one or more Tensors.
        in_dims (int or Tuple[Optional[int]]): Specifies which dimension of the
            inputs should be mapped over. If `in_dims` is a Tuple, then it should have
            one element per input. 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.

    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:
        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 `vmap` is to compute batched dot products. PyTorch
    doesn't provide a batched `torch.dot` API; instead of unsuccessfully
    rummaging through docs, use `vmap` to construct a new function.

        >>> torch.dot                            # [D], [D] -> []
        >>> batched_dot = torch.vmap(torch.dot)  # [N, D], [N, D] -> [N]
        >>> x, y = torch.randn(2, 5), torch.randn(2, 5)
        >>> batched_dot(x, y)

    `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)

    `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 `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)

    .. note::
        vmap does not provide general autobatching or handle variable-length
        sequences out of the box.
    zotorch.vmap is an experimental prototype that is subject to change and/or deletion. Please use at your own risk.c                     sf   t ˆˆ ƒ tj ¡ }z@tˆ| |ˆ ƒ\}}ˆ |Ž }t|ˆ ƒ t|ˆ||ˆ ƒW tj ¡  S tj ¡  0 d S r   )rA   r1   Z_CZ_vmapmode_increment_nestingr5   r?   r<   Z_vmapmode_decrement_nesting)r	   r/   r4   r3   r&   ©r   r   r6   r   r   Úwrapped   s    



þzvmap.<locals>.wrapped)ÚwarningsÚwarnÚ	functoolsÚwraps)r   r   r6   rG   r   rF   r   Úvmap�   s    _ÿ
rL   )r   r   )r1   rJ   r   Útypingr   r   r   r   r   rH   r!   Z	in_dims_tZ
out_dims_tr   r%   r*   Ústrr.   r5   r<   r?   rA   r"   rL   r   r   r   r   Ú<module>   s4   þü 
ÿý
