



"""simple docstring"""
import inspect

import jax
import jax.lax as lax
import jax.numpy as jnp

from ..utils import add_start_docstrings
from ..utils.logging import get_logger


A:   Any								=		get_logger(__name__)


A:   Tuple								=		R"\n    Args:\n        input_ids (`jnp.ndarray` of shape `(batch_size, sequence_length)`):\n            Indices of input sequence tokens in the vocabulary.\n\n            Indices can be obtained using [`PreTrainedTokenizer`]. See [`PreTrainedTokenizer.encode`] and\n            [`PreTrainedTokenizer.__call__`] for details.\n\n            [What are input IDs?](../glossary#input-ids)\n        scores (`jnp.ndarray` of shape `(batch_size, config.vocab_size)`):\n            Prediction scores of a language modeling head. These can be logits for each vocabulary when not using beam\n            search or log softmax for each vocabulary token when using beam search\n        kwargs (`Dict[str, Any]`, *optional*):\n            Additional logits processor specific kwargs.\n\n    Return:\n        `jnp.ndarray` of shape `(batch_size, config.vocab_size)`: The processed prediction scores.\n\n"



class       SCREAMING_SNAKE_CASE__  :

   @add_start_docstrings(_SCREAMING_SNAKE_CASE						)
   def __call__(   self      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE						)  ->      jnp.ndarray:





    '''simple docstring'''




    raise NotImplementedError(
        F"{self.__class__} is an abstract class. Only classes inheriting this class can be called."						)



class       SCREAMING_SNAKE_CASE__  :

   @add_start_docstrings(_SCREAMING_SNAKE_CASE						)
   def __call__(   self      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE						)  ->      jnp.ndarray:





    '''simple docstring'''




    raise NotImplementedError(
        F"{self.__class__} is an abstract class. Only classes inheriting this class can be called."						)



class       SCREAMING_SNAKE_CASE__  (					UpperCAmelCase__ ):

   @add_start_docstrings(_SCREAMING_SNAKE_CASE						)
   def __call__(   self      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE      ,     **_SCREAMING_SNAKE_CASE						)  ->      jnp.ndarray:





    '''simple docstring'''




    for processor in self:
     UpperCAmelCase	:					List[Any]	=	inspect.signature(processor.__call__						).parameters
     if len(_SCREAMING_SNAKE_CASE						) > 3:
      if not all(arg in kwargs for arg in list(function_args.keys()						)[2:]						):
       raise ValueError(
           F"Make sure that all the required parameters: {list(function_args.keys()						)} for "
           F"{processor.__class__} are passed to the logits processor."						)
      UpperCAmelCase	:					Dict	=	processor(_SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE      ,     **_SCREAMING_SNAKE_CASE						)
     else:
      UpperCAmelCase	:					Any	=	processor(_SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE						)
    return scores



class       SCREAMING_SNAKE_CASE__  (					UpperCAmelCase__ ):

   def __init__(   self      ,     _SCREAMING_SNAKE_CASE						)  ->      Optional[Any]:





    '''simple docstring'''




    if not isinstance(_SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE						) or not (temperature > 0):
     raise ValueError(F"`temperature` has to be a strictly positive float, but is {temperature}"						)

    UpperCAmelCase	:					str	=	temperature




   def __call__(   self      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE						)  ->      jnp.ndarray:





    '''simple docstring'''




    UpperCAmelCase	:					List[Any]	=	scores / self.temperature
    return scores



