a
    d]                     @   s  U d dl mZmZmZ d dlZd dlmZ d dlm	Z	 d dl
Z
d dlZd dlZd dlmZmZmZmZ d dlm  mZ d dlmZ d dlmZ g dZe Zeeef ed	< e Zeeef ed
< ejejjj gZ!G dd dZ"e" Z#dd Z$dd Z%dd Z&e'dddZ(d'eej e)e)ee)e)f dddZ*dZ+dZ,dZ-dZ.dZ/ed ed d!d"Z0ed ed d#d$Z1G d%d& d&Z2dS )(    )OrderedDictdefaultdictabcN)deepcopy)chain)CallableDictListTuple)RemovableHandle)is_compiling)	Optimizer register_optimizer_step_pre_hook!register_optimizer_step_post_hook_global_optimizer_pre_hooks_global_optimizer_post_hooksc                   @   s   e Zd ZdZdd ZdS )_RequiredParameterzCSingleton class representing a required parameter for an Optimizer.c                 C   s   dS )Nz<required parameter> selfr   r   ^/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/torch/optim/optimizer.py__repr__   s    z_RequiredParameter.__repr__N)__name__
__module____qualname____doc__r   r   r   r   r   r      s   r   c                    s    fdd}|S )Nc              	      sN   t  }z4t | jd   | g|R i |}W t | nt | 0 |S )Ndifferentiable)torchZis_grad_enabledZset_grad_enableddefaults)r   argskwargsZ	prev_gradretfuncr   r   	_use_grad   s    z/_use_grad_for_differentiable.<locals>._use_gradr   )r#   r$   r   r"   r   _use_grad_for_differentiable   s    r%   c                 C   s    t j st r| S |  S d S N)r   jitis_scriptingr   itemxr   r   r   
_get_value'   s    r,   c                 C   s"   t j st rt | S | S d S r&   )r   r'   r(   r   stackr*   r   r   r   _stack_if_compiling.   s    
r.   r*   c                 C   s,   t j st| t jr|  S t| S d S r&   )r   r'   r(   
isinstanceTensorsqrtmathr*   r   r   r   _dispatch_sqrt4   s    r3   F)paramsr   	use_fusedreturnc                 C   sH   t j s|rdS |o&tdd | D }| o>tdd | D }||fS )N)FFc                 s   s2   | ]*}|d u p(t |tv o(|jo(t|V  qd S r&   )type_foreach_supported_typesis_cudar   is_floating_point.0pr   r   r   	<genexpr>E   s   z/_default_to_fused_or_foreach.<locals>.<genexpr>c                 s   s(   | ] }|d u pt |tv o|jV  qd S r&   )r7   r8   r9   r;   r   r   r   r>   H   s   )r   r'   r(   all)r4   r   r5   Zfusedforeachr   r   r   _default_to_fused_or_foreach@   s    rA   a+  foreach (bool, optional): whether foreach implementation of optimizer
            is used. If unspecified by the user (so foreach is None), we will try to use
            foreach over the for-loop implementation on CUDA, since it is usually
            significantly more performant. (default: None)a(  fused (bool, optional): whether the fused implementation (CUDA only) is used.
            Currently, `torch.float64`, `torch.float32`, `torch.float16`, and `torch.bfloat16`
            are supported. (default: None)

    .. note:: The foreach and fused implementations are typically faster than the for-loop,
              single-tensor implementation. Thus, if the user has not specified BOTH flags
              (i.e., when foreach = fused = None), we will attempt defaulting to the foreach
              implementation when the tensors are all on CUDA. For example, if the user specifies
              True for fused but nothing for foreach, we will run the fused implementation. If
              the user specifies False for foreach but nothing for fused (or False for fused but
              nothing for foreach), we will run the for-loop implementation. If the user specifies
              True for both foreach and fused, we will prioritize fused over foreach, as it is
              typically faster. We attempt to use the fastest, so the hierarchy goes fused ->
              foreach -> for-loop. HOWEVER, since the fused implementation is relatively new,
              we want to give it sufficient bake-in time, so we default to foreach and NOT
              fused when the user has not specified either flag.a   capturable (bool, optional): whether this instance is safe to
            capture in a CUDA graph. Passing True can impair ungraphed performance,
            so if you don't intend to graph capture this instance, leave it False
            (default: False)a]  differentiable (bool, optional): whether autograd should
            occur through the optimizer step in training. Otherwise, the step()
            function runs in a torch.no_grad() context. Setting to True can impair
            performance, so leave it False if you don't intend to run autograd
            through this instance (default: False)zymaximize (bool, optional): maximize the params based on the
            objective, instead of minimizing (default: False).Nhookr6   c                 C   s   t t}| t|j< |S )a  Register a pre hook common to all optimizers. The hook should have the following
    signature::

        hook(optimizer, args, kwargs) -> None or modified args and kwargs

    Args:
        hook (Callable): A user defined hook which is registered on all optimizers.

    Returns:
        :class:`torch.utils.hooks.RemoveableHandle`:
            a handle that can be used to remove the added hook by calling
            ``handle.remove()``
    )hooksr   r   idrD   handler   r   r   r   t   s    

