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 					A							(    nn.Module					):


   def __init__(self					:						Union[str, Any]	,  __UpperCAmelCase					:						int	,  __UpperCAmelCase					:						int	,  __UpperCAmelCase					:						Union[int, Tuple[int, int]]	,  __UpperCAmelCase					:						Union[int, Tuple[int, int], str] = 0	,  __UpperCAmelCase					:						bool = False	,  __UpperCAmelCase					:						Union[int, Tuple[int, int]] = 1	,  )						->    None:
         """simple docstring"""



         super().__init__()
         UpperCAmelCase__								=  nn.Convad(
             in_channels=__UpperCAmelCase	,  out_channels=__UpperCAmelCase	,  kernel_size=__UpperCAmelCase	,  padding=__UpperCAmelCase	,  bias=__UpperCAmelCase	,  dilation=__UpperCAmelCase	,  )
         UpperCAmelCase__								=  nn.BatchNormad(__UpperCAmelCase		)
         UpperCAmelCase__								=  nn.ReLU()





   def       lowercase_				(self					:						List[str]	,  __UpperCAmelCase					:						torch.Tensor		)						->    torch.Tensor:
         """simple docstring"""



         UpperCAmelCase__								=  self.conv(__UpperCAmelCase		)
         UpperCAmelCase__								=  self.batch_norm(__UpperCAmelCase		)
         UpperCAmelCase__								=  self.activation(__UpperCAmelCase		)

         return output





class 					A							(    nn.Module					):


   def __init__(self					:						int	,  __UpperCAmelCase					:						int	,  __UpperCAmelCase					:						int	,  __UpperCAmelCase					:						int		)						->    None:
         """simple docstring"""



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





   def       lowercase_				(self					:						List[Any]	,  __UpperCAmelCase					:						torch.Tensor		)						->    torch.Tensor:
         """simple docstring"""



         UpperCAmelCase__								=  input
         for layer in self.layers:
               UpperCAmelCase__								=  layer(__UpperCAmelCase		)
         return hidden_state





class 					A							(    nn.Module					):


   def __init__(self					:						Tuple	,  __UpperCAmelCase					:						Tuple[int, ...]	,  __UpperCAmelCase					:						int	,  __UpperCAmelCase					:						int	,  __UpperCAmelCase					:						bool		)						->    None:
         """simple docstring"""



         super().__init__()
         UpperCAmelCase__								=  pool_scales
         UpperCAmelCase__								=  align_corners
         UpperCAmelCase__								=  in_channels
         UpperCAmelCase__								=  channels
         UpperCAmelCase__								=  []
         for i, pool_scale in enumerate(__UpperCAmelCase		):
               UpperCAmelCase__								=  UperNetPyramidPoolingBlock(pool_scale=__UpperCAmelCase	,  in_channels=__UpperCAmelCase	,  channels=__UpperCAmelCase		)
               self.blocks.append(__UpperCAmelCase		)
               self.add_module(str(__UpperCAmelCase		)	,  __UpperCAmelCase		)





   def       lowercase_				(self					:						str	,  __UpperCAmelCase					:						torch.Tensor		)						->    List[torch.Tensor]:
         """simple docstring"""



         UpperCAmelCase__								=  []
         for ppm in self.blocks:
               UpperCAmelCase__								=  ppm(__UpperCAmelCase		)
               UpperCAmelCase__								=  nn.functional.interpolate(
                   __UpperCAmelCase	,  size=x.size()[2:]	,  mode="bilinear"	,  align_corners=self.align_corners		)
               ppm_outs.append(__UpperCAmelCase		)
         return ppm_outs





