


import argparse
import json
from pathlib import Path

import requests
import timm
import torch
from huggingface_hub import hf_hub_download
from PIL import Image

from transformers import DeiTConfig, DeiTForImageClassificationWithTeacher, DeiTImageProcessor
from transformers.utils import logging


logging.set_verbosity_info()
UpperCAmelCase_				:			Optional[Any]   =	logging.get_logger(__name__)







def 	SCREAMING_SNAKE_CASE_						(      __A			:      str  ,   __A			:      List[str]=False    )     ->		str:

       """simple docstring"""

       a_ :		Union[str, Any]							=  []
       for i in range(config.num_hidden_layers    ):
              # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms
              rename_keys.append((F"""blocks.{i}.norm1.weight""", F"""deit.encoder.layer.{i}.layernorm_before.weight""")    )
              rename_keys.append((F"""blocks.{i}.norm1.bias""", F"""deit.encoder.layer.{i}.layernorm_before.bias""")    )
              rename_keys.append((F"""blocks.{i}.attn.proj.weight""", F"""deit.encoder.layer.{i}.attention.output.dense.weight""")    )
              rename_keys.append((F"""blocks.{i}.attn.proj.bias""", F"""deit.encoder.layer.{i}.attention.output.dense.bias""")    )
              rename_keys.append((F"""blocks.{i}.norm2.weight""", F"""deit.encoder.layer.{i}.layernorm_after.weight""")    )
              rename_keys.append((F"""blocks.{i}.norm2.bias""", F"""deit.encoder.layer.{i}.layernorm_after.bias""")    )
              rename_keys.append((F"""blocks.{i}.mlp.fc1.weight""", F"""deit.encoder.layer.{i}.intermediate.dense.weight""")    )
              rename_keys.append((F"""blocks.{i}.mlp.fc1.bias""", F"""deit.encoder.layer.{i}.intermediate.dense.bias""")    )
              rename_keys.append((F"""blocks.{i}.mlp.fc2.weight""", F"""deit.encoder.layer.{i}.output.dense.weight""")    )
              rename_keys.append((F"""blocks.{i}.mlp.fc2.bias""", F"""deit.encoder.layer.{i}.output.dense.bias""")    )

       # projection layer + position embeddings
       rename_keys.extend(
           [
               ('cls_token', 'deit.embeddings.cls_token'),
               ('dist_token', 'deit.embeddings.distillation_token'),
               ('patch_embed.proj.weight', 'deit.embeddings.patch_embeddings.projection.weight'),
               ('patch_embed.proj.bias', 'deit.embeddings.patch_embeddings.projection.bias'),
               ('pos_embed', 'deit.embeddings.position_embeddings'),
           ]    )

       if base_model:
              # layernorm + pooler
              rename_keys.extend(
                  [
                      ('norm.weight', 'layernorm.weight'),
                      ('norm.bias', 'layernorm.bias'),
                      ('pre_logits.fc.weight', 'pooler.dense.weight'),
                      ('pre_logits.fc.bias', 'pooler.dense.bias'),
                  ]    )

              # if just the base model, we should remove "deit" from all keys that start with "deit"
              a_ :		List[str]							=  [(pair[0], pair[1][4:]) if pair[1].startswith('deit'    ) else pair for pair in rename_keys]
       else:
              # layernorm + classification heads
              rename_keys.extend(
                  [
                      ('norm.weight', 'deit.layernorm.weight'),
                      ('norm.bias', 'deit.layernorm.bias'),
                      ('head.weight', 'cls_classifier.weight'),
                      ('head.bias', 'cls_classifier.bias'),
                      ('head_dist.weight', 'distillation_classifier.weight'),
                      ('head_dist.bias', 'distillation_classifier.bias'),
                  ]    )

       return rename_keys







