Ë
    S²jØ   ã                   óX  — d dl mZ d dlZd dl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 g d
¢Z G d„ de«      Z G d„ de«      Z G d„ dee«      Z G d„ de«      Z G d„ dee«      Z G d„ de«      Z G d„ dee«      Z G d„ de«      Z G d„ dee«      Z G d„ de«      Zy)é    )ÚAnyN)ÚTensor)Ú
functionalÚinit)Ú	ParameterÚUninitializedBufferÚUninitializedParameteré   )ÚSyncBatchNorm)ÚLazyModuleMixin)ÚModule)ÚBatchNorm1dÚLazyBatchNorm1dÚBatchNorm2dÚLazyBatchNorm2dÚBatchNorm3dÚLazyBatchNorm3dr   c                   óÌ   ‡ — e Zd ZU dZdZg d¢Zeed<   eed<   edz  ed<   e	ed<   e	ed	<   	 	 	 	 	 	 dd
dœdedededz  de	d	e	de	ddfˆ fd„Z
dd„Zdd„Zd„ Zd„ Z	 	 dˆ fd„Zˆ xZS )Ú	_NormBasez,Common base of _InstanceNorm and _BatchNorm.é   )Útrack_running_statsÚmomentumÚepsÚnum_featuresÚaffiner   r   Nr   r   r   T©Úbiasr   Úreturnc                ó   •— ||dœ}	t         ‰| �  «        || _        || _        || _        || _        || _        | j
                  r^t        t        j                  |fi |	¤Ž«      | _
        |r%t        t        j                  |fi |	¤Ž«      | _        n7| j                  dd «       n$| j                  dd «       | j                  dd «       | j                  r±| j                  dt        j                  |fi |	¤Ž«       | j                  dt        j                  |fi |	¤Ž«       |  |  | j                  dt        j                   	 ddt        j"                  i|	j%                  «       D �
�ci c]  \  }
}|
dk7  sŒ|
|“Œ c}}
¤Ž«       |  n6| j                  dd «       | j                  dd «       | j                  dd «       | j'                  «        y c c}}
w )	N©ÚdeviceÚdtyper   ÚweightÚrunning_meanÚrunning_varÚnum_batches_trackedr"   ©r   )ÚsuperÚ__init__r   r   r   r   r   r   ÚtorchÚemptyr#   r   Úregister_parameterÚregister_bufferÚzerosÚonesÚtensorÚlongÚitemsÚreset_parameters)Úselfr   r   r   r   r   r!   r"   r   Úfactory_kwargsÚkÚvÚ	__class__s               €úY/var/www/html/ia-enhanced/venv/lib/python3.12/site-packages/torch/nn/modules/batchnorm.pyr)   z_NormBase.__init__&   s¢  ø€ ð %+°UÑ;ˆÜ‰ÑÔØ(ˆÔØˆŒØ ˆŒØˆŒØ#6ˆÔ Ø�;Š;Ü#¤E§K¡K°Ñ$OÀÑ$OÓPˆDŒKÙÜ%¤e§k¡k°,Ñ&QÀ.Ñ&QÓR�•	à×'Ñ'¨°Õ5à×#Ñ# H¨dÔ3Ø×#Ñ# F¨DÔ1Ø×#Ò#Ø× Ñ Ø¤§¡¨LÑ K¸NÑ Kôð × Ñ ØœuŸz™z¨,ÑI¸.ÑIôñ ÙØ× Ñ Ø%Ü—‘ØñäŸ*™*ðð )7×(<Ñ(<Ó(>×O¡  1À!ÀwÃ,�q˜!‘tÓOñ	ôò à× Ñ  °Ô6Ø× Ñ  °Ô5Ø× Ñ Ð!6¸Ô=Ø×ÑÕùó Ps   Å#G
Å1G
c                 ó¼   — | j                   rP| j                  j                  «        | j                  j	                  d«       | j
                  j                  «        y y )Nr
   )r   r$   Úzero_r%   Úfill_r&   ©r4   s    r9   Úreset_running_statsz_NormBase.reset_running_stats[   sJ   € Ø×#Ò#ð ×Ñ×#Ñ#Ô%Ø×Ñ×"Ñ" 1Ô%Ø×$Ñ$×*Ñ*Õ,ð $ó    c                 óÔ   — | j                  «        | j                  rLt        j                  | j                  «       | j
                  � t        j                  | j
                  «       y y y ©N)r>   r   r   Úones_r#   r   Úzeros_r=   s    r9   r3   z_NormBase.reset_parametersc   sI   € Ø× Ñ Ô"Ø�;Š;Ü�J‰J�t—{‘{Ô#Ø�y‰yÐ$Ü—‘˜DŸI™IÕ&ð %ð r?   c                 ó   — t         ‚rA   )ÚNotImplementedError©r4   Úinputs     r9   Ú_check_input_dimz_NormBase._check_input_dimj   s   € Ü!Ð!r?   c                 óZ   —  dj                   di | j                  ¤d| j                  d ui¤ŽS )Nz{{num_features}, eps={eps}, momentum={momentum}, affine={affine}, bias={use_bias}, track_running_stats={track_running_stats}Úuse_bias© )ÚformatÚ__dict__r   r=   s    r9   Ú
extra_reprz_NormBase.extra_reprm   s:   € ðPð IßIOÉñà—-‘-ñà*.¯)©)¸4Ð*?òð	
r?   c           	      ód  •— |j                  dd «      }|�|dk  r�| j                  ru|dz   }	|	|vrl| j                  �8| j                  j                  t	        j                  d«      k7  r| j                  n$t	        j
                  dt        j                  ¬«      ||	<   t        ‰
