"""simple docstring"""






from __future__ import annotations

import inspect
import unittest

import numpy as np

from transformers import ResNetConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
       import tensorflow as tf

       from transformers import TFResNetForImageClassification, TFResNetModel
       from transformers.models.resnet.modeling_tf_resnet import TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
       from PIL import Image

       from transformers import AutoImageProcessor


class     UpperCAmelCase						:



    """simple docstring"""

    def __init__(   self    ,			_UpperCAmelCase    ,			_UpperCAmelCase=3    ,			_UpperCAmelCase=32    ,			_UpperCAmelCase=3    ,			_UpperCAmelCase=10    ,			_UpperCAmelCase=[10, 20, 30, 40]    ,			_UpperCAmelCase=[1, 1, 2, 1]    ,			_UpperCAmelCase=True    ,			_UpperCAmelCase=True    ,			_UpperCAmelCase="relu"    ,			_UpperCAmelCase=3    ,			_UpperCAmelCase=None    ,			):
       lowercase__:   Optional[Any]					=      parent
       lowercase__:   Union[str, Any]					=      batch_size
       lowercase__:   int					=      image_size
       lowercase__:   Optional[Any]					=      num_channels
       lowercase__:   Optional[int]					=      embeddings_size
       lowercase__:   Dict					=      hidden_sizes
       lowercase__:   Union[str, Any]					=      depths
       lowercase__:   str					=      is_training
       lowercase__:   Optional[int]					=      use_labels
       lowercase__:   List[str]					=      hidden_act
       lowercase__:   Dict					=      num_labels
       lowercase__:   Any					=      scope
       lowercase__:   Optional[Any]					=      len(_UpperCAmelCase							)






    def _snake_case			(   self							):
       lowercase__:   Union[str, Any]					=      floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]							)

       lowercase__:   List[Any]					=      None
       if self.use_labels:
          lowercase__:   Any					=      ids_tensor([self.batch_size]    ,			self.num_labels							)

       lowercase__:   Optional[int]					=      self.get_config()

       return config, pixel_values, labels






    def _snake_case			(   self							):
       return ResNetConfig(
           num_channels=self.num_channels    ,			embeddings_size=self.embeddings_size    ,			hidden_sizes=self.hidden_sizes    ,			depths=self.depths    ,			hidden_act=self.hidden_act    ,			num_labels=self.num_labels    ,			image_size=self.image_size    ,			)






    def _snake_case			(   self    ,			_UpperCAmelCase    ,			_UpperCAmelCase    ,			_UpperCAmelCase							):
       lowercase__:   Optional[Any]					=      TFResNetModel(config=_UpperCAmelCase							)
       lowercase__:   Dict					=      model(_UpperCAmelCase							)
       # expected last hidden states: B, C, H // 32, W // 32
       self.parent.assertEqual(
           result.last_hidden_state.shape    ,			(self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32)    ,			)






    def _snake_case			(   self    ,			_UpperCAmelCase    ,			_UpperCAmelCase    ,			_UpperCAmelCase							):
       lowercase__:   str					=      self.num_labels
       lowercase__:   int					=      TFResNetForImageClassification(_UpperCAmelCase							)
       lowercase__:   Optional[Any]					=      model(_UpperCAmelCase    ,			labels=_UpperCAmelCase							)
       self.parent.assertEqual(result.logits.shape    ,			(self.batch_size, self.num_labels)							)






    def _snake_case			(   self							):
       lowercase__:   int					=      self.prepare_config_and_inputs()
       lowercase__, lowercase__, lowercase__:   Optional[Any]					=      config_and_inputs
       lowercase__:   Union[str, Any]					=      {'''pixel_values''': pixel_values}
       return config, inputs_dict