class 					A							(    nn.Module					):


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



         super().__init__()

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

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

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


   def       lowercase_				(self					:						int		)						->    Any:
         """simple docstring"""



         self.apply(self._init_weights		)


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



         if isinstance(__UpperCAmelCase	,  nn.Convad		):
               module.weight.data.normal_(mean=0.0	,  std=self.config.initializer_range		)
               if module.bias is not None:
                     module.bias.data.zero_()


   def       lowercase_				(self					:						int	,  __UpperCAmelCase					:						Optional[int]		)						->    Tuple:
         """simple docstring"""



         UpperCAmelCase__								=  inputs[-1]
         UpperCAmelCase__								=  [x]
         psp_outs.extend(self.psp_modules(__UpperCAmelCase		)		)
         UpperCAmelCase__								=  torch.cat(__UpperCAmelCase	,  dim=1		)
         UpperCAmelCase__								=  self.bottleneck(__UpperCAmelCase		)

         return output





   def       lowercase_				(self					:						Tuple	,  __UpperCAmelCase					:						torch.Tensor		)						->    torch.Tensor:
         """simple docstring"""



         UpperCAmelCase__								=  [lateral_conv(encoder_hidden_states[i]		) for i, lateral_conv in enumerate(self.lateral_convs		)]

         laterals.append(self.psp_forward(__UpperCAmelCase		)		)

         # build top-down path
         UpperCAmelCase__								=  len(__UpperCAmelCase		)
         for i in range(used_backbone_levels - 1	,  0	,  -1		):
               UpperCAmelCase__								=  laterals[i - 1].shape[2:]
               UpperCAmelCase__								=  laterals[i - 1] + nn.functional.interpolate(
                   laterals[i]	,  size=__UpperCAmelCase	,  mode="bilinear"	,  align_corners=self.align_corners		)

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

         return output