r   c                 C   s   t t}| t|j< |S )a  Register a post hook common to all optimizers. The hook should have the following
    signature::

        hook(optimizer, args, kwargs) -> None

    Args:
        hook (Callable): A user defined hook which is registered on all optimizers.

    Returns:
        :class:`torch.utils.hooks.RemoveableHandle`:
            a handle that can be used to remove the added hook by calling
            ``handle.remove()``
    )rE   r   r   rF   rG   r   r   r   r      s    

r   c                   @   s   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d Zdd Z	e
dd Zdd Zed edddZed edddZdd Zdd Zd%edddZd d! Zd"d# Zd$S )&r   aX  Base class for all optimizers.

    .. warning::
        Parameters need to be specified as collections that have a deterministic
        ordering that is consistent between runs. Examples of objects that don't
        satisfy those properties are sets and iterators over values of dictionaries.

    Args:
        params (iterable): an iterable of :class:`torch.Tensor` s or
            :class:`dict` s. Specifies what Tensors should be optimized.
        defaults: (dict): a dict containing default values of optimization
            options (used when a parameter group doesn't specify them).
    c                 C   s   t jd || _t | _t | _|   t|t j	rHt
dt | tt| _g | _t|}t|dkrttdt|d tsd|ig}|D ]}| | qd| _d S )Nzpython.optimizerzZparams argument given to the optimizer should be an iterable of Tensors or dicts, but got r   z%optimizer got an empty parameter listr4   T)r   Z_CZ_log_api_usage_oncer   r   _optimizer_step_pre_hooks_optimizer_step_post_hooks_patch_step_functionr/   r0   	TypeErrortypenamer   dictstateparam_groupslistlen
ValueErroradd_param_group$_warned_capturable_if_run_uncaptured)r   r4   r   rP   param_groupr   r   r   __init__   s&    

zOptimizer.__init__c                 C   s   | j | j| jdS )Nr   rO   rP   rX   r   r   r   r   __getstate__   s    zOptimizer.__getstate__c                 C   sJ   | j | d| j vrt | _d| j vr0t | _|   | jdd d S )NrI   rJ   r   F)__dict__updater   rI   rJ   rK   r   
setdefault)r   rO   r   r   r   __setstate__   s    