def 	SCREAMING_SNAKE_CASE_						(      __A			:      str  ,   __A			:      Optional[int]  ,   __A			:      List[str]=False    )     ->		Optional[Any]:

       """simple docstring"""

       for i in range(config.num_hidden_layers    ):
              if base_model:
                     a_ :		Any							=  ''
              else:
                     a_ :		List[Any]							=  'deit.'
              # read in weights + bias of input projection layer (in timm, this is a single matrix + bias)
              a_ :		int							=  state_dict.pop(F"""blocks.{i}.attn.qkv.weight"""    )
              a_ :		Dict							=  state_dict.pop(F"""blocks.{i}.attn.qkv.bias"""    )
              # next, add query, keys and values (in that order) to the state dict
              a_ :		List[str]							=  in_proj_weight[
                  : config.hidden_size, :
              ]
              a_ :		Union[str, Any]							=  in_proj_bias[: config.hidden_size]
              a_ :		Optional[int]							=  in_proj_weight[
                  config.hidden_size : config.hidden_size * 2, :
              ]
              a_ :		Union[str, Any]							=  in_proj_bias[
                  config.hidden_size : config.hidden_size * 2
              ]
              a_ :		Optional[Any]							=  in_proj_weight[
                  -config.hidden_size :, :
              ]
              a_ :		List[Any]							=  in_proj_bias[-config.hidden_size :]







def 	SCREAMING_SNAKE_CASE_						(      __A			:      Optional[int]  ,   __A			:      Union[str, Any]  ,   __A			:      Optional[int]    )     ->		Union[str, Any]:

       """simple docstring"""

       a_ :		Optional[Any]							=  dct.pop(__A    )
       a_ :		List[str]							=  val







def 	SCREAMING_SNAKE_CASE_						(      )     ->		List[Any]:

       """simple docstring"""

       a_ :		Union[str, Any]							=  'http://images.cocodataset.org/val2017/000000039769.jpg'
       a_ :		Dict							=  Image.open(requests.get(__A  ,   stream=__A    ).raw    )
       return im







@torch.no_grad()
def 	SCREAMING_SNAKE_CASE_						(      __A			:      Optional[int]  ,   __A			:      Union[str, Any]    )     ->		Dict:

       """simple docstring"""

       a_ :		Optional[int]							=  DeiTConfig()
       # all deit models have fine-tuned heads
       a_ :		List[str]							=  False
       # dataset (fine-tuned on ImageNet 2012), patch_size and image_size
       a_ :		Optional[int]							=  10_00
       a_ :		Dict							=  'huggingface/label-files'
       a_ :		Dict							=  'imagenet-1k-id2label.json'
       a_ :		List[Any]							=  json.load(open(hf_hub_download(__A  ,   __A  ,   repo_type='dataset'    )  ,   'r'    )    )
       a_ :		Any							=  {int(__A    ): v for k, v in idalabel.items()}
       a_ :		List[Any]							=  idalabel
       a_ :		Optional[int]							=  {v: k for k, v in idalabel.items()}
       a_ :		List[Any]							=  int(deit_name[-6:-4]    )
       a_ :		List[str]							=  int(deit_name[-3:]    )
       # size of the architecture
       if deit_name[9:].startswith('tiny'    ):
              a_ :		int							=  1_92
              a_ :		Any							=  7_68
              a_ :		Any							=  12
              a_ :		Dict							=  3
       elif deit_name[9:].startswith('small'    ):
              a_ :		Tuple							=  3_84
              a_ :		str							=  15_36
              a_ :		Any							=  12
              a_ :		Any							=  6
       if deit_name[9:].startswith('base'    ):
              pass
       elif deit_name[4:].startswith('large'    ):
              a_ :		Union[str, Any]							=  10_24
              a_ :		Optional[Any]							=  40_96
              a_ :		Any							=  24
              a_ :		int							=  16

       # load original model from timm
       a_ :		Optional[int]							=  timm.create_model(__A  ,   pretrained=__A    )
       timm_model.eval()

       # load state_dict of original model, remove and rename some keys
       a_ :		Any							=  timm_model.state_dict()
       a_ :		List[Any]							=  create_rename_keys(__A  ,   __A    )
       for src, dest in rename_keys:
              rename_key(__A  ,   __A  ,   __A    )
       read_in_q_k_v(__A  ,   __A  ,   __A    )

       # load HuggingFace model
       a_ :		Tuple							=  DeiTForImageClassificationWithTeacher(__A    ).eval()
       model.load_state_dict(__A    )

       # Check outputs on an image, prepared by DeiTImageProcessor
       a_ :		List[str]							=  int(
           (2_56 / 2_24) * config.image_size    )  # to maintain same ratio w.r.t. 224 images, see https://github.com/facebookresearch/deit/blob/ab5715372db8c6cad5740714b2216d55aeae052e/datasets.py#L103
       a_ :		Tuple							=  DeiTImageProcessor(size=__A  ,   crop_size=config.image_size    )
       a_ :		Optional[Any]							=  image_processor(images=prepare_img()  ,   return_tensors='pt'    )
       a_ :		Any							=  encoding['pixel_values']
       a_ :		List[Any]							=  model(__A    )

       a_ :		str							=  timm_model(__A    )
       assert timm_logits.shape == outputs.logits.shape
       assert torch.allclose(__A  ,   outputs.logits  ,   atol=1e-3    )

       Path(__A    ).mkdir(exist_ok=__A    )
       print(F"""Saving model {deit_name} to {pytorch_dump_folder_path}"""    )
       model.save_pretrained(__A    )
       print(F"""Saving image processor to {pytorch_dump_folder_path}"""    )
       image_processor.save_pretrained(__A    )


