


'''simple docstring'''






import shutil
import tempfile
import unittest

import numpy as np
import pytest

from transformers.testing_utils import require_vision
from transformers.utils import is_vision_available


if is_vision_available():
  from PIL import Image

  from transformers import (
      AutoProcessor,
      BertTokenizerFast,
      BlipImageProcessor,
      GPTaTokenizer,
      InstructBlipProcessor,
      PreTrainedTokenizerFast,
  )






@require_vision
class    __snake_case       (   unittest.TestCase):







    """simple docstring"""



    def __lowercase   (   self    :  Any		)   ->  Tuple:
      lowerCAmelCase_			:      List[str]			=   tempfile.mkdtemp()

      lowerCAmelCase_			:      Dict			=   BlipImageProcessor()
      lowerCAmelCase_			:      str			=   GPTaTokenizer.from_pretrained("""hf-internal-testing/tiny-random-GPT2Model"""		)
      lowerCAmelCase_			:      Optional[Any]			=   BertTokenizerFast.from_pretrained("""hf-internal-testing/tiny-random-bert"""		)

      lowerCAmelCase_			:      List[Any]			=   InstructBlipProcessor(lowerCamelCase    ,						lowerCamelCase    ,						lowerCamelCase		)

      processor.save_pretrained(self.tmpdirname		)

    def __lowercase   (   self    :  Optional[int]    ,						**lowerCamelCase    :  Any		)   ->  Any:
      return AutoProcessor.from_pretrained(self.tmpdirname    ,						**lowerCamelCase		).tokenizer

    def __lowercase   (   self    :  int    ,						**lowerCamelCase    :  Optional[Any]		)   ->  Tuple:
      return AutoProcessor.from_pretrained(self.tmpdirname    ,						**lowerCamelCase		).image_processor

    def __lowercase   (   self    :  Tuple    ,						**lowerCamelCase    :  Union[str, Any]		)   ->  Optional[int]:
      return AutoProcessor.from_pretrained(self.tmpdirname    ,						**lowerCamelCase		).qformer_tokenizer

    def __lowercase   (   self    :  Optional[Any]		)   ->  Optional[Any]:
      shutil.rmtree(self.tmpdirname		)

    def __lowercase   (   self    :  List[str]		)   ->  Union[str, Any]:
      lowerCAmelCase_			:      str			=   [np.random.randint(2_55    ,						size=(3, 30, 4_00)    ,						dtype=np.uinta		)]

      lowerCAmelCase_			:      Any			=   [Image.fromarray(np.moveaxis(lowerCamelCase    ,						0    ,						-1		)		) for x in image_inputs]

      return image_inputs

    def __lowercase   (   self    :  Union[str, Any]		)   ->  int:
      lowerCAmelCase_			:      Optional[int]			=   InstructBlipProcessor(
          tokenizer=self.get_tokenizer()    ,						image_processor=self.get_image_processor()    ,						qformer_tokenizer=self.get_qformer_tokenizer()    ,						)
      processor.save_pretrained(self.tmpdirname		)

      lowerCAmelCase_			:      Optional[Any]			=   self.get_tokenizer(bos_token="""(BOS)"""    ,						eos_token="""(EOS)"""		)
      lowerCAmelCase_			:      Optional[Any]			=   self.get_image_processor(do_normalize=lowerCamelCase    ,						padding_value=1.0		)

      lowerCAmelCase_			:      str			=   InstructBlipProcessor.from_pretrained(
          self.tmpdirname    ,						bos_token="""(BOS)"""    ,						eos_token="""(EOS)"""    ,						do_normalize=lowerCamelCase    ,						padding_value=1.0		)

      self.assertEqual(processor.tokenizer.get_vocab()    ,						tokenizer_add_kwargs.get_vocab()		)
      self.assertIsInstance(processor.tokenizer    ,						lowerCamelCase		)

      self.assertEqual(processor.image_processor.to_json_string()    ,						image_processor_add_kwargs.to_json_string()		)
      self.assertIsInstance(processor.image_processor    ,						lowerCamelCase		)
      self.assertIsInstance(processor.qformer_tokenizer    ,						lowerCamelCase		)

    def __lowercase   (   self    :  Optional[int]		)   ->  Optional[int]:
      lowerCAmelCase_			:      Optional[Any]			=   self.get_image_processor()
      lowerCAmelCase_			:      Dict			=   self.get_tokenizer()
      lowerCAmelCase_			:      int			=   self.get_qformer_tokenizer()

      lowerCAmelCase_			:      str			=   InstructBlipProcessor(
          tokenizer=lowerCamelCase    ,						image_processor=lowerCamelCase    ,						qformer_tokenizer=lowerCamelCase		)

      lowerCAmelCase_			:      List[Any]			=   self.prepare_image_inputs()

      lowerCAmelCase_			:      Union[str, Any]			=   image_processor(lowerCamelCase    ,						return_tensors="""np"""		)
      lowerCAmelCase_			:      List[str]			=   processor(images=lowerCamelCase    ,						return_tensors="""np"""		)

      for key in input_feat_extract.keys():
        self.assertAlmostEqual(input_feat_extract[key].sum()    ,						input_processor[key].sum()    ,						delta=1E-2		)

    def __lowercase   (   self    :  Dict		)   ->  Optional[int]:
      lowerCAmelCase_			:      Optional[int]			=   self.get_image_processor()
      lowerCAmelCase_			:      int			=   self.get_tokenizer()
      lowerCAmelCase_			:      Optional[Any]			=   self.get_qformer_tokenizer()

      lowerCAmelCase_			:      int			=   InstructBlipProcessor(
          tokenizer=lowerCamelCase    ,						image_processor=lowerCamelCase    ,						qformer_tokenizer=lowerCamelCase		)

      lowerCAmelCase_			:      Tuple			=   """lower newer"""

      lowerCAmelCase_			:      str			=   processor(text=lowerCamelCase		)

      lowerCAmelCase_			:      List[str]			=   tokenizer(lowerCamelCase    ,						return_token_type_ids=lowerCamelCase		)
      lowerCAmelCase_			:      Any			=   qformer_tokenizer(lowerCamelCase    ,						return_token_type_ids=lowerCamelCase		)

      for key in encoded_tokens.keys():
        self.assertListEqual(encoded_tokens[key]    ,						encoded_processor[key]		)

      for key in encoded_tokens_qformer.keys():
        self.assertListEqual(encoded_tokens_qformer[key]    ,						encoded_processor["""qformer_""" + key]		)

    def __lowercase   (   self    :  Optional[Any]		)   ->  List[str]:
      lowerCAmelCase_			:      Optional[Any]			=   self.get_image_processor()
      lowerCAmelCase_			:      Union[str, Any]			=   self.get_tokenizer()
      lowerCAmelCase_			:      List[Any]			=   self.get_qformer_tokenizer()

      lowerCAmelCase_			:      List[Any]			=   InstructBlipProcessor(
          tokenizer=lowerCamelCase    ,						image_processor=lowerCamelCase    ,						qformer_tokenizer=lowerCamelCase		)

      lowerCAmelCase_			:      Union[str, Any]			=   """lower newer"""
      lowerCAmelCase_			:      str			=   self.prepare_image_inputs()

      lowerCAmelCase_			:      Optional[Any]			=   processor(text=lowerCamelCase    ,						images=lowerCamelCase		)

      self.assertListEqual(
          list(inputs.keys()		)    ,						["""input_ids""", """attention_mask""", """qformer_input_ids""", """qformer_attention_mask""", """pixel_values"""]    ,						)

      # test if it raises when no input is passed
      with pytest.raises(lowerCamelCase		):
        processor()

    def __lowercase   (   self    :  int		)   ->  Tuple:
      lowerCAmelCase_			:      List[Any]			=   self.get_image_processor()
      lowerCAmelCase_			:      List[str]			=   self.get_tokenizer()
      lowerCAmelCase_			:      Optional[Any]			=   self.get_qformer_tokenizer()

      lowerCAmelCase_			:      List[Any]			=   InstructBlipProcessor(
          tokenizer=lowerCamelCase    ,						image_processor=lowerCamelCase    ,						qformer_tokenizer=lowerCamelCase		)

      lowerCAmelCase_			:      Optional[Any]			=   [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]

      lowerCAmelCase_			:      Tuple			=   processor.batch_decode(lowerCamelCase		)
      lowerCAmelCase_			:      str			=   tokenizer.batch_decode(lowerCamelCase		)

      self.assertListEqual(lowerCamelCase    ,						lowerCamelCase		)





    def __lowercase   (   self    :  Optional[Any]		)   ->  Tuple:
      lowerCAmelCase_			:      List[Any]			=   self.get_image_processor()
      lowerCAmelCase_			:      List[str]			=   self.get_tokenizer()
      lowerCAmelCase_			:      str			=   self.get_qformer_tokenizer()

      lowerCAmelCase_			:      List[Any]			=   InstructBlipProcessor(
          tokenizer=lowerCamelCase    ,						image_processor=lowerCamelCase    ,						qformer_tokenizer=lowerCamelCase		)

      lowerCAmelCase_			:      Dict			=   """lower newer"""
      lowerCAmelCase_			:      Tuple			=   self.prepare_image_inputs()

      lowerCAmelCase_			:      int			=   processor(text=lowerCamelCase    ,						images=lowerCamelCase		)

      self.assertListEqual(
          list(inputs.keys()		)    ,						["""input_ids""", """attention_mask""", """qformer_input_ids""", """qformer_attention_mask""", """pixel_values"""]    ,						)