| �!  |||||||«       y )NÚversionr   r&   Úmetar   )r"   )	Úgetr   r&   r!   r*   r0   r1   r(   Ú_load_from_state_dict)r4   Ú
state_dictÚprefixÚlocal_metadataÚstrictÚmissing_keysÚunexpected_keysÚ
error_msgsrP   Únum_batches_tracked_keyr8   s             €r9   rS   z_NormBase._load_from_state_dictu   s¹   ø€ ð !×$Ñ$ Y°Ó5ˆàˆO˜w¨š{°×0HÒ0Hð '-Ð/DÑ&DÐ#Ø&¨jÑ8ð ×/Ñ/Ð;Ø×0Ñ0×7Ñ7¼5¿<¹<ÈÓ;OÒOð ×,Ò,ô Ÿ™ a¬u¯z©zÔ:ð	 Ð2Ñ3ô 	‰Ñ%ØØØØØØØõ	
r?   ©çñhãˆµøä>çš™™™™™¹?TTNN©r   N)Ú__name__Ú
__module__Ú__qualname__Ú__doc__Ú_versionÚ__constants__ÚintÚ__annotations__ÚfloatÚboolr)   r>   r3   rH   rN   rS   Ú__classcell__©r8   s   @r9   r   r      sÄ   ø… Ù6à€HÚX€MØÓØ	ƒJØ�d‰lÓØƒLØÓð Ø!$ØØ$(ØØð3 ð ò3 àð3 ð ð3 ð ˜$‘,ð	3 ð
 ð3 ð "ð3 ð ð3 ð 
õ3 ój-ó'ò"ò
ð 
ð 
÷ 
ñ  
r?   r   c                   óf   ‡ — e Zd Z	 	 	 	 	 	 dddœdedededz  deded	ed
dfˆ fd„Zded
efd„Zˆ xZ	S )Ú
_BatchNormTNr   r   r   r   r   r   r   r   c                ó@   •— ||dœ}	t        ‰
| �  |||||fi |	¤d|i¤Ž y ©Nr    r   )r(   r)   )r4   r   r   r   r   r   r!   r"   r   r5   r8   s             €r9   r)   z_BatchNorm.__init__™   s?   ø€ ð %+°UÑ;ˆÜ‰ÑØØØØØñ	
ð ñ	
ð ô	
r?   rG   c           
      óœ  — | j                  |«       | j                  €d}n| j                  }| j                  rd| j                  rX| j                  �L| j                  j                  d«       | j                  €dt        | j                  «      z  }n| j                  }	 | j                  rd}n| j                  d u xr | j                  d u }	 t        j                  || j                  r| j                  r| j                  nd | j                  r| j                  r| j                  nd | j                  | j                  ||| j                  «      S )Nç        r
   ç      ð?T)rH   r   Útrainingr   r&   Úadd_rh   r$   r%   ÚFÚ
batch_normr#   r   r   )r4   rG   Úexponential_average_factorÚbn_trainings       r9   Úforwardz_BatchNorm.forward°   s'  € Ø×Ñ˜eÔ$ð
 �=‰=Ð Ø),Ñ&à)-¯©Ð&à�=Š=˜T×5Ò5à×'Ñ'Ð3Ø×(Ñ(×-Ñ-¨aÔ0Ø—=‘=Ð(Ø14´u¸T×=UÑ=UÓ7VÑ1VÑ.à15·±Ð.ð	ð �=Š=Ø‰Kà×,Ñ,°Ð4ÒT¸4×;KÑ;KÈtÐ;SˆKð	ô
 �|‰|Øð —}’}¨×(@Ò(@ð ×!Ò!àà$(§M¢M°T×5MÒ5MˆD×ÒÐSWØ�K‰KØ�I‰IØØ&Ø�H‰Hó
ð 	
r?   r\   )
r`   ra   rb   rf   rh   ri   r)   r   ry   rj   rk   s   @r9   rm   rm   ˜   s�   ø„ ð Ø!$ØØ$(ØØð
ð ò
àð
ð ð
ð ˜$‘,ð	
ð
 ð
ð "ð
ð ð
ð 
õ
ð.0
˜Vð 0
¨÷ 0
r?   rm   c                   ó`   ‡ — e Zd ZU eed<   eed<   	 	 	 	 	 	 dddœ	 d	ˆ fd„Zd	ˆ fd„Zd	d„Zˆ xZS )
Ú_LazyNormBaser#   r   Tr   c          
      óÄ  •— ||dœ}t        ‰| �  d||ddfi |¤ddi¤Ž || _        || _        | j                  r"t	        di |¤Ž| _        |rt	        di |¤Ž| _        | j                  rtt        di |¤Ž| _        t        di |¤Ž| _	        t        j                  	 ddt        j                  i|j                  «       D �	�
ci c]  \  }	}
|	dk7  sŒ|	|
“Œ c}
}	¤Ž| _        y y c c}
}	w )Nr    r   Fr   r"   rK   r'   )r(   r)   r   r   r	   r#   r   r   r$   r%   r*   r0   r1   r2   r&   )r4   r   r   r   r   r!   r"   r   r5   r6   r7   r8   s              €r9   r)   z_LazyNormBase.__init__ç   sú   ø€ ð %+°UÑ;ˆä‰Ñð ØØØØñ
	
ð ñ
	
ð ó
	