if __name__ == "__main__":
   UpperCAmelCase_				:			Union[str, Any]   =	argparse.ArgumentParser()
   # Required parameters
   parser.add_argument(
       '--deit_name',
       default='vit_deit_base_distilled_patch16_224',
       type=str,
       help='Name of the DeiT timm model you\'d like to convert.',
   )
   parser.add_argument(
       '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.'
   )

   UpperCAmelCase_				:			Any   =	parser.parse_args()
   convert_deit_checkpoint(args.deit_name, args.pytorch_dump_folder_path)






from typing import List, Optional, Tuple, Union

import torch
from torch import nn
from torch.nn import CrossEntropyLoss

from ... import AutoBackbone
from ...modeling_outputs import SemanticSegmenterOutput
from ...modeling_utils import PreTrainedModel
from ...utils import add_start_docstrings, add_start_docstrings_to_model_forward, replace_return_docstrings
from ...utils.backbone_utils import BackboneMixin
from .configuration_upernet import UperNetConfig


UpperCAmelCase_				:			Dict   =	[
    'openmmlab/upernet-convnext-tiny',
    # See all UperNet models at https://huggingface.co/models?filter=upernet
]

# General docstring
UpperCAmelCase_				:			Dict   =	'UperNetConfig'
class 			SCREAMING_SNAKE_CASE__  (    nn.Module      ):
      def __init__(	self    :	int					,							SCREAMING_SNAKE_CASE__    :	int					,							SCREAMING_SNAKE_CASE__    :	int					,							SCREAMING_SNAKE_CASE__    :	Union[int, Tuple[int, int]]					,							SCREAMING_SNAKE_CASE__    :	Union[int, Tuple[int, int], str] = 0					,							SCREAMING_SNAKE_CASE__    :	bool = False					,							SCREAMING_SNAKE_CASE__    :	Union[int, Tuple[int, int]] = 1					,							)		->      None:
             super().__init__()
             a_ :		Dict							=  nn.Convad(
                 in_channels=SCREAMING_SNAKE_CASE__					,							out_channels=SCREAMING_SNAKE_CASE__					,							kernel_size=SCREAMING_SNAKE_CASE__					,							padding=SCREAMING_SNAKE_CASE__					,							bias=SCREAMING_SNAKE_CASE__					,							dilation=SCREAMING_SNAKE_CASE__					,							)
             a_ :		List[str]							=  nn.BatchNormad(SCREAMING_SNAKE_CASE__					)
             a_ :		Tuple							=  nn.ReLU()

      def 	SCREAMING_SNAKE_CASE							(	self    :	Optional[int]					,							SCREAMING_SNAKE_CASE__    :	torch.Tensor					)		->      torch.Tensor:
             a_ :		int							=  self.conv(SCREAMING_SNAKE_CASE__					)
             a_ :		Optional[int]							=  self.batch_norm(SCREAMING_SNAKE_CASE__					)
             a_ :		List[Any]							=  self.activation(SCREAMING_SNAKE_CASE__					)

             return output
