codingutf8 2023 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 mobilevitv2 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 mobilevitv2pretrainedconfigarchivemap applemobilevitv21 0 https huggingface coapplemobilevitv21 0resolvemainconfig json class mobilevitv2configpretrainedconfig r this is the configuration class to store the configuration of a mobilevitv2model it is used to instantiate a mobilevitv2 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 mobilevitv2 applemobilevitv21 0https huggingface coapplemobilevitv21 0 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 expandratio float optional defaults to 2 0 expansion factor for the mobilenetv2 layers hiddenact str or function optional defaults to swish 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 mobilevitv2 layer outputstride int optional defaults to 32 the ratio of the spatial resolution of the output to the resolution of the input image 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 asppoutchannels int optional defaults to 512 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 nattnblocks listint optional defaults to 2 4 3 the number of attention blocks in each mobilevitv2layer baseattnunitdims listint optional defaults to 128 192 256 the base multiplier for dimensions of attention blocks in each mobilevitv2layer widthmultiplier float optional defaults to 1 0 the width multiplier for mobilevitv2 ffnmultiplier int optional defaults to 2 the ffn multiplier for mobilevitv2 attndropout float optional defaults to 0 0 the dropout in the attention layer ffndropout float optional defaults to 0 0 the dropout between ffn layers example python from transformers import mobilevitv2config mobilevitv2model initializing a mobilevitv2small style configuration configuration mobilevitv2config initializing a model from the mobilevitv2small style configuration model mobilevitv2modelconfiguration accessing the model configuration configuration model config modeltype mobilevitv2 def init self numchannels3 imagesize256 patchsize2 expandratio2 0 hiddenactswish convkernelsize3 outputstride32 classifierdropoutprob0 1 initializerrange0 02 layernormeps1e5 asppoutchannels512 atrousrates6 12 18 asppdropoutprob0 1 semanticlossignoreindex255 nattnblocks2 4 3 baseattnunitdims128 192 256 widthmultiplier1 0 ffnmultiplier2 attndropout0 0 ffndropout0 0 kwargs super initkwargs self numchannels numchannels self imagesize imagesize self patchsize patchsize self expandratio expandratio self hiddenact hiddenact self convkernelsize convkernelsize self outputstride outputstride self initializerrange initializerrange self layernormeps layernormeps self nattnblocks nattnblocks self baseattnunitdims baseattnunitdims self widthmultiplier widthmultiplier self ffnmultiplier ffnmultiplier self ffndropout ffndropout self attndropout attndropout self classifierdropoutprob classifierdropoutprob decode head attributes for semantic segmentation self asppoutchannels asppoutchannels self atrousrates atrousrates self asppdropoutprob asppdropoutprob self semanticlossignoreindex semanticlossignoreindex class mobilevitv2onnxconfigonnxconfig 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 2023 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 mobilevitv2 model configuration this is the configuration class to store the configuration of a mobilevitv2model it is used to instantiate a mobilevitv2 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 mobilevitv2 apple mobilevitv2 1 0 https huggingface co apple mobilevitv2 1 0 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 expand_ratio float optional defaults to 2 0 expansion factor for the mobilenetv2 layers hidden_act str or function optional defaults to swish 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 mobilevitv2 layer output_stride int optional defaults to 32 the ratio of the spatial resolution of the output to the resolution of the input image 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 aspp_out_channels int optional defaults to 512 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 n_attn_blocks list int optional defaults to 2 4 3 the number of attention blocks in each mobilevitv2layer base_attn_unit_dims list int optional defaults to 128 192 256 the base multiplier for dimensions of attention blocks in each mobilevitv2layer width_multiplier float optional defaults to 1 0 the width multiplier for mobilevitv2 ffn_multiplier int optional defaults to 2 the ffn multiplier for mobilevitv2 attn_dropout float optional defaults to 0 0 the dropout in the attention layer ffn_dropout float optional defaults to 0 0 the dropout between ffn layers example python from transformers import mobilevitv2config mobilevitv2model initializing a mobilevitv2 small style configuration configuration mobilevitv2config initializing a model from the mobilevitv2 small style configuration model mobilevitv2model 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__)

MOBILEVITV2_PRETRAINED_CONFIG_ARCHIVE_MAP = {
    "apple/mobilevitv2-1.0": "https://huggingface.co/apple/mobilevitv2-1.0/resolve/main/config.json",
}


class MobileViTV2Config(PretrainedConfig):
    r

    model_type = "mobilevitv2"

    def __init__(
        self,
        num_channels=3,
        image_size=256,
        patch_size=2,
        expand_ratio=2.0,
        hidden_act="swish",
        conv_kernel_size=3,
        output_stride=32,
        classifier_dropout_prob=0.1,
        initializer_range=0.02,
        layer_norm_eps=1e-5,
        aspp_out_channels=512,
        atrous_rates=[6, 12, 18],
        aspp_dropout_prob=0.1,
        semantic_loss_ignore_index=255,
        n_attn_blocks=[2, 4, 3],
        base_attn_unit_dims=[128, 192, 256],
        width_multiplier=1.0,
        ffn_multiplier=2,
        attn_dropout=0.0,
        ffn_dropout=0.0,
        **kwargs,
    ):
        super().__init__(**kwargs)

        self.num_channels = num_channels
        self.image_size = image_size
        self.patch_size = patch_size
        self.expand_ratio = expand_ratio
        self.hidden_act = hidden_act
        self.conv_kernel_size = conv_kernel_size
        self.output_stride = output_stride
        self.initializer_range = initializer_range
        self.layer_norm_eps = layer_norm_eps
        self.n_attn_blocks = n_attn_blocks
        self.base_attn_unit_dims = base_attn_unit_dims
        self.width_multiplier = width_multiplier
        self.ffn_multiplier = ffn_multiplier
        self.ffn_dropout = ffn_dropout
        self.attn_dropout = attn_dropout
        self.classifier_dropout_prob = classifier_dropout_prob

        
        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 MobileViTV2OnnxConfig(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