class       SCREAMING_SNAKE_CASE__  (					UpperCAmelCase__ ):

   def __init__(   self      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE = -float("""Inf"""						)      ,     _SCREAMING_SNAKE_CASE = 1						)  ->      List[str]:





    '''simple docstring'''




    if not isinstance(_SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE						) or (top_p < 0 or top_p > 1.0):
     raise ValueError(F"`top_p` has to be a float > 0 and < 1, but is {top_p}"						)
    if not isinstance(_SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE						) or (min_tokens_to_keep < 1):
     raise ValueError(F"`min_tokens_to_keep` has to be a positive integer, but is {min_tokens_to_keep}"						)

    UpperCAmelCase	:					int	=	top_p
    UpperCAmelCase	:					Optional[int]	=	filter_value
    UpperCAmelCase	:					Optional[int]	=	min_tokens_to_keep




   def __call__(   self      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE						)  ->      jnp.ndarray:





    '''simple docstring'''




    UpperCAmelCase	,		UpperCAmelCase	:					Tuple	=	lax.top_k(_SCREAMING_SNAKE_CASE      ,     scores.shape[-1]						)

    UpperCAmelCase	:					Tuple	=	jnp.full_like(_SCREAMING_SNAKE_CASE      ,     self.filter_value						)
    UpperCAmelCase	:					Tuple	=	jax.nn.softmax(_SCREAMING_SNAKE_CASE      ,     axis=-1						).cumsum(axis=-1						)
    UpperCAmelCase	:					Optional[Any]	=	cumulative_probs < self.top_p

    # include the token that is higher than top_p as well
    UpperCAmelCase	:					List[str]	=	jnp.roll(_SCREAMING_SNAKE_CASE      ,     1						)
    score_mask |= score_mask.at[:, 0].set(_SCREAMING_SNAKE_CASE						)

    # min tokens to keep
    UpperCAmelCase	:					Tuple	=	score_mask.at[:, : self.min_tokens_to_keep].set(_SCREAMING_SNAKE_CASE						)

    UpperCAmelCase	:					Union[str, Any]	=	jnp.where(_SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE						)
    UpperCAmelCase	:					List[str]	=	jax.lax.sort_key_val(_SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE						)[-1]

    return next_scores



class       SCREAMING_SNAKE_CASE__  (					UpperCAmelCase__ ):

   def __init__(   self      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE = -float("""Inf"""						)      ,     _SCREAMING_SNAKE_CASE = 1						)  ->      Any:





    '''simple docstring'''




    if not isinstance(_SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE						) or top_k <= 0:
     raise ValueError(F"`top_k` has to be a strictly positive integer, but is {top_k}"						)

    UpperCAmelCase	:					Optional[int]	=	max(_SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE						)
    UpperCAmelCase	:					Union[str, Any]	=	filter_value




   def __call__(   self      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE						)  ->      jnp.ndarray:





    '''simple docstring'''




    UpperCAmelCase	,		UpperCAmelCase	:					List[Any]	=	scores.shape
    UpperCAmelCase	:					Optional[int]	=	jnp.full(batch_size * vocab_size      ,     self.filter_value						)

    UpperCAmelCase	:					int	=	min(self.top_k      ,     scores.shape[-1]						)  # Safety check
    UpperCAmelCase	,		UpperCAmelCase	:					List[str]	=	lax.top_k(_SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE						)
    UpperCAmelCase	:					List[str]	=	jnp.broadcast_to((jnp.arange(_SCREAMING_SNAKE_CASE						) * vocab_size)[:, None]      ,     (batch_size, topk)						).flatten()
    UpperCAmelCase	:					Union[str, Any]	=	topk_scores.flatten()
    UpperCAmelCase	:					Optional[int]	=	topk_indices.flatten() + shift

    UpperCAmelCase	:					Optional[Any]	=	next_scores_flat.at[topk_indices_flat].set(_SCREAMING_SNAKE_CASE						)
    UpperCAmelCase	:					Tuple	=	next_scores_flat.reshape(_SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE						)
    return next_scores



class       SCREAMING_SNAKE_CASE__  (					UpperCAmelCase__ ):

   def __init__(   self      ,     _SCREAMING_SNAKE_CASE						)  ->      List[str]:





    '''simple docstring'''




    UpperCAmelCase	:					str	=	bos_token_id




   def __call__(   self      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE						)  ->      jnp.ndarray:





    '''simple docstring'''




    UpperCAmelCase	:					Optional[int]	=	jnp.full(scores.shape      ,     -float("""inf"""						)						)

    UpperCAmelCase	:					Optional[int]	=	1 - jnp.bool_(cur_len - 1						)

    UpperCAmelCase	:					Optional[int]	=	jnp.where(_SCREAMING_SNAKE_CASE      ,     new_scores.at[:, self.bos_token_id].set(0						)      ,     _SCREAMING_SNAKE_CASE						)

    return scores



class       SCREAMING_SNAKE_CASE__  (					UpperCAmelCase__ ):

   def __init__(   self      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE						)  ->      Any:





    '''simple docstring'''




    UpperCAmelCase	:					Union[str, Any]	=	max_length
    UpperCAmelCase	:					Optional[int]	=	eos_token_id




   def __call__(   self      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE						)  ->      jnp.ndarray:





    '''simple docstring'''




    UpperCAmelCase	:					Any	=	jnp.full(scores.shape      ,     -float("""inf"""						)						)

    UpperCAmelCase	:					Dict	=	1 - jnp.bool_(cur_len - self.max_length + 1						)

    UpperCAmelCase	:					int	=	jnp.where(_SCREAMING_SNAKE_CASE      ,     new_scores.at[:, self.eos_token_id].set(0						)      ,     _SCREAMING_SNAKE_CASE						)

    return scores