class 			SCREAMING_SNAKE_CASE__  (    nn.Module      ):
      def __init__(	self    :	str					,							SCREAMING_SNAKE_CASE__    :	int					,							SCREAMING_SNAKE_CASE__    :	int					,							SCREAMING_SNAKE_CASE__    :	int					)		->      None:
             super().__init__()
             a_ :		str							=  [
                 nn.AdaptiveAvgPoolad(SCREAMING_SNAKE_CASE__					),
                 UperNetConvModule(SCREAMING_SNAKE_CASE__					,							SCREAMING_SNAKE_CASE__					,							kernel_size=1					),
             ]
             for i, layer in enumerate(self.layers					):
                    self.add_module(str(SCREAMING_SNAKE_CASE__					)					,							SCREAMING_SNAKE_CASE__					)

      def 	SCREAMING_SNAKE_CASE							(	self    :	Any					,							SCREAMING_SNAKE_CASE__    :	torch.Tensor					)		->      torch.Tensor:
             a_ :		Optional[int]							=  input
             for layer in self.layers:
                    a_ :		int							=  layer(SCREAMING_SNAKE_CASE__					)
             return hidden_state
class 			SCREAMING_SNAKE_CASE__  (    nn.Module      ):
      def __init__(	self    :	Tuple					,							SCREAMING_SNAKE_CASE__    :	Tuple[int, ...]					,							SCREAMING_SNAKE_CASE__    :	int					,							SCREAMING_SNAKE_CASE__    :	int					,							SCREAMING_SNAKE_CASE__    :	bool					)		->      None:
             super().__init__()
             a_ :		Tuple							=  pool_scales
             a_ :		List[Any]							=  align_corners
             a_ :		Tuple							=  in_channels
             a_ :		Optional[Any]							=  channels
             a_ :		Tuple							=  []
             for i, pool_scale in enumerate(SCREAMING_SNAKE_CASE__					):
                    a_ :		Optional[int]							=  UperNetPyramidPoolingBlock(pool_scale=SCREAMING_SNAKE_CASE__					,							in_channels=SCREAMING_SNAKE_CASE__					,							channels=SCREAMING_SNAKE_CASE__					)
                    self.blocks.append(SCREAMING_SNAKE_CASE__					)
                    self.add_module(str(SCREAMING_SNAKE_CASE__					)					,							SCREAMING_SNAKE_CASE__					)

      def 	SCREAMING_SNAKE_CASE							(	self    :	Any					,							SCREAMING_SNAKE_CASE__    :	torch.Tensor					)		->      List[torch.Tensor]:
             a_ :		List[Any]							=  []
             for ppm in self.blocks:
                    a_ :		List[Any]							=  ppm(SCREAMING_SNAKE_CASE__					)
                    a_ :		str							=  nn.functional.interpolate(
                        SCREAMING_SNAKE_CASE__					,							size=x.size()[2:]					,							mode='bilinear'					,							align_corners=self.align_corners					)
                    ppm_outs.append(SCREAMING_SNAKE_CASE__					)
             return ppm_outs
