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 swin transformer 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 swinpretrainedconfigarchivemap microsoftswintinypatch4window7224 https huggingface comicrosoftswintinypatch4window7224resolvemainconfig json see all swin models at https huggingface comodels filterswin class swinconfigbackboneconfigmixin pretrainedconfig r this is the configuration class to store the configuration of a swinmodel it is used to instantiate a swin 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 swin microsoftswintinypatch4window7224https huggingface comicrosoftswintinypatch4window7224 architecture configuration objects inherit from pretrainedconfig and can be used to control the model outputs read the documentation from pretrainedconfig for more information args imagesize int optional defaults to 224 the size resolution of each image patchsize int optional defaults to 4 the size resolution of each patch numchannels int optional defaults to 3 the number of input channels embeddim int optional defaults to 96 dimensionality of patch embedding depths listint optional defaults to 2 2 6 2 depth of each layer in the transformer encoder numheads listint optional defaults to 3 6 12 24 number of attention heads in each layer of the transformer encoder windowsize int optional defaults to 7 size of windows mlpratio float optional defaults to 4 0 ratio of mlp hidden dimensionality to embedding dimensionality qkvbias bool optional defaults to true whether or not a learnable bias should be added to the queries keys and values hiddendropoutprob float optional defaults to 0 0 the dropout probability for all fully connected layers in the embeddings and encoder attentionprobsdropoutprob float optional defaults to 0 0 the dropout ratio for the attention probabilities droppathrate float optional defaults to 0 1 stochastic depth rate hiddenact str or function optional defaults to gelu the nonlinear activation function function or string in the encoder if string gelu relu selu and gelunew are supported useabsoluteembeddings bool optional defaults to false whether or not to add absolute position embeddings to the patch embeddings 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 encoderstride int optional defaults to 32 factor to increase the spatial resolution by in the decoder head for masked image modeling 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 example python from transformers import swinconfig swinmodel initializing a swin microsoftswintinypatch4window7224 style configuration configuration swinconfig initializing a model with random weights from the microsoftswintinypatch4window7224 style configuration model swinmodelconfiguration accessing the model configuration configuration model config modeltype swin attributemap numattentionheads numheads numhiddenlayers numlayers def init self imagesize224 patchsize4 numchannels3 embeddim96 depths2 2 6 2 numheads3 6 12 24 windowsize7 mlpratio4 0 qkvbiastrue hiddendropoutprob0 0 attentionprobsdropoutprob0 0 droppathrate0 1 hiddenactgelu useabsoluteembeddingsfalse initializerrange0 02 layernormeps1e5 encoderstride32 outfeaturesnone outindicesnone kwargs super initkwargs self imagesize imagesize self patchsize patchsize self numchannels numchannels self embeddim embeddim self depths depths self numlayers lendepths self numheads numheads self windowsize windowsize self mlpratio mlpratio self qkvbias qkvbias self hiddendropoutprob hiddendropoutprob self attentionprobsdropoutprob attentionprobsdropoutprob self droppathrate droppathrate self hiddenact hiddenact self useabsoluteembeddings useabsoluteembeddings self layernormeps layernormeps self initializerrange initializerrange self encoderstride encoderstride we set the hiddensize attribute in order to make swin work with visionencoderdecodermodel this indicates the channel dimension after the last stage of the model self hiddensize intembeddim 2 lendepths 1 self stagenames stem fstageidx for idx in range1 lendepths 1 self outfeatures self outindices getalignedoutputfeaturesoutputindices outfeaturesoutfeatures outindicesoutindices stagenamesself stagenames class swinonnxconfigonnxconfig 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 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 swin transformer model configuration see all swin models at https huggingface co models filter swin this is the configuration class to store the configuration of a swinmodel it is used to instantiate a swin 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 swin microsoft swin tiny patch4 window7 224 https huggingface co microsoft swin tiny patch4 window7 224 architecture configuration objects inherit from pretrainedconfig and can be used to control the model outputs read the documentation from pretrainedconfig for more information args image_size int optional defaults to 224 the size resolution of each image patch_size int optional defaults to 4 the size resolution of each patch num_channels int optional defaults to 3 the number of input channels embed_dim int optional defaults to 96 dimensionality of patch embedding depths list int optional defaults to 2 2 6 2 depth of each layer in the transformer encoder num_heads list int optional defaults to 3 6 12 24 number of attention heads in each layer of the transformer encoder window_size int optional defaults to 7 size of windows mlp_ratio float optional defaults to 4 0 ratio of mlp hidden dimensionality to embedding dimensionality qkv_bias bool optional defaults to true whether or not a learnable bias should be added to the queries keys and values hidden_dropout_prob float optional defaults to 0 0 the dropout probability for all fully connected layers in the embeddings and encoder attention_probs_dropout_prob float optional defaults to 0 0 the dropout ratio for the attention probabilities drop_path_rate float optional defaults to 0 1 stochastic depth rate hidden_act str or function optional defaults to gelu the non linear activation function function or string in the encoder if string gelu relu selu and gelu_new are supported use_absolute_embeddings bool optional defaults to false whether or not to add absolute position embeddings to the patch embeddings 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 encoder_stride int optional defaults to 32 factor to increase the spatial resolution by in the decoder head for masked image modeling 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 example python from transformers import swinconfig swinmodel initializing a swin microsoft swin tiny patch4 window7 224 style configuration configuration swinconfig initializing a model with random weights from the microsoft swin tiny patch4 window7 224 style configuration model swinmodel configuration accessing the model configuration configuration model config we set the hidden_size attribute in order to make swin work with visionencoderdecodermodel this indicates the channel dimension after the last stage of the model
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__)