'''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					:  Optional[int]											=      [
    "openmmlab/upernet-convnext-tiny",
    # See all UperNet models at https://huggingface.co/models?filter=upernet
]

# General docstring
__A					:  int											=      "UperNetConfig"






class    __snake_case       (   nn.Module):







    """simple docstring"""



    def __init__(   self    :  Tuple    ,						lowerCamelCase    :  int    ,						lowerCamelCase    :  int    ,						lowerCamelCase    :  Union[int, Tuple[int, int]]    ,						lowerCamelCase    :  Union[int, Tuple[int, int], str] = 0    ,						lowerCamelCase    :  bool = False    ,						lowerCamelCase    :  Union[int, Tuple[int, int]] = 1    ,						)   ->  None:
      super().__init__()
      lowerCAmelCase_			:      int			=   nn.Convad(
          in_channels=lowerCamelCase    ,						out_channels=lowerCamelCase    ,						kernel_size=lowerCamelCase    ,						padding=lowerCamelCase    ,						bias=lowerCamelCase    ,						dilation=lowerCamelCase    ,						)
      lowerCAmelCase_			:      Dict			=   nn.BatchNormad(lowerCamelCase		)
      lowerCAmelCase_			:      Dict			=   nn.ReLU()





    def __lowercase   (   self    :  Tuple    ,						lowerCamelCase    :  torch.Tensor		)   ->  torch.Tensor:
      lowerCAmelCase_			:      Optional[Any]			=   self.conv(lowerCamelCase		)
      lowerCAmelCase_			:      Tuple			=   self.batch_norm(lowerCamelCase		)
      lowerCAmelCase_			:      Union[str, Any]			=   self.activation(lowerCamelCase		)

      return output







class    __snake_case       (   nn.Module):







    """simple docstring"""



    def __init__(   self    :  List[str]    ,						lowerCamelCase    :  int    ,						lowerCamelCase    :  int    ,						lowerCamelCase    :  int		)   ->  None:
      super().__init__()
      lowerCAmelCase_			:      str			=   [
          nn.AdaptiveAvgPoolad(lowerCamelCase		),
          UperNetConvModule(lowerCamelCase    ,						lowerCamelCase    ,						kernel_size=1		),
      ]
      for i, layer in enumerate(self.layers		):
        self.add_module(str(lowerCamelCase		)    ,						lowerCamelCase		)





    def __lowercase   (   self    :  List[str]    ,						lowerCamelCase    :  torch.Tensor		)   ->  torch.Tensor:
      lowerCAmelCase_			:      List[Any]			=   input
      for layer in self.layers:
        lowerCAmelCase_			:      Tuple			=   layer(lowerCamelCase		)
      return hidden_state







class    __snake_case       (   nn.Module):







    """simple docstring"""



    def __init__(   self    :  Optional[int]    ,						lowerCamelCase    :  Tuple[int, ...]    ,						lowerCamelCase    :  int    ,						lowerCamelCase    :  int    ,						lowerCamelCase    :  bool		)   ->  None:
      super().__init__()
      lowerCAmelCase_			:      List[str]			=   pool_scales
      lowerCAmelCase_			:      Union[str, Any]			=   align_corners
      lowerCAmelCase_			:      Tuple			=   in_channels
      lowerCAmelCase_			:      List[str]			=   channels
      lowerCAmelCase_			:      Tuple			=   []
      for i, pool_scale in enumerate(lowerCamelCase		):
        lowerCAmelCase_			:      Optional[int]			=   UperNetPyramidPoolingBlock(pool_scale=lowerCamelCase    ,						in_channels=lowerCamelCase    ,						channels=lowerCamelCase		)
        self.blocks.append(lowerCamelCase		)
        self.add_module(str(lowerCamelCase		)    ,						lowerCamelCase		)





    def __lowercase   (   self    :  Optional[Any]    ,						lowerCamelCase    :  torch.Tensor		)   ->  List[torch.Tensor]:
      lowerCAmelCase_			:      Any			=   []
      for ppm in self.blocks:
        lowerCAmelCase_			:      Any			=   ppm(lowerCamelCase		)
        lowerCAmelCase_			:      Union[str, Any]			=   nn.functional.interpolate(
            lowerCamelCase    ,						size=x.size()[2:]    ,						mode="""bilinear"""    ,						align_corners=self.align_corners		)
        ppm_outs.append(lowerCamelCase		)
      return ppm_outs







class    __snake_case       (   nn.Module):







    """simple docstring"""



    def __init__(   self    :  int    ,						lowerCamelCase    :  List[str]    ,						lowerCamelCase    :  List[Any]		)   ->  Dict:
      super().__init__()

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

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

      lowerCAmelCase_			:      List[Any]			=   UperNetConvModule(
          len(self.in_channels		) * self.channels    ,						self.channels    ,						kernel_size=3    ,						padding=1    ,						)

    def __lowercase   (   self    :  List[Any]		)   ->  Any:
      self.apply(self._init_weights		)

    def __lowercase   (   self    :  Optional[int]    ,						lowerCamelCase    :  str		)   ->  List[Any]:
      if isinstance(lowerCamelCase    ,						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 __lowercase   (   self    :  List[str]    ,						lowerCamelCase    :  Optional[Any]		)   ->  Any:
      lowerCAmelCase_			:      Union[str, Any]			=   inputs[-1]
      lowerCAmelCase_			:      List[str]			=   [x]
      psp_outs.extend(self.psp_modules(lowerCamelCase		)		)
      lowerCAmelCase_			:      str			=   torch.cat(lowerCamelCase    ,						dim=1		)
      lowerCAmelCase_			:      str			=   self.bottleneck(lowerCamelCase		)

      return output





    def __lowercase   (   self    :  Dict    ,						lowerCamelCase    :  torch.Tensor		)   ->  torch.Tensor:
      # build laterals
      lowerCAmelCase_			:      Optional[int]			=   [lateral_conv(encoder_hidden_states[i]		) for i, lateral_conv in enumerate(self.lateral_convs		)]

      laterals.append(self.psp_forward(lowerCamelCase		)		)

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

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

      return output







class    __snake_case       (   nn.Module):







    """simple docstring"""



    def __init__(   self    :  List[str]    ,						lowerCamelCase    :  Dict    ,						lowerCamelCase    :  int = 2    ,						lowerCamelCase    :  int = 3    ,						lowerCamelCase    :  Union[int, Tuple[int, int]] = 1		)   ->  None:
      super().__init__()

      lowerCAmelCase_			:      List[Any]			=   config
      lowerCAmelCase_			:      Dict			=   config.auxiliary_in_channels
      lowerCAmelCase_			:      Optional[Any]			=   config.auxiliary_channels
      lowerCAmelCase_			:      Dict			=   config.auxiliary_num_convs
      lowerCAmelCase_			:      int			=   config.auxiliary_concat_input
      lowerCAmelCase_			:      List[Any]			=   in_index

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

      lowerCAmelCase_			:      Any			=   nn.Convad(self.channels    ,						config.num_labels    ,						kernel_size=1		)

    def __lowercase   (   self    :  int		)   ->  List[Any]:
      self.apply(self._init_weights		)

    def __lowercase   (   self    :  Union[str, Any]    ,						lowerCamelCase    :  Optional[Any]		)   ->  Optional[Any]:
      if isinstance(lowerCamelCase    ,						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 __lowercase   (   self    :  Any    ,						lowerCamelCase    :  torch.Tensor		)   ->  torch.Tensor:
      # just take the relevant feature maps
      lowerCAmelCase_			:      Dict			=   encoder_hidden_states[self.in_index]
      lowerCAmelCase_			:      List[str]			=   self.convs(lowerCamelCase		)
      if self.concat_input:
        lowerCAmelCase_			:      int			=   self.conv_cat(torch.cat([hidden_states, output]    ,						dim=1		)		)
      lowerCAmelCase_			:      Union[str, Any]			=   self.classifier(lowerCamelCase		)
      return output







class    __snake_case       (   _SCREAMING_SNAKE_CASE):







    """simple docstring"""



    lowercase    =					UperNetConfig
    lowercase    =					'pixel_values'
    lowercase    =					True

    def __lowercase   (   self    :  List[str]    ,						lowerCamelCase    :  Dict		)   ->  Optional[Any]:
      if isinstance(lowerCamelCase    ,						lowerCamelCase		):
        module.backbone.init_weights()
        module.decode_head.init_weights()
        module.auxiliary_head.init_weights()

    def __lowercase   (   self    :  Optional[int]		)   ->  int:
      self.backbone.init_weights()
      self.decode_head.init_weights()
      self.auxiliary_head.init_weights()





    def __lowercase   (   self    :  Union[str, Any]    ,						lowerCamelCase    :  List[str]    ,						lowerCamelCase    :  Any=False		)   ->  Optional[int]:
      if isinstance(lowerCamelCase    ,						lowerCamelCase		):
        lowerCAmelCase_			:      str			=   value







__A					:  Union[str, Any]											=      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					:  str											=      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.'	,_SCREAMING_SNAKE_CASE	,)
class    __snake_case       (   _SCREAMING_SNAKE_CASE):







    """simple docstring"""



    def __init__(   self    :  Any    ,						lowerCamelCase    :  List[Any]		)   ->  Union[str, Any]:
      super().__init__(lowerCamelCase		)

      lowerCAmelCase_			:      Union[str, Any]			=   AutoBackbone.from_config(config.backbone_config		)

      # Semantic segmentation head(s)
      lowerCAmelCase_			:      Optional[Any]			=   UperNetHead(lowerCamelCase    ,						in_channels=self.backbone.channels		)
      lowerCAmelCase_			:      List[Any]			=   UperNetFCNHead(lowerCamelCase		) 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=lowerCamelCase    ,						config_class=_CONFIG_FOR_DOC		)
    def __lowercase   (   self    :  Any    ,						lowerCamelCase    :  Optional[torch.Tensor] = None    ,						lowerCamelCase    :  Optional[bool] = None    ,						lowerCamelCase    :  Optional[bool] = None    ,						lowerCamelCase    :  Optional[torch.Tensor] = None    ,						lowerCamelCase    :  Optional[bool] = None    ,						)   ->  Union[tuple, SemanticSegmenterOutput]:
      lowerCAmelCase_			:      int			=   return_dict if return_dict is not None else self.config.use_return_dict
      lowerCAmelCase_			:      Any			=   (
          output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
      )
      lowerCAmelCase_			:      Tuple			=   output_attentions if output_attentions is not None else self.config.output_attentions

      lowerCAmelCase_			:      Dict			=   self.backbone.forward_with_filtered_kwargs(
          lowerCamelCase    ,						output_hidden_states=lowerCamelCase    ,						output_attentions=lowerCamelCase		)
      lowerCAmelCase_			:      Union[str, Any]			=   outputs.feature_maps

      lowerCAmelCase_			:      Dict			=   self.decode_head(lowerCamelCase		)
      lowerCAmelCase_			:      Optional[Any]			=   nn.functional.interpolate(lowerCamelCase    ,						size=pixel_values.shape[2:]    ,						mode="""bilinear"""    ,						align_corners=lowerCamelCase		)

      lowerCAmelCase_			:      Tuple			=   None
      if self.auxiliary_head is not None:
        lowerCAmelCase_			:      Optional[int]			=   self.auxiliary_head(lowerCamelCase		)
        lowerCAmelCase_			:      Union[str, Any]			=   nn.functional.interpolate(
            lowerCamelCase    ,						size=pixel_values.shape[2:]    ,						mode="""bilinear"""    ,						align_corners=lowerCamelCase		)

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

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

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