zOptimizer.__setstate__c                 C   sp   | j jd }t| jD ]L\}}|d7 }|d|7 }t| D ] }|dkr@|d||| 7 }q@q|d7 }|S )Nz (
zParameter Group {0}
r4   z    {0}: {1}
))	__class__r   	enumeraterP   formatsortedkeys)r   format_stringigroupkeyr   r   r   r      s    zOptimizer.__repr__c                 C   s~   t jrzt j rzt j }|rFtdd | jD sFtd| jj	 d t
| ddsztdd | jD rz|sztd d	| _d S )
Nc                 s   s   | ]}|d  V  qdS Z
capturableNr   r<   rg   r   r   r   r>          z=Optimizer._cuda_graph_capture_health_check.<locals>.<genexpr>z;Attempting CUDA graph capture of step() for an instance of z' but param_groups' capturable is False.rU   Fc                 s   s   | ]}|d  V  qdS ri   r   rj   r   r   r   r>      rk   a   This instance was constructed with capturable=True or some of all the param_groups came with capturable=True, but step() is running without CUDA graph capture. If you never intend to graph-capture this instance, capturable=True can impair performance, and you should set capturable=False.T)r   Zhas_cudaZcudaZis_availableZis_current_stream_capturingr?   rP   RuntimeErrorr`   r   getattrwarningswarnrU   )r   Z	capturingr   r   r    _cuda_graph_capture_health_check   s$    

z*Optimizer._cuda_graph_capture_health_checkc                 C   s   dS )a  Entry point for `torch.profile.profiler`.

        When python tracing is enabled the profiler will hook into this
        function at the CPython level to inspect the optimizer's parameters and
        param groups. It is called it after `step()` since many optimizers
        lazily initialize state.

        This is a workaround due to lack of a proper step hook on the optimizer,
        and will be removed if it exists.
        Nr   r   r   r   r   _optimizer_step_code   s    zOptimizer._optimizer_step_codec                    s   t   fdd}|S )Nc            	         s   | ^}}d |jj}tjj| tt	 |j
	 D ]L}||| |}|d ur:t|trrt|dkrr|\} }q:t  d| dq: | i |}|  t|j	 t	 D ]}||| | q|W  d    S 1 s0    Y  d S )NzOptimizer.step#{}.step   z? must return None or a tuple of (new_args, new_kwargs),but got .)rb   r`   r   r   autogradprofilerrecord_functionr   r   valuesrI   r/   tuplerR   rl   rq   rJ   r   )	r   r    r   _Zprofile_nameZpre_hookresultoutZ	post_hookr"   r   r   wrapper	  s     
z,Optimizer.profile_hook_step.<locals>.wrapper)	functoolswraps)r#   r|   r   r"   r   profile_hook_step  s    zOptimizer.profile_hook_stepc                 C   sD   d | jj| _t| jjdd }|s@| | jj| j_d| jj_d S )Nz Optimizer.zero_grad#{}.zero_gradhookedT)rb   r`   r   _zero_grad_profile_namerm   stepr   r   )r   r   r   r   r   rK   #  s
    zOptimizer._patch_step_functionrB   rC   c                 C   s   t | j}|| j|j< |S )a  Register an optimizer step pre hook which will be called before
        optimizer step. It should have the following signature::

            hook(optimizer, args, kwargs) -> None or modified args and kwargs

        The ``optimizer`` argument is the optimizer instance being used. If
        args and kwargs are modified by the pre-hook, then the transformed
        values are returned as a tuple containing the new_args and new_kwargs.

        Args:
            hook (Callable): The user defined hook to be registered.

        Returns:
            :class:`torch.utils.hooks.RemoveableHandle`:
                a handle that can be used to remove the added hook by calling
                ``handle.remove()``
        )rE   r   rI   rF   r   rD   rH   r   r   r   register_step_pre_hook*  s    z Optimizer.register_step_pre_hookc                 C   s   t | j}|| j|j< |S )a  Register an optimizer step post hook which will be called after optimizer step.
        It should have the following signature::

            hook(optimizer, args, kwargs) -> None

        The ``optimizer`` argument is the optimizer instance being used.

        Args:
            hook (Callable): The user defined hook to be registered.

        Returns:
            :class:`torch.utils.hooks.RemoveableHandle`:
                a handle that can be used to remove the added hook by calling
                ``handle.remove()``
        )rE   r   rJ   rF   r   r   r   r   register_step_post_hook@  s    z!Optimizer.register_step_post_hookc                    sL   i dfdd  fdd| j D }fdd| j D }||dS )	aK  Returns the state of the optimizer as a :class:`dict`.

        It contains two entries:

        * state - a dict holding current optimization state. Its content
            differs between optimizer classes.
        * param_groups - a list containing all parameter groups where each
            parameter group is a dict
        r   c                    sb   dd |   D }  fddt| d D   fdd| d D |d< t|d 7 |S )Nc                 S   s   i | ]\}}|d kr||qS )r4   r   r<   kvr   r   r   
