o
    wiT                     @   s  d Z ddlZddlmZmZ ddlZddlZddlmZ ddlm	Z	m
Z
mZ ddlmZ ddlmZmZmZ dd	lmZ dd
lmZmZ ddlmZ eeZdedefddZd/deeef defddZ G dd dej!Z"G dd dej#Z$G dd dej!Z%G dd dej!Z&G dd dej!Z'G d d! d!ej!Z(G d"d# d#ej!Z)G d$d% d%ej!Z*eG d&d' d'eZ+eG d(d) d)e+Z,ed*d+G d,d- d-e+Z-g d.Z.dS )0zPyTorch EfficientNet model.    N)OptionalUnion)nn)BCEWithLogitsLossCrossEntropyLossMSELoss   )ACT2FN)BaseModelOutputWithNoAttention(BaseModelOutputWithPoolingAndNoAttention$ImageClassifierOutputWithNoAttention)PreTrainedModel)auto_docstringlogging   )EfficientNetConfigconfignum_channelsc                 C   sJ   | j }|| j9 }t|t||d  | | }|d| k r!||7 }t|S )z<
    Round number of filters based on depth multiplier.
       g?)depth_divisorwidth_coefficientmaxint)r   r   divisornew_dim r   s/home/ubuntu/sommelier/.venv/lib/python3.10/site-packages/transformers/models/efficientnet/modeling_efficientnet.pyround_filters'   s   
r   Tkernel_sizeadjustc                 C   sn   t | tr	| | f} | d d | d d f}|r)|d d |d |d d |d fS |d |d |d |d fS )aJ  
    Utility function to get the tuple padding value for the depthwise convolution.

    Args:
        kernel_size (`int` or `tuple`):
            Kernel size of the convolution layers.
        adjust (`bool`, *optional*, defaults to `True`):
            Adjusts padding value to apply to right and bottom sides of the input.
    r   r   r   )
isinstancer   )r   r   correctr   r   r   correct_pad6   s   

$r"   c                       s<   e Zd ZdZdef fddZdejdejfddZ  Z	S )	EfficientNetEmbeddingszL
    A module that corresponds to the stem module of the original work.
    r   c                    sh   t    t|d| _tjdd| _tj|j| jddddd| _	tj
| j|j|jd	| _t|j | _d S )
N    )r   r   r   r   paddingr   r   validFr   strider&   bias)epsmomentum)super__init__r   out_dimr   	ZeroPad2dr&   Conv2dr   convolutionBatchNorm2dbatch_norm_epsbatch_norm_momentum	batchnormr	   
hidden_act
activationselfr   	__class__r   r   r.   O   s   
zEfficientNetEmbeddings.__init__pixel_valuesreturnc                 C   s,   |  |}| |}| |}| |}|S N)r&   r2   r6   r8   )r:   r=   featuresr   r   r   forwardZ   s
   



zEfficientNetEmbeddings.forward)
__name__
__module____qualname____doc__r   r.   torchTensorrA   __classcell__r   r   r;   r   r#   J   s    r#   c                       s,   e Zd Z							d fdd	Z  ZS )	EfficientNetDepthwiseConv2dr   r   r   Tzerosc	           
         s*   || }	t  j||	|||||||d	 d S )N)	in_channelsout_channelsr   r)   r&   dilationgroupsr*   padding_mode)r-   r.   )
r:   rK   depth_multiplierr   r)   r&   rM   r*   rO   rL   r;   r   r   r.   d   s   
z$EfficientNetDepthwiseConv2d.__init__)r   r   r   r   r   TrJ   )rB   rC   rD   r.   rH   r   r   r;   r   rI   c   s    rI   c                       sH   e Zd ZdZdedededef fddZdejd	ej	fd
dZ
  ZS )EfficientNetExpansionLayerz_
    This corresponds to the expansion phase of each block in the original implementation.
    r   in_dimr/   r)   c                    sB   t    tj||dddd| _tj||jd| _t|j	 | _
