a
    Ž¥»aÓ  ã                   @   s8   d dl Z ddlmZ ddlmZmZ G dd„ deƒZdS )é    Né   )Ú_functional)Ú	OptimizerÚrequiredc                       sJ   e Zd ZdZeddddf‡ fdd„	Z‡ fdd„Ze ¡ dd	d
„ƒZ	‡  Z
S )ÚSGDa  Implements stochastic gradient descent (optionally with momentum).

    .. math::
       \begin{aligned}
            &\rule{110mm}{0.4pt}                                                                 \\
            &\textbf{input}      : \gamma \text{ (lr)}, \: \theta_0 \text{ (params)}, \: f(\theta)
                \text{ (objective)}, \: \lambda \text{ (weight decay)},                          \\
            &\hspace{13mm} \:\mu \text{ (momentum)}, \:\tau \text{ (dampening)},\:nesterov\\[-1.ex]
            &\rule{110mm}{0.4pt}                                                                 \\
            &\textbf{for} \: t=1 \: \textbf{to} \: \ldots \: \textbf{do}                         \\
            &\hspace{5mm}g_t           \leftarrow   \nabla_{\theta} f_t (\theta_{t-1})           \\
            &\hspace{5mm}\textbf{if} \: \lambda \neq 0                                           \\
            &\hspace{10mm} g_t \leftarrow g_t + \lambda  \theta_{t-1}                            \\
            &\hspace{5mm}\textbf{if} \: \mu \neq 0                                               \\
            &\hspace{10mm}\textbf{if} \: t > 1                                                   \\
            &\hspace{15mm} \textbf{b}_t \leftarrow \mu \textbf{b}_{t-1} + (1-\tau) g_t           \\
            &\hspace{10mm}\textbf{else}                                                          \\
            &\hspace{15mm} \textbf{b}_t \leftarrow g_t                                           \\
            &\hspace{10mm}\textbf{if} \: nesterov                                                \\
            &\hspace{15mm} g_t \leftarrow g_{t-1} + \mu \textbf{b}_t                             \\
            &\hspace{10mm}\textbf{else}                                                   \\[-1.ex]
            &\hspace{15mm} g_t  \leftarrow  \textbf{b}_t                                         \\
            &\hspace{5mm}\theta_t \leftarrow \theta_{t-1} - \gamma g_t                    \\[-1.ex]
            &\rule{110mm}{0.4pt}                                                          \\[-1.ex]
            &\bf{return} \:  \theta_t                                                     \\[-1.ex]
            &\rule{110mm}{0.4pt}                                                          \\[-1.ex]
       \end{aligned}

    Nesterov momentum is based on the formula from
    `On the importance of initialization and momentum in deep learning`__.

    Args:
        params (iterable): iterable of parameters to optimize or dicts defining
            parameter groups
        lr (float): learning rate
        momentum (float, optional): momentum factor (default: 0)
        weight_decay (float, optional): weight decay (L2 penalty) (default: 0)
        dampening (float, optional): dampening for momentum (default: 0)
        nesterov (bool, optional): enables Nesterov momentum (default: False)

    Example:
        >>> optimizer = torch.optim.SGD(model.parameters(), lr=0.1, momentum=0.9)
        >>> optimizer.zero_grad()
        >>> loss_fn(model(input), target).backward()
        >>> optimizer.step()

    __ http://www.cs.toronto.edu/%7Ehinton/absps/momentum.pdf

    .. note::
        The implementation of SGD with Momentum/Nesterov subtly differs from
        Sutskever et. al. and implementations in some other frameworks.

        Considering the specific case of Momentum, the update can be written as

        .. math::
            \begin{aligned}
                v_{t+1} & = \mu * v_{t} + g_{t+1}, \\
                p_{t+1} & = p_{t} - \text{lr} * v_{t+1},
            \end{aligned}

        where :math:`p`, :math:`g`, :math:`v` and :math:`\mu` denote the
        parameters, gradient, velocity, and momentum respectively.

        This is in contrast to Sutskever et. al. and
        other frameworks which employ an update of the form

        .. math::
            \begin{aligned}
                v_{t+1} & = \mu * v_{t} + \text{lr} * g_{t+1}, \\
                p_{t+1} & = p_{t} - v_{t+1}.
            \end{aligned}

        The Nesterov version is analogously modified.
    r   Fc                    sŽ   |t ur|dk rtd |¡ƒ‚|dk r4td |¡ƒ‚|dk rJtd |¡ƒ‚t|||||d�}|rx|dksp|dkrxtdƒ‚tt| ƒ ||¡ d S )Ng        zInvalid learning rate: {}zInvalid momentum value: {}zInvalid weight_decay value: {})ÚlrÚmomentumÚ	dampeningÚweight_decayÚnesterovr   z8Nesterov momentum requires a momentum and zero dampening)r   Ú
ValueErrorÚformatÚdictÚsuperr   Ú__init__)ÚselfÚparamsr   r   r	   r
   r   Údefaults©Ú	__class__© úI/home/yuhw/wc/pochoir/venv/lib/python3.9/site-packages/torch/optim/sgd.pyr   R   s    ÿzSGD.__init__c                    s,   t t| ƒ |¡ | jD ]}| dd¡ qd S )Nr   F)r   r   Ú__setstate__Úparam_groupsÚ
setdefault)r   ÚstateÚgroupr   r   r   r   a   s    
zSGD.__setstate__Nc                 C   s  d}|dur:t  ¡ � |ƒ }W d  ƒ n1 s00    Y  | jD ]Ò}g }g }g }|d }|d }|d }	|d }
|d }|d D ]P}|jdur€| |¡ | |j¡ | j| }d|vrÂ| d¡ q€| |d ¡ q€tj|||||||	|
d	� t||ƒD ]\}}| j| }||d< qöq@|S )
z±Performs a single optimization step.

        Args:
            closure (callable, optional): A closure that reevaluates the model
                and returns the loss.
        Nr
   r   r	   r   r   r   Úmomentum_buffer)r
   r   r   r	   r   )	ÚtorchZenable_gradr   ZgradÚappendr   ÚFZsgdÚzip)r   ÚclosureZlossr   Zparams_with_gradZd_p_listZmomentum_buffer_listr
   r   r	   r   r   Úpr   r   r   r   r   Ústepf   sD    
$



ù

zSGD.step)N)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r   r   r   Zno_gradr$   Ú__classcell__r   r   r   r   r      s   Kÿr   )r   Ú r   r    Z	optimizerr   r   r   r   r   r   r   Ú<module>   s   