
# Copyright 2023 The HuggingFace Team. All rights reserved.
#
# 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.
from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available


UpperCAmelCase__		:     Union[str, Any]     			=      {"configuration_timm_backbone": ["TimmBackboneConfig"]}


try:
   if not is_torch_available():
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   pass
else:
   UpperCAmelCase__		:     Tuple     			=      ["TimmBackbone"]


if TYPE_CHECKING:
   from .configuration_timm_backbone import TimmBackboneConfig

   try:
      if not is_torch_available():
         raise OptionalDependencyNotAvailable()
   except OptionalDependencyNotAvailable:
      pass
   else:
      from .modeling_timm_backbone import TimmBackbone

else:
   import sys

   UpperCAmelCase__		:     List[Any]     			=      _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)











import copy
from typing import Dict, Optional

from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ..auto import CONFIG_MAPPING
from ..detr import DetrConfig
from ..swin import SwinConfig


a		:       Optional[Any]			     = {
    "facebook/maskformer-swin-base-ade": (
        "https://huggingface.co/facebook/maskformer-swin-base-ade/blob/main/config.json"
    )
    # See all MaskFormer models at https://huggingface.co/models?filter=maskformer
}

a		:       Optional[Any]			     = logging.get_logger(__name__)
class     a    ( lowercase__   ):



      """simple docstring"""


      a  : str							       =	'maskformer'
      a  : Dict							       =	{'hidden_size': 'mask_feature_size'}
      a  : Optional[Any]							       =	['resnet', 'swin']
      a  : List[Any]							       =	['detr']
      def __init__(      self					:			Optional[int]		,      __lowercase					:			int = 256		,      __lowercase					:			int = 256		,      __lowercase					:			float = 0.1		,      __lowercase					:			bool = False		,      __lowercase					:			Optional[Dict] = None		,      __lowercase					:			Optional[Dict] = None		,      __lowercase					:			float = 0.02		,      __lowercase					:			float = 1.0		,      __lowercase					:			float = 1.0		,      __lowercase					:			float = 1.0		,      __lowercase					:			float = 20.0		,      __lowercase					:			Optional[bool] = None		,      **__lowercase					:			Tuple		,      )							->      str:
        if backbone_config is None:
          # fall back to https://huggingface.co/microsoft/swin-base-patch4-window12-384-in22k
          __UpperCAmelCase							:	List[str]           =  SwinConfig(
              image_size=384		,      in_channels=3		,      patch_size=4		,      embed_dim=128		,      depths=[2, 2, 18, 2]		,      num_heads=[4, 8, 16, 32]		,      window_size=12		,      drop_path_rate=0.3		,      out_features=["""stage1""", """stage2""", """stage3""", """stage4"""]		,      )

        if isinstance(__lowercase		,      __lowercase					):
          __UpperCAmelCase							:	Dict           =  backbone_config.pop("""model_type"""					)
          __UpperCAmelCase							:	Tuple           =  CONFIG_MAPPING[backbone_model_type]
          __UpperCAmelCase							:	List[str]           =  config_class.from_dict(__lowercase					)

        # verify that the backbone is supported
        if backbone_config.model_type not in self.backbones_supported:
          logger.warning_once(
              f"""Backbone {backbone_config.model_type} is not a supported model and may not be compatible with MaskFormer. """
              f"""Supported model types: {",".join(self.backbones_supported					)}"""					)

        if decoder_config is None:
          # fall back to https://huggingface.co/facebook/detr-resnet-50
          __UpperCAmelCase							:	List[Any]           =  DetrConfig()
        else:
          # verify that the decoder is supported
          __UpperCAmelCase							:	List[Any]           =  (
              decoder_config.pop("""model_type"""					) if isinstance(__lowercase		,      __lowercase					) else decoder_config.model_type
          )
          if decoder_type not in self.decoders_supported:
            raise ValueError(
                f"""Transformer Decoder {decoder_type} not supported, please use one of"""
                f""" {",".join(self.decoders_supported					)}"""					)
          if isinstance(__lowercase		,      __lowercase					):
            __UpperCAmelCase							:	Dict           =  CONFIG_MAPPING[decoder_type]
            __UpperCAmelCase							:	Union[str, Any]           =  config_class.from_dict(__lowercase					)

        __UpperCAmelCase							:	Optional[Any]           =  backbone_config
        __UpperCAmelCase							:	List[str]           =  decoder_config
        # main feature dimension for the model
        __UpperCAmelCase							:	Union[str, Any]           =  fpn_feature_size
        __UpperCAmelCase							:	Optional[Any]           =  mask_feature_size
        # initializer
        __UpperCAmelCase							:	int           =  init_std
        __UpperCAmelCase							:	Any           =  init_xavier_std
        # Hungarian matcher && loss
        __UpperCAmelCase							:	Any           =  cross_entropy_weight
        __UpperCAmelCase							:	Optional[Any]           =  dice_weight
        __UpperCAmelCase							:	List[str]           =  mask_weight
        __UpperCAmelCase							:	Union[str, Any]           =  use_auxiliary_loss
        __UpperCAmelCase							:	int           =  no_object_weight
        __UpperCAmelCase							:	int           =  output_auxiliary_logits

        __UpperCAmelCase							:	Optional[Any]           =  self.decoder_config.encoder_attention_heads
        __UpperCAmelCase							:	Dict           =  self.decoder_config.num_hidden_layers
        super().__init__(**__lowercase					)
      @classmethod
      def 	UpperCAmelCase      (      cls					:			int		,      __lowercase					:			PretrainedConfig		,      __lowercase					:			PretrainedConfig		,      **__lowercase					:			str					)							->      Tuple:
        return cls(
            backbone_config=__lowercase		,      decoder_config=__lowercase		,      **__lowercase		,      )




      def 	UpperCAmelCase      (      self					:			List[Any]					)							->      Dict[str, any]:
        __UpperCAmelCase							:	Optional[Any]           =  copy.deepcopy(self.__dict__					)
        __UpperCAmelCase							:	Optional[int]           =  self.backbone_config.to_dict()
        __UpperCAmelCase							:	Any           =  self.decoder_config.to_dict()
        __UpperCAmelCase							:	Tuple           =  self.__class__.model_type
        return output


