


import inspect
import unittest

from transformers import DecisionTransformerConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
     import torch

     from transformers import DecisionTransformerModel
     from transformers.models.decision_transformer.modeling_decision_transformer import (
         DECISION_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
     )
class 			SCREAMING_SNAKE_CASE__  :
      def __init__(	self    :	Union[str, Any]					,							SCREAMING_SNAKE_CASE__    :	Any					,							SCREAMING_SNAKE_CASE__    :	Dict=1_3					,							SCREAMING_SNAKE_CASE__    :	str=7					,							SCREAMING_SNAKE_CASE__    :	Any=6					,							SCREAMING_SNAKE_CASE__    :	Optional[int]=1_7					,							SCREAMING_SNAKE_CASE__    :	Any=2_3					,							SCREAMING_SNAKE_CASE__    :	List[str]=1_1					,							SCREAMING_SNAKE_CASE__    :	List[Any]=True					,							)		->      str:
             a_ :		List[Any]							=  parent
             a_ :		Dict							=  batch_size
             a_ :		Any							=  seq_length
             a_ :		Tuple							=  act_dim
             a_ :		str							=  state_dim
             a_ :		str							=  hidden_size
             a_ :		Dict							=  max_length
             a_ :		Any							=  is_training
      def 	SCREAMING_SNAKE_CASE							(	self    :	Union[str, Any]					)		->      Union[str, Any]:
             a_ :		Optional[int]							=  floats_tensor((self.batch_size, self.seq_length, self.state_dim)					)
             a_ :		Tuple							=  floats_tensor((self.batch_size, self.seq_length, self.act_dim)					)
             a_ :		int							=  floats_tensor((self.batch_size, self.seq_length, 1)					)
             a_ :		str							=  floats_tensor((self.batch_size, self.seq_length, 1)					)
             a_ :		Optional[Any]							=  ids_tensor((self.batch_size, self.seq_length)					,							vocab_size=1_0_0_0					)
             a_ :		Optional[int]							=  random_attention_mask((self.batch_size, self.seq_length)					)

             a_ :		Any							=  self.get_config()

             return (
                 config,
                 states,
                 actions,
                 rewards,
                 returns_to_go,
                 timesteps,
                 attention_mask,
             )
      def 	SCREAMING_SNAKE_CASE							(	self    :	List[str]					)		->      Any:
             return DecisionTransformerConfig(
                 batch_size=self.batch_size					,							seq_length=self.seq_length					,							act_dim=self.act_dim					,							state_dim=self.state_dim					,							hidden_size=self.hidden_size					,							max_length=self.max_length					,							)
      def 	SCREAMING_SNAKE_CASE							(	self    :	str					,							SCREAMING_SNAKE_CASE__    :	List[Any]					,							SCREAMING_SNAKE_CASE__    :	int					,							SCREAMING_SNAKE_CASE__    :	Optional[Any]					,							SCREAMING_SNAKE_CASE__    :	Union[str, Any]					,							SCREAMING_SNAKE_CASE__    :	int					,							SCREAMING_SNAKE_CASE__    :	Tuple					,							SCREAMING_SNAKE_CASE__    :	str					,							)		->      Optional[Any]:
             a_ :		str							=  DecisionTransformerModel(config=__A					)
             model.to(__A					)
             model.eval()
             a_ :		Optional[Any]							=  model(__A					,							__A					,							__A					,							__A					,							__A					,							__A					)

             self.parent.assertEqual(result.state_preds.shape					,							states.shape					)
             self.parent.assertEqual(result.action_preds.shape					,							actions.shape					)
             self.parent.assertEqual(result.return_preds.shape					,							returns_to_go.shape					)
             self.parent.assertEqual(
                 result.last_hidden_state.shape					,							(self.batch_size, self.seq_length * 3, self.hidden_size)					)  # seq length *3 as there are 3 modelities: states, returns and actions

      def 	SCREAMING_SNAKE_CASE							(	self    :	Optional[Any]					)		->      Optional[Any]:
             a_ :		Optional[Any]							=  self.prepare_config_and_inputs()
             (
                 a_	
             ) :		Optional[Any]							=  config_and_inputs
             a_ :		Optional[Any]							=  {
                 """states""": states,
                 """actions""": actions,
                 """rewards""": rewards,
                 """returns_to_go""": returns_to_go,
                 """timesteps""": timesteps,
                 """attention_mask""": attention_mask,
             }
             return config, inputs_dict