ð ˆŒØ#6ˆÔ Ø�;Š;ä0ÑB°>ÑBˆDŒKÙä2ÑD°^ÑD�”	Ø×#Ò#ä 3Ñ E°nÑ EˆDÔä2ÑD°^ÑDˆDÔÜ',§|¡|Øñ(ä—j‘jð(ð %3×$8Ñ$8Ó$:×K™D˜A˜q¸aÀ7»l�1�a‘4ÓKñ	(ˆDÕ$ð $ùó Ls   Â<CÃ
Cc                 ód   •— | j                  «       s| j                  dk7  rt        ‰| �  «        y y y )Nr   )Úhas_uninitialized_paramsr   r(   r3   )r4   r8   s    €r9   r3   z_LazyNormBase.reset_parameters  s0   ø€ à×,Ñ,Ô.°4×3DÑ3DÈÒ3IÜ‰GÑ$Õ&ð 4JÐ.r?   c                 ó|  — | j                  «       �r+|j                  d   | _        | j                  r¢t	        | j
                  t        «      st        d«      ‚| j
                  j                  | j                  f«       | j                  �Kt	        | j                  t        «      st        d«      ‚| j                  j                  | j                  f«       | j                  rL| j                  j                  | j                  f«       | j                  j                  | j                  f«       | j                  «        y y )Nr
   z-self.weight must be an UninitializedParameterz+self.bias must be an UninitializedParameter)r~   Úshaper   r   Ú
isinstancer#   r	   ÚAssertionErrorÚmaterializer   r   r$   r%   r3   rF   s     r9   Úinitialize_parametersz#_LazyNormBase.initialize_parameters  s  € à×(Ñ(Õ*Ø %§¡¨A¡ˆDÔØ�{Š{Ü! $§+¡+Ô/EÔFÜ(ØGóð ð —‘×'Ñ'¨×):Ñ):Ð(<Ô=Ø—9‘9Ð(Ü% d§i¡iÔ1GÔHÜ,ØIóð ð —I‘I×)Ñ)¨4×+<Ñ+<Ð*>Ô?Ø×'Ò'Ø×!Ñ!×-Ñ-Ø×&Ñ&Ð(ôð × Ñ ×,Ñ,Ø×&Ñ&Ð(ôð ×!Ñ!Õ#ð+ +r?   r\   r_   )	r`   ra   rb   r	   rg   r)   r3   r„   rj   rk   s   @r9   r{   r{   ã   sG   ø… Ø"Ó"Ø
 Ó ð ØØØ ØØð*ð ñ*ð 
õ*õX'÷
$r?   r{   c                   ó   — e Zd ZdZdd„Zy)r   a‚  Applies Batch Normalization over a 2D or 3D input.

    Method described in the paper
    `Batch Normalization: Accelerating Deep Network Training by Reducing
    Internal Covariate Shift <https://arxiv.org/abs/1502.03167>`__ .

    .. math::

        y = \frac{x - \mathrm{E}[x]}{\sqrt{\mathrm{Var}[x] + \epsilon}} * \gamma + \beta

    The mean and standard-deviation are calculated per-dimension over
    the mini-batches and :math:`\gamma` and :math:`\beta` are learnable parameter vectors
    of size `C` (where `C` is the number of features or channels of the input). By default, the
    elements of :math:`\gamma` are set to 1 and the elements of :math:`\beta` are set to 0.
    At train time in the forward pass, the variance is calculated via the biased estimator,
    equivalent to ``torch.var(input, correction=0)``. However, the value stored in the
    moving average of the variance is calculated via the unbiased  estimator, equivalent to
    ``torch.var(input, correction=1)``.

    Also by default, during training this layer keeps running estimates of its
    computed mean and variance, which are then used for normalization during
    evaluation. The running estimates are kept with a default :attr:`momentum`
    of 0.1.

    If :attr:`track_running_stats` is set to ``False``, this layer then does not
    keep running estimates, and batch statistics are instead used during
    evaluation time as well.

    .. note::
        This :attr:`momentum` argument is different from one used in optimizer
        classes and the conventional notion of momentum. Mathematically, the
        update rule for running statistics here is
        :math:`\hat{x}_\text{new} = (1 - \text{momentum}) \times \hat{x} + \text{momentum} \times x_t`,
        where :math:`\hat{x}` is the estimated statistic and :math:`x_t` is the
        new observed value.

    Because the Batch Normalization is done over the `C` dimension, computing statistics
    on `(N, L)` slices, it's common terminology to call this Temporal Batch Normalization.

    Args:
        num_features: number of features or channels :math:`C` of the input
        eps: a value added to the denominator for numerical stability.
            Default: 1e-5
        momentum: the value used for the running_mean and running_var
            computation. Can be set to ``None`` for cumulative moving average
            (i.e. simple average). Default: 0.1
        affine: a boolean value that when set to ``True``, this module has
            learnable affine parameters. Default: ``True``
        track_running_stats: a boolean value that when set to ``True``, this
            module tracks the running mean and variance, and when set to ``False``,
            this module does not track such statistics, and initializes statistics
            buffers :attr:`running_mean` and :attr:`running_var` as ``None``.
            When these buffers are ``None``, this module always uses batch statistics.
            in both training and eval modes. Default: ``True``
        bias: If set to ``False``, the layer will not learn an additive bias (only relevant if
            :attr:`affine` is ``True``). Default: ``True``

    Shape:
        - Input: :math:`(N, C)` or :math:`(N, C, L)`, where :math:`N` is the batch size,
          :math:`C` is the number of features or channels, and :math:`L` is the sequence length
        - Output: :math:`(N, C)` or :math:`(N, C, L)` (same shape as input)

    Examples::

        >>> # With Learnable Parameters
        >>> m = nn.BatchNorm1d(100)
        >>> # Without Learnable Parameters
        >>> m = nn.BatchNorm1d(100, affine=False)
        >>> input = torch.randn(20, 100)
        >>> output = m(input)
    Nc                 óŒ   — |j                  «       dk7  r1|j                  «       dk7  rt        d|j                  «       › d�«      ‚y y ©Nr   é   zexpected 2D or 3D input (got úD input)©ÚdimÚ
