


from typing import List, Optional, Tuple, Union

import torch
from torch import nn
from torch.nn import CrossEntropyLoss

from ... import AutoBackbone
from ...modeling_outputs import SemanticSegmenterOutput
from ...modeling_utils import PreTrainedModel
from ...utils import add_start_docstrings, add_start_docstrings_to_model_forward, replace_return_docstrings
from ...utils.backbone_utils import BackboneMixin
from .configuration_upernet import UperNetConfig


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

# General docstring
A      = "UperNetConfig"


class     lowercase__  (					nn.Module		):






  def __init__(					self      :					int		,						_lowercase      :					int		,						_lowercase      :					int		,						_lowercase      :					Union[int, Tuple[int, int]]		,						_lowercase      :					Union[int, Tuple[int, int], str] = 0		,						_lowercase      :					bool = False		,						_lowercase      :					Union[int, Tuple[int, int]] = 1		,						):




         """simple docstring"""







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






  def 			_UpperCAmelCase  (					self      :					Optional[int]		,						_lowercase      :					torch.Tensor ):




         """simple docstring"""







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

         return output




class     lowercase__  (					nn.Module		):






  def __init__(					self      :					Union[str, Any]		,						_lowercase      :					int		,						_lowercase      :					int		,						_lowercase      :					int ):




         """simple docstring"""







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






  def 			_UpperCAmelCase  (					self      :					Dict		,						_lowercase      :					torch.Tensor ):




         """simple docstring"""







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




class     lowercase__  (					nn.Module		):






  def __init__(					self      :					List[Any]		,						_lowercase      :					Tuple[int, ...]		,						_lowercase      :					int		,						_lowercase      :					int		,						_lowercase      :					bool ):




         """simple docstring"""







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






  def 			_UpperCAmelCase  (					self      :					Optional[int]		,						_lowercase      :					torch.Tensor ):




         """simple docstring"""







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




class     lowercase__  (					nn.Module		):






  def __init__(					self      :					Union[str, Any]		,						_lowercase      :					str		,						_lowercase      :					List[str] ):




         """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(_lowercase		,						self.channels		,						kernel_size=1 )
                UpperCAmelCase__										=     UperNetConvModule(self.channels		,						self.channels		,						kernel_size=3		,						padding=1 )
                self.lateral_convs.append(_lowercase )
                self.fpn_convs.append(_lowercase )

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






  def 			_UpperCAmelCase  (					self      :					Union[str, Any] ):




         """simple docstring"""







         self.apply(self._init_weights )






  def 			_UpperCAmelCase  (					self      :					List[str]		,						_lowercase      :					Optional[int] ):




         """simple docstring"""







         if isinstance(_lowercase		,						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 			_UpperCAmelCase  (					self      :					Tuple		,						_lowercase      :					Optional[int] ):




         """simple docstring"""







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

         return output






  def 			_UpperCAmelCase  (					self      :					List[Any]		,						_lowercase      :					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(_lowercase ) )

         # build top-down path
         UpperCAmelCase__										=     len(_lowercase )
         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=_lowercase		,						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(_lowercase		,						dim=1 )
         UpperCAmelCase__										=     self.fpn_bottleneck(_lowercase )
         UpperCAmelCase__										=     self.classifier(_lowercase )

         return output




class     lowercase__  (					nn.Module		):






  def __init__(					self      :					Tuple		,						_lowercase      :					List[Any]		,						_lowercase      :					int = 2		,						_lowercase      :					int = 3		,						_lowercase      :					Union[int, Tuple[int, int]] = 1 ):




         """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=_lowercase		,						padding=_lowercase		,						dilation=_lowercase ) )
         for i in range(self.num_convs - 1 ):
                convs.append(
                    UperNetConvModule(
                        self.channels		,						self.channels		,						kernel_size=_lowercase		,						padding=_lowercase		,						dilation=_lowercase ) )
         if self.num_convs == 0:
                UpperCAmelCase__										=     nn.Identity()
         else:
                UpperCAmelCase__										=     nn.Sequential(*_lowercase )
         if self.concat_input:
                UpperCAmelCase__										=     UperNetConvModule(
                    self.in_channels + self.channels		,						self.channels		,						kernel_size=_lowercase		,						padding=kernel_size // 2 )

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






  def 			_UpperCAmelCase  (					self      :					Dict ):




         """simple docstring"""







         self.apply(self._init_weights )






  def 			_UpperCAmelCase  (					self      :					Optional[int]		,						_lowercase      :					int ):




         """simple docstring"""







         if isinstance(_lowercase		,						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 			_UpperCAmelCase  (					self      :					str		,						_lowercase      :					torch.Tensor ):




         """simple docstring"""







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




class     lowercase__  (					__SCREAMING_SNAKE_CASE		):
  A__=  UperNetConfig
  A__=  'pixel_values'
  A__=  True






  def 			_UpperCAmelCase  (					self      :					int		,						_lowercase      :					int ):




         """simple docstring"""







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






  def 			_UpperCAmelCase  (					self      :					List[Any] ):




         """simple docstring"""







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






  def 			_UpperCAmelCase  (					self      :					Optional[int]		,						_lowercase      :					List[str]		,						_lowercase      :					Dict=False ):




         """simple docstring"""







         if isinstance(_lowercase		,						_lowercase ):
                UpperCAmelCase__										=     value




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

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


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






  def __init__(					self      :					Any		,						_lowercase      :					Optional[int] ):




         """simple docstring"""







         super().__init__(_lowercase )

         UpperCAmelCase__										=     AutoBackbone.from_config(config.backbone_config )

         # Semantic segmentation head(s)
         UpperCAmelCase__										=     UperNetHead(_lowercase		,						in_channels=self.backbone.channels )
         UpperCAmelCase__										=     UperNetFCNHead(_lowercase ) 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=_lowercase		,						config_class=_CONFIG_FOR_DOC )
  def 			_UpperCAmelCase  (					self      :					Tuple		,						_lowercase      :					Optional[torch.Tensor] = None		,						_lowercase      :					Optional[bool] = None		,						_lowercase      :					Optional[bool] = None		,						_lowercase      :					Optional[torch.Tensor] = None		,						_lowercase      :					Optional[bool] = None		,						):




         """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(
             _lowercase		,						output_hidden_states=_lowercase		,						output_attentions=_lowercase )
         UpperCAmelCase__										=     outputs.feature_maps

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

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

         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(_lowercase		,						_lowercase )
                       UpperCAmelCase__										=     loss_fct(_lowercase		,						_lowercase )
                       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=_lowercase		,						logits=_lowercase		,						hidden_states=outputs.hidden_states		,						attentions=outputs.attentions		,						)









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



       '''simple docstring'''





       UpperCAmelCase__										=     len(__A			)
       for i in range(__A			):
              for j in range(i + 1 ,						__A			):
                     if numbers[j] < numbers[i]:
                            UpperCAmelCase__						,			UpperCAmelCase__										=     numbers[j], numbers[i]
       return numbers


if __name__ == "__main__":
    A      = input("Enter numbers separated by a comma:\n").strip()
    A      = [int(item) for item in user_input.split(",")]
    print(exchange_sort(unsorted))





