o
    h-                     @   sX  d dl Z d dlmZmZmZ d dlmZ d dlZd dlmZ d dl	m
Z
 dgZddd	eeef d
eeef fddZe j			dddd	eeef dededef
ddZeded		ddddddd	eeef deeeef  deeeef  dedefddZ		ddddddd	eeef deeeef  deeeef  dedefddZdS )    N)AnyOptionalUnion)
deprecated)Tensor)NamedMemberAccessorfunctional_callmoduleztorch.nn.Moduleparameters_and_buffersreturnc                    s>  i }| | jdd | | jdd i }| D ]\}}||vr't ||< || | qi }| D ]}t|dkrF|D ]}|||< q?q5t  }	t }
|	D ]}||v r]|
| qR|
D ]&}|| }t|	|
dkrt fdd|D dkrt
dt| dq`  }|
D ]}|| D ]} | ||< qq|S )a  
    Unties all tied tensors in the module to parameters_and_buffers.

    This function returns a new untied_parameters_and_buffers dictionary and leave the original
    untied_parameters_and_buffers dictionary unchanged. It adds new (missing) keys for tied tensors
    in the module to untied_parameters_and_buffers. The value of the new key is the user-given value
    in the original parameters_and_buffers dictionary.

    If there are more than one user-given values for the same tied tensor, it will raise an error.

    For example, if the module has two tied weights self.foo and self.tied_foo and the user passes
    {'foo': foo_value, ...}, this will return {'foo': foo_value, 'tied_foo': foo_value, ...}. If the
    user passes {'foo': foo_value, 'tied_foo': tied_foo_value, ...}, it will raise an error. If the
    user passes {'foo': foo_value, 'tied_foo': foo_value, ...}, it will not raise an error.

    Args:
        module (torch.nn.Module): the module to determine which tensors are tied.
        parameters_and_buffers (Dict[str, Tensor]): a map of {name: tensor} for reparamaterizing the module.

    Returns:
        A new untied version of the parameters_and_buffers dictionary.

    Raises:
        ValueError: if there are more than one user-given values for the same tied tensor.
    F)remove_duplicate   c                    s   h | ]} | qS  r   ).0	tied_namer
   r   l/var/www/html/construction_image-detection-poc/venv/lib/python3.10/site-packages/torch/nn/utils/stateless.py	<setcomp>O   s    z+_untie_named_tensors_map.<locals>.<setcomp>z-functional_call got multiple values for keys z2, which are tied. Consider using tie_weights=False)updatenamed_parametersnamed_buffersitemssetaddvalueslenkeysintersection
ValueErrorsortedcopy)r	   r
   all_named_tensorstensor_to_tied_names_mapnametensortied_names_map
tied_namesr   given_namesgiven_names_for_tied_tensors
given_nameuntied_parameters_and_buffersr   r   r   _untie_named_tensors_map   sL   



r+   Ftie_weightsstrictstack_weightsc                 #   sX   |}|}|rt | |}n|}t| }|r[||\}}g }	t|dkr3|	ddtt| d t|dkrH|	ddtt| d t|	dkr[td	| 
 d|	i }
z.|j|dd	\}
}d V  W |rutt|
 }
|j|
dd	\ }| fd
d|D  d S |rtt|
 }
|j|
dd	\ }| fd
d|D  w )Nr   zUnexpected key(s): z, .zMissing key(s): z'Error(s) in reparametrizing for {}:
	{}z
	T)allow_missingc                    s   i | ]}| v r| | qS r   r   )r   knew_parameters_and_buffersr   r   
<dictcomp>   s
    z)_reparametrize_module.<locals>.<dictcomp>)r+   r   
check_keysr   appendjoinmapreprRuntimeErrorformat	_get_nameswap_tensors_dictdictreversedr   r   )r	   r
   r,   r-   r.   r*   accessormissing_keysunexpected_keys
error_msgsorig_parameters_and_buffers_r   r2   r   _reparametrize_moduleb   sp   






rF   z`torch.nn.utils.stateless.functional_call` is deprecated as of PyTorch 2.0 and will be removed in a future version of PyTorch. Please use `torch.func.functional_call` instead which is a drop-in replacement.)categoryTr,   r-   argskwargsc                C   s   t | |||||dS )a  Perform a functional call on the module by replacing the module parameters and buffers with the provided ones.

    .. warning::

        This API is deprecated as of PyTorch 2.0 and will be removed in a future
        version of PyTorch. Please use :func:`torch.func.functional_call` instead,
        which is a drop-in replacement for this API.

    .. note:: If the module has active parametrizations, passing a value in the
        :attr:`parameters_and_buffers` 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 `parameters_and_buffers` 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.)

    Args:
        module (torch.nn.Module): the module to call
        parameters_and_buffers (dict of str and Tensor): the parameters that will be used in
            the module call.
        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 reparamaterized 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``.
    rH   )_functional_callr	   r
   rI   rJ   r,   r-   r   r   r   r      s   Jc                C   s   t j st j st| t jjt jjt jjfrtdt| t j	j
r'td|d u r-i }|d u r4d}nt|ts<|f}t| |||d | |i |W  d    S 1 sVw   Y  d S )Nz3The stateless API can't be used with Jitted modulesz;The stateless API can't be used with nn.DataParallel moduler   rH   )torchjit
is_tracingis_scripting
isinstanceRecursiveScriptModuleScriptModuleScriptFunctionr:   nnDataParalleltuplerF   rL   r   r   r   rK      s8   
$rK   )FFF)NN)
contextlibtypingr   r   r   typing_extensionsr   rM   r   %torch.nn.utils._named_member_accessorr   __all__r>   strr+   contextmanagerboolrF   FutureWarningrW   r   rK   r   r   r   r   <module>   s   


T
?	
Q