SWIN_PRETRAINED_CONFIG_ARCHIVE_MAP = {
    "microsoft/swin-tiny-patch4-window7-224": (
        "https://huggingface.co/microsoft/swin-tiny-patch4-window7-224/resolve/main/config.json"
    ),
    
}


class SwinConfig(BackboneConfigMixin, PretrainedConfig):
    r

    model_type = "swin"

    attribute_map = {
        "num_attention_heads": "num_heads",
        "num_hidden_layers": "num_layers",
    }

    def __init__(
        self,
        image_size=224,
        patch_size=4,
        num_channels=3,
        embed_dim=96,
        depths=[2, 2, 6, 2],
        num_heads=[3, 6, 12, 24],
        window_size=7,
        mlp_ratio=4.0,
        qkv_bias=True,
        hidden_dropout_prob=0.0,
        attention_probs_dropout_prob=0.0,
        drop_path_rate=0.1,
        hidden_act="gelu",
        use_absolute_embeddings=False,
        initializer_range=0.02,
        layer_norm_eps=1e-5,
        encoder_stride=32,
        out_features=None,
        out_indices=None,
        **kwargs,
    ):
        super().__init__(**kwargs)

        self.image_size = image_size
        self.patch_size = patch_size
        self.num_channels = num_channels
        self.embed_dim = embed_dim
        self.depths = depths
        self.num_layers = len(depths)
        self.num_heads = num_heads
        self.window_size = window_size
        self.mlp_ratio = mlp_ratio
        self.qkv_bias = qkv_bias
        self.hidden_dropout_prob = hidden_dropout_prob
        self.attention_probs_dropout_prob = attention_probs_dropout_prob
        self.drop_path_rate = drop_path_rate
        self.hidden_act = hidden_act
        self.use_absolute_embeddings = use_absolute_embeddings
        self.layer_norm_eps = layer_norm_eps
        self.initializer_range = initializer_range
        self.encoder_stride = encoder_stride
        
        
        self.hidden_size = int(embed_dim * 2 ** (len(depths) - 1))
        self.stage_names = ["stem"] + [f"stage{idx}" for idx in range(1, len(depths) + 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
        )


class SwinOnnxConfig(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