@require_tf
class     UpperCAmelCase						(_UpperCAmelCase    ,_UpperCAmelCase    ,unittest.TestCase  ):



    """simple docstring"""

    _UpperCAmelCase	:Any						    = (TFResNetModel, TFResNetForImageClassification) if is_tf_available() else ()
    _UpperCAmelCase	:List[str]						    = (
        {"feature-extraction": TFResNetModel, "image-classification": TFResNetForImageClassification}
        if is_tf_available()
        else {}
    )

    _UpperCAmelCase	:Any						    = False
    _UpperCAmelCase	:List[str]						    = False
    _UpperCAmelCase	:Optional[Any]						    = False
    _UpperCAmelCase	:Tuple						    = False
    _UpperCAmelCase	:List[Any]						    = False






    def _snake_case			(   self							):
       lowercase__:   Union[str, Any]					=      TFResNetModelTester(self							)
       lowercase__:   Optional[int]					=      ConfigTester(self    ,			config_class=_UpperCAmelCase    ,			has_text_modality=_UpperCAmelCase							)






    def _snake_case			(   self							):
       self.create_and_test_config_common_properties()
       self.config_tester.create_and_test_config_to_json_string()
       self.config_tester.create_and_test_config_to_json_file()
       self.config_tester.create_and_test_config_from_and_save_pretrained()
       self.config_tester.create_and_test_config_with_num_labels()
       self.config_tester.check_config_can_be_init_without_params()
       self.config_tester.check_config_arguments_init()






    def _snake_case			(   self							):
       return






    @unittest.skip(reason='''ResNet does not use inputs_embeds'''							)
    def _snake_case			(   self							):
       pass






    @unittest.skip(reason='''ResNet does not support input and output embeddings'''							)
    def _snake_case			(   self							):
       pass






    def _snake_case			(   self							):
       lowercase__, lowercase__:   int					=      self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
          lowercase__:   Optional[Any]					=      model_class(_UpperCAmelCase							)
          lowercase__:   str					=      inspect.signature(model.call							)
          # signature.parameters is an OrderedDict => so arg_names order is deterministic
          lowercase__:   int					=      [*signature.parameters.keys()]

          lowercase__:   Optional[Any]					=      ['''pixel_values''']
          self.assertListEqual(arg_names[:1]    ,			_UpperCAmelCase							)






    def _snake_case			(   self							):
       lowercase__:   Any					=      self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*_UpperCAmelCase							)






    def _snake_case			(   self							):
       def check_hidden_states_output(_UpperCAmelCase    ,			_UpperCAmelCase    ,			_UpperCAmelCase							):
          lowercase__:   Union[str, Any]					=      model_class(_UpperCAmelCase							)
          lowercase__:   List[Any]					=      model(**self._prepare_for_class(_UpperCAmelCase    ,			_UpperCAmelCase							)							)

          lowercase__:   Union[str, Any]					=      outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

          lowercase__:   Tuple					=      self.model_tester.num_stages
          self.assertEqual(len(_UpperCAmelCase							)    ,			expected_num_stages + 1							)

          # ResNet's feature maps are of shape (batch_size, num_channels, height, width)
          self.assertListEqual(
              list(hidden_states[0].shape[-2:]							)    ,			[self.model_tester.image_size // 4, self.model_tester.image_size // 4]    ,			)

       lowercase__, lowercase__:   Optional[Any]					=      self.model_tester.prepare_config_and_inputs_for_common()
       lowercase__:   Union[str, Any]					=      ['''basic''', '''bottleneck''']
       for model_class in self.all_model_classes:
          for layer_type in layers_type:
             lowercase__:   Tuple					=      layer_type
             lowercase__:   Any					=      True
             check_hidden_states_output(_UpperCAmelCase    ,			_UpperCAmelCase    ,			_UpperCAmelCase							)

             # check that output_hidden_states also work using config
             del inputs_dict["output_hidden_states"]
             lowercase__:   List[str]					=      True

             check_hidden_states_output(_UpperCAmelCase    ,			_UpperCAmelCase    ,			_UpperCAmelCase							)






    def _snake_case			(   self							):
       lowercase__:   Optional[int]					=      self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*_UpperCAmelCase							)






    @slow
    def _snake_case			(   self							):
       for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
          lowercase__:   Dict					=      TFResNetModel.from_pretrained(_UpperCAmelCase							)
          self.assertIsNotNone(_UpperCAmelCase							)



def SCREAMING_SNAKE_CASE__			(   )  ->  List[Any]:
   lowercase__:   List[Any]					=      Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' )
   return image




@require_tf
@require_vision
class     UpperCAmelCase						(unittest.TestCase  ):



    """simple docstring"""

    @cached_property
    def _snake_case			(   self							):
       return (
           AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]							)
           if is_vision_available()
           else None
       )






    @slow
    def _snake_case			(   self							):
       lowercase__:   Tuple					=      TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]							)

       lowercase__:   Any					=      self.default_image_processor
       lowercase__:   List[Any]					=      prepare_img()
       lowercase__:   List[Any]					=      image_processor(images=_UpperCAmelCase    ,			return_tensors='''tf'''							)

       # forward pass
       lowercase__:   Dict					=      model(**_UpperCAmelCase							)

       # verify the logits
       lowercase__:   int					=      tf.TensorShape((1, 1000)							)
       self.assertEqual(outputs.logits.shape    ,			_UpperCAmelCase							)

       lowercase__:   Dict					=      tf.constant([-11.1_069, -9.7_877, -8.3_777]							)

       self.assertTrue(np.allclose(outputs.logits[0, :3].numpy()    ,			_UpperCAmelCase    ,			atol=1e-4							)							)