ValueErrorrF   s     r9   rH   zBatchNorm1d._check_input_dim{  ó@   € Ø�9‰9‹;˜!Ò §	¡	£¨qÒ 0ÜÐ<¸U¿Y¹Y»[¸MÈÐRÓSÐSð !1Ðr?   r_   ©r`   ra   rb   rc   rH   rK   r?   r9   r   r   2  s   „ ñFôPTr?   r   c                   ó   — e Zd ZdZeZdd„Zy)r   aì  A :class:`torch.nn.BatchNorm1d` module with lazy initialization.

    Lazy initialization based on the ``num_features`` argument of the :class:`BatchNorm1d` that is inferred
    from the ``input.size(1)``.
    The attributes that will be lazily initialized are `weight`, `bias`,
    `running_mean` and `running_var`.

    Check the :class:`torch.nn.modules.lazy.LazyModuleMixin` for further documentation
    on lazy modules and their limitations.

    Args:
        eps: a value added to the denominator for numerical stability.
            Default: 1e-5
        momentum: the value used for the running_mean and running_var
            computation. Can be set to ``None`` for cumulative moving average
            (i.e. simple average). Default: 0.1
        affine: a boolean value that when set to ``True``, this module has
            learnable affine parameters. Default: ``True``
        track_running_stats: a boolean value that when set to ``True``, this
            module tracks the running mean and variance, and when set to ``False``,
            this module does not track such statistics, and initializes statistics
            buffers :attr:`running_mean` and :attr:`running_var` as ``None``.
            When these buffers are ``None``, this module always uses batch statistics.
            in both training and eval modes. Default: ``True``
        bias: If set to ``False``, the layer will not learn an additive bias (only relevant if
            :attr:`affine` is ``True``). Default: ``True``
    Nc                 óŒ   — |j                  «       dk7  r1|j                  «       dk7  rt        d|j                  «       › d�«      ‚y y r‡   rŠ   rF   s     r9   rH   z LazyBatchNorm1d._check_input_dimŸ  r�   r?   r_   )r`   ra   rb   rc   r   Úcls_to_becomerH   rK   r?   r9   r   r   €  s   „ ñð8  €MôTr?   r   c                   ó   — e Zd ZdZdd„Zy)r   a3  Applies Batch Normalization over a 4D input.

    4D is a mini-batch of 2D inputs
    with additional channel dimension. Method described in the paper
    `Batch Normalization: Accelerating Deep Network Training by Reducing
    Internal Covariate Shift <https://arxiv.org/abs/1502.03167>`__ .

    .. math::

        y = \frac{x - \mathrm{E}[x]}{ \sqrt{\mathrm{Var}[x] + \epsilon}} * \gamma + \beta

    The mean and standard-deviation are calculated per-dimension over
    the mini-batches and :math:`\gamma` and :math:`\beta` are learnable parameter vectors
    of size `C` (where `C` is the input size). By default, the elements of :math:`\gamma` are set
    to 1 and the elements of :math:`\beta` are set to 0. At train time in the forward pass, the
    standard-deviation is calculated via the biased estimator, equivalent to
    ``torch.var(input, correction=0)``. However, the value stored in the moving average of the
    standard-deviation is calculated via the unbiased  estimator, equivalent to
    ``torch.var(input, correction=1)``.

    Also by default, during training this layer keeps running estimates of its
    computed mean and variance, which are then used for normalization during
    evaluation. The running estimates are kept with a default :attr:`momentum`
    of 0.1.

    If :attr:`track_running_stats` is set to ``False``, this layer then does not
    keep running estimates, and batch statistics are instead used during
    evaluation time as well.

    .. note::
        This :attr:`momentum` argument is different from one used in optimizer
        classes and the conventional notion of momentum. Mathematically, the
        update rule for running statistics here is
        :math:`\hat{x}_\text{new} = (1 - \text{momentum}) \times \hat{x} + \text{momentum} \times x_t`,
        where :math:`\hat{x}` is the estimated statistic and :math:`x_t` is the
        new observed value.

    Because the Batch Normalization is done over the `C` dimension, computing statistics
    on `(N, H, W)` slices, it's common terminology to call this Spatial Batch Normalization.

    Args:
        num_features: :math:`C` from an expected input of size
            :math:`(N, C, H, W)`
        eps: a value added to the denominator for numerical stability.
            Default: 1e-5
        momentum: the value used for the running_mean and running_var
            computation. Can be set to ``None`` for cumulative moving average
            (i.e. simple average). Default: 0.1
        affine: a boolean value that when set to ``True``, this module has
            learnable affine parameters. Default: ``True``
        track_running_stats: a boolean value that when set to ``True``, this
            module tracks the running mean and variance, and when set to ``False``,
            this module does not track such statistics, and initializes statistics
            buffers :attr:`running_mean` and :attr:`running_var` as ``None``.
            When these buffers are ``None``, this module always uses batch statistics.
            in both training and eval modes. Default: ``True``
        bias: If set to ``False``, the layer will not learn an additive bias (only relevant if
            :attr:`affine` is ``True``). Default: ``True``

    Shape:
        - Input: :math:`(N, C, H, W)`
        - Output: :math:`(N, C, H, W)` (same shape as input)

    Examples::

        >>> # With Learnable Parameters
        >>> m = nn.BatchNorm2d(100)
        >>> # Without Learnable Parameters
        >>> m = nn.BatchNorm2d(100, affine=False)
        >>> input = torch.randn(20, 100, 35, 45)
        >>> output = m(input)
    Nc                 ód   — |j                  «       dk7  rt        d|j                  «       › d�«      ‚y ©Né   zexpected 4D input (got r‰   rŠ   rF   s     r9   rH   zBatchNorm2d._check_input_dimî  ó0   € Ø�9‰9‹;˜!ÒÜÐ6°u·y±y³{°mÀ8ÐLÓMÐMð r?   r_   rŽ   rK   r?   r9   r   r   ¤  ó   „ ñGôRNr?   r   c                   ó   — e Zd ZdZeZdd„Zy)r   aï  A :class:`torch.nn.BatchNorm2d` module with lazy initialization.

    Lazy initialization is done for the ``num_features`` argument of the :class:`BatchNorm2d` that is inferred
    from the ``input.size(1)``.
    The attributes that will be lazily initialized are `weight`, `bias`,
    `running_mean` and `running_var`.

    Check the :class:`torch.nn.modules.lazy.LazyModuleMixin` for further documentation
    on lazy modules and their limitations.

    Args:
        eps: a value added to the denominator for numerical stability.
            Default: 1e-5
        momentum: the value used for the running_mean and running_var
            computation. Can be set to ``None`` for cumulative moving average
            (i.e. simple average). Default: 0.1
        affine: a boolean value that when set to ``True``, this module has
            learnable affine parameters. Default: ``True``
        track_running_stats: a boolean value that when set to ``True``, this
            module tracks the running mean and variance, and when set to ``False``,
            this module does not track such statistics, and initializes statistics
            buffers :attr:`running_mean` and :attr:`running_var` as ``None``.
            When these buffers are ``None``, this module always uses batch statistics.
            in both training and eval modes. Default: ``True``
        bias: If set to ``False``, the layer will not learn an additive bias (only relevant if
            :attr:`affine` is ``True``). Default: ``True``
    Nc                 ód   — |j                  «       dk7  rt        d|j                  «       › d�«      ‚y r”   rŠ   rF   s     r9   rH   z LazyBatchNorm2d._check_input_dim  r–   r?   r_   )r`   ra   rb   rc   r   r‘   rH   rK   r?   r9   r   r   ó  ó   „ ñð8  €MôNr?   r   c                   ó   — e Zd ZdZdd„Zy)r   ah  Applies Batch Normalization over a 5D input.

    5D is a mini-batch of 3D inputs with additional channel dimension as described in the paper
    `Batch Normalization: Accelerating Deep Network Training by Reducing
    Internal Covariate Shift <https://arxiv.org/abs/1502.03167>`__ .

    .. math::

        y = \frac{x - \mathrm{E}[x]}{ \sqrt{\mathrm{Var}[x] + \epsilon}} * \gamma + \beta

    The mean and standard-deviation are calculated per-dimension over
    the mini-batches and :math:`\gamma` and :math:`\beta` are learnable parameter vectors
    of size `C` (where `C` is the input size). By default, the elements of :math:`\gamma` are set
    to 1 and the elements of :math:`\beta` are set to 0. At train time in the forward pass, the
    standard-deviation is calculated via the biased estimator, equivalent to
    ``torch.var(input, correction=0)``. However, the value stored in the moving average of the
    standard-deviation is calculated via the unbiased  estimator, equivalent to
    ``torch.var(input, correction=1)``.

    Also by default, during training this layer keeps running estimates of its
    computed mean and variance, which are then used for normalization during
    evaluation. The running estimates are kept with a default :attr:`momentum`
    of 0.1.

    If :attr:`track_running_stats` is set to ``False``, this layer then does not
    keep running estimates, and batch statistics are instead used during
    evaluation time as well.

    .. note::
        This :attr:`momentum` argument is different from one used in optimizer
        classes and the conventional notion of momentum. Mathematically, the
        update rule for running statistics here is
        :math:`\hat{x}_\text{new} = (1 - \text{momentum}) \times \hat{x} + \text{momentum} \times x_t`,
        where :math:`\hat{x}` is the estimated statistic and :math:`x_t` is the
        new observed value.

    Because the Batch Normalization is done over the `C` dimension, computing statistics
    on `(N, D, H, W)` slices, it's common terminology to call this Volumetric Batch Normalization
    or Spatio-temporal Batch Normalization.

    Args:
        num_features: :math:`C` from an expected input of size
            :math:`(N, C, D, H, W)`
        eps: a value added to the denominator for numerical stability.
            Default: 1e-5
        momentum: the value used for the running_mean and running_var
            computation. Can be set to ``None`` for cumulative moving average
            (i.e. simple average). Default: 0.1
        affine: a boolean value that when set to ``True``, this module has
            learnable affine parameters. Default: ``True``
        track_running_stats: a boolean value that when set to ``True``, this
            module tracks the running mean and variance, and when set to ``False``,
            this module does not track such statistics, and initializes statistics
            buffers :attr:`running_mean` and :attr:`running_var` as ``None``.
            When these buffers are ``None``, this module always uses batch statistics.
            in both training and eval modes. Default: ``True``
        bias: If set to ``False``, the layer will not learn an additive bias (only relevant if
            :attr:`affine` is ``True``). Default: ``True``

    Shape:
        - Input: :math:`(N, C, D, H, W)`
        - Output: :math:`(N, C, D, H, W)` (same shape as input)

    Examples::

        >>> # With Learnable Parameters
        >>> m = nn.BatchNorm3d(100)
        >>> # Without Learnable Parameters
        >>> m = nn.BatchNorm3d(100, affine=False)
        >>> input = torch.randn(20, 100, 35, 45, 10)
        >>> output = m(input)
    Nc                 ód   — |j                  «       dk7  rt        d|j                  «       › d�«      ‚y ©Né   zexpected 5D input (got r‰   rŠ   rF   s     r9   rH   zBatchNorm3d._check_input_dima  r–   r?   r_   rŽ   rK   r?   r9   r   r     r—   r?   r   c                   ó   — e Zd ZdZeZdd„Zy)r   aï  A :class:`torch.nn.BatchNorm3d` module with lazy initialization.

    Lazy initialization is done for the ``num_features`` argument of the :class:`BatchNorm3d` that is inferred
    from the ``input.size(1)``.
    The attributes that will be lazily initialized are `weight`, `bias`,
    `running_mean` and `running_var`.

    Check the :class:`torch.nn.modules.lazy.LazyModuleMixin` for further documentation
    on lazy modules and their limitations.

    Args:
        eps: a value added to the denominator for numerical stability.
            Default: 1e-5
        momentum: the value used for the running_mean and running_var
            computation. Can be set to ``None`` for cumulative moving average
            (i.e. simple average). Default: 0.1
        affine: a boolean value that when set to ``True``, this module has
            learnable affine parameters. Default: ``True``
        track_running_stats: a boolean value that when set to ``True``, this
            module tracks the running mean and variance, and when set to ``False``,
            this module does not track such statistics, and initializes statistics
            buffers :attr:`running_mean` and :attr:`running_var` as ``None``.
            When these buffers are ``None``, this module always uses batch statistics.
            in both training and eval modes. Default: ``True``
        bias: If set to ``False``, the layer will not learn an additive bias (only relevant if
            :attr:`affine` is ``True``). Default: ``True``
    Nc                 ód   — |j                  «       dk7  rt        d|j                  «       › d�«      ‚y r�   rŠ   rF   s     r9   rH   z LazyBatchNorm3d._check_input_dim…  r–   r?   r_   )r`   ra   rb   rc   r   r‘   rH   rK   r?   r9   r   r   f  rš   r?   r   c                   ó˜   ‡ — e Zd ZdZ	 	 	 	 	 	 	 dddœdedededz  ded	ed
edz  deddfˆ fd„Zdd„Z	dd„Z
dedefd„Zedd„«       Zˆ xZS )r   aª  Applies Batch Normalization over a N-Dimensional input.

    The N-D input is a mini-batch of [N-2]D inputs with additional channel dimension) as described in the paper
    `Batch Normalization: Accelerating Deep Network Training by Reducing
    Internal Covariate Shift <https://arxiv.org/abs/1502.03167>`__ .

    .. math::

        y = \frac{x - \mathrm{E}[x]}{ \sqrt{\mathrm{Var}[x] + \epsilon}} * \gamma + \beta

    The mean and standard-deviation are calculated per-dimension over all
    mini-batches of the same process groups. :math:`\gamma` and :math:`\beta`
    are learnable parameter vectors of size `C` (where `C` is the input size).
    By default, the elements of :math:`\gamma` are sampled from
    :math:`\mathcal{U}(0, 1)` and the elements of :math:`\beta` are set to 0.
    The standard-deviation is calculated via the biased estimator, equivalent to
    `torch.var(input, correction=0)`.

    Also by default, during training this layer keeps running estimates of its
    computed mean and variance, which are then used for normalization during
    evaluation. The running estimates are kept with a default :attr:`momentum`
    of 0.1.

    If :attr:`track_running_stats` is set to ``False``, this layer then does not
    keep running estimates, and batch statistics are instead used during
    evaluation time as well.

    .. note::
        This :attr:`momentum` argument is different from one used in optimizer
        classes and the conventional notion of momentum. Mathematically, the
        update rule for running statistics here is
        :math:`\hat{x}_\text{new} = (1 - \text{momentum}) \times \hat{x} + \text{momentum} \times x_t`,
        where :math:`\hat{x}` is the estimated statistic and :math:`x_t` is the
        new observed value.

    Because the Batch Normalization is done for each channel in the ``C`` dimension, computing
    statistics on ``(N, +)`` slices, it's common terminology to call this Volumetric Batch
    Normalization or Spatio-temporal Batch Normalization.

    Currently :class:`SyncBatchNorm` only supports
    :class:`~torch.nn.DistributedDataParallel` (DDP) with single GPU per process. Use
    :meth:`torch.nn.SyncBatchNorm.convert_sync_batchnorm()` to convert
    :attr:`BatchNorm*D` layer to :class:`SyncBatchNorm` before wrapping
    Network with DDP.

    Args:
        num_features: :math:`C` from an expected input of size
            :math:`(N, C, +)`
        eps: a value added to the denominator for numerical stability.
            Default: ``1e-5``
        momentum: the value used for the running_mean and running_var
            computation. Can be set to ``None`` for cumulative moving average
            (i.e. simple average). Default: 0.1
        affine: a boolean value that when set to ``True``, this module has
            learnable affine parameters. Default: ``True``
        track_running_stats: a boolean value that when set to ``True``, this
            module tracks the running mean and variance, and when set to ``False``,
            this module does not track such statistics, and initializes statistics
            buffers :attr:`running_mean` and :attr:`running_var` as ``None``.
            When these buffers are ``None``, this module always uses batch statistics.
            in both training and eval modes. Default: ``True``
        process_group: synchronization of stats happen within each process group
            individually. Default behavior is synchronization across the whole
            world
        bias: If set to ``False``, the layer will not learn an additive bias (only relevant if
            :attr:`affine` is ``True``). Default: ``True``

    Shape:
        - Input: :math:`(N, C, +)`
        - Output: :math:`(N, C, +)` (same shape as input)

    .. note::
        Synchronization of batchnorm statistics occurs only while training, i.e.
        synchronization is disabled when ``model.eval()`` is set or if
        ``self.training`` is otherwise ``False``.

    Examples::

        >>> # xdoctest: +SKIP
        >>> # With Learnable Parameters
        >>> m = nn.SyncBatchNorm(100)
        >>> # creating process group (optional)
        >>> # ranks is a list of int identifying rank ids.
        >>> ranks = list(range(8))
        >>> r1, r2 = ranks[:4], ranks[4:]
        >>> # Note: every rank calls into new_group for every
        >>> # process group created, even if that rank is not
        >>> # part of the group.
        >>> process_groups = [torch.distributed.new_group(pids) for pids in [r1, r2]]
        >>> process_group = process_groups[0 if dist.get_rank() <= 3 else 1]
        >>> # Without Learnable Parameters
        >>> m = nn.BatchNorm3d(100, affine=False, process_group=process_group)
        >>> input = torch.randn(20, 100, 35, 45, 10)
        >>> output = m(input)

        >>> # network is nn.BatchNorm layer
        >>> sync_bn_network = nn.SyncBatchNorm.convert_sync_batchnorm(network, process_group)
        >>> # only single gpu per process is currently supported
        >>> ddp_sync_bn_network = torch.nn.parallel.DistributedDataParallel(
        >>>                         sync_bn_network,
        >>>                         device_ids=[args.local_rank],
        >>>                         output_device=args.local_rank)
    TNr   r   r   r   r   r   Úprocess_groupr   r   c	                óN   •— ||dœ}
