codingutf8 2022 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 mobilevit 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 logger logging getloggername mobilevitpretrainedconfigarchivemap applemobilevitsmall https huggingface coapplemobilevitsmallresolvemainconfig json applemobilevitxsmall https huggingface coapplemobilevitxsmallresolvemainconfig json applemobilevitxxsmall https huggingface coapplemobilevitxxsmallresolvemainconfig json appledeeplabv3mobilevitsmall https huggingface coappledeeplabv3mobilevitsmallresolvemainconfig json appledeeplabv3mobilevitxsmall https huggingface coappledeeplabv3mobilevitxsmallresolvemainconfig json appledeeplabv3mobilevitxxsmall https huggingface coappledeeplabv3mobilevitxxsmallresolvemainconfig json see all mobilevit models at https huggingface comodels filtermobilevit class mobilevitconfigpretrainedconfig r this is the configuration class to store the configuration of a mobilevitmodel it is used to instantiate a mobilevit 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 mobilevit applemobilevitsmallhttps huggingface coapplemobilevitsmall architecture configuration objects inherit from pretrainedconfig and can be used to control the model outputs read the documentation from pretrainedconfig for more information args numchannels int optional defaults to 3 the number of input channels imagesize int optional defaults to 256 the size resolution of each image patchsize int optional defaults to 2 the size resolution of each patch hiddensizes listint optional defaults to 144 192 240 dimensionality hidden size of the transformer encoders at each stage neckhiddensizes listint optional defaults to 16 32 64 96 128 160 640 the number of channels for the feature maps of the backbone numattentionheads int optional defaults to 4 number of attention heads for each attention layer in the transformer encoder mlpratio float optional defaults to 2 0 the ratio of the number of channels in the output of the mlp to the number of channels in the input expandratio float optional defaults to 4 0 expansion factor for the mobilenetv2 layers hiddenact str or function optional defaults to silu the nonlinear activation function function or string in the transformer encoder and convolution layers convkernelsize int optional defaults to 3 the size of the convolutional kernel in the mobilevit layer outputstride int optional defaults to 32 the ratio of the spatial resolution of the output to the resolution of the input image hiddendropoutprob float optional defaults to 0 1 the dropout probabilitiy for all fully connected layers in the transformer encoder attentionprobsdropoutprob float optional defaults to 0 0 the dropout ratio for the attention probabilities classifierdropoutprob float optional defaults to 0 1 the dropout ratio for attached classifiers initializerrange float optional defaults to 0 02 the standard deviation of the truncatednormalinitializer for initializing all weight matrices layernormeps float optional defaults to 1e05 the epsilon used by the layer normalization layers qkvbias bool optional defaults to true whether to add a bias to the queries keys and values asppoutchannels int optional defaults to 256 number of output channels used in the aspp layer for semantic segmentation atrousrates listint optional defaults to 6 12 18 dilation atrous factors used in the aspp layer for semantic segmentation asppdropoutprob float optional defaults to 0 1 the dropout ratio for the aspp layer for semantic segmentation semanticlossignoreindex int optional defaults to 255 the index that is ignored by the loss function of the semantic segmentation model example python from transformers import mobilevitconfig mobilevitmodel initializing a mobilevitsmall style configuration configuration mobilevitconfig initializing a model from the mobilevitsmall style configuration model mobilevitmodelconfiguration accessing the model configuration configuration model config modeltype mobilevit def init self numchannels3 imagesize256 patchsize2 hiddensizes144 192 240 neckhiddensizes16 32 64 96 128 160 640 numattentionheads4 mlpratio2 0 expandratio4 0 hiddenactsilu convkernelsize3 outputstride32 hiddendropoutprob0 1 attentionprobsdropoutprob0 0 classifierdropoutprob0 1 initializerrange0 02 layernormeps1e5 qkvbiastrue asppoutchannels256 atrousrates6 12 18 asppdropoutprob0 1 semanticlossignoreindex255 kwargs super initkwargs self numchannels numchannels self imagesize imagesize self patchsize patchsize self hiddensizes hiddensizes self neckhiddensizes neckhiddensizes self numattentionheads numattentionheads self mlpratio mlpratio self expandratio expandratio self hiddenact hiddenact self convkernelsize convkernelsize self outputstride outputstride self hiddendropoutprob hiddendropoutprob self attentionprobsdropoutprob attentionprobsdropoutprob self classifierdropoutprob classifierdropoutprob self initializerrange initializerrange self layernormeps layernormeps self qkvbias qkvbias decode head attributes for semantic segmentation self asppoutchannels asppoutchannels self atrousrates atrousrates self asppdropoutprob asppdropoutprob self semanticlossignoreindex semanticlossignoreindex class mobilevitonnxconfigonnxconfig torchonnxminimumversion version parse1 11 property def inputsself mappingstr mappingint str return ordereddictpixelvalues 0 batch 1 numchannels 2 height 3 width property def outputsself mappingstr mappingint str if self task imageclassification return ordereddictlogits 0 batch else return ordereddictlasthiddenstate 0 batch pooleroutput 0 batch property def atolforvalidationself float return 1e4 coding utf 8 2022 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 mobilevit model configuration see all mobilevit models at https huggingface co models filter mobilevit this is the configuration class to store the configuration of a mobilevitmodel it is used to instantiate a mobilevit 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 mobilevit apple mobilevit small https huggingface co apple mobilevit small architecture configuration objects inherit from pretrainedconfig and can be used to control the model outputs read the documentation from pretrainedconfig for more information args num_channels int optional defaults to 3 the number of input channels image_size int optional defaults to 256 the size resolution of each image patch_size int optional defaults to 2 the size resolution of each patch hidden_sizes list int optional defaults to 144 192 240 dimensionality hidden size of the transformer encoders at each stage neck_hidden_sizes list int optional defaults to 16 32 64 96 128 160 640 the number of channels for the feature maps of the backbone num_attention_heads int optional defaults to 4 number of attention heads for each attention layer in the transformer encoder mlp_ratio float optional defaults to 2 0 the ratio of the number of channels in the output of the mlp to the number of channels in the input expand_ratio float optional defaults to 4 0 expansion factor for the mobilenetv2 layers hidden_act str or function optional defaults to silu the non linear activation function function or string in the transformer encoder and convolution layers conv_kernel_size int optional defaults to 3 the size of the convolutional kernel in the mobilevit layer output_stride int optional defaults to 32 the ratio of the spatial resolution of the output to the resolution of the input image hidden_dropout_prob float optional defaults to 0 1 the dropout probabilitiy for all fully connected layers in the transformer encoder attention_probs_dropout_prob float optional defaults to 0 0 the dropout ratio for the attention probabilities classifier_dropout_prob float optional defaults to 0 1 the dropout ratio for attached classifiers 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 05 the epsilon used by the layer normalization layers qkv_bias bool optional defaults to true whether to add a bias to the queries keys and values aspp_out_channels int optional defaults to 256 number of output channels used in the aspp layer for semantic segmentation atrous_rates list int optional defaults to 6 12 18 dilation atrous factors used in the aspp layer for semantic segmentation aspp_dropout_prob float optional defaults to 0 1 the dropout ratio for the aspp layer for semantic segmentation semantic_loss_ignore_index int optional defaults to 255 the index that is ignored by the loss function of the semantic segmentation model example python from transformers import mobilevitconfig mobilevitmodel initializing a mobilevit small style configuration configuration mobilevitconfig initializing a model from the mobilevit small style configuration model mobilevitmodel configuration accessing the model configuration configuration model config decode head attributes for semantic segmentation
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