"""simple docstring"""






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


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

# General docstring
__A			   = "UperNetConfig"


class     UpperCAmelCase						(nn.Module  ):



    """simple docstring"""

    def __init__(   self    ,			_UpperCAmelCase    ,			_UpperCAmelCase    ,			_UpperCAmelCase    ,			_UpperCAmelCase = 0    ,			_UpperCAmelCase = False    ,			_UpperCAmelCase = 1    ,			):
       super().__init__()
       lowercase__:   List[Any]					=      nn.Convad(
           in_channels=_UpperCAmelCase    ,			out_channels=_UpperCAmelCase    ,			kernel_size=_UpperCAmelCase    ,			padding=_UpperCAmelCase    ,			bias=_UpperCAmelCase    ,			dilation=_UpperCAmelCase    ,			)
       lowercase__:   List[Any]					=      nn.BatchNormad(_UpperCAmelCase							)
       lowercase__:   int					=      nn.ReLU()






    def _snake_case			(   self    ,			_UpperCAmelCase							):
       lowercase__:   Dict					=      self.conv(_UpperCAmelCase							)
       lowercase__:   Optional[int]					=      self.batch_norm(_UpperCAmelCase							)
       lowercase__:   List[Any]					=      self.activation(_UpperCAmelCase							)

       return output



class     UpperCAmelCase						(nn.Module  ):



    """simple docstring"""

    def __init__(   self    ,			_UpperCAmelCase    ,			_UpperCAmelCase    ,			_UpperCAmelCase							):
       super().__init__()
       lowercase__:   int					=      [
           nn.AdaptiveAvgPoolad(_UpperCAmelCase							),
           UperNetConvModule(_UpperCAmelCase    ,			_UpperCAmelCase    ,			kernel_size=1							),
       ]
       for i, layer in enumerate(self.layers							):
          self.add_module(str(_UpperCAmelCase							)    ,			_UpperCAmelCase							)






    def _snake_case			(   self    ,			_UpperCAmelCase							):
       lowercase__:   Any					=      input
       for layer in self.layers:
          lowercase__:   Any					=      layer(_UpperCAmelCase							)
       return hidden_state