@require_torch
class 			SCREAMING_SNAKE_CASE__  (    A__						,   A__						,   A__						,   unittest.TestCase      ):
      snake_case__    :					Any					       =						(DecisionTransformerModel,) if is_torch_available() else ()
      snake_case__    :					Tuple					       =						()
      snake_case__    :					Optional[int]					       =						{"feature-extraction": DecisionTransformerModel} if is_torch_available() else {}

      # Ignoring of a failing test from GenerationTesterMixin, as the model does not use inputs_ids
      snake_case__    :					str					       =						False

      # Ignoring of a failing tests from ModelTesterMixin, as the model does not implement these features
      snake_case__    :					Optional[Any]					       =						False
      snake_case__    :					Union[str, Any]					       =						False
      snake_case__    :					Dict					       =						False
      snake_case__    :					Tuple					       =						False
      snake_case__    :					str					       =						False
      snake_case__    :					Any					       =						False
      snake_case__    :					Optional[Any]					       =						False
      snake_case__    :					Dict					       =						False
      snake_case__    :					List[str]					       =						False
      def 	SCREAMING_SNAKE_CASE							(	self    :	Optional[int]					)		->      Optional[int]:
             a_ :		int							=  DecisionTransformerModelTester(self					)
             a_ :		str							=  ConfigTester(self					,							config_class=__A					,							hidden_size=3_7					)
      def 	SCREAMING_SNAKE_CASE							(	self    :	Optional[Any]					)		->      Union[str, Any]:
             self.config_tester.run_common_tests()
      def 	SCREAMING_SNAKE_CASE							(	self    :	int					)		->      str:
             a_ :		Optional[Any]							=  self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_model(*__A					)
      @slow
      def 	SCREAMING_SNAKE_CASE							(	self    :	int					)		->      Optional[Any]:
             for model_name in DECISION_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                    a_ :		Tuple							=  DecisionTransformerModel.from_pretrained(__A					)
                    self.assertIsNotNone(__A					)

      def 	SCREAMING_SNAKE_CASE							(	self    :	Optional[Any]					)		->      str:
             a_ :		Any							=  self.model_tester.prepare_config_and_inputs_for_common()

             for model_class in self.all_model_classes:
                    a_ :		List[str]							=  model_class(__A					)
                    a_ :		List[str]							=  inspect.signature(model.forward					)
                    # signature.parameters is an OrderedDict => so arg_names order is deterministic
                    a_ :		Union[str, Any]							=  [*signature.parameters.keys()]

                    a_ :		Any							=  [
                        """states""",
                        """actions""",
                        """rewards""",
                        """returns_to_go""",
                        """timesteps""",
                        """attention_mask""",
                    ]

                    self.assertListEqual(arg_names[: len(__A					)]					,							__A					)
@require_torch
class 			SCREAMING_SNAKE_CASE__  (    unittest.TestCase      ):
      @slow
      def 	SCREAMING_SNAKE_CASE							(	self    :	Union[str, Any]					)		->      Optional[Any]:
             a_ :		Optional[Any]							=  2  # number of steps of autoregressive prediction we will perform
             a_ :		Optional[int]							=  1_0  # defined by the RL environment, may be normalized
             a_ :		Any							=  DecisionTransformerModel.from_pretrained('edbeeching/decision-transformer-gym-hopper-expert'					)
             a_ :		Any							=  model.to(__A					)
             a_ :		List[str]							=  model.config
             torch.manual_seed(0					)
             a_ :		List[str]							=  torch.randn(1					,							1					,							config.state_dim					).to(device=__A					,							dtype=torch.floataa					)  # env.reset()

             a_ :		Union[str, Any]							=  torch.tensor(
                 [[0.242793, -0.28693074, 0.8742613], [0.67815274, -0.08101085, -0.12952147]]					,							device=__A					)

             a_ :		List[str]							=  torch.tensor(__A					,							device=__A					,							dtype=torch.floataa					).reshape(1					,							1					,							1					)
             a_ :		Optional[int]							=  state
             a_ :		Any							=  torch.zeros(1					,							0					,							config.act_dim					,							device=__A					,							dtype=torch.floataa					)
             a_ :		Optional[Any]							=  torch.zeros(1					,							0					,							device=__A					,							dtype=torch.floataa					)
             a_ :		Tuple							=  torch.tensor(0					,							device=__A					,							dtype=torch.long					).reshape(1					,							1					)

             for step in range(__A					):
                    a_ :		Tuple							=  torch.cat([actions, torch.zeros(1					,							1					,							config.act_dim					,							device=__A					)]					,							dim=1					)
                    a_ :		List[Any]							=  torch.cat([rewards, torch.zeros(1					,							1					,							device=__A					)]					,							dim=1					)

                    a_ :		Optional[Any]							=  torch.ones(1					,							states.shape[1]					).to(dtype=torch.long					,							device=states.device					)

                    with torch.no_grad():
                           a_ :		Optional[Any]							=  model(
                               states=__A					,							actions=__A					,							rewards=__A					,							returns_to_go=__A					,							timesteps=__A					,							attention_mask=__A					,							return_dict=__A					,							)

                    self.assertEqual(action_pred.shape					,							actions.shape					)
                    self.assertTrue(torch.allclose(action_pred[0, -1]					,							expected_outputs[step]					,							atol=1E-4					)					)
                    a_ :		Union[str, Any]							=  (  # env.step(action)
                        torch.randn(1					,							1					,							config.state_dim					).to(device=__A					,							dtype=torch.floataa					),
                        1.0,
                        False,
                        {},
                    )

                    a_ :		Any							=  action_pred[0, -1]
                    a_ :		Optional[int]							=  torch.cat([states, state]					,							dim=1					)
                    a_ :		List[str]							=  returns_to_go[0, -1] - reward
                    a_ :		Optional[int]							=  torch.cat([returns_to_go, pred_return.reshape(1					,							1					,							1					)]					,							dim=1					)
                    a_ :		Optional[Any]							=  torch.cat(
                        [timesteps, torch.ones((1, 1)					,							device=__A					,							dtype=torch.long					) * (step + 1)]					,							dim=1					)






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					,							)