d S )Nr   sameFrK   rL   r   r&   r*   )num_featuresr+   )r-   r.   r   r1   expand_convr3   r4   	expand_bnr	   r7   
expand_act)r:   r   rR   r/   r)   r;   r   r   r.      s   
z#EfficientNetExpansionLayer.__init__hidden_statesr>   c                 C   s"   |  |}| |}| |}|S r?   )rV   rW   rX   r:   rY   r   r   r   rA      s   


z"EfficientNetExpansionLayer.forward)rB   rC   rD   rE   r   r   r.   rF   FloatTensorrG   rA   rH   r   r   r;   r   rQ   }   s    rQ   c                
       sL   e Zd ZdZdededededef
 fddZd	ej	d
ej
fddZ  ZS )EfficientNetDepthwiseLayerzk
    This corresponds to the depthwise convolution phase of each block in the original implementation.
    r   rR   r)   r   adjust_paddingc                    sv   t    || _| jdkrdnd}t||d}tj|d| _t||||dd| _tj	||j
|jd| _t|j | _d S )	Nr   r'   rS   )r   r%   Fr(   rU   r+   r,   )r-   r.   r)   r"   r   r0   depthwise_conv_padrI   depthwise_convr3   r4   r5   depthwise_normr	   r7   depthwise_act)r:   r   rR   r)   r   r]   conv_padr&   r;   r   r   r.      s   


z#EfficientNetDepthwiseLayer.__init__rY   r>   c                 C   s6   | j dkr
| |}| |}| |}| |}|S )Nr   )r)   r_   r`   ra   rb   rZ   r   r   r   rA      s   




z"EfficientNetDepthwiseLayer.forwardrB   rC   rD   rE   r   r   boolr.   rF   r[   rG   rA   rH   r   r   r;   r   r\      s    r\   c                	       sJ   e Zd ZdZddedededef fddZd	ej	d
ej
fddZ  ZS )EfficientNetSqueezeExciteLayerzl
    This corresponds to the Squeeze and Excitement phase of each block in the original implementation.
    Fr   rR   
expand_dimexpandc                    s   t    |r	|n|| _tdt||j | _tjdd| _	tj
| j| jddd| _tj
| j| jddd| _t|j | _t | _d S )Nr   )output_sizerS   )rK   rL   r   r&   )r-   r.   dimr   r   squeeze_expansion_ratiodim_ser   AdaptiveAvgPool2dsqueezer1   reducerh   r	   r7   
act_reduceSigmoid
act_expand)r:   r   rR   rg   rh   r;   r   r   r.      s$   
z'EfficientNetSqueezeExciteLayer.__init__rY   r>   c                 C   sF   |}|  |}| |}| |}| |}| |}t||}|S r?   )rn   ro   rp   rh   rr   rF   mul)r:   rY   inputsr   r   r   rA      s   




z&EfficientNetSqueezeExciteLayer.forward)Frd   r   r   r;   r   rf      s     rf   c                       sV   e Zd ZdZdedededededef fdd	Zd
e	j
de	j
de	jfddZ  ZS )EfficientNetFinalBlockLayerz[
    This corresponds to the final phase of each block in the original implementation.
    r   rR   r/   r)   	drop_rateid_skipc                    sX   t    |dko| | _tj||dddd| _tj||j|jd| _	tj
|d| _d S )Nr   rS   FrT   r^   p)r-   r.   apply_dropoutr   r1   project_convr3   r4   r5   
project_bnDropoutdropout)r:   r   rR   r/   r)   rv   rw   r;   r   r   r.      s   

z$EfficientNetFinalBlockLayer.__init__
embeddingsrY   r>   c                 C   s0   |  |}| |}| jr| |}|| }|S r?   )r{   r|   rz   r~   )r:   r   rY   r   r   r   rA      s   


z#EfficientNetFinalBlockLayer.forwardrB   rC   rD   rE   r   r   floatre   r.   rF   r[   rG   rA   rH   r   r   r;   r   ru      s     $ru   c                       s\   e Zd ZdZdededededededed	ed
ef fddZde	j
de	jfddZ  ZS )EfficientNetBlocka  
    This corresponds to the expansion and depthwise convolution phase of each block in the original implementation.

    Args:
        config ([`EfficientNetConfig`]):
            Model configuration class.
        in_dim (`int`):
            Number of input channels.
        out_dim (`int`):
            Number of output channels.
        stride (`int`):
            Stride size to be used in convolution layers.
        expand_ratio (`int`):
            Expand ratio to set the output dimensions for the expansion and squeeze-excite layers.
        kernel_size (`int`):
            Kernel size for the depthwise convolution layer.
        drop_rate (`float`):
            Dropout rate to be used in the final phase of each block.
        id_skip (`bool`):
            Whether to apply dropout and sum the final hidden states with the input embeddings during the final phase
            of each block. Set to `True` for the first block of each stage.
        adjust_padding (`bool`):
            Whether to apply padding to only right and bottom side of the input kernel before the depthwise convolution
            operation, set to `True` for inputs with odd input sizes.
    r   rR   r/   r)   expand_ratior   rv   rw   r]   c
                    s   t    || _| jdkrdnd| _|| }
| jr"t|||
|d| _t|| jr)|
n||||	d| _t|||
| jd| _	t
|| jrB|
n|||||d| _d S )Nr   TF)r   rR   r/   r)   )r   rR   r)   r   r]   )r   rR   rg   rh   )r   rR   r/   r)   rv   rw   )r-   r.   r   rh   rQ   	expansionr\   r`   rf   squeeze_exciteru   
projection)r:   r   rR   r/   r)   r   r   rv   rw   r]   expand_in_dimr;   r   r   r.   !  s4   

