CoolFace
Apppublic

Aluode/PerceptionLabPortable

sourceHugging Faceupdated 9mo agoView on Hugging Face
0likes
modeling_bit.cpython-310.pyc237 linesDownload Raw Back to __pycache__
1o

2.�Yiqo�	@sdZddlZddlZddlmZddlZddlZddlmZm	Z	ddl3mZddlm
Z
mZmZmZddlmZdd	lmZmZdd4lmZddlmZe�e�Zd=deeeffdd�ZGdd�de	j �Z!Gdd�de	j"�Z#Gdd�de	j$�Z%Gdd�de	j&�Z'Gdd�de	j$�Z(d>dejde)dedejfd d!�Z*Gd"d#�d#e	j$�Z+d?d%d&�Z,Gd'd(�d(e	j$�Z-Gd)d*�d*e	j$�Z.Gd+d,�d,e	j$�Z/Gd-d.�d.e	j$�Z0Gd/d0�d0e	j$�Z1eGd1d2�d2e��Z2eGd3d4�d4e2��Z3ed5d6�Gd7d8�d8e2��Z4ed9d6�Gd:d;�d;e2e��Z5gd<�Z6dS)@z9PyTorch BiT model. Also supports backbone for ViT hybrid.�N)�Optional)�Tensor�nn�)�ACT2FN)�BackboneOutput�BaseModelOutputWithNoAttention�(BaseModelOutputWithPoolingAndNoAttention�$ImageClassifierOutputWithNoAttention)�PreTrainedModel)�auto_docstring�logging)�
BackboneMixin�)�	BitConfig��returncCs�d}|dur|d||dd}||fSt|t�r_|��}|dkrI|dkrA||dddkrA|d||dd}||fSd}d}||fS|dkrSd}||fS|d||dd}||fS)	al5    Utility function to get the tuple padding value given the kernel_size and padding.6 7    Args:8        padding (Union[`str`, `int`], *optional*):9            Padding value, can be either `"same"`, `"valid"`. If a different value is provided the default padding from10            PyTorch is used.11        kernel_size (`int`, *optional*, defaults to 7):12            Kernel size of the convolution layers.13        stride (`int`, *optional*, defaults to 1):14            Stride value of the convolution layers.15        dilation (`int`, *optional*, defaults to 1):16            Dilation value of the convolution layers.17    FNr�ZsamerT�valid)�18isinstance�str�lower)�padding�kernel_size�stride�dilationZdynamic�r��E:\DocsHouse\542 percep lab latest\PerceptionLab\PerceptionLab_Portable\python_embed\Lib\site-packages\transformers/models/bit/modeling_bit.py�get_padding_value)s$19���rcs6eZdZdZ						d20�fdd�	Zdd	�Z�ZS)�WeightStandardizedConv2dz�Conv2d with Weight Standardization. Includes TensorFlow compatible SAME padding. Used for ViT Hybrid model.21 22    Paper: [Micro-Batch Training with Batch-Channel Normalization and Weight23    Standardization](https://huggingface.co/papers/1903.10520v2)24    r�SAMEF�����ư>c2526sTt||||d�\}}27t�j||||||||d�|28r"t|||�|_nd|_|	|_dS)N)rr)rrr�groups�bias)r�super�__init__�DynamicPad2d�pad�eps)�selfZ29in_channel�out_channelsrrrrr"r#r(Z30is_dynamic��	__class__rrr%Ys�3132z!WeightStandardizedConv2d.__init__c	Csj|jdur33|�|�}tjj|j�d|jd�dddd|jd��|j�}tj�	|||j34|j|j|j
|j�}|S)Nr�����T�)�trainingZmomentumr()r'r�35functionalZ36batch_norm�weightZreshaper*r(Z37reshape_asZconv2dr#rrrr")r)�hidden_stater1rrr�forwardvs3839���z WeightStandardizedConv2d.forward)rr rrFr!��__name__�40__module__�__qualname__�__doc__r%r3�
__classcell__rrr+rrRs�rcs*eZdZdZd�fdd�	Zdd�Z�ZS)	�BitGroupNormActivationzQ41    A module that combines group normalization with an activation function.42    ��h㈵��>Tcs8t�j|j|||d�|rt|j|_dSt��|_dS)N)r(�affine)r$r%�43num_groupsr�44hidden_act�45activationr�Identity)r)�config�num_channelsr(r<�apply_activationr+rrr%�szBitGroupNormActivation.__init__cCs*tj�||j|j|j|j�}|�|�}|S�N)rr0Z46group_normr=r1r#r(r?)r)r2rrrr3�s47zBitGroupNormActivation.forward)r;TTr4rrr+rr:�sr:cs*eZdZdZd�fdd�	Zdd�Z�ZS)r&z�48    A module that wraps dynamic padding of any input, given the parameters of the convolutional layer and the input49    hidden states.50    rcsjt���t|t�r||f}t|t�r||f}t|t�r ||f}||_||_||_||_dd�}||_dS)NcSs0tt�||�d||d|d|d�S)Nrr)�max�math�ceil)�xrrrrrr�compute_padding�s0z.DynamicPad2d.__init__.<locals>.compute_padding)	r$r%r�intrrr�valuerI)r)rrrrKrIr+rrr%�s5152535455zDynamicPad2d.__init__cCs�|��dd�\}}|�||jd|jd|jd�}|�||jd|jd|jd�}|dks4|dkrNtjj||d||d|d||dg|jd�}|S)N�����rrr)rK)	�sizerIrrrrr0r'rK)r)�inputZinput_heightZinput_width�padding_height�
padding_widthrrrr3�s""5657��58zDynamicPad2d.forward)rr4rrr+rr&�sr&cs<eZdZdZ						d
def�fd	d59�
Zdd�Z�ZS)�BitMaxPool2dz1Tensorflow like 'SAME' wrapper for 2D max poolingNrF�rrrTrcs�t|tjj�r	|n||f}t|tjj�r|n||f}t|tjj�r#|n||f}t��|||||�|r=t||||�|_dSt�	�|_dSrD)60r�collections�abc�Iterabler$r%r&r'rr@)r)rrr�	ceil_moderZ
padding_value�use_dynamic_paddingr+rrr%�s61zBitMaxPool2d.__init__cCs*|�|�}tj�||j|j|j|j|j�SrD)	r'rr0Z62max_pool2drrrrrV�r)�
hidden_statesrrrr3�s63�zBitMaxPool2d.forward)NrFrRrT)r5r6r7r8rJr%r3r9rrr+rrQ�s��rQcs8eZdZdZdef�fdd�Zdedefdd�Z�ZS)	�
BitEmbeddingszL64    BiT Embeddings (stem) composed of a single aggressive convolution.65    rAcs�t���t|j|jddd|jd�|_tdd|jd�|_	|jdur.|j�66�dkr.t��|_
ntjdd	d67�|_
|jdkrDt||jd�|_nt��|_|j|_dS)
Nrr�:�0�yE>)rrr(rr)rrrWr )rrrrr.)rrK�
preactivation�rB)r$r%rrB�embedding_size�global_padding�convolutionrQZembedding_dynamic_padding�pooler�upperrr@r'Z
ConstantPad2d�68layer_typer:�norm�r)rAr+rrr%�s"69�	7071zBitEmbeddings.__init__�pixel_valuesrcCsH|jd}||jkrtd��|�|�}|�|�}|�|�}|�|�}|S)NrzeMake sure that the channel dimension of the pixel values match with the one set in the configuration.)�shaperB�72ValueErrorr`r'rdra)r)rfrBZ	embeddingrrrr3s7374�75767778zBitEmbeddings.forward)	r5r6r7r8rr%rr3r9rrr+rrZ�srZr.FrN�	drop_probr/cCsd|dks|s|Sd|}|jdfd|jd}|tj||j|jd�}|��|�|�|}|S)aF79    Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).80 81    Comment by Ross Wightman: This is the same as the DropConnect impl I created for EfficientNet, etc networks,82    however, the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...83    See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for changing the84    layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use 'survival rate' as the85    argument.86    r.rr)r)�dtype�device)rg�ndim�torchZrandrjrkZfloor_�div)rNrir/Z	keep_probrgZ
random_tensor�outputrrr�	drop_paths87rpcsTeZdZdZddeeddf�fdd�
Zdejdejfdd	�Z	de88fd89d�Z�ZS)
�BitDropPathzXDrop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).Nrircst���||_dSrD)r$r%ri)r)rir+rrr%/s9091zBitDropPath.__init__rYcCst||j|j�SrD)rprir/rXrrrr33�zBitDropPath.forwardcCsd|j��S)Nzp=)ri)r)rrr�92extra_repr6szBitDropPath.extra_reprrD)
r5r6r7r8r�floatr%rmrr3rrsr9rrr+rrq,s93rq�cCs:|}t|t||d�||�}|d|kr||7}|S)Nrg�������?)rErJ)rKZdivisorZ	min_value�	new_valuerrr�make_div:s94rwc�:eZdZdZ								d�fdd�	Zd	d95�Z�ZS)�BitPreActivationBottleneckLayeraPre-activation (v2) bottleneck block.96    Follows the implementation of "Identity Mappings in Deep Residual Networks":97    https://github.com/KaimingHe/resnet-1k-layers/blob/master/resnet-pre-act.lua98 99    Except it puts the stride on 3x3 conv when available.100    N��?rr.Fc	s�t���|p|}|p|}t||�}|101r t||||dd�|_nd|_t||�|_t||dd|jd�|_	t||d�|_102t||d||d|jd�|_t||�|_t||dd|jd�|_
|	d	krdt|	�|_dSt��|_dS)103NT�r�preactrr[�r(rr]r)rr"r(rr)r$r%rw�BitDownsampleConv�104downsampler:�norm1rr_�conv1�norm2�conv2�norm3�conv3rqrr@rp)r)rA�in_channelsr*�bottle_ratiorr�first_dilationr"�drop_path_rate�is_first_layerZmid_channelsr+rrr%Js,105
106��$z(BitPreActivationBottleneckLayer.__init__cCs^|�|�}|}|jdur|�|�}|�|�}|�|�|��}|�|�|��}|�|�}||SrD)r�rr�r�r�r�r�rp)r)rYZhidden_states_preact�shortcutrrrr3vs107108109110111z'BitPreActivationBottleneckLayer.forward�NrzrrNrr.Fr4rrr+rryBs�,rycrx)�BitBottleneckLayerz\Non Pre-activation bottleneck block, equivalent to V1.5/V1b bottleneck. Used for ViT Hybrid.Nrzrr.Fc112s�t���|p|}|p|}t||�}|113r t||||dd�|_nd|_t||dd|jd�|_t||d�|_	t||d|||d|jd�|_114t||d�|_t||dd|jd�|_t||dd	�|_
|	d115kret|	�nt��|_t|j|_dS)NFr{rr[r}r]r)rrr"r(r�rBrCr)r$r%rwr~rrr_r�r:r�r�r�r�r�rqrr@rprr>r?)r)rAr�r*r�rrr�r"r�r�Zmid_chsr+rrr%�s<116
117��118zBitBottleneckLayer.__init__cCsp|}|jdur|�|�}|�|�}|�|�}|�|�}|�|�}|�|�}|�|�}|�|�}|�||�}|SrD)	rr�r�r�r�r�r�rpr?)r)rYr�rrrr3�s119120121122123124125126127zBitBottleneckLayer.forwardr�r4rrr+rr��s�1r�cs*eZdZ		d�fdd�	Zdd�Z�ZS)r~rTcsHt���t||d|d|jd�|_|rt��|_dSt||dd�|_dS)Nrr[)rr(rFr�)	r$r%rr_�convrr@r:rd)r)rAr�r*rr|r+rrr%�s128����zBitDownsampleConv.__init__cCs|�|�|��SrD)rdr�)r)rHrrrr3�rrzBitDownsampleConv.forward)rT)r5r6r7r%r3r9rrr+rr~�s129�r~cs@eZdZdZ		d�fdd�	Zdd�Zded	efd130d�Z�ZS)
�BitStagez7131    A ResNet v2 stage composed by stacked layers.132    rzNc	s�t���|dvrdnd}	|jdkrt}133nt}134|}t��|_t|�D]$}|�	|||�\}}
}|j�135t|�|136|||||||	|
|d�	�|}|}	q"dS)N)rrrrZ137bottleneck)rrr�r�r�r�)r$r%rcr�ryr�138Sequential�layers�range�_get_updated_hyperparameters�139add_moduler)r)rAr�r*rr�depthr��
layer_dropoutr�Z	layer_cls�prev_chs�	layer_idxr�r�r+rrr%�s8140141142143����zBitStage.__init__cCs0|r||}nd}|dkrd}|dk}|||fS)zt144        Get the new hyper-parameters with respect to the previous ones and the index of the current layer.145        r.rrr)r)r�rr�r�r�rrrr�s146147z%BitStage._get_updated_hyperparametersrNrcCs$|}t|j�D]\}}||�}q|SrD)�	enumerater�)r)rNr2�_�layerrrrr3)s148zBitStage.forward)rzN)	r5r6r7r8r%r�rr3r9rrr+rr��s�.r�c	sHeZdZdef�fdd�Zdd�Z	dded	ed149edefdd
�Z	�Z150S)�151BitEncoderrAc
152s�t���t�g�|_|j}d}d}dd�t�t�	d|j153t|j����
|j�D�}tt|j|j|��D]-\}\}}}	|�|||||�\}154}}t|||155||||	d�}|156}||9}|j�t|�|�q3dS)N�rcSsg|]}|���qSr)�tolist)�.0rHrrr�157<listcomp>;s��z'BitEncoder.__init__.<locals>.<listcomp>r)rrr�r�)r$r%rZ158ModuleList�stagesr^rmr�npZlinspacer��sumZdepths�splitr��zip�hidden_sizesr�r�r�r)
r)rAr��current_striderZlayer_dropouts�	stage_idxZ
current_depth�current_hidden_sizer�r*r�stager+rrr%1s6159"��160161��162�zBitEncoder.__init__cCs>t||j�}|dkr
dnd}||jkr||9}d}|||fS)Nrrr)rwZwidth_factorZ
output_stride)r)r�r�r�rrAr*rrrrr�Ws163164z'BitEncoder._get_updated_hyperparametersFTr2�output_hidden_states�return_dictrcCsb|rdnd}|jD]
}|r||f}||�}q	|r||f}|s+tdd�||fD��St||d�S)Nrcss�|]	}|dur|VqdSrDr)r��vrrr�	<genexpr>ns�z%BitEncoder.forward.<locals>.<genexpr>)�last_hidden_staterY)r��tupler)r)r2r�r�rYZstage_modulerrrr3_s165166167168�zBitEncoder.forward)FT)r5r6r7rr%r�r�boolrr3r9rrr+rr�0s&	�����r�c@s,eZdZUeed<dZdZdgZdd�ZdS)�BitPreTrainedModelrA�bitrfrZcCs�t|tj�rtjj|jddd�dSt|tj�rMtjj|jt�	d�d�|j169durKtj�|j�\}}|dkr=dt�	|�nd}tj�|j170||�dSdSt|tj
tjf�rhtj�|jd�tj�|j171d�dSdS)NZfan_outZrelu)�modeZnonlinearity�)�arr)rr�Conv2d�initZkaiming_normal_r1�LinearZkaiming_uniform_rF�sqrtr#Z_calculate_fan_in_and_fan_outZuniform_ZBatchNorm2d�	GroupNormZ	constant_)r)�moduleZfan_inr��boundrrr�
_init_weights}s172��z BitPreTrainedModel._init_weightsN)	r5r6r7r�__annotations__Zbase_model_prefixZmain_input_nameZ_no_split_modulesr�rrrrr�vs173r�c174sFeZdZ�fdd�Ze	d175dedeedeedefdd	��Z	�Z176S)�BitModelcsdt��|�||_t|�|_t|�|_|jdkr!t||j	dd�nt177��|_t178�
d�|_|��dS)Nr\r-r])rr)r$r%rArZ�embedderr��encoderrcr:r�rr@rdZAdaptiveAvgPool2dra�	post_initrer+rrr%�s179180181��zBitModel.__init__Nrfr�r�rcCs�|dur|n|jj}|dur|n|jj}|�|�}|j|||d�}|d}|�|�}|�|�}|s;||f|dd�St|||jd�S)N�r�r�rr)r��
pooler_outputrY)	rAr��use_return_dictr�r�rdrar	rY)r)rfr�r�Zembedding_outputZencoder_outputsr��
pooled_outputrrrr3�s"�182�183184�zBitModel.forward�NN)r5r6r7r%rrrr�r	r3r9rrr+rr��s�����r�z�185    BiT Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for186    ImageNet.187    )Zcustom_introcs\eZdZ�fdd�Ze				ddeejdeejdee	dee	de188f189d	d190��Z�ZS)�BitForImageClassificationcs^t��|�|j|_t|�|_t�t��|jdkr#t�|j	d|j�nt�191��|_|��dS)Nrr-)
r$r%Z192num_labelsr�r�rr�ZFlattenr�r�r@�193classifierr�rer+rrr%�s194$�z"BitForImageClassification.__init__Nrf�labelsr�r�rc195Cs�|dur|n|jj}|j|||d�}|r|jn|d}|�|�}d}|dur.|�|||j�}|sD|f|dd�}	|durB|f|	S|	St|||jd�S)a0196        labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):197            Labels for computing the image classification/regression loss. Indices should be in `[0, ...,198            config.num_labels - 1]`. If `config.num_labels > 1` a classification loss is computed (Cross-Entropy).199        Nr�rr)�loss�logitsrY)rAr�r�r�r�Z
loss_functionr200rY)201r)rfr�r�r��outputsr�r�r�rorrrr3�s
202z!BitForImageClassification.forward)NNNN)
r5r6r7r%rrrmZFloatTensorZ203LongTensorr�r204r3r9rrr+rr��s$������r�zL205    BiT backbone, to be used with frameworks like DETR and MaskFormer.206    c207sJeZdZdZ�fdd�Ze	ddedeedeede	fd	d208��Z209�ZS)�BitBackboneFcs>t��|�t��|�t|�|_|jg|j|_|��dSrD)	r$r%Z_init_backboner�r�r^r�Znum_featuresr�rer+rrr%�s210211zBitBackbone.__init__Nrfr�r�rc212Cs�|dur|n|jj}|dur|n|jj}|j|ddd�}|j}d}t|j�D]\}}||jvr6|||f7}q&|sF|f}	|rD|	|jf7}	|	St||rP|jdd�Sddd�S)aN213        Examples:214 215        ```python216        >>> from transformers import AutoImageProcessor, AutoBackbone217        >>> import torch218        >>> from PIL import Image219        >>> import requests220 221        >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"222        >>> image = Image.open(requests.get(url, stream=True).raw)223 224        >>> processor = AutoImageProcessor.from_pretrained("google/bit-50")225        >>> model = AutoBackbone.from_pretrained("google/bit-50")226 227        >>> inputs = processor(image, return_tensors="pt")228        >>> outputs = model(**inputs)229        ```NTr�r)�feature_mapsrYZ230attentions)	rAr�r�r�rYr�Zstage_namesZout_featuresr)231r)rfr�r�r�rYr��idxr�rorrrr3s.�232���zBitBackbone.forwardr�)r5r6r7Zhas_attentionsr%rrrr�rr3r9rrr+rr��s233�����r�)r�r�r�r�)Nrrr)r.F)ru)7r8rSrF�typingr�numpyr�rmrrZactivationsrZmodeling_outputsrrr	r234Zmodeling_utilsr�utilsrr
Zutils.backbone_utilsrZconfiguration_bitrZ235get_loggerr5�loggerr�r�rr�rr�r:�Moduler&Z	MaxPool2drQrZrtrprqrwryr�r~r�r�r�r�r�r��__all__rrrr�<module>sR236)03 3237DIJF1�.�>
Aluode/PerceptionLabPortable · CoolFace