t        ‰| �  |||||fi |
¤d|	i¤Ž || _        y ro   )r(   r)   r¢   )r4   r   r   r   r   r   r¢   r!   r"   r   r5   r8   s              €r9   r)   zSyncBatchNorm.__init__ó  sI   ø€ ð %+°UÑ;ˆÜ‰ÑØØØØØñ	
ð ñ	
ð ó	
ð +ˆÕr?   c                 ód   — |j                  «       dk  rt        d|j                  «       › d�«      ‚y )Nr   z expected at least 2D input (got r‰   rŠ   rF   s     r9   rH   zSyncBatchNorm._check_input_dim  s/   € Ø�9‰9‹;˜Š?ÜÐ?ÀÇ	Á	Ã¸}ÈHÐUÓVÐVð r?   c                 óB   — |j                  d«      dk(  rt        d«      ‚y )Nr
   r   z9SyncBatchNorm number of input channels should be non-zero)ÚsizerŒ   rF   s     r9   Ú_check_non_zero_input_channelsz,SyncBatchNorm._check_non_zero_input_channels  s'   € Ø�:‰:�a‹=˜AÒÜØKóð ð r?   rG   c                 ó¢  — | j                  |«       | j                  |«       | j                  €d}n| j                  }| j                  rt| j                  rh| j
                  €t        d«      ‚| j
                  j                  d«       | j                  €d| j
                  j                  «       z  }n| j                  }	 | j                  rd}n| j                  du xr | j                  du }	 | j                  r| j                  r| j                  nd}| j                  r| j                  r| j                  nd}|xrL | j                  xr> t        j                  j                  «       xr t        j                  j                  «       }|rÂ|j                  j                   ddd	t        j"                  j%                  «       fvr*t'        d
