import enum
import warnings

from .. import MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING
from ..utils import add_end_docstrings, is_tf_available
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_tf_available():
      import tensorflow as tf





class      A							(				enum.Enum     ):
   __UpperCAmelCase : Optional[Any]      =			0
   __UpperCAmelCase : Union[str, Any]      =			1
   __UpperCAmelCase : List[str]      =			2





@add_end_docstrings(UpperCAmelCase_     )
class      A							(				UpperCAmelCase_     ):
   __UpperCAmelCase : str      =			'\n    In 1991, the remains of Russian Tsar Nicholas II and his family (except for Alexei and Maria) are discovered. The\n    voice of Nicholas\'s young son, Tsarevich Alexei Nikolaevich, narrates the remainder of the story. 1883 Western\n    Siberia, a young Grigori Rasputin is asked by his father and a group of men to perform magic. Rasputin has a vision\n    and denounces one of the men as a horse thief. Although his father initially slaps him for making such an\n    accusation, Rasputin watches as the man is chased outside and beaten. Twenty years later, Rasputin sees a vision of\n    the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous, with people, even a bishop,\n    begging for his blessing. <eod> </s> <eos>\n    '


   def __init__(self     :						Dict       ,  *__UpperCAmelCase     :						Union[str, Any]       ,  **__UpperCAmelCase     :						str		)						->				List[Any]:
         """simple docstring"""



         super().__init__(*__UpperCAmelCase       ,  **__UpperCAmelCase		)
         self.check_model_type(
             TF_MODEL_FOR_CAUSAL_LM_MAPPING if self.framework == "tf" else MODEL_FOR_CAUSAL_LM_MAPPING		)
         if "prefix" not in self._preprocess_params:
               # This is very specific. The logic is quite complex and needs to be done
               # as a "default".
               # It also defines both some preprocess_kwargs and generate_kwargs
               # which is why we cannot put them in their respective methods.
               UpperCAmelCase__								=  None
               if self.model.config.prefix is not None:
                     UpperCAmelCase__								=  self.model.config.prefix
               if prefix is None and self.model.__class__.__name__ in [
                   "XLNetLMHeadModel",
                   "TransfoXLLMHeadModel",
                   "TFXLNetLMHeadModel",
                   "TFTransfoXLLMHeadModel",
               ]:
                     # For XLNet and TransformerXL we add an article to the prompt to give more state to the model.
                     UpperCAmelCase__								=  self.XL_PREFIX
               if prefix is not None:
                     # Recalculate some generate_kwargs linked to prefix.
                     UpperCAmelCase__		,      UpperCAmelCase__		,      UpperCAmelCase__								=  self._sanitize_parameters(prefix=__UpperCAmelCase       ,  **self._forward_params		)
                     UpperCAmelCase__								=  {**self._preprocess_params, **preprocess_params}
                     UpperCAmelCase__								=  {**self._forward_params, **forward_params}


   def 			lowercase_      (self     :						Any       ,  __UpperCAmelCase     :						str=None       ,  __UpperCAmelCase     :						List[str]=None       ,  __UpperCAmelCase     :						Union[str, Any]=None       ,  __UpperCAmelCase     :						Optional[int]=None       ,  __UpperCAmelCase     :						Any=None       ,  __UpperCAmelCase     :						str=None       ,  __UpperCAmelCase     :						Optional[int]=None       ,  __UpperCAmelCase     :						Tuple=None       ,  **__UpperCAmelCase     :						Optional[int]       ,  )						->				List[Any]:
         """simple docstring"""



         UpperCAmelCase__								=  {}
         if prefix is not None:
               UpperCAmelCase__								=  prefix
         if prefix:
               UpperCAmelCase__								=  self.tokenizer(
                   __UpperCAmelCase       ,  padding=__UpperCAmelCase       ,  add_special_tokens=__UpperCAmelCase       ,  return_tensors=self.framework		)
               UpperCAmelCase__								=  prefix_inputs["input_ids"].shape[-1]

         if handle_long_generation is not None:
               if handle_long_generation not in {"hole"}:
                     raise ValueError(
                         f"""{handle_long_generation} is not a valid value for `handle_long_generation` parameter expected"""
                         " [None, 'hole']"		)
               UpperCAmelCase__								=  handle_long_generation

         preprocess_params.update(__UpperCAmelCase		)
         UpperCAmelCase__								=  generate_kwargs

         UpperCAmelCase__								=  {}
         if return_full_text is not None and return_type is None:
               if return_text is not None:
                     raise ValueError("`return_text` is mutually exclusive with `return_full_text`"		)
               if return_tensors is not None:
                     raise ValueError("`return_full_text` is mutually exclusive with `return_tensors`"		)
               UpperCAmelCase__								=  ReturnType.FULL_TEXT if return_full_text else ReturnType.NEW_TEXT
         if return_tensors is not None and return_type is None:
               if return_text is not None:
                     raise ValueError("`return_text` is mutually exclusive with `return_tensors`"		)
               UpperCAmelCase__								=  ReturnType.TENSORS
         if return_type is not None:
               UpperCAmelCase__								=  return_type
         if clean_up_tokenization_spaces is not None:
               UpperCAmelCase__								=  clean_up_tokenization_spaces

         if stop_sequence is not None:
               UpperCAmelCase__								=  self.tokenizer.encode(__UpperCAmelCase       ,  add_special_tokens=__UpperCAmelCase		)
               if len(__UpperCAmelCase		) > 1:
                     warnings.warn(
                         "Stopping on a multiple token sequence is not yet supported on transformers. The first token of"
                         " the stop sequence will be used as the stop sequence string in the interim."		)
               UpperCAmelCase__								=  stop_sequence_ids[0]

         return preprocess_params, forward_params, postprocess_params


   def 			lowercase_      (self     :						Union[str, Any]       ,  *__UpperCAmelCase     :						Tuple       ,  **__UpperCAmelCase     :						Union[str, Any]		)						->				Union[str, Any]:
         """simple docstring"""



         if self.model.__class__.__name__ in ["TransfoXLLMHeadModel"]:
               kwargs.update({"add_space_before_punct_symbol": True}		)

         return super()._parse_and_tokenize(*__UpperCAmelCase       ,  **__UpperCAmelCase		)


   def __call__(self     :						Dict       ,  __UpperCAmelCase     :						List[Any]       ,  **__UpperCAmelCase     :						Tuple		)						->				List[Any]:
         """simple docstring"""



         return super().__call__(__UpperCAmelCase       ,  **__UpperCAmelCase		)


   def 			lowercase_      (self     :						List[str]       ,  __UpperCAmelCase     :						List[str]       ,  __UpperCAmelCase     :						Union[str, Any]=""       ,  __UpperCAmelCase     :						Any=None       ,  **__UpperCAmelCase     :						List[str]		)						->				int:
         """simple docstring"""



         UpperCAmelCase__								=  self.tokenizer(
             prefix + prompt_text       ,  padding=__UpperCAmelCase       ,  add_special_tokens=__UpperCAmelCase       ,  return_tensors=self.framework		)
         UpperCAmelCase__								=  prompt_text

         if handle_long_generation == "hole":
               UpperCAmelCase__								=  inputs["input_ids"].shape[-1]
               if "max_new_tokens" in generate_kwargs:
                     UpperCAmelCase__								=  generate_kwargs["max_new_tokens"]
               else:
                     UpperCAmelCase__								=  generate_kwargs.get("max_length"       ,  self.model.config.max_length		) - cur_len
                     if new_tokens < 0:
                           raise ValueError("We cannot infer how many new tokens are expected"		)
               if cur_len + new_tokens > self.tokenizer.model_max_length:
                     UpperCAmelCase__								=  self.tokenizer.model_max_length - new_tokens
                     if keep_length <= 0:
                           raise ValueError(
                               "We cannot use `hole` to handle this generation the number of desired tokens exceeds the"
                               " models max length"		)

                     UpperCAmelCase__								=  inputs["input_ids"][:, -keep_length:]
                     if "attention_mask" in inputs:
                           UpperCAmelCase__								=  inputs["attention_mask"][:, -keep_length:]

         return inputs


   def 			lowercase_      (self     :						List[Any]       ,  __UpperCAmelCase     :						str       ,  **__UpperCAmelCase     :						Tuple		)						->				Any:
         """simple docstring"""



         UpperCAmelCase__								=  model_inputs["input_ids"]
         UpperCAmelCase__								=  model_inputs.get("attention_mask"       ,  __UpperCAmelCase		)
         # Allow empty prompts
         if input_ids.shape[1] == 0:
               UpperCAmelCase__								=  None
               UpperCAmelCase__								=  None
               UpperCAmelCase__								=  1
         else:
               UpperCAmelCase__								=  input_ids.shape[0]
         UpperCAmelCase__								=  model_inputs.pop("prompt_text"		)

         # If there is a prefix, we may need to adjust the generation length. Do so without permanently modifying
         # generate_kwargs, as some of the parameterization may come from the initialization of the pipeline.
         UpperCAmelCase__								=  generate_kwargs.pop("prefix_length"       ,  0		)
         if prefix_length > 0:
               UpperCAmelCase__								=  "max_new_tokens" in generate_kwargs or (
                   "generation_config" in generate_kwargs
                   and generate_kwargs["generation_config"].max_new_tokens is not None
               )
               if not has_max_new_tokens:
                     UpperCAmelCase__								=  generate_kwargs.get("max_length"		) or self.model.config.max_length
                     generate_kwargs["max_length"] += prefix_length
               UpperCAmelCase__								=  "min_new_tokens" in generate_kwargs or (
                   "generation_config" in generate_kwargs
                   and generate_kwargs["generation_config"].min_new_tokens is not None
               )
               if not has_min_new_tokens and "min_length" in generate_kwargs:
                     generate_kwargs["min_length"] += prefix_length

        # BS x SL
         UpperCAmelCase__								=  self.model.generate(input_ids=__UpperCAmelCase       ,  attention_mask=__UpperCAmelCase       ,  **__UpperCAmelCase		)
         UpperCAmelCase__								=  generated_sequence.shape[0]
         if self.framework == "pt":
               UpperCAmelCase__								=  generated_sequence.reshape(__UpperCAmelCase       ,  out_b // in_b       ,  *generated_sequence.shape[1:]		)
         elif self.framework == "tf":
               UpperCAmelCase__								=  tf.reshape(__UpperCAmelCase       ,  (in_b, out_b // in_b, *generated_sequence.shape[1:])		)
         return {"generated_sequence": generated_sequence, "input_ids": input_ids, "prompt_text": prompt_text}





   def 			lowercase_      (self     :						Optional[Any]       ,  __UpperCAmelCase     :						Dict       ,  __UpperCAmelCase     :						Optional[Any]=ReturnType.FULL_TEXT       ,  __UpperCAmelCase     :						List[Any]=True		)						->				List[Any]:
         """simple docstring"""



         UpperCAmelCase__								=  model_outputs["generated_sequence"][0]
         UpperCAmelCase__								=  model_outputs["input_ids"]
         UpperCAmelCase__								=  model_outputs["prompt_text"]
         UpperCAmelCase__								=  generated_sequence.numpy().tolist()
         UpperCAmelCase__								=  []
         for sequence in generated_sequence:
               if return_type == ReturnType.TENSORS:
                     UpperCAmelCase__								=  {"generated_token_ids": sequence}
               elif return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}:
                     # Decode text
                     UpperCAmelCase__								=  self.tokenizer.decode(
                         __UpperCAmelCase       ,  skip_special_tokens=__UpperCAmelCase       ,  clean_up_tokenization_spaces=__UpperCAmelCase       ,  )

                     # Remove PADDING prompt of the sequence if XLNet or Transfo-XL model is used
                     if input_ids is None:
                           UpperCAmelCase__								=  0
                     else:
                           UpperCAmelCase__								=  len(
                               self.tokenizer.decode(
                                   input_ids[0]       ,  skip_special_tokens=__UpperCAmelCase       ,  clean_up_tokenization_spaces=__UpperCAmelCase       ,  )		)

                     if return_type == ReturnType.FULL_TEXT:
                           UpperCAmelCase__								=  prompt_text + text[prompt_length:]
                     else:
                           UpperCAmelCase__								=  text[prompt_length:]

                     UpperCAmelCase__								=  {"generated_text": all_text}
               records.append(__UpperCAmelCase		)

         return records







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


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

# General docstring
__UpperCamelCase						=      '''UperNetConfig'''
class 					lowerCAmelCase	(					nn.Module    ):




		'''simple docstring'''







		def __init__(	self						,       lowerCAmelCase__						,       lowerCAmelCase__						,       lowerCAmelCase__						,       lowerCAmelCase__ = 0						,       lowerCAmelCase__ = False						,       lowerCAmelCase__ = 1						,       )     ->							None:
								super().__init__()
								SCREAMING_SNAKE_CASE													=					nn.Convad(
								    in_channels=lowerCAmelCase__						,       out_channels=lowerCAmelCase__						,       kernel_size=lowerCAmelCase__						,       padding=lowerCAmelCase__						,       bias=lowerCAmelCase__						,       dilation=lowerCAmelCase__						,       )
								SCREAMING_SNAKE_CASE													=					nn.BatchNormad(lowerCAmelCase__				)
								SCREAMING_SNAKE_CASE													=					nn.ReLU()







		def 							__A						(	self						,       lowerCAmelCase__				)     ->							torch.Tensor:
								SCREAMING_SNAKE_CASE													=					self.conv(lowerCAmelCase__				)
								SCREAMING_SNAKE_CASE													=					self.batch_norm(lowerCAmelCase__				)
								SCREAMING_SNAKE_CASE													=					self.activation(lowerCAmelCase__				)

								return output





class 					lowerCAmelCase	(					nn.Module    ):




		'''simple docstring'''







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







		def 							__A						(	self						,       lowerCAmelCase__				)     ->							torch.Tensor:
								SCREAMING_SNAKE_CASE													=					input
								for layer in self.layers:
														SCREAMING_SNAKE_CASE													=					layer(lowerCAmelCase__				)
								return hidden_state





class 					lowerCAmelCase	(					nn.Module    ):




		'''simple docstring'''







		def __init__(	self						,       lowerCAmelCase__						,       lowerCAmelCase__						,       lowerCAmelCase__						,       lowerCAmelCase__				)     ->							None:
								super().__init__()
								SCREAMING_SNAKE_CASE													=					pool_scales
								SCREAMING_SNAKE_CASE													=					align_corners
								SCREAMING_SNAKE_CASE													=					in_channels
								SCREAMING_SNAKE_CASE													=					channels
								SCREAMING_SNAKE_CASE													=					[]
								for i, pool_scale in enumerate(lowerCAmelCase__				):
														SCREAMING_SNAKE_CASE													=					UperNetPyramidPoolingBlock(pool_scale=lowerCAmelCase__						,       in_channels=lowerCAmelCase__						,       channels=lowerCAmelCase__				)
														self.blocks.append(lowerCAmelCase__				)
														self.add_module(str(lowerCAmelCase__				)						,       lowerCAmelCase__				)







		def 							__A						(	self						,       lowerCAmelCase__				)     ->							List[torch.Tensor]:
								SCREAMING_SNAKE_CASE													=					[]
								for ppm in self.blocks:
														SCREAMING_SNAKE_CASE													=					ppm(lowerCAmelCase__				)
														SCREAMING_SNAKE_CASE													=					nn.functional.interpolate(
														    lowerCAmelCase__						,       size=x.size()[2:]						,       mode='bilinear'						,       align_corners=self.align_corners				)
														ppm_outs.append(lowerCAmelCase__				)
								return ppm_outs





class 					lowerCAmelCase	(					nn.Module    ):




		'''simple docstring'''







		def __init__(	self						,       lowerCAmelCase__						,       lowerCAmelCase__				)     ->							List[str]:
								super().__init__()

								SCREAMING_SNAKE_CASE													=					config
								SCREAMING_SNAKE_CASE													=					config.pool_scales  # e.g. (1, 2, 3, 6)
								SCREAMING_SNAKE_CASE													=					in_channels
								SCREAMING_SNAKE_CASE													=					config.hidden_size
								SCREAMING_SNAKE_CASE													=					False
								SCREAMING_SNAKE_CASE													=					nn.Convad(self.channels						,       config.num_labels						,       kernel_size=1				)

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

								SCREAMING_SNAKE_CASE													=					UperNetConvModule(
								    len(self.in_channels				) * self.channels						,       self.channels						,       kernel_size=3						,       padding=1						,       )







		def 							__A						(	self				)     ->							int:
								self.apply(self._init_weights				)







		def 							__A						(	self						,       lowerCAmelCase__				)     ->							Tuple:
								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 							__A						(	self						,       lowerCAmelCase__				)     ->							Optional[int]:
								SCREAMING_SNAKE_CASE													=					inputs[-1]
								SCREAMING_SNAKE_CASE													=					[x]
								psp_outs.extend(self.psp_modules(lowerCAmelCase__				)				)
								SCREAMING_SNAKE_CASE													=					torch.cat(lowerCAmelCase__						,       dim=1				)
								SCREAMING_SNAKE_CASE													=					self.bottleneck(lowerCAmelCase__				)

								return output







		def 							__A						(	self						,       lowerCAmelCase__				)     ->							torch.Tensor:
								# build laterals
								SCREAMING_SNAKE_CASE													=					[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
								SCREAMING_SNAKE_CASE													=					len(lowerCAmelCase__				)
								for i in range(used_backbone_levels - 1						,       0						,       -1				):
														SCREAMING_SNAKE_CASE													=					laterals[i - 1].shape[2:]
														SCREAMING_SNAKE_CASE													=					laterals[i - 1] + nn.functional.interpolate(
														    laterals[i]						,       size=lowerCAmelCase__						,       mode='bilinear'						,       align_corners=self.align_corners				)

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

								return output





class 					lowerCAmelCase	(					nn.Module    ):




		'''simple docstring'''







		def __init__(	self						,       lowerCAmelCase__						,       lowerCAmelCase__ = 2						,       lowerCAmelCase__ = 3						,       lowerCAmelCase__ = 1				)     ->							None:
								super().__init__()

								SCREAMING_SNAKE_CASE													=					config
								SCREAMING_SNAKE_CASE													=					config.auxiliary_in_channels
								SCREAMING_SNAKE_CASE													=					config.auxiliary_channels
								SCREAMING_SNAKE_CASE													=					config.auxiliary_num_convs
								SCREAMING_SNAKE_CASE													=					config.auxiliary_concat_input
								SCREAMING_SNAKE_CASE													=					in_index

								SCREAMING_SNAKE_CASE													=					(kernel_size // 2) * dilation
								SCREAMING_SNAKE_CASE													=					[]
								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:
														SCREAMING_SNAKE_CASE													=					nn.Identity()
								else:
														SCREAMING_SNAKE_CASE													=					nn.Sequential(*lowerCAmelCase__				)
								if self.concat_input:
														SCREAMING_SNAKE_CASE													=					UperNetConvModule(
														    self.in_channels + self.channels						,       self.channels						,       kernel_size=lowerCAmelCase__						,       padding=kernel_size // 2				)

								SCREAMING_SNAKE_CASE													=					nn.Convad(self.channels						,       config.num_labels						,       kernel_size=1				)







		def 							__A						(	self				)     ->							Dict:
								self.apply(self._init_weights				)







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





class 					lowerCAmelCase	(					lowerCamelCase_    ):




		'''simple docstring'''







		SCREAMING_SNAKE_CASE_						:     int								=     UperNetConfig
		SCREAMING_SNAKE_CASE_						:     Optional[Any]								=     """pixel_values"""
		SCREAMING_SNAKE_CASE_						:     Optional[int]								=     True







		def 							__A						(	self						,       lowerCAmelCase__				)     ->							List[str]:
								if isinstance(lowerCAmelCase__						,       lowerCAmelCase__				):
														module.backbone.init_weights()
														module.decode_head.init_weights()
														module.auxiliary_head.init_weights()







		def 							__A						(	self				)     ->							int:
								self.backbone.init_weights()
								self.decode_head.init_weights()
								self.auxiliary_head.init_weights()







		def 							__A						(	self						,       lowerCAmelCase__						,       lowerCAmelCase__=False				)     ->							str:
								if isinstance(lowerCAmelCase__						,       lowerCAmelCase__				):
														SCREAMING_SNAKE_CASE													=					value





__UpperCamelCase						=      R'''
    Parameters:
    This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use
    it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
    behavior.
        config ([`UperNetConfig`]): Model configuration class with all the parameters of the model.
            Initializing with a config file does not load the weights associated with the model, only the
            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
'''

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




		'''simple docstring'''







		def __init__(	self						,       lowerCAmelCase__				)     ->							Optional[int]:
								super().__init__(lowerCAmelCase__				)

								SCREAMING_SNAKE_CASE													=					AutoBackbone.from_config(config.backbone_config				)

								# Semantic segmentation head(s)
								SCREAMING_SNAKE_CASE													=					UperNetHead(lowerCAmelCase__						,       in_channels=self.backbone.channels				)
								SCREAMING_SNAKE_CASE													=					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 							__A						(	self						,       lowerCAmelCase__ = None						,       lowerCAmelCase__ = None						,       lowerCAmelCase__ = None						,       lowerCAmelCase__ = None						,       lowerCAmelCase__ = None						,       )     ->							Union[tuple, SemanticSegmenterOutput]:
								SCREAMING_SNAKE_CASE													=					return_dict if return_dict is not None else self.config.use_return_dict
								SCREAMING_SNAKE_CASE													=					(
								    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
								)
								SCREAMING_SNAKE_CASE													=					output_attentions if output_attentions is not None else self.config.output_attentions

								SCREAMING_SNAKE_CASE													=					self.backbone.forward_with_filtered_kwargs(
								    lowerCAmelCase__						,       output_hidden_states=lowerCAmelCase__						,       output_attentions=lowerCAmelCase__				)
								SCREAMING_SNAKE_CASE													=					outputs.feature_maps

								SCREAMING_SNAKE_CASE													=					self.decode_head(lowerCAmelCase__				)
								SCREAMING_SNAKE_CASE													=					nn.functional.interpolate(lowerCAmelCase__						,       size=pixel_values.shape[2:]						,       mode='bilinear'						,       align_corners=lowerCAmelCase__				)

								SCREAMING_SNAKE_CASE													=					None
								if self.auxiliary_head is not None:
														SCREAMING_SNAKE_CASE													=					self.auxiliary_head(lowerCAmelCase__				)
														SCREAMING_SNAKE_CASE													=					nn.functional.interpolate(
														    lowerCAmelCase__						,       size=pixel_values.shape[2:]						,       mode='bilinear'						,       align_corners=lowerCAmelCase__				)

								SCREAMING_SNAKE_CASE													=					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
																				SCREAMING_SNAKE_CASE													=					CrossEntropyLoss(ignore_index=self.config.loss_ignore_index				)
																				SCREAMING_SNAKE_CASE													=					loss_fct(lowerCAmelCase__						,       lowerCAmelCase__				)
																				SCREAMING_SNAKE_CASE													=					loss_fct(lowerCAmelCase__						,       lowerCAmelCase__				)
																				SCREAMING_SNAKE_CASE													=					main_loss + self.config.auxiliary_loss_weight * auxiliary_loss

								if not return_dict:
														if output_hidden_states:
																				SCREAMING_SNAKE_CASE													=					(logits,) + outputs[1:]
														else:
																				SCREAMING_SNAKE_CASE													=					(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						,       )