class       SCREAMING_SNAKE_CASE__  (					UpperCAmelCase__ ):

   def __init__(   self      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE						)  ->      int:





    '''simple docstring'''




    if not isinstance(_SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE						) or min_length < 0:
     raise ValueError(F"`min_length` has to be a positive integer, but is {min_length}"						)

    if not isinstance(_SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE						) or eos_token_id < 0:
     raise ValueError(F"`eos_token_id` has to be a positive integer, but is {eos_token_id}"						)

    UpperCAmelCase	:					List[Any]	=	min_length
    UpperCAmelCase	:					Any	=	eos_token_id




   def __call__(   self      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE						)  ->      jnp.ndarray:





    '''simple docstring'''




    UpperCAmelCase	:					Union[str, Any]	=	1 - jnp.clip(cur_len - self.min_length      ,     0      ,     1						)

    UpperCAmelCase	:					List[Any]	=	jnp.where(_SCREAMING_SNAKE_CASE      ,     scores.at[:, self.eos_token_id].set(-float("""inf"""						)						)      ,     _SCREAMING_SNAKE_CASE						)

    return scores



class       SCREAMING_SNAKE_CASE__  (					UpperCAmelCase__ ):

   def __init__(   self      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE						)  ->      Tuple:





    '''simple docstring'''




    UpperCAmelCase	:					str	=	list(_SCREAMING_SNAKE_CASE						)
    UpperCAmelCase	:					Optional[Any]	=	begin_index




   def __call__(   self      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE						)  ->      Optional[Any]:





    '''simple docstring'''




    UpperCAmelCase	:					Any	=	1 - jnp.bool_(cur_len - self.begin_index						)

    UpperCAmelCase	:					Optional[Any]	=	jnp.where(_SCREAMING_SNAKE_CASE      ,     scores.at[:, self.begin_suppress_tokens].set(-float("""inf"""						)						)      ,     _SCREAMING_SNAKE_CASE						)

    return scores



class       SCREAMING_SNAKE_CASE__  (					UpperCAmelCase__ ):

   def __init__(   self      ,     _SCREAMING_SNAKE_CASE						)  ->      int:





    '''simple docstring'''




    UpperCAmelCase	:					str	=	list(_SCREAMING_SNAKE_CASE						)




   def __call__(   self      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE						)  ->      jnp.ndarray:





    '''simple docstring'''




    UpperCAmelCase	:					List[Any]	=	scores.at[..., self.suppress_tokens].set(-float("""inf"""						)						)

    return scores



class       SCREAMING_SNAKE_CASE__  (					UpperCAmelCase__ ):

   def __init__(   self      ,     _SCREAMING_SNAKE_CASE						)  ->      Tuple:





    '''simple docstring'''




    UpperCAmelCase	:					Union[str, Any]	=	dict(_SCREAMING_SNAKE_CASE						)
    # Converts the dictionary of format {index: token} containing the tokens to be forced to an array, where the
    # index of the array corresponds to the index of the token to be forced, for XLA compatibility.
    # Indexes without forced tokens will have a negative value.
    UpperCAmelCase	:					List[Any]	=	jnp.ones((max(force_token_map.keys()						) + 1)      ,     dtype=jnp.intaa						) * -1
    for index, token in force_token_map.items():
     if token is not None:
      UpperCAmelCase	:					List[Any]	=	force_token_array.at[index].set(_SCREAMING_SNAKE_CASE						)
    UpperCAmelCase	:					str	=	jnp.intaa(_SCREAMING_SNAKE_CASE						)




   def __call__(   self      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE						)  ->      jnp.ndarray:





    '''simple docstring'''




    def _force_token(_SCREAMING_SNAKE_CASE						):
     UpperCAmelCase	:					int	=	scores.shape[0]
     UpperCAmelCase	:					List[Any]	=	self.force_token_array[generation_idx]

     UpperCAmelCase	:					int	=	jnp.ones_like(_SCREAMING_SNAKE_CASE      ,     dtype=scores.dtype						) * -float("""inf"""						)
     UpperCAmelCase	:					List[str]	=	jnp.zeros((batch_size, 1)      ,     dtype=scores.dtype						)
     UpperCAmelCase	:					List[Any]	=	lax.dynamic_update_slice(_SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE      ,     (0, current_token)						)
     return new_scores

    UpperCAmelCase	:					Dict	=	lax.cond(
        cur_len >= self.force_token_array.shape[0]      ,     lambda: scores      ,     lambda: lax.cond(
            self.force_token_array[cur_len] >= 0      ,     lambda: _force_token(_SCREAMING_SNAKE_CASE						)      ,     lambda: scores      ,     )      ,     )
    return scores