t        j"                  j%                  «       › �«      ‚t        j                  j(                  j*                  }| j,                  r| j,                  }t        j                  j/                  |«      }|dkD  }|s:t1        j2                  |||| j4                  | j6                  ||| j8                  «      S |st        d«      ‚t;        j<                  || j4                  | j6                  ||| j8                  |«	      S )z(
        Runs the forward pass.
        Nrq   z$num_batches_tracked must not be Noner
   rr   TÚcudaÚhpuÚxpuz;SyncBatchNorm expected input tensor to be on GPU or XPU or zbn_training must be True)rH   r§   r   rs   r   r&   r‚   rt   Úitemr$   r%   r*   ÚdistributedÚis_availableÚis_initializedr!   ÚtypeÚ_CÚ_get_privateuse1_backend_namerŒ   ÚgroupÚWORLDr¢   Úget_world_sizeru   rv   r#   r   r   Úsync_batch_normÚapply)	r4   rG   rw   rx   r$   r%   Ú	need_syncr¢   Ú
world_sizes	            r9   ry   zSyncBatchNorm.forward  s–  € ð 	×Ñ˜eÔ$Ø×+Ñ+¨EÔ2ð
 �=‰=Ð Ø),Ñ&à)-¯©Ð&à�=Š=˜T×5Ò5Ø×'Ñ'Ð/Ü$Ð%KÓLÐLØ×$Ñ$×)Ñ)¨!Ô,Ø�}‰}Ð$Ø-0°4×3KÑ3K×3PÑ3PÓ3RÑ-RÑ*à-1¯]©]Ð*ð	ð �=Š=Ø‰Kà×,Ñ,°Ð4ÒT¸4×;KÑ;KÈtÐ;SˆKð	ð &*§]¢]°d×6NÒ6NˆD×ÒÐTXð 	ð %)§M¢M°T×5MÒ5MˆD×ÒÐSWð 	ð ò 3Ø—‘ò3ä×!Ñ!×.Ñ.Ó0ò3ô ×!Ñ!×0Ñ0Ó2ð	 	ñ à�|‰|× Ñ ØØØÜ—‘×6Ñ6Ó8ð	)ñ ô !ØQÜ—x‘x×=Ñ=Ó?Ð@ðBóð ô
 "×-Ñ-×3Ñ3×9Ñ9ˆMØ×!Ò!Ø $× 2Ñ 2�Ü×*Ñ*×9Ñ9¸-ÓHˆJØ" Q™ˆIñ Ü—<‘<ØØØØ—‘Ø—	‘	ØØ*Ø—‘ó	ð 	ñ Ü$Ð%?Ó@Ð@Ü"×(Ñ(ØØ—‘Ø—	‘	ØØØ—‘Ø*ØØó
