Aluode/PerceptionLabPortable
0
1# coding=utf-82# Copyright 2021 NVIDIA and The HuggingFace Inc. team. All rights reserved.3#4# Licensed under the Apache License, Version 2.0 (the "License");5# you may not use this file except in compliance with the License.6# You may obtain a copy of the License at7#8# http://www.apache.org/licenses/LICENSE-2.09#10# Unless required by applicable law or agreed to in writing, software11# distributed under the License is distributed on an "AS IS" BASIS,12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13# See the License for the specific language governing permissions and14# limitations under the License.15"""SegFormer model configuration"""16 17import warnings18from collections import OrderedDict19from collections.abc import Mapping20 21from packaging import version22 23from ...configuration_utils import PretrainedConfig24from ...onnx import OnnxConfig25from ...utils import logging26 27 28logger = logging.get_logger(__name__)29 30 31class SegformerConfig(PretrainedConfig):32 r"""33 This is the configuration class to store the configuration of a [`SegformerModel`]. It is used to instantiate an34 SegFormer model according to the specified arguments, defining the model architecture. Instantiating a35 configuration with the defaults will yield a similar configuration to that of the SegFormer36 [nvidia/segformer-b0-finetuned-ade-512-512](https://huggingface.co/nvidia/segformer-b0-finetuned-ade-512-512)37 architecture.38 39 Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the40 documentation from [`PretrainedConfig`] for more information.41 42 Args:43 num_channels (`int`, *optional*, defaults to 3):44 The number of input channels.45 num_encoder_blocks (`int`, *optional*, defaults to 4):46 The number of encoder blocks (i.e. stages in the Mix Transformer encoder).47 depths (`list[int]`, *optional*, defaults to `[2, 2, 2, 2]`):48 The number of layers in each encoder block.49 sr_ratios (`list[int]`, *optional*, defaults to `[8, 4, 2, 1]`):50 Sequence reduction ratios in each encoder block.51 hidden_sizes (`list[int]`, *optional*, defaults to `[32, 64, 160, 256]`):52 Dimension of each of the encoder blocks.53 patch_sizes (`list[int]`, *optional*, defaults to `[7, 3, 3, 3]`):54 Patch size before each encoder block.55 strides (`list[int]`, *optional*, defaults to `[4, 2, 2, 2]`):56 Stride before each encoder block.57 num_attention_heads (`list[int]`, *optional*, defaults to `[1, 2, 5, 8]`):58 Number of attention heads for each attention layer in each block of the Transformer encoder.59 mlp_ratios (`list[int]`, *optional*, defaults to `[4, 4, 4, 4]`):60 Ratio of the size of the hidden layer compared to the size of the input layer of the Mix FFNs in the61 encoder blocks.62 hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):63 The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,64 `"relu"`, `"selu"` and `"gelu_new"` are supported.65 hidden_dropout_prob (`float`, *optional*, defaults to 0.0):66 The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.67 attention_probs_dropout_prob (`float`, *optional*, defaults to 0.0):68 The dropout ratio for the attention probabilities.69 classifier_dropout_prob (`float`, *optional*, defaults to 0.1):70 The dropout probability before the classification head.71 initializer_range (`float`, *optional*, defaults to 0.02):72 The standard deviation of the truncated_normal_initializer for initializing all weight matrices.73 drop_path_rate (`float`, *optional*, defaults to 0.1):74 The dropout probability for stochastic depth, used in the blocks of the Transformer encoder.75 layer_norm_eps (`float`, *optional*, defaults to 1e-06):76 The epsilon used by the layer normalization layers.77 decoder_hidden_size (`int`, *optional*, defaults to 256):78 The dimension of the all-MLP decode head.79 semantic_loss_ignore_index (`int`, *optional*, defaults to 255):80 The index that is ignored by the loss function of the semantic segmentation model.81 82 Example:83 84 ```python85 >>> from transformers import SegformerModel, SegformerConfig86 87 >>> # Initializing a SegFormer nvidia/segformer-b0-finetuned-ade-512-512 style configuration88 >>> configuration = SegformerConfig()89 90 >>> # Initializing a model from the nvidia/segformer-b0-finetuned-ade-512-512 style configuration91 >>> model = SegformerModel(configuration)92 93 >>> # Accessing the model configuration94 >>> configuration = model.config95 ```"""96 97 model_type = "segformer"98 99 def __init__(100 self,101 num_channels=3,102 num_encoder_blocks=4,103 depths=[2, 2, 2, 2],104 sr_ratios=[8, 4, 2, 1],105 hidden_sizes=[32, 64, 160, 256],106 patch_sizes=[7, 3, 3, 3],107 strides=[4, 2, 2, 2],108 num_attention_heads=[1, 2, 5, 8],109 mlp_ratios=[4, 4, 4, 4],110 hidden_act="gelu",111 hidden_dropout_prob=0.0,112 attention_probs_dropout_prob=0.0,113 classifier_dropout_prob=0.1,114 initializer_range=0.02,115 drop_path_rate=0.1,116 layer_norm_eps=1e-6,117 decoder_hidden_size=256,118 semantic_loss_ignore_index=255,119 **kwargs,120 ):121 super().__init__(**kwargs)122 123 if "reshape_last_stage" in kwargs and kwargs["reshape_last_stage"] is False:124 warnings.warn(125 "Reshape_last_stage is set to False in this config. This argument is deprecated and will soon be"126 " removed, as the behaviour will default to that of reshape_last_stage = True.",127 FutureWarning,128 )129 130 self.num_channels = num_channels131 self.num_encoder_blocks = num_encoder_blocks132 self.depths = depths133 self.sr_ratios = sr_ratios134 self.hidden_sizes = hidden_sizes135 self.patch_sizes = patch_sizes136 self.strides = strides137 self.mlp_ratios = mlp_ratios138 self.num_attention_heads = num_attention_heads139 self.hidden_act = hidden_act140 self.hidden_dropout_prob = hidden_dropout_prob141 self.attention_probs_dropout_prob = attention_probs_dropout_prob142 self.classifier_dropout_prob = classifier_dropout_prob143 self.initializer_range = initializer_range144 self.drop_path_rate = drop_path_rate145 self.layer_norm_eps = layer_norm_eps146 self.decoder_hidden_size = decoder_hidden_size147 self.reshape_last_stage = kwargs.get("reshape_last_stage", True)148 self.semantic_loss_ignore_index = semantic_loss_ignore_index149 150 151class SegformerOnnxConfig(OnnxConfig):152 torch_onnx_minimum_version = version.parse("1.11")153 154 @property155 def inputs(self) -> Mapping[str, Mapping[int, str]]:156 return OrderedDict(157 [158 ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}),159 ]160 )161 162 @property163 def atol_for_validation(self) -> float:164 return 1e-4165 166 @property167 def default_onnx_opset(self) -> int:168 return 12169 170 171__all__ = ["SegformerConfig", "SegformerOnnxConfig"]172 