class 			SCREAMING_SNAKE_CASE__  (    nn.Module      ):
      def __init__(	self    :	Tuple					,							SCREAMING_SNAKE_CASE__    :	Any					,							SCREAMING_SNAKE_CASE__    :	str					)		->      Tuple:
             super().__init__()

             a_ :		List[str]							=  config
             a_ :		Optional[int]							=  config.pool_scales  # e.g. (1, 2, 3, 6)
             a_ :		int							=  in_channels
             a_ :		Dict							=  config.hidden_size
             a_ :		Optional[Any]							=  False
             a_ :		Tuple							=  nn.Convad(self.channels					,							config.num_labels					,							kernel_size=1					)

             # PSP Module
             a_ :		int							=  UperNetPyramidPoolingModule(
                 self.pool_scales					,							self.in_channels[-1]					,							self.channels					,							align_corners=self.align_corners					,							)
             a_ :		int							=  UperNetConvModule(
                 self.in_channels[-1] + len(self.pool_scales					) * self.channels					,							self.channels					,							kernel_size=3					,							padding=1					,							)
             # FPN Module
             a_ :		str							=  nn.ModuleList()
             a_ :		Dict							=  nn.ModuleList()
             for in_channels in self.in_channels[:-1]:  # skip the top layer
                    a_ :		str							=  UperNetConvModule(SCREAMING_SNAKE_CASE__					,							self.channels					,							kernel_size=1					)
                    a_ :		Union[str, Any]							=  UperNetConvModule(self.channels					,							self.channels					,							kernel_size=3					,							padding=1					)
                    self.lateral_convs.append(SCREAMING_SNAKE_CASE__					)
                    self.fpn_convs.append(SCREAMING_SNAKE_CASE__					)

             a_ :		Optional[int]							=  UperNetConvModule(
                 len(self.in_channels					) * self.channels					,							self.channels					,							kernel_size=3					,							padding=1					,							)
      def 	SCREAMING_SNAKE_CASE							(	self    :	Optional[Any]					)		->      str:
             self.apply(self._init_weights					)
      def 	SCREAMING_SNAKE_CASE							(	self    :	List[str]					,							SCREAMING_SNAKE_CASE__    :	Dict					)		->      str:
             if isinstance(SCREAMING_SNAKE_CASE__					,							nn.Convad					):
                    module.weight.data.normal_(mean=0.0					,							std=self.config.initializer_range					)
                    if module.bias is not None:
                           module.bias.data.zero_()
      def 	SCREAMING_SNAKE_CASE							(	self    :	Optional[Any]					,							SCREAMING_SNAKE_CASE__    :	Tuple					)		->      Dict:
             a_ :		Dict							=  inputs[-1]
             a_ :		str							=  [x]
             psp_outs.extend(self.psp_modules(SCREAMING_SNAKE_CASE__					)					)
             a_ :		List[Any]							=  torch.cat(SCREAMING_SNAKE_CASE__					,							dim=1					)
             a_ :		Dict							=  self.bottleneck(SCREAMING_SNAKE_CASE__					)

             return output

      def 	SCREAMING_SNAKE_CASE							(	self    :	str					,							SCREAMING_SNAKE_CASE__    :	torch.Tensor					)		->      torch.Tensor:
             # build laterals
             a_ :		List[str]							=  [lateral_conv(encoder_hidden_states[i]					) for i, lateral_conv in enumerate(self.lateral_convs					)]

             laterals.append(self.psp_forward(SCREAMING_SNAKE_CASE__					)					)

             # build top-down path
             a_ :		List[str]							=  len(SCREAMING_SNAKE_CASE__					)
             for i in range(used_backbone_levels - 1					,							0					,							-1					):
                    a_ :		Optional[Any]							=  laterals[i - 1].shape[2:]
                    a_ :		List[Any]							=  laterals[i - 1] + nn.functional.interpolate(
                        laterals[i]					,							size=SCREAMING_SNAKE_CASE__					,							mode='bilinear'					,							align_corners=self.align_corners					)

             # build outputs
             a_ :		List[Any]							=  [self.fpn_convs[i](laterals[i]					) for i in range(used_backbone_levels - 1					)]
             # append psp feature
             fpn_outs.append(laterals[-1]					)

             for i in range(used_backbone_levels - 1					,							0					,							-1					):
                    a_ :		int							=  nn.functional.interpolate(
                        fpn_outs[i]					,							size=fpn_outs[0].shape[2:]					,							mode='bilinear'					,							align_corners=self.align_corners					)
             a_ :		Optional[int]							=  torch.cat(SCREAMING_SNAKE_CASE__					,							dim=1					)
             a_ :		Tuple							=  self.fpn_bottleneck(SCREAMING_SNAKE_CASE__					)
             a_ :		Dict							=  self.classifier(SCREAMING_SNAKE_CASE__					)

             return output