ð 
r?   c           
      ó*  — |}t        |t        j                  j                  j                  j
                  «      �rt        j                  j                  |j                  |j                  |j                  |j                  |j                  ||j                  du¬«      }|j                  r?t        j                  «       5  |j                  |_        |j                  |_        ddd«       |j                  |_        |j                   |_        |j"                  |_        |j$                  |_        t'        |d«      r|j(                  |_        |j+                  «       D ]'  \  }}|j-                  || j/                  ||«      «       Œ) ~|S # 1 sw Y   Œ§xY w)aa  Converts all :attr:`BatchNorm*D` layers in the model to :class:`torch.nn.SyncBatchNorm` layers.

        Args:
            module (nn.Module): module containing one or more :attr:`BatchNorm*D` layers
            process_group (optional): process group to scope synchronization,
                default is the whole world

        Returns:
            The original :attr:`module` with the converted :class:`torch.nn.SyncBatchNorm`
            layers. If the original :attr:`module` is a :attr:`BatchNorm*D` layer,
            a new :class:`torch.nn.SyncBatchNorm` layer object will be returned
            instead.

        Example::

            >>> # Network with nn.BatchNorm layer
            >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA)
            >>> module = torch.nn.Sequential(
            >>>            torch.nn.Linear(20, 100),
            >>>            torch.nn.BatchNorm1d(100),
            >>>          ).cuda()
            >>> # creating process group (optional)
            >>> # ranks is a list of int identifying rank ids.
            >>> ranks = list(range(8))
            >>> r1, r2 = ranks[:4], ranks[4:]
            >>> # Note: every rank calls into new_group for every
            >>> # process group created, even if that rank is not
            >>> # part of the group.
            >>> # xdoctest: +SKIP("distributed")
            >>> process_groups = [torch.distributed.new_group(pids) for pids in [r1, r2]]
            >>> process_group = process_groups[0 if dist.get_rank() <= 3 else 1]
            >>> sync_bn_module = torch.nn.SyncBatchNorm.convert_sync_batchnorm(module, process_group)

        Nr   Úqconfig)r�   r*   ÚnnÚmodulesÚ	batchnormrm   r   r   r   r   r   r   r   Úno_gradr#   r$   r%   r&   rs   Úhasattrr»   Únamed_childrenÚ
