





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


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

# General docstring
SCREAMING_SNAKE_CASE__					=   "UperNetConfig"

class 		lowercase					(					nn.Module					):





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





      def     _snake_case			(       self      ,						lowercase )		->     torch.Tensor:
            lowerCAmelCase  						=       self.conv(lowercase )
            lowerCAmelCase  						=       self.batch_norm(lowercase )
            lowerCAmelCase  						=       self.activation(lowercase )

            return output







class 		lowercase					(					nn.Module					):





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





      def     _snake_case			(       self      ,						lowercase )		->     torch.Tensor:
            lowerCAmelCase  						=       input
            for layer in self.layers:
                  lowerCAmelCase  						=       layer(lowercase )
            return hidden_state







class 		lowercase					(					nn.Module					):





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





      def     _snake_case			(       self      ,						lowercase )		->     List[torch.Tensor]:
            lowerCAmelCase  						=       []
            for ppm in self.blocks:
                  lowerCAmelCase  						=       ppm(lowercase )
                  lowerCAmelCase  						=       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      ,						lowercase      ,						lowercase )		->     Union[str, Any]:
            super().__init__()

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

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

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





      def     _snake_case			(       self )		->     str:
            self.apply(self._init_weights )





      def     _snake_case			(       self      ,						lowercase )		->     List[str]:
            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     _snake_case			(       self      ,						lowercase )		->     Dict:
            lowerCAmelCase  						=       inputs[-1]
            lowerCAmelCase  						=       [x]
            psp_outs.extend(self.psp_modules(lowercase ) )
            lowerCAmelCase  						=       torch.cat(lowercase      ,						dim=1 )
            lowerCAmelCase  						=       self.bottleneck(lowercase )

            return output





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

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

            return output







class 		lowercase					(					nn.Module					):





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

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

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

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





      def     _snake_case			(       self )		->     Any:
            self.apply(self._init_weights )





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







class 		lowercase					(					_UpperCAmelCase					):
      _SCREAMING_SNAKE_CASE					=      UperNetConfig
      _SCREAMING_SNAKE_CASE					=      'pixel_values'
      _SCREAMING_SNAKE_CASE					=      True





      def     _snake_case			(       self      ,						lowercase )		->     Union[str, Any]:
            if isinstance(lowercase      ,						lowercase ):
                  module.backbone.init_weights()
                  module.decode_head.init_weights()
                  module.auxiliary_head.init_weights()





      def     _snake_case			(       self )		->     List[Any]:
            self.backbone.init_weights()
            self.decode_head.init_weights()
            self.auxiliary_head.init_weights()





      def     _snake_case			(       self      ,						lowercase      ,						lowercase=False )		->     Any:
            if isinstance(lowercase      ,						lowercase ):
                  lowerCAmelCase  						=       value







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

SCREAMING_SNAKE_CASE__					=   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 		lowercase					(					_UpperCAmelCase					):





      def __init__(       self      ,						lowercase )		->     Union[str, Any]:
            super().__init__(lowercase )

            lowerCAmelCase  						=       AutoBackbone.from_config(config.backbone_config )

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

            lowerCAmelCase  						=       self.backbone.forward_with_filtered_kwargs(
                lowercase      ,						output_hidden_states=lowercase      ,						output_attentions=lowercase )
            lowerCAmelCase  						=       outputs.feature_maps

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

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

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

            if not return_dict:
                  if output_hidden_states:
                        lowerCAmelCase  						=       (logits,) + outputs[1:]
                  else:
                        lowerCAmelCase  						=       (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 A_	(		A__				)  ->		int:
       stooge(A__		,      0		,      len(A__				) - 1				)
       return arr



def A_	(		A__		,      A__		,      A__				)  ->		List[Any]:
       if i >= h:
              return

       # If first element is smaller than the last then swap them
       if arr[i] > arr[h]:
              a__ ,							a__						:	List[str] =				arr[h], arr[i]

       # If there are more than 2 elements in the array
       if h - i + 1 > 2:
              a__						:	Dict =				(int)((h - i + 1) / 3				)

              # Recursively sort first 2/3 elements
              stooge(A__		,      A__		,      (h - t)				)

              # Recursively sort last 2/3 elements
              stooge(A__		,      i + t		,      (A__)				)

              # Recursively sort first 2/3 elements
              stooge(A__		,      A__		,      (h - t)				)


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