class     UpperCAmelCase						(nn.Module  ):



    """simple docstring"""

    def __init__(   self    ,			_UpperCAmelCase    ,			_UpperCAmelCase    ,			_UpperCAmelCase    ,			_UpperCAmelCase							):
       super().__init__()
       lowercase__:   int					=      pool_scales
       lowercase__:   Optional[Any]					=      align_corners
       lowercase__:   Optional[int]					=      in_channels
       lowercase__:   Optional[Any]					=      channels
       lowercase__:   List[Any]					=      []
       for i, pool_scale in enumerate(_UpperCAmelCase							):
          lowercase__:   Optional[int]					=      UperNetPyramidPoolingBlock(pool_scale=_UpperCAmelCase    ,			in_channels=_UpperCAmelCase    ,			channels=_UpperCAmelCase							)
          self.blocks.append(_UpperCAmelCase							)
          self.add_module(str(_UpperCAmelCase							)    ,			_UpperCAmelCase							)






    def _snake_case			(   self    ,			_UpperCAmelCase							):
       lowercase__:   Union[str, Any]					=      []
       for ppm in self.blocks:
          lowercase__:   Tuple					=      ppm(_UpperCAmelCase							)
          lowercase__:   Any					=      nn.functional.interpolate(
              _UpperCAmelCase    ,			size=x.size()[2:]    ,			mode='''bilinear'''    ,			align_corners=self.align_corners							)
          ppm_outs.append(_UpperCAmelCase							)
       return ppm_outs