<dictcomp>d  rk   z<Optimizer.state_dict.<locals>.pack_group.<locals>.<dictcomp>c                    s&   i | ]\}}t | vrt ||qS r   rF   )r<   rf   r=   param_mappingsr   r   r   e  s   r4   c                    s   g | ]} t | qS r   r   r;   r   r   r   
<listcomp>g  rk   z<Optimizer.state_dict.<locals>.pack_group.<locals>.<listcomp>)itemsr[   ra   rR   )rg   packed)r   start_indexr   r   
pack_groupb  s
    "z(Optimizer.state_dict.<locals>.pack_groupc                    s   g | ]} |qS r   r   r<   g)r   r   r   r   j  rk   z(Optimizer.state_dict.<locals>.<listcomp>c                    s.   i | ]&\}}t |tjr$ t| n||qS r   )r/   r   r0   rF   r   r   r   r   r   l  s   z(Optimizer.state_dict.<locals>.<dictcomp>rO   rP   )rP   rO   r   )r   rP   Zpacked_stater   )r   r   r   r   
state_dictT  s    
zOptimizer.state_dictc                    s&  t |}| j}|d }t|t|kr.tddd |D }dd |D }tdd t||D rjtddd	 ttd
d |D tdd |D D }d fdd	 tt	}|d 
 D ]0\}}	||v r|| }
 |
|	||
< q|	||< qdd fddt||D }| ||d dS )zLoads the optimizer state.

        Args:
            state_dict (dict): optimizer state. Should be an object returned
                from a call to :meth:`state_dict`.
        rP   z<loaded state dict has a different number of parameter groupsc                 s   s   | ]}t |d  V  qdS r4   NrR   r   r   r   r   r>     rk   z,Optimizer.load_state_dict.<locals>.<genexpr>c                 s   s   | ]}t |d  V  qdS r   r   r   r   r   r   r>     rk   c                 s   s   | ]\}}||kV  qd S r&   r   )r<   Zp_lenZs_lenr   r   r   r>     rk   z]loaded state dict contains a parameter group that doesn't match the size of optimizer's groupc                 S   s   i | ]\}}||qS r   r   )r<   Zold_idr=   r   r   r   r     rk   z-Optimizer.load_state_dict.<locals>.<dictcomp>c                 s   s   | ]}|d  V  qdS r   r   r   r   r   r   r>     rk   c                 s   s   | ]}|d  V  qdS r   r   r   r   r   r   r>     rk   Nc                    s   t |tjr8|dkr4  r(| j}| j}|S t |trZ fdd| D S t |t	j
rt| fdd|D S |S dS )zBMake a deep copy of value, casting all tensors to device of param.r   c                    s    i | ]\}}| ||d qS ))rh   r   r   castparamr   r   r     rk   z;Optimizer.load_state_dict.<locals>.cast.<locals>.<dictcomp>c                 3   s   | ]} |V  qd S r&   r   )r<   r   r   r   r   r>     rk   z:Optimizer.load_state_dict.<locals>.cast.<locals>.<genexpr>N)r/   r   r0   r:   todtypedevicerN   r   container_abcsIterabler7   )r   valuerh   )r   )r   r   r     s    
z'Optimizer.load_state_dict.<locals>.castrO   c                 S   s   | d |d< |S )Nr4   r   )rg   Z	new_groupr   r   r   update_group  s    z/Optimizer.load_state_dict.<locals>.update_groupc                    s   g | ]\}} ||qS r   r   )r<   r   Zng)r   r   r   r     s   z-Optimizer.load_state_dict.<locals>.<listcomp>r   )N)r   rP   rR   rS   anyzipr   from_iterabler   rN   r   r]   )r   r   groupsZsaved_groupsZ
param_lensZ
saved_lensZid_maprO   r   r   r   rP   r   )r   r   r   load_state_dicts  s4    