zEfficientNetBlock.__init__rY   r>   c                 C   s<   |}| j dkr| |}| |}| |}| ||}|S )Nr   )r   r   r`   r   r   )r:   rY   r   r   r   r   rA   J  s   



zEfficientNetBlock.forwardr   r   r   r;   r   r     s,    	
)r   c                	       sP   e Zd ZdZdef fddZ		ddejdee	 d	ee	 d
e
fddZ  ZS )EfficientNetEncoderz
    Forward propagates the embeddings through each EfficientNet block.

    Args:
        config ([`EfficientNetConfig`]):
            Model configuration class.
    r   c                    s~  t    |_|j_fdd t|j}t fdd|jD }d}g }t|D ]k}t	||j| }t	||j
| }|j| }	|j| }
|j| }t |j| D ]@}|dkr]dnd}|dkredn|	}	|dkrm|n|}||jv rvdnd}|j| | }t||||	|
||||d		}|| |d7 }qUq+t|_tj|t	|d
dddd_tj|j|j|jd_t|j _d S )Nc                    s   t t j|  S r?   )r   mathceildepth_coefficient)repeats)r:   r   r   round_repeatse  s   z3EfficientNetEncoder.__init__.<locals>.round_repeatsc                 3   s    | ]} |V  qd S r?   r   ).0n)r   r   r   	<genexpr>j  s    z/EfficientNetEncoder.__init__.<locals>.<genexpr>r   TFr   )	r   rR   r/   r)   r   r   rv   rw   r]   i   rS   rT   r^   )r-   r.   r   r   lenrK   sumnum_block_repeatsranger   rL   strideskernel_sizesexpand_ratiosdepthwise_paddingdrop_connect_rater   appendr   
ModuleListblocksr1   top_convr3   
hidden_dimr4   r5   top_bnr	   r7   top_activation)r:   r   num_base_blocks
num_blockscurr_block_numr   irR   r/   r)   r   r   jrw   r]   rv   blockr;   )r   r:   r   r.   `  s\   






zEfficientNetEncoder.__init__FTrY   output_hidden_statesreturn_dictr>   c                 C   st   |r|fnd }| j D ]}||}|r||f7 }q
| |}| |}| |}|s4tdd ||fD S t||dS )Nc                 s   s    | ]	}|d ur|V  qd S r?   r   )r   vr   r   r   r     s    z.EfficientNetEncoder.forward.<locals>.<genexpr>)last_hidden_staterY   )r   r   r   r   tupler
   )r:   rY   r   r   all_hidden_statesr   r   r   r   rA     s   