class 			SCREAMING_SNAKE_CASE__  (    nn.Module      ):
      def __init__(	self    :	int					,							SCREAMING_SNAKE_CASE__    :	Any					,							SCREAMING_SNAKE_CASE__    :	int = 2					,							SCREAMING_SNAKE_CASE__    :	int = 3					,							SCREAMING_SNAKE_CASE__    :	Union[int, Tuple[int, int]] = 1					)		->      None:
             super().__init__()

             a_ :		Optional[int]							=  config
             a_ :		str							=  config.auxiliary_in_channels
             a_ :		Optional[int]							=  config.auxiliary_channels
             a_ :		List[str]							=  config.auxiliary_num_convs
             a_ :		Dict							=  config.auxiliary_concat_input
             a_ :		int							=  in_index

             a_ :		List[Any]							=  (kernel_size // 2) * dilation
             a_ :		List[Any]							=  []
             convs.append(
                 UperNetConvModule(
                     self.in_channels					,							self.channels					,							kernel_size=SCREAMING_SNAKE_CASE__					,							padding=SCREAMING_SNAKE_CASE__					,							dilation=SCREAMING_SNAKE_CASE__					)					)
             for i in range(self.num_convs - 1					):
                    convs.append(
                        UperNetConvModule(
                            self.channels					,							self.channels					,							kernel_size=SCREAMING_SNAKE_CASE__					,							padding=SCREAMING_SNAKE_CASE__					,							dilation=SCREAMING_SNAKE_CASE__					)					)
             if self.num_convs == 0:
                    a_ :		Optional[int]							=  nn.Identity()
             else:
                    a_ :		int							=  nn.Sequential(*SCREAMING_SNAKE_CASE__					)
             if self.concat_input:
                    a_ :		Union[str, Any]							=  UperNetConvModule(
                        self.in_channels + self.channels					,							self.channels					,							kernel_size=SCREAMING_SNAKE_CASE__					,							padding=kernel_size // 2					)

             a_ :		List[str]							=  nn.Convad(self.channels					,							config.num_labels					,							kernel_size=1					)
      def 	SCREAMING_SNAKE_CASE							(	self    :	Optional[int]					)		->      List[str]:
             self.apply(self._init_weights					)
      def 	SCREAMING_SNAKE_CASE							(	self    :	Union[str, Any]					,							SCREAMING_SNAKE_CASE__    :	Any					)		->      List[str]:
             if isinstance(SCREAMING_SNAKE_CASE__					,							nn.Convad					):
                    module.weight.data.normal_(mean=0.0					,							std=self.config.initializer_range					)
                    if module.bias is not None:
                           module.bias.data.zero_()

      def 	SCREAMING_SNAKE_CASE							(	self    :	Union[str, Any]					,							SCREAMING_SNAKE_CASE__    :	torch.Tensor					)		->      torch.Tensor:
             # just take the relevant feature maps
             a_ :		Optional[int]							=  encoder_hidden_states[self.in_index]
             a_ :		int							=  self.convs(SCREAMING_SNAKE_CASE__					)
             if self.concat_input:
                    a_ :		Optional[Any]							=  self.conv_cat(torch.cat([hidden_states, output]					,							dim=1					)					)
             a_ :		Dict							=  self.classifier(SCREAMING_SNAKE_CASE__					)
             return output
class 			SCREAMING_SNAKE_CASE__  (    lowercase__      ):
      snake_case__    :					Any					       =						UperNetConfig
      snake_case__    :					Optional[int]					       =						'''pixel_values'''
      snake_case__    :					Optional[int]					       =						True
      def 	SCREAMING_SNAKE_CASE							(	self    :	List[str]					,							SCREAMING_SNAKE_CASE__    :	Optional[Any]					)		->      str:
             if isinstance(SCREAMING_SNAKE_CASE__					,							SCREAMING_SNAKE_CASE__					):
                    module.backbone.init_weights()
                    module.decode_head.init_weights()
                    module.auxiliary_head.init_weights()
      def 	SCREAMING_SNAKE_CASE							(	self    :	Dict					)		->      Dict:
             self.backbone.init_weights()
             self.decode_head.init_weights()
             self.auxiliary_head.init_weights()

      def 	SCREAMING_SNAKE_CASE							(	self    :	Optional[int]					,							SCREAMING_SNAKE_CASE__    :	str					,							SCREAMING_SNAKE_CASE__    :	int=False					)		->      Any:
             if isinstance(SCREAMING_SNAKE_CASE__					,							SCREAMING_SNAKE_CASE__					):
                    a_ :		Dict							=  value
UpperCAmelCase_				:			int   =	R'\n    Parameters:\n    This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use\n    it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n    behavior.\n        config ([`UperNetConfig`]): Model configuration class with all the parameters of the model.\n            Initializing with a config file does not load the weights associated with the model, only the\n            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n'

UpperCAmelCase_				:			Tuple   =	R'\n    Args:\n        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n            Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using\n            [`AutoImageProcessor`]. See [`SegformerImageProcessor.__call__`] for details.\n        output_attentions (`bool`, *optional*):\n            Whether or not to return the attentions tensors of all attention layers in case the backbone has them. See\n            `attentions` under returned tensors for more detail.\n        output_hidden_states (`bool`, *optional*):\n            Whether or not to return the hidden states of all layers of the backbone. See `hidden_states` under\n            returned tensors for more detail.\n        return_dict (`bool`, *optional*):\n            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n'
@add_start_docstrings(
    '''UperNet framework leveraging any vision backbone e.g. for ADE20k, CityScapes.'''						,   lowercase__						,   )
class 			SCREAMING_SNAKE_CASE__  (    lowercase__      ):
      def __init__(	self    :	Union[str, Any]					,							SCREAMING_SNAKE_CASE__    :	Optional[int]					)		->      str:
             super().__init__(SCREAMING_SNAKE_CASE__					)

             a_ :		List[str]							=  AutoBackbone.from_config(config.backbone_config					)

             # Semantic segmentation head(s)
             a_ :		List[Any]							=  UperNetHead(SCREAMING_SNAKE_CASE__					,							in_channels=self.backbone.channels					)
             a_ :		Dict							=  UperNetFCNHead(SCREAMING_SNAKE_CASE__					) if config.use_auxiliary_head else None

             # Initialize weights and apply final processing
             self.post_init()

      @add_start_docstrings_to_model_forward(UPERNET_INPUTS_DOCSTRING.format('batch_size, sequence_length'					)					)
      @replace_return_docstrings(output_type=SCREAMING_SNAKE_CASE__					,							config_class=_CONFIG_FOR_DOC					)
      def 	SCREAMING_SNAKE_CASE							(	self    :	List[Any]					,							SCREAMING_SNAKE_CASE__    :	Optional[torch.Tensor] = None					,							SCREAMING_SNAKE_CASE__    :	Optional[bool] = None					,							SCREAMING_SNAKE_CASE__    :	Optional[bool] = None					,							SCREAMING_SNAKE_CASE__    :	Optional[torch.Tensor] = None					,							SCREAMING_SNAKE_CASE__    :	Optional[bool] = None					,							)		->      Union[tuple, SemanticSegmenterOutput]:
             a_ :		Optional[Any]							=  return_dict if return_dict is not None else self.config.use_return_dict
             a_ :		Tuple							=  (
                 output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
             )
             a_ :		int							=  output_attentions if output_attentions is not None else self.config.output_attentions

             a_ :		str							=  self.backbone.forward_with_filtered_kwargs(
                 SCREAMING_SNAKE_CASE__					,							output_hidden_states=SCREAMING_SNAKE_CASE__					,							output_attentions=SCREAMING_SNAKE_CASE__					)
             a_ :		Optional[int]							=  outputs.feature_maps

             a_ :		Tuple							=  self.decode_head(SCREAMING_SNAKE_CASE__					)
             a_ :		List[Any]							=  nn.functional.interpolate(SCREAMING_SNAKE_CASE__					,							size=pixel_values.shape[2:]					,							mode='bilinear'					,							align_corners=SCREAMING_SNAKE_CASE__					)

             a_ :		Union[str, Any]							=  None
             if self.auxiliary_head is not None:
                    a_ :		Any							=  self.auxiliary_head(SCREAMING_SNAKE_CASE__					)
                    a_ :		int							=  nn.functional.interpolate(
                        SCREAMING_SNAKE_CASE__					,							size=pixel_values.shape[2:]					,							mode='bilinear'					,							align_corners=SCREAMING_SNAKE_CASE__					)

             a_ :		List[Any]							=  None
             if labels is not None:
                    if self.config.num_labels == 1:
                           raise ValueError('The number of labels should be greater than one'					)
                    else:
                           # compute weighted loss
                           a_ :		List[str]							=  CrossEntropyLoss(ignore_index=self.config.loss_ignore_index					)
                           a_ :		Optional[Any]							=  loss_fct(SCREAMING_SNAKE_CASE__					,							SCREAMING_SNAKE_CASE__					)
                           a_ :		str							=  loss_fct(SCREAMING_SNAKE_CASE__					,							SCREAMING_SNAKE_CASE__					)
                           a_ :		str							=  main_loss + self.config.auxiliary_loss_weight * auxiliary_loss

             if not return_dict:
                    if output_hidden_states:
                           a_ :		Optional[Any]							=  (logits,) + outputs[1:]
                    else:
                           a_ :		List[str]							=  (logits,) + outputs[2:]
                    return ((loss,) + output) if loss is not None else output

             return SemanticSegmenterOutput(
                 loss=SCREAMING_SNAKE_CASE__					,							logits=SCREAMING_SNAKE_CASE__					,							hidden_states=outputs.hidden_states					,							attentions=outputs.attentions					,							)