add_moduleÚconvert_sync_batchnorm)ÚclsÚmoduler¢   Úmodule_outputÚnameÚchilds         r9   rÃ   z$SyncBatchNorm.convert_sync_batchnormy  sM  € ðH ˆÜ�fœeŸh™h×.Ñ.×8Ñ8×CÑCÕDÜ!ŸH™H×2Ñ2Ø×#Ñ#Ø—
‘
Ø—‘Ø—‘Ø×*Ñ*ØØ—[‘[¨Ð,ð 3ó ˆMð �}Š}Ü—]‘]“_ñ 5Ø+1¯=©=�MÔ(Ø)/¯©�MÔ&÷5ð *0×)<Ñ)<ˆMÔ&Ø(.×(:Ñ(:ˆMÔ%Ø06×0JÑ0JˆMÔ-Ø%+§_¡_ˆMÔ"Ü�v˜yÔ)Ø(.¯©�Ô%Ø!×0Ñ0Ó2ò 	‰KˆD�%Ø×$Ñ$Ø�c×0Ñ0°¸ÓFõð	ð ØÐ÷5ð 5ús   Ã #F	Æ	F)r]   r^   TTNNNr_   rA   )r`   ra   rb   rc   rf   rh   ri   r   r)   rH   r§   r   ry   ÚclassmethodrÃ   rj   rk   s   @r9   r   r   Š  s¼   ø„ ñfðV Ø!$ØØ$(Ø$(ØØð+ð ò+àð+ð ð+ð ˜$‘,ð	+ð
 ð+ð "ð+ð ˜T‘zð+ð ð+ð 
õ+ó2Wóða˜Vð a¨ó aðF ò=ó ô=r?   r   )Útypingr   r*   r   Útorch.nnr   ru   r   Útorch.nn.parameterr   r   r	   Ú
_functionsr   r¶   Úlazyr   rÅ   r   Ú__all__r   rm   r{   r   r   r   r   r   r   rK   r?   r9   ú<module>rÐ      sÊ   ðå ã Ý ß *ß UÑ Uå 8Ý !Ý ò€ô|
�ô |
ô~H
�ô H
ôVL$�O Yô L$ô^KT�*ô KTô\!T�m Zô !TôHLN�*ô LNô^!N�m Zô !NôHLN�*ô LNô^!N�m Zô !NôHm�Jõ mr?   