zEfficientNetEncoder.forward)FT)rB   rC   rD   rE   r   r.   rF   r[   r   re   r
   rA   rH   r   r   r;   r   r   W  s    :r   c                   @   s$   e Zd ZeZdZdZg Zdd ZdS )EfficientNetPreTrainedModelefficientnetr=   c                 C   st   t |tjtjfr#|jjjd| jjd |j	dur!|j	j
  dS dS t |tjr8|j	j
  |jjd dS dS )zInitialize the weightsg        )meanstdNg      ?)r    r   Linearr1   weightdatanormal_r   initializer_ranger*   zero_	LayerNormfill_)r:   moduler   r   r   _init_weights  s   
z)EfficientNetPreTrainedModel._init_weightsN)	rB   rC   rD   r   config_classbase_model_prefixmain_input_name_no_split_modulesr   r   r   r   r   r     s    r   c                       s^   e Zd Zdef fddZe			ddeej dee	 dee	 de
eef fd	d
Z  ZS )EfficientNetModelr   c                    s~   t  | || _t|| _t|| _|jdkr"tj	|j
dd| _n|jdkr1tj|j
dd| _ntd|j |   d S )Nr   T)	ceil_moder   z2config.pooling must be one of ['mean', 'max'] got )r-   r.   r   r#   r   r   encoderpooling_typer   	AvgPool2dr   pooler	MaxPool2d
ValueErrorpooling	post_initr9   r;   r   r   r.     s   



zEfficientNetModel.__init__Nr=   r   r   r>   c                 C   s   |d ur|n| j j}|d ur|n| j j}|d u rtd| |}| j|||d}|d }| |}||jd d }|sH||f|dd   S t	|||j
dS )Nz You have to specify pixel_valuesr   r   r   r   r   )r   pooler_outputrY   )r   r   use_return_dictr   r   r   r   reshapeshaper   rY   )r:   r=   r   r   embedding_outputencoder_outputsr   pooled_outputr   r   r   rA     s*   

zEfficientNetModel.forward)NNN)rB   rC   rD   r   r.   r   r   rF   r[   re   r   r   r   rA   rH   r   r   r;   r   r     s    
r   z
    EfficientNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g.
    for ImageNet.
    )custom_introc                       sd   e Zd Z fddZe				ddeej deej dee	 dee	 de
eef f
d	d
Z  ZS )"EfficientNetForImageClassificationc                    sd   t  | |j| _|| _t|| _tj|jd| _	| jdkr't
|j| jnt | _|   d S )Nrx   r   )r-   r.   
num_labelsr   r   r   r   r}   dropout_rater~   r   r   Identity
classifierr   r9   r;   r   r   r.     s   
$z+EfficientNetForImageClassification.__init__Nr=   labelsr   r   r>   c                 C   sl  |dur|n| j j}| j|||d}|r|jn|d }| |}| |}d}|dur| j jdu rU| jdkr;d| j _n| jdkrQ|jt	j
ksL|jt	jkrQd| j _nd| j _| j jdkrst }	| jdkrm|	| | }n+|	||}n%| j jdkrt }	|	|d| j|d}n| j jdkrt }	|	||}|s|f|dd  }
|dur|f|
 S |
S t|||jd	S )
a  
        labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
            config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
            `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
        Nr   r   
regressionsingle_label_classificationmulti_label_classificationr   )losslogitsrY   )r   r   r   r   r~   r   problem_typer   dtyperF   longr   r   rn   r   viewr   r   rY   )r:   r=   r   r   r   outputsr   r   r   loss_fctoutputr   r   r   rA     s@   



"


z*EfficientNetForImageClassification.forward)NNNN)rB   rC   rD   r.   r   r   rF   r[   
LongTensorre   r   r   r   rA   rH   r   r   r;   r   r     s$    
r   )r   r   r   )T)/rE   r   typingr   r   rF   torch.utils.checkpointr   torch.nnr   r   r   activationsr	   modeling_outputsr
   r   r   modeling_utilsr   utilsr   r   configuration_efficientnetr   
get_loggerrB   loggerr   r   r   re   r"   Moduler#   r1   rI   rQ   r\   rf   ru   r   r   r   r   r   __all__r   r   r   r   <module>   s@   
''!QZ8E