class       SCREAMING_SNAKE_CASE__  (					UpperCAmelCase__ ):

   def __init__(   self      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE						)  ->      Union[str, Any]:





    '''simple docstring'''




    UpperCAmelCase	:					Tuple	=	generate_config.eos_token_id
    UpperCAmelCase	:					List[Any]	=	generate_config.no_timestamps_token_id
    UpperCAmelCase	:					str	=	generate_config.no_timestamps_token_id + 1

    UpperCAmelCase	:					int	=	decoder_input_length + 1

    if generate_config.is_multilingual:
     # room for language token and task token
     self.begin_index += 2
    if hasattr(_SCREAMING_SNAKE_CASE      ,     """max_initial_timestamp_index"""						):
     UpperCAmelCase	:					Union[str, Any]	=	generate_config.max_initial_timestamp_index
    else:
     UpperCAmelCase	:					Dict	=	model_config.vocab_size
    if self.max_initial_timestamp_index is None:
     UpperCAmelCase	:					Union[str, Any]	=	model_config.vocab_size




   def __call__(   self      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE						)  ->      Dict:





    '''simple docstring'''




    UpperCAmelCase	:					Optional[int]	=	scores.at[:, self.no_timestamps_token_id].set(-float("""inf"""						)						)

    def handle_pairs(_SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE						):
     UpperCAmelCase	:					Optional[int]	=	jnp.where((cur_len - self.begin_index) >= 1      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE						)
     UpperCAmelCase	:					str	=	jnp.where(
         input_ids_k[cur_len - 1] >= self.timestamp_begin      ,     True and last_was_timestamp      ,     _SCREAMING_SNAKE_CASE      ,     )

     UpperCAmelCase	:					Dict	=	jnp.where((cur_len - self.begin_index) < 2      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE						)
     UpperCAmelCase	:					List[str]	=	jnp.where(
         input_ids_k[cur_len - 2] >= self.timestamp_begin      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE      ,     )

     return jnp.where(
         _SCREAMING_SNAKE_CASE      ,     jnp.where(
             penultimate_was_timestamp > 0      ,     scores_k.at[self.timestamp_begin :].set(-float("""inf"""						)						)      ,     scores_k.at[: self.eos_token_id].set(-float("""inf"""						)						)      ,     )      ,     _SCREAMING_SNAKE_CASE      ,     )

    UpperCAmelCase	:					Optional[int]	=	jax.vmap(_SCREAMING_SNAKE_CASE						)(_SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE						)

    UpperCAmelCase	:					Union[str, Any]	=	jnp.where(cur_len == self.begin_index      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE						)
    UpperCAmelCase	:					Tuple	=	jnp.where(
        self.max_initial_timestamp_index is not None      ,     True and apply_max_initial_timestamp      ,     _SCREAMING_SNAKE_CASE      ,     )

    UpperCAmelCase	:					Union[str, Any]	=	self.timestamp_begin + self.max_initial_timestamp_index

    UpperCAmelCase	:					Any	=	jnp.where(
        _SCREAMING_SNAKE_CASE      ,     scores.at[:, last_allowed + 1 :].set(-float("""inf"""						)						)      ,     _SCREAMING_SNAKE_CASE      ,     )

    # if sum of probability over timestamps is above any other token, sample timestamp
    UpperCAmelCase	:					Dict	=	jax.nn.log_softmax(_SCREAMING_SNAKE_CASE      ,     axis=-1						)

    def handle_cumulative_probs(_SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE						):
     UpperCAmelCase	:					Any	=	jax.nn.logsumexp(logprobs_k[self.timestamp_begin :]      ,     axis=-1						)
     UpperCAmelCase	:					Union[str, Any]	=	jnp.max(logprobs_k[: self.timestamp_begin]						)
     return jnp.where(
         timestamp_logprob > max_text_token_logprob      ,     scores_k.at[: self.timestamp_begin].set(-float("""inf"""						)						)      ,     _SCREAMING_SNAKE_CASE      ,     )

    UpperCAmelCase	:					str	=	jax.vmap(_SCREAMING_SNAKE_CASE						)(_SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE						)

    return scores




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