class     UpperCAmelCase						(nn.Module  ):



    """simple docstring"""

    def __init__(   self    ,			_UpperCAmelCase    ,			_UpperCAmelCase							):
       super().__init__()

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

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

       lowercase__:   Any					=      UperNetConvModule(
           len(self.in_channels							) * self.channels    ,			self.channels    ,			kernel_size=3    ,			padding=1    ,			)






    def _snake_case			(   self							):
       self.apply(self._init_weights							)






    def _snake_case			(   self    ,			_UpperCAmelCase							):
       if isinstance(_UpperCAmelCase    ,			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 _snake_case			(   self    ,			_UpperCAmelCase							):
       lowercase__:   List[str]					=      inputs[-1]
       lowercase__:   str					=      [x]
       psp_outs.extend(self.psp_modules(_UpperCAmelCase							)							)
       lowercase__:   Dict					=      torch.cat(_UpperCAmelCase    ,			dim=1							)
       lowercase__:   Tuple					=      self.bottleneck(_UpperCAmelCase							)

       return output






    def _snake_case			(   self    ,			_UpperCAmelCase							):
       # build laterals
       lowercase__:   Dict					=      [lateral_conv(encoder_hidden_states[i]							) for i, lateral_conv in enumerate(self.lateral_convs							)]

       laterals.append(self.psp_forward(_UpperCAmelCase							)							)

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

       # build outputs
       lowercase__:   str					=      [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							):
          lowercase__:   Any					=      nn.functional.interpolate(
              fpn_outs[i]    ,			size=fpn_outs[0].shape[2:]    ,			mode='''bilinear'''    ,			align_corners=self.align_corners							)
       lowercase__:   int					=      torch.cat(_UpperCAmelCase    ,			dim=1							)
       lowercase__:   Tuple					=      self.fpn_bottleneck(_UpperCAmelCase							)
       lowercase__:   Dict					=      self.classifier(_UpperCAmelCase							)

       return output



class     UpperCAmelCase						(nn.Module  ):



    """simple docstring"""

    def __init__(   self    ,			_UpperCAmelCase    ,			_UpperCAmelCase = 2    ,			_UpperCAmelCase = 3    ,			_UpperCAmelCase = 1							):
       super().__init__()

       lowercase__:   Optional[Any]					=      config
       lowercase__:   Optional[Any]					=      config.auxiliary_in_channels
       lowercase__:   List[Any]					=      config.auxiliary_channels
       lowercase__:   Tuple					=      config.auxiliary_num_convs
       lowercase__:   Any					=      config.auxiliary_concat_input
       lowercase__:   Optional[int]					=      in_index

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

       lowercase__:   Union[str, Any]					=      nn.Convad(self.channels    ,			config.num_labels    ,			kernel_size=1							)






    def _snake_case			(   self							):
       self.apply(self._init_weights							)






    def _snake_case			(   self    ,			_UpperCAmelCase							):
       if isinstance(_UpperCAmelCase    ,			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 _snake_case			(   self    ,			_UpperCAmelCase							):
       # just take the relevant feature maps
       lowercase__:   Dict					=      encoder_hidden_states[self.in_index]
       lowercase__:   Optional[int]					=      self.convs(_UpperCAmelCase							)
       if self.concat_input:
          lowercase__:   Optional[int]					=      self.conv_cat(torch.cat([hidden_states, output]    ,			dim=1							)							)
       lowercase__:   Dict					=      self.classifier(_UpperCAmelCase							)
       return output



class     UpperCAmelCase						(_UpperCAmelCase  ):



    """simple docstring"""

    _UpperCAmelCase	:Dict						    = UperNetConfig
    _UpperCAmelCase	:int						    = "pixel_values"
    _UpperCAmelCase	:Optional[Any]						    = True






    def _snake_case			(   self    ,			_UpperCAmelCase							):
       if isinstance(_UpperCAmelCase    ,			_UpperCAmelCase							):
          module.backbone.init_weights()
          module.decode_head.init_weights()
          module.auxiliary_head.init_weights()






    def _snake_case			(   self							):
       self.backbone.init_weights()
       self.decode_head.init_weights()
       self.auxiliary_head.init_weights()






    def _snake_case			(   self    ,			_UpperCAmelCase    ,			_UpperCAmelCase=False							):
       if isinstance(_UpperCAmelCase    ,			_UpperCAmelCase							):
          lowercase__:   Any					=      value



__A			   = 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"

__A			   = 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."    ,_UpperCAmelCase    ,)
class     UpperCAmelCase						(_UpperCAmelCase  ):



    """simple docstring"""

    def __init__(   self    ,			_UpperCAmelCase							):
       super().__init__(_UpperCAmelCase							)

       lowercase__:   Optional[int]					=      AutoBackbone.from_config(config.backbone_config							)

       # Semantic segmentation head(s)
       lowercase__:   Any					=      UperNetHead(_UpperCAmelCase    ,			in_channels=self.backbone.channels							)
       lowercase__:   Tuple					=      UperNetFCNHead(_UpperCAmelCase							) 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=_UpperCAmelCase    ,			config_class=_CONFIG_FOR_DOC							)
    def _snake_case			(   self    ,			_UpperCAmelCase = None    ,			_UpperCAmelCase = None    ,			_UpperCAmelCase = None    ,			_UpperCAmelCase = None    ,			_UpperCAmelCase = None    ,			):
       lowercase__:   Tuple					=      return_dict if return_dict is not None else self.config.use_return_dict
       lowercase__:   Any					=      (
           output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
       )
       lowercase__:   str					=      output_attentions if output_attentions is not None else self.config.output_attentions

       lowercase__:   List[str]					=      self.backbone.forward_with_filtered_kwargs(
           _UpperCAmelCase    ,			output_hidden_states=_UpperCAmelCase    ,			output_attentions=_UpperCAmelCase							)
       lowercase__:   Tuple					=      outputs.feature_maps

       lowercase__:   Union[str, Any]					=      self.decode_head(_UpperCAmelCase							)
       lowercase__:   str					=      nn.functional.interpolate(_UpperCAmelCase    ,			size=pixel_values.shape[2:]    ,			mode='''bilinear'''    ,			align_corners=_UpperCAmelCase							)

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

       lowercase__:   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
             lowercase__:   List[str]					=      CrossEntropyLoss(ignore_index=self.config.loss_ignore_index							)
             lowercase__:   Optional[Any]					=      loss_fct(_UpperCAmelCase    ,			_UpperCAmelCase							)
             lowercase__:   Dict					=      loss_fct(_UpperCAmelCase    ,			_UpperCAmelCase							)
             lowercase__:   int					=      main_loss + self.config.auxiliary_loss_weight * auxiliary_loss

       if not return_dict:
          if output_hidden_states:
             lowercase__:   Tuple					=      (logits,) + outputs[1:]
          else:
             lowercase__:   Optional[int]					=      (logits,) + outputs[2:]
          return ((loss,) + output) if loss is not None else output

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