class 					A							(    nn.Module					):


   def __init__(self					:						List[Any]	,  __UpperCAmelCase					:						Any	,  __UpperCAmelCase					:						int = 2	,  __UpperCAmelCase					:						int = 3	,  __UpperCAmelCase					:						Union[int, Tuple[int, int]] = 1		)						->    None:
         """simple docstring"""



         super().__init__()

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

         UpperCAmelCase__								=  (kernel_size // 2) * dilation
         UpperCAmelCase__								=  []
         convs.append(
             UperNetConvModule(
                 self.in_channels	,  self.channels	,  kernel_size=__UpperCAmelCase	,  padding=__UpperCAmelCase	,  dilation=__UpperCAmelCase		)		)
         for i in range(self.num_convs - 1		):
               convs.append(
                   UperNetConvModule(
                       self.channels	,  self.channels	,  kernel_size=__UpperCAmelCase	,  padding=__UpperCAmelCase	,  dilation=__UpperCAmelCase		)		)
         if self.num_convs == 0:
               UpperCAmelCase__								=  nn.Identity()
         else:
               UpperCAmelCase__								=  nn.Sequential(*__UpperCAmelCase		)
         if self.concat_input:
               UpperCAmelCase__								=  UperNetConvModule(
                   self.in_channels + self.channels	,  self.channels	,  kernel_size=__UpperCAmelCase	,  padding=kernel_size // 2		)

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


   def       lowercase_				(self					:						Optional[Any]		)						->    Tuple:
         """simple docstring"""



         self.apply(self._init_weights		)


   def       lowercase_				(self					:						Optional[int]	,  __UpperCAmelCase					:						Optional[int]		)						->    str:
         """simple docstring"""



         if isinstance(__UpperCAmelCase	,  nn.Convad		):
               module.weight.data.normal_(mean=0.0	,  std=self.config.initializer_range		)
               if module.bias is not None:
                     module.bias.data.zero_()





   def       lowercase_				(self					:						Optional[Any]	,  __UpperCAmelCase					:						torch.Tensor		)						->    torch.Tensor:
         """simple docstring"""



         UpperCAmelCase__								=  encoder_hidden_states[self.in_index]
         UpperCAmelCase__								=  self.convs(__UpperCAmelCase		)
         if self.concat_input:
               UpperCAmelCase__								=  self.conv_cat(torch.cat([hidden_states, output]	,  dim=1		)		)
         UpperCAmelCase__								=  self.classifier(__UpperCAmelCase		)
         return output





class 					A							(    UpperCAmelCase_					):
   __UpperCAmelCase			:			int              =      UperNetConfig
   __UpperCAmelCase			:			int              =      'pixel_values'
   __UpperCAmelCase			:			List[Any]              =      True


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



         if isinstance(__UpperCAmelCase	,  __UpperCAmelCase		):
               module.backbone.init_weights()
               module.decode_head.init_weights()
               module.auxiliary_head.init_weights()


   def       lowercase_				(self					:						Dict		)						->    Tuple:
         """simple docstring"""



         self.backbone.init_weights()
         self.decode_head.init_weights()
         self.auxiliary_head.init_weights()





   def       lowercase_				(self					:						Optional[int]	,  __UpperCAmelCase					:						Any	,  __UpperCAmelCase					:						Optional[int]=False		)						->    List[Any]:
         """simple docstring"""



         if isinstance(__UpperCAmelCase	,  __UpperCAmelCase		):
               UpperCAmelCase__								=  value




UpperCamelCase__    							= 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__    							= R'\n    Args:\n        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n            Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using\n            [`AutoImageProcessor`]. See [`SegformerImageProcessor.__call__`] for details.\n        output_attentions (`bool`, *optional*):\n            Whether or not to return the attentions tensors of all attention layers in case the backbone has them. See\n            `attentions` under returned tensors for more detail.\n        output_hidden_states (`bool`, *optional*):\n            Whether or not to return the hidden states of all layers of the backbone. See `hidden_states` under\n            returned tensors for more detail.\n        return_dict (`bool`, *optional*):\n            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n'





@add_start_docstrings(
    'UperNet framework leveraging any vision backbone e.g. for ADE20k, CityScapes.'		,    UpperCAmelCase_		,    )
class 					A							(    UpperCAmelCase_					):


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



         super().__init__(__UpperCAmelCase		)

         UpperCAmelCase__								=  AutoBackbone.from_config(config.backbone_config		)

         # Semantic segmentation head(s)
         UpperCAmelCase__								=  UperNetHead(__UpperCAmelCase	,  in_channels=self.backbone.channels		)
         UpperCAmelCase__								=  UperNetFCNHead(__UpperCAmelCase		) if config.use_auxiliary_head else None

         # Initialize weights and apply final processing
         self.post_init()





   @add_start_docstrings_to_model_forward(UPERNET_INPUTS_DOCSTRING.format("batch_size, sequence_length"		)		)
   @replace_return_docstrings(output_type=__UpperCAmelCase	,  config_class=_CONFIG_FOR_DOC		)
   def       lowercase_				(self					:						Optional[int]	,  __UpperCAmelCase					:						Optional[torch.Tensor] = None	,  __UpperCAmelCase					:						Optional[bool] = None	,  __UpperCAmelCase					:						Optional[bool] = None	,  __UpperCAmelCase					:						Optional[torch.Tensor] = None	,  __UpperCAmelCase					:						Optional[bool] = None	,  )						->    Union[tuple, SemanticSegmenterOutput]:
         """simple docstring"""



         UpperCAmelCase__								=  return_dict if return_dict is not None else self.config.use_return_dict
         UpperCAmelCase__								=  (
             output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
         )
         UpperCAmelCase__								=  output_attentions if output_attentions is not None else self.config.output_attentions

         UpperCAmelCase__								=  self.backbone.forward_with_filtered_kwargs(
             __UpperCAmelCase	,  output_hidden_states=__UpperCAmelCase	,  output_attentions=__UpperCAmelCase		)
         UpperCAmelCase__								=  outputs.feature_maps

         UpperCAmelCase__								=  self.decode_head(__UpperCAmelCase		)
         UpperCAmelCase__								=  nn.functional.interpolate(__UpperCAmelCase	,  size=pixel_values.shape[2:]	,  mode="bilinear"	,  align_corners=__UpperCAmelCase		)

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

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

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

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




from __future__ import annotations




def        lowerCAmelCase_			(					__A							)					->    list[int]:







      '''simple docstring'''


      if len(__A							) == 0:
            return array

      UpperCAmelCase__		,				UpperCAmelCase__								=  min(__A							), max(__A							)

      # Compute the variables
      UpperCAmelCase__								=  _max - _min + 1
      UpperCAmelCase__		,				UpperCAmelCase__								=  [0] * holes_range, [0] * holes_range

      # Make the sorting.
      for i in array:
            UpperCAmelCase__								=  i - _min
            UpperCAmelCase__								=  i
            holes_repeat[index] += 1

      # Makes the array back by replacing the numbers.
      UpperCAmelCase__								=  0
      for i in range(__A							):
            while holes_repeat[i] > 0:
                  UpperCAmelCase__								=  holes[i]
                  index += 1
                  holes_repeat[i] -= 1

    # Returns the sorted array.
      return array


if __name__ == "__main__":
      import doctest

      doctest.testmod()
      UpperCamelCase__    							= input('Enter numbers separated by comma:\n')
      UpperCamelCase__    							= [int(x) for x in user_input.split(',')]
      print(pigeon_sort(unsorted))