zOptimizer.load_state_dictT)set_to_nonec           	      C   s  | j dd}t| ds |   |r0tdd }tjj| j	 | j
D ]}|d D ]r}|jdurT|rnd|_qT|jjdur|j  n|jd |r|jjr|j  qT||jj |jj |j qTqH|r| D ] \}}| D ]}t| qqW d   n1 s0    Y  dS )a  Sets the gradients of all optimized :class:`torch.Tensor` s to zero.

        Args:
            set_to_none (bool): instead of setting to zero, set the grads to None.
                This will in general have lower memory footprint, and can modestly improve performance.
                However, it changes certain behaviors. For example:
                1. When the user tries to access a gradient and perform manual ops on it,
                a None attribute or a Tensor full of 0s will behave differently.
                2. If the user requests ``zero_grad(set_to_none=True)`` followed by a backward pass, ``.grad``\ s
                are guaranteed to be None for params that did not receive a gradient.
                3. ``torch.optim`` optimizers have a different behavior if the gradient is 0 or None
                (in one case it does the step with a gradient of 0 and in the other it skips
                the step altogether).
        r@   Fr   c                   S   s   t tS r&   )r   rQ   r   r   r   r   <lambda>  rk   z%Optimizer.zero_grad.<locals>.<lambda>r4   N)r   gethasattrrK   r   r   rt   ru   rv   r   rP   ZgradZgrad_fnZdetach_Zrequires_grad_Z	is_sparseZzero_r   r   appendr   rw   Z_foreach_zero_)	r   r   r@   Zper_device_and_dtype_gradsrg   r=   ry   Zper_dtype_gradsZgradsr   r   r   	zero_grad  s*    


 zOptimizer.zero_gradc                 C   s   t dS )af  Performs a single optimization step (parameter update).

        Args:
            closure (Callable): A closure that reevaluates the model and
                returns the loss. Optional for most optimizers.

        .. note::
            Unless otherwise specified, this function should not modify the
            ``.grad`` field of the parameters.
        N)NotImplementedError)r   closurer   r   r   r     s    zOptimizer.stepc                 C   s\  t |tsJ d|d }t |tjr2|g|d< n t |trFtdnt||d< |d D ]D}t |tjs|tdt| | j	ddsZ|j
sZ|jsZtdqZ| j D ]2\}}|tu r||vrtd| q||| q|d }t|tt|kr
tjd	d
d t }| jD ]}|t|d  q|t|d sLtd| j| dS )a  Add a param group to the :class:`Optimizer` s `param_groups`.

        This can be useful when fine tuning a pre-trained network as frozen layers can be made
        trainable and added to the :class:`Optimizer` as training progresses.

        Args:
            param_group (dict): Specifies what Tensors should be optimized along with group
                specific optimization options.
        zparam group must be a dictr4   zoptimizer parameters need to be organized in ordered collections, but the ordering of tensors in sets will change between runs. Please use a list instead.z>optimizer can only optimize Tensors, but one of the params is r   Nz can't optimize a non-leaf TensorzJparameter group didn't specify a value of required optimization parameter zoptimizer contains a parameter group with duplicate parameters; in future, this will cause an error; see github.com/pytorch/pytorch/issues/40967 for more information   )
stacklevelz7some parameters appear in more than one parameter group)r/   rN   r   r0   setrL   rQ   rM   r   r   Zis_leafZretains_gradrS   r   requiredr\   rR   rn   ro   rP   r[   
isdisjointr   )r   rV   r4   r   namedefaultZ	param_setrg   r   r   r   rT     s>    




zOptimizer.add_param_groupN)T)r   r   r   r   rW   rY   r]   r   rp   rq   staticmethodr   rK   r   r   r   r   r   r   boolr   r   rT   r   r   r   r   r      s"   	
@)r   )F)3collectionsr   r   r   r   r   copyr   	itertoolsr   rn   r}   r2   typingr   r   r	   r
   Ztorch.utils.hooksutilsrE   r   Ztorch._utilsr   __all__r   int__annotations__r   r0   nnZ	parameter	Parameterr8   r   r   r%   r,   r.   floatr3   r   rA   Z_foreach_docZ
_fused_docZ_capturable_docZ_differentiable_docZ_maximize_docr   r   r   r   r   r   r   <module>   sB    