logger = logging.get_logger(__name__)

MOBILEVIT_PRETRAINED_CONFIG_ARCHIVE_MAP = {
    "apple/mobilevit-small": "https://huggingface.co/apple/mobilevit-small/resolve/main/config.json",
    "apple/mobilevit-x-small": "https://huggingface.co/apple/mobilevit-x-small/resolve/main/config.json",
    "apple/mobilevit-xx-small": "https://huggingface.co/apple/mobilevit-xx-small/resolve/main/config.json",
    "apple/deeplabv3-mobilevit-small": (
        "https://huggingface.co/apple/deeplabv3-mobilevit-small/resolve/main/config.json"
    ),
    "apple/deeplabv3-mobilevit-x-small": (
        "https://huggingface.co/apple/deeplabv3-mobilevit-x-small/resolve/main/config.json"
    ),
    "apple/deeplabv3-mobilevit-xx-small": (
        "https://huggingface.co/apple/deeplabv3-mobilevit-xx-small/resolve/main/config.json"
    ),
    
}


class MobileViTConfig(PretrainedConfig):
    r

    model_type = "mobilevit"

    def __init__(
        self,
        num_channels=3,
        image_size=256,
        patch_size=2,
        hidden_sizes=[144, 192, 240],
        neck_hidden_sizes=[16, 32, 64, 96, 128, 160, 640],
        num_attention_heads=4,
        mlp_ratio=2.0,
        expand_ratio=4.0,
        hidden_act="silu",
        conv_kernel_size=3,
        output_stride=32,
        hidden_dropout_prob=0.1,
        attention_probs_dropout_prob=0.0,
        classifier_dropout_prob=0.1,
        initializer_range=0.02,
        layer_norm_eps=1e-5,
        qkv_bias=True,
        aspp_out_channels=256,
        atrous_rates=[6, 12, 18],
        aspp_dropout_prob=0.1,
        semantic_loss_ignore_index=255,
        **kwargs,
    ):
        super().__init__(**kwargs)

        self.num_channels = num_channels
        self.image_size = image_size
        self.patch_size = patch_size
        self.hidden_sizes = hidden_sizes
        self.neck_hidden_sizes = neck_hidden_sizes
        self.num_attention_heads = num_attention_heads
        self.mlp_ratio = mlp_ratio
        self.expand_ratio = expand_ratio
        self.hidden_act = hidden_act
        self.conv_kernel_size = conv_kernel_size
        self.output_stride = output_stride
        self.hidden_dropout_prob = hidden_dropout_prob
        self.attention_probs_dropout_prob = attention_probs_dropout_prob
        self.classifier_dropout_prob = classifier_dropout_prob
        self.initializer_range = initializer_range
        self.layer_norm_eps = layer_norm_eps
        self.qkv_bias = qkv_bias

        
        self.aspp_out_channels = aspp_out_channels
        self.atrous_rates = atrous_rates
        self.aspp_dropout_prob = aspp_dropout_prob
        self.semantic_loss_ignore_index = semantic_loss_ignore_index


class MobileViTOnnxConfig(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 outputs(self) -> Mapping[str, Mapping[int, str]]:
        if self.task == "image-classification":
            return OrderedDict([("logits", {0: "batch"})])
        else:
            return OrderedDict([("last_hidden_state", {0: "batch"}), ("pooler_output", {0: "batch"})])

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