codingutf8 microsoft research and the huggingface inc team licensed under the apache license version 2 0 the license you may not use this file except in compliance with the license you may obtain a copy of the license at http www apache orglicenseslicense2 0 unless required by applicable law or agreed to in writing software distributed under the license is distributed on an as is basis without warranties or conditions of any kind either express or implied see the license for the specific language governing permissions and limitations under the license beit model configuration from collections import ordereddict from typing import mapping from packaging import version from configurationutils import pretrainedconfig from onnx import onnxconfig from utils import logging from utils backboneutils import backboneconfigmixin getalignedoutputfeaturesoutputindices logger logging getloggername beitpretrainedconfigarchivemap microsoftbeitbasepatch16224pt22k https huggingface comicrosoftbeitbasepatch16224pt22kresolvemainconfig json see all beit models at https huggingface comodels filterbeit class beitconfigbackboneconfigmixin pretrainedconfig r this is the configuration class to store the configuration of a beitmodel it is used to instantiate an beit model according to the specified arguments defining the model architecture instantiating a configuration with the defaults will yield a similar configuration to that of the beit microsoftbeitbasepatch16224pt22khttps huggingface comicrosoftbeitbasepatch16224pt22k architecture args vocabsize int optional defaults to 8192 vocabulary size of the beit model defines the number of different image tokens that can be used during pretraining hiddensize int optional defaults to 768 dimensionality of the encoder layers and the pooler layer numhiddenlayers int optional defaults to 12 number of hidden layers in the transformer encoder numattentionheads int optional defaults to 12 number of attention heads for each attention layer in the transformer encoder intermediatesize int optional defaults to 3072 dimensionality of the intermediate i e feedforward layer in the transformer encoder hiddenact str or function optional defaults to gelu the nonlinear activation function function or string in the encoder and pooler if string gelu relu selu and gelunew are supported hiddendropoutprob float optional defaults to 0 0 the dropout probability for all fully connected layers in the embeddings encoder and pooler attentionprobsdropoutprob float optional defaults to 0 0 the dropout ratio for the attention probabilities initializerrange float optional defaults to 0 02 the standard deviation of the truncatednormalinitializer for initializing all weight matrices layernormeps float optional defaults to 1e12 the epsilon used by the layer normalization layers imagesize int optional defaults to 224 the size resolution of each image patchsize int optional defaults to 16 the size resolution of each patch numchannels int optional defaults to 3 the number of input channels usemasktoken bool optional defaults to false whether to use a mask token for masked image modeling useabsolutepositionembeddings bool optional defaults to false whether to use bertstyle absolute position embeddings userelativepositionbias bool optional defaults to false whether to use t5style relative position embeddings in the selfattention layers usesharedrelativepositionbias bool optional defaults to false whether to use the same relative position embeddings across all selfattention layers of the transformer layerscaleinitvalue float optional defaults to 0 1 scale to use in the selfattention layers 0 1 for base 1e5 for large set 0 to disable layer scale droppathrate float optional defaults to 0 1 stochastic depth rate per sample when applied in the main path of residual layers usemeanpooling bool optional defaults to true whether to mean pool the final hidden states of the patches instead of using the final hidden state of the cls token before applying the classification head poolscales tupleint optional defaults to 1 2 3 6 pooling scales used in pooling pyramid module applied on the last feature map useauxiliaryhead bool optional defaults to true whether to use an auxiliary head during training auxiliarylossweight float optional defaults to 0 4 weight of the crossentropy loss of the auxiliary head auxiliarychannels int optional defaults to 256 number of channels to use in the auxiliary head auxiliarynumconvs int optional defaults to 1 number of convolutional layers to use in the auxiliary head auxiliaryconcatinput bool optional defaults to false whether to concatenate the output of the auxiliary head with the input before the classification layer semanticlossignoreindex int optional defaults to 255 the index that is ignored by the loss function of the semantic segmentation model outfeatures liststr optional if used as backbone list of features to output can be any of stem stage1 stage2 etc depending on how many stages the model has if unset and outindices is set will default to the corresponding stages if unset and outindices is unset will default to the last stage outindices listint optional if used as backbone list of indices of features to output can be any of 0 1 2 etc depending on how many stages the model has if unset and outfeatures is set will default to the corresponding stages if unset and outfeatures is unset will default to the last stage addfpn bool optional defaults to false whether to add a fpn as part of the backbone only relevant for beitbackbone reshapehiddenstates bool optional defaults to true whether to reshape the feature maps to 4d tensors of shape batchsize hiddensize height width in case the model is used as backbone if false the feature maps will be 3d tensors of shape batchsize seqlen hiddensize only relevant for beitbackbone example python from transformers import beitconfig beitmodel initializing a beit beitbasepatch16224pt22k style configuration configuration beitconfig initializing a model with random weights from the beitbasepatch16224pt22k style configuration model beitmodelconfiguration accessing the model configuration configuration model config modeltype beit def init self vocabsize8192 hiddensize768 numhiddenlayers12 numattentionheads12 intermediatesize3072 hiddenactgelu hiddendropoutprob0 0 attentionprobsdropoutprob0 0 initializerrange0 02 layernormeps1e12 imagesize224 patchsize16 numchannels3 usemasktokenfalse useabsolutepositionembeddingsfalse userelativepositionbiasfalse usesharedrelativepositionbiasfalse layerscaleinitvalue0 1 droppathrate0 1 usemeanpoolingtrue poolscales1 2 3 6 useauxiliaryheadtrue auxiliarylossweight0 4 auxiliarychannels256 auxiliarynumconvs1 auxiliaryconcatinputfalse semanticlossignoreindex255 outfeaturesnone outindicesnone addfpnfalse reshapehiddenstatestrue kwargs super initkwargs self vocabsize vocabsize self hiddensize hiddensize self numhiddenlayers numhiddenlayers self numattentionheads numattentionheads self intermediatesize intermediatesize self hiddenact hiddenact self hiddendropoutprob hiddendropoutprob self attentionprobsdropoutprob attentionprobsdropoutprob self initializerrange initializerrange self layernormeps layernormeps self imagesize imagesize self patchsize patchsize self numchannels numchannels self usemasktoken usemasktoken self useabsolutepositionembeddings useabsolutepositionembeddings self userelativepositionbias userelativepositionbias self usesharedrelativepositionbias usesharedrelativepositionbias self layerscaleinitvalue layerscaleinitvalue self droppathrate droppathrate self usemeanpooling usemeanpooling decode head attributes semantic segmentation self poolscales poolscales auxiliary head attributes semantic segmentation self useauxiliaryhead useauxiliaryhead self auxiliarylossweight auxiliarylossweight self auxiliarychannels auxiliarychannels self auxiliarynumconvs auxiliarynumconvs self auxiliaryconcatinput auxiliaryconcatinput self semanticlossignoreindex semanticlossignoreindex handle backwards compatibility if segmentationindices in kwargs logger warning the segmentationindices argument is deprecated and will be removed in a future version use outindices instead futurewarning outindices kwargs popsegmentationindices backbone attributes self stagenames stem fstageidx for idx in range1 self numhiddenlayers 1 self outfeatures self outindices getalignedoutputfeaturesoutputindices outfeaturesoutfeatures outindicesoutindices stagenamesself stagenames self addfpn addfpn self reshapehiddenstates reshapehiddenstates copied from transformers models vit configurationvit vitonnxconfig class beitonnxconfigonnxconfig torchonnxminimumversion version parse1 11 property def inputsself mappingstr mappingint str return ordereddict pixelvalues 0 batch 1 numchannels 2 height 3 width property def atolforvalidationself float return 1e4 coding utf 8 microsoft research and the huggingface inc team licensed under the apache license version 2 0 the license you may not use this file except in compliance with the license you may obtain a copy of the license at http www apache org licenses license 2 0 unless required by applicable law or agreed to in writing software distributed under the license is distributed on an as is basis without warranties or conditions of any kind either express or implied see the license for the specific language governing permissions and limitations under the license beit model configuration see all beit models at https huggingface co models filter beit this is the configuration class to store the configuration of a beitmodel it is used to instantiate an beit model according to the specified arguments defining the model architecture instantiating a configuration with the defaults will yield a similar configuration to that of the beit microsoft beit base patch16 224 pt22k https huggingface co microsoft beit base patch16 224 pt22k architecture args vocab_size int optional defaults to 8192 vocabulary size of the beit model defines the number of different image tokens that can be used during pre training hidden_size int optional defaults to 768 dimensionality of the encoder layers and the pooler layer num_hidden_layers int optional defaults to 12 number of hidden layers in the transformer encoder num_attention_heads int optional defaults to 12 number of attention heads for each attention layer in the transformer encoder intermediate_size int optional defaults to 3072 dimensionality of the intermediate i e feed forward layer in the transformer encoder hidden_act str or function optional defaults to gelu the non linear activation function function or string in the encoder and pooler if string gelu relu selu and gelu_new are supported hidden_dropout_prob float optional defaults to 0 0 the dropout probability for all fully connected layers in the embeddings encoder and pooler attention_probs_dropout_prob float optional defaults to 0 0 the dropout ratio for the attention probabilities initializer_range float optional defaults to 0 02 the standard deviation of the truncated_normal_initializer for initializing all weight matrices layer_norm_eps float optional defaults to 1e 12 the epsilon used by the layer normalization layers image_size int optional defaults to 224 the size resolution of each image patch_size int optional defaults to 16 the size resolution of each patch num_channels int optional defaults to 3 the number of input channels use_mask_token bool optional defaults to false whether to use a mask token for masked image modeling use_absolute_position_embeddings bool optional defaults to false whether to use bert style absolute position embeddings use_relative_position_bias bool optional defaults to false whether to use t5 style relative position embeddings in the self attention layers use_shared_relative_position_bias bool optional defaults to false whether to use the same relative position embeddings across all self attention layers of the transformer layer_scale_init_value float optional defaults to 0 1 scale to use in the self attention layers 0 1 for base 1e 5 for large set 0 to disable layer scale drop_path_rate float optional defaults to 0 1 stochastic depth rate per sample when applied in the main path of residual layers use_mean_pooling bool optional defaults to true whether to mean pool the final hidden states of the patches instead of using the final hidden state of the cls token before applying the classification head pool_scales tuple int optional defaults to 1 2 3 6 pooling scales used in pooling pyramid module applied on the last feature map use_auxiliary_head bool optional defaults to true whether to use an auxiliary head during training auxiliary_loss_weight float optional defaults to 0 4 weight of the cross entropy loss of the auxiliary head auxiliary_channels int optional defaults to 256 number of channels to use in the auxiliary head auxiliary_num_convs int optional defaults to 1 number of convolutional layers to use in the auxiliary head auxiliary_concat_input bool optional defaults to false whether to concatenate the output of the auxiliary head with the input before the classification layer semantic_loss_ignore_index int optional defaults to 255 the index that is ignored by the loss function of the semantic segmentation model out_features list str optional if used as backbone list of features to output can be any of stem stage1 stage2 etc depending on how many stages the model has if unset and out_indices is set will default to the corresponding stages if unset and out_indices is unset will default to the last stage out_indices list int optional if used as backbone list of indices of features to output can be any of 0 1 2 etc depending on how many stages the model has if unset and out_features is set will default to the corresponding stages if unset and out_features is unset will default to the last stage add_fpn bool optional defaults to false whether to add a fpn as part of the backbone only relevant for beitbackbone reshape_hidden_states bool optional defaults to true whether to reshape the feature maps to 4d tensors of shape batch_size hidden_size height width in case the model is used as backbone if false the feature maps will be 3d tensors of shape batch_size seq_len hidden_size only relevant for beitbackbone example python from transformers import beitconfig beitmodel initializing a beit beit base patch16 224 pt22k style configuration configuration beitconfig initializing a model with random weights from the beit base patch16 224 pt22k style configuration model beitmodel configuration accessing the model configuration configuration model config decode head attributes semantic segmentation auxiliary head attributes semantic segmentation handle backwards compatibility backbone attributes copied from transformers models vit configuration_vit vitonnxconfig
from collections import OrderedDict
from typing import Mapping

from packaging import version

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices


logger = logging.get_logger(__name__)

BEIT_PRETRAINED_CONFIG_ARCHIVE_MAP = {
    "microsoft/beit-base-patch16-224-pt22k": (
        "https://huggingface.co/microsoft/beit-base-patch16-224-pt22k/resolve/main/config.json"
    ),
    
}


class BeitConfig(BackboneConfigMixin, PretrainedConfig):
    r

    model_type = "beit"

    def __init__(
        self,
        vocab_size=8192,
        hidden_size=768,
        num_hidden_layers=12,
        num_attention_heads=12,
        intermediate_size=3072,
        hidden_act="gelu",
        hidden_dropout_prob=0.0,
        attention_probs_dropout_prob=0.0,
        initializer_range=0.02,
        layer_norm_eps=1e-12,
        image_size=224,
        patch_size=16,
        num_channels=3,
        use_mask_token=False,
        use_absolute_position_embeddings=False,
        use_relative_position_bias=False,
        use_shared_relative_position_bias=False,
        layer_scale_init_value=0.1,
        drop_path_rate=0.1,
        use_mean_pooling=True,
        pool_scales=[1, 2, 3, 6],
        use_auxiliary_head=True,
        auxiliary_loss_weight=0.4,
        auxiliary_channels=256,
        auxiliary_num_convs=1,
        auxiliary_concat_input=False,
        semantic_loss_ignore_index=255,
        out_features=None,
        out_indices=None,
        add_fpn=False,
        reshape_hidden_states=True,
        **kwargs,
    ):
        super().__init__(**kwargs)

        self.vocab_size = vocab_size
        self.hidden_size = hidden_size
        self.num_hidden_layers = num_hidden_layers
        self.num_attention_heads = num_attention_heads
        self.intermediate_size = intermediate_size
        self.hidden_act = hidden_act
        self.hidden_dropout_prob = hidden_dropout_prob
        self.attention_probs_dropout_prob = attention_probs_dropout_prob
        self.initializer_range = initializer_range
        self.layer_norm_eps = layer_norm_eps

        self.image_size = image_size
        self.patch_size = patch_size
        self.num_channels = num_channels
        self.use_mask_token = use_mask_token
        self.use_absolute_position_embeddings = use_absolute_position_embeddings
        self.use_relative_position_bias = use_relative_position_bias
        self.use_shared_relative_position_bias = use_shared_relative_position_bias
        self.layer_scale_init_value = layer_scale_init_value
        self.drop_path_rate = drop_path_rate
        self.use_mean_pooling = use_mean_pooling
        
        self.pool_scales = pool_scales
        
        self.use_auxiliary_head = use_auxiliary_head
        self.auxiliary_loss_weight = auxiliary_loss_weight
        self.auxiliary_channels = auxiliary_channels
        self.auxiliary_num_convs = auxiliary_num_convs
        self.auxiliary_concat_input = auxiliary_concat_input
        self.semantic_loss_ignore_index = semantic_loss_ignore_index

        
        if "segmentation_indices" in kwargs:
            logger.warning(
                "The `segmentation_indices` argument is deprecated and will be removed in a future version, use `out_indices` instead.",
                FutureWarning,
            )
            out_indices = kwargs.pop("segmentation_indices")

        
        self.stage_names = ["stem"] + [f"stage{idx}" for idx in range(1, self.num_hidden_layers + 1)]
        self._out_features, self._out_indices = get_aligned_output_features_output_indices(
            out_features=out_features, out_indices=out_indices, stage_names=self.stage_names
        )
        self.add_fpn = add_fpn
        self.reshape_hidden_states = reshape_hidden_states



class BeitOnnxConfig(OnnxConfig):
    torch_onnx_minimum_version = version.parse("1.11")

    @property
    def inputs(self) -> Mapping[str, Mapping[int, str]]:
        return OrderedDict(
            [
                ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}),
            ]
        )

    @property
    def atol_for_validation(self) -> float:
        return 1e-4