

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







				def __init__(       self     :		str		,					UpperCAmelCase__     :		Optional[int]		,					UpperCAmelCase__     :		int		,					UpperCAmelCase__     :		Optional[Any]		,					UpperCAmelCase__     :		Optional[Any] = 0		,					UpperCAmelCase__     :		List[str] = False		,					UpperCAmelCase__     :		Optional[int] = 1		,					):
										'''simple docstring'''
										super().__init__()
										lowercase :							Tuple    		=nn.Convad(
										    in_channels=A_		,					out_channels=A_		,					kernel_size=A_		,					padding=A_		,					bias=A_		,					dilation=A_		,					)
										lowercase :							int    		=nn.BatchNormad(A_   )
										lowercase :							Union[str, Any]    		=nn.ReLU()







				def  lowerCamelCase_	(       self     :		Any		,					UpperCAmelCase__     :		List[str]   ):
										'''simple docstring'''
										lowercase :							str    		=self.conv(A_   )
										lowercase :							Tuple    		=self.batch_norm(A_   )
										lowercase :							int    		=self.activation(A_   )

										return output





class 		__SCREAMING_SNAKE_CASE							(			nn.Module      ):







				def __init__(       self     :		Union[str, Any]		,					UpperCAmelCase__     :		Any		,					UpperCAmelCase__     :		Union[str, Any]		,					UpperCAmelCase__     :		Any   ):
										'''simple docstring'''
										super().__init__()
										lowercase :							str    		=[
										    nn.AdaptiveAvgPoolad(A_   ),
										    UperNetConvModule(A_		,					A_		,					kernel_size=1   ),
										]
										for i, layer in enumerate(self.layers   ):
																self.add_module(str(A_   )		,					A_   )







				def  lowerCamelCase_	(       self     :		Union[str, Any]		,					UpperCAmelCase__     :		int   ):
										'''simple docstring'''
										lowercase :							Any    		=input
										for layer in self.layers:
																lowercase :							List[Any]    		=layer(A_   )
										return hidden_state





class 		__SCREAMING_SNAKE_CASE							(			nn.Module      ):







				def __init__(       self     :		Optional[Any]		,					UpperCAmelCase__     :		List[Any]		,					UpperCAmelCase__     :		str		,					UpperCAmelCase__     :		Dict		,					UpperCAmelCase__     :		Optional[int]   ):
										'''simple docstring'''
										super().__init__()
										lowercase :							List[Any]    		=pool_scales
										lowercase :							Tuple    		=align_corners
										lowercase :							Any    		=in_channels
										lowercase :							Optional[int]    		=channels
										lowercase :							Dict    		=[]
										for i, pool_scale in enumerate(A_   ):
																lowercase :							Optional[Any]    		=UperNetPyramidPoolingBlock(pool_scale=A_		,					in_channels=A_		,					channels=A_   )
																self.blocks.append(A_   )
																self.add_module(str(A_   )		,					A_   )







				def  lowerCamelCase_	(       self     :		Optional[Any]		,					UpperCAmelCase__     :		Optional[int]   ):
										'''simple docstring'''
										lowercase :							str    		=[]
										for ppm in self.blocks:
																lowercase :							int    		=ppm(A_   )
																lowercase :							int    		=nn.functional.interpolate(
																    A_		,					size=x.size()[2:]		,					mode='''bilinear'''		,					align_corners=self.align_corners   )
																ppm_outs.append(A_   )
										return ppm_outs





class 		__SCREAMING_SNAKE_CASE							(			nn.Module      ):







				def __init__(       self     :		Dict		,					UpperCAmelCase__     :		Optional[int]		,					UpperCAmelCase__     :		Tuple   ):
										'''simple docstring'''
										super().__init__()

										lowercase :							str    		=config
										lowercase :							Dict    		=config.pool_scales  # e.g. (1, 2, 3, 6)
										lowercase :							Union[str, Any]    		=in_channels
										lowercase :							Optional[Any]    		=config.hidden_size
										lowercase :							Optional[int]    		=False
										lowercase :							Any    		=nn.Convad(self.channels		,					config.num_labels		,					kernel_size=1   )

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

										lowercase :							int    		=UperNetConvModule(
										    len(self.in_channels   ) * self.channels		,					self.channels		,					kernel_size=3		,					padding=1		,					)







				def  lowerCamelCase_	(       self     :		Tuple   ):
										'''simple docstring'''
										self.apply(self._init_weights   )







				def  lowerCamelCase_	(       self     :		Optional[Any]		,					UpperCAmelCase__     :		Dict   ):
										'''simple docstring'''
										if isinstance(A_		,					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  lowerCamelCase_	(       self     :		List[Any]		,					UpperCAmelCase__     :		List[Any]   ):
										'''simple docstring'''
										lowercase :							List[Any]    		=inputs[-1]
										lowercase :							int    		=[x]
										psp_outs.extend(self.psp_modules(A_   )   )
										lowercase :							List[Any]    		=torch.cat(A_		,					dim=1   )
										lowercase :							int    		=self.bottleneck(A_   )

										return output







				def  lowerCamelCase_	(       self     :		Dict		,					UpperCAmelCase__     :		Union[str, Any]   ):
										'''simple docstring'''
										# build laterals
										lowercase :							Dict    		=[lateral_conv(encoder_hidden_states[i]   ) for i, lateral_conv in enumerate(self.lateral_convs   )]

										laterals.append(self.psp_forward(A_   )   )

										# build top-down path
										lowercase :							List[str]    		=len(A_   )
										for i in range(used_backbone_levels - 1		,					0		,					-1   ):
																lowercase :							List[Any]    		=laterals[i - 1].shape[2:]
																lowercase :							List[str]    		=laterals[i - 1] + nn.functional.interpolate(
																    laterals[i]		,					size=A_		,					mode='''bilinear'''		,					align_corners=self.align_corners   )

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

										return output





class 		__SCREAMING_SNAKE_CASE							(			nn.Module      ):







				def __init__(       self     :		List[Any]		,					UpperCAmelCase__     :		str		,					UpperCAmelCase__     :		List[str] = 2		,					UpperCAmelCase__     :		Any = 3		,					UpperCAmelCase__     :		List[str] = 1   ):
										'''simple docstring'''
										super().__init__()

										lowercase :							Optional[int]    		=config
										lowercase :							Union[str, Any]    		=config.auxiliary_in_channels
										lowercase :							Optional[Any]    		=config.auxiliary_channels
										lowercase :							List[str]    		=config.auxiliary_num_convs
										lowercase :							List[str]    		=config.auxiliary_concat_input
										lowercase :							str    		=in_index

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

										lowercase :							List[str]    		=nn.Convad(self.channels		,					config.num_labels		,					kernel_size=1   )







				def  lowerCamelCase_	(       self     :		str   ):
										'''simple docstring'''
										self.apply(self._init_weights   )







				def  lowerCamelCase_	(       self     :		Optional[Any]		,					UpperCAmelCase__     :		Dict   ):
										'''simple docstring'''
										if isinstance(A_		,					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  lowerCamelCase_	(       self     :		List[str]		,					UpperCAmelCase__     :		List[str]   ):
										'''simple docstring'''
										# just take the relevant feature maps
										lowercase :							Tuple    		=encoder_hidden_states[self.in_index]
										lowercase :							List[Any]    		=self.convs(A_   )
										if self.concat_input:
																lowercase :							Tuple    		=self.conv_cat(torch.cat([hidden_states, output]		,					dim=1   )   )
										lowercase :							Optional[int]    		=self.classifier(A_   )
										return output





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







				def  lowerCamelCase_	(       self     :		Union[str, Any]		,					UpperCAmelCase__     :		Any   ):
										'''simple docstring'''
										if isinstance(A_		,					A_   ):
																module.backbone.init_weights()
																module.decode_head.init_weights()
																module.auxiliary_head.init_weights()







				def  lowerCamelCase_	(       self     :		str   ):
										'''simple docstring'''
										self.backbone.init_weights()
										self.decode_head.init_weights()
										self.auxiliary_head.init_weights()







				def  lowerCamelCase_	(       self     :		Dict		,					UpperCAmelCase__     :		Tuple		,					UpperCAmelCase__     :		Union[str, Any]=False   ):
										'''simple docstring'''
										if isinstance(A_		,					A_   ):
																lowercase :							str    		=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.'						,							lowercase__						,							)
class 		__SCREAMING_SNAKE_CASE							(			lowercase__      ):







				def __init__(       self     :		str		,					UpperCAmelCase__     :		Optional[Any]   ):
										'''simple docstring'''
										super().__init__(A_   )

										lowercase :							str    		=AutoBackbone.from_config(config.backbone_config   )

										# Semantic segmentation head(s)
										lowercase :							int    		=UperNetHead(A_		,					in_channels=self.backbone.channels   )
										lowercase :							Dict    		=UperNetFCNHead(A_   ) 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=A_		,					config_class=_CONFIG_FOR_DOC   )
				def  lowerCamelCase_	(       self     :		Union[str, Any]		,					UpperCAmelCase__     :		Optional[Any] = None		,					UpperCAmelCase__     :		List[str] = None		,					UpperCAmelCase__     :		Optional[Any] = None		,					UpperCAmelCase__     :		Optional[int] = None		,					UpperCAmelCase__     :		str = None		,					):
										'''simple docstring'''
										lowercase :							List[Any]    		=return_dict if return_dict is not None else self.config.use_return_dict
										lowercase :							List[str]    		=(
										    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
										)
										lowercase :							Optional[int]    		=output_attentions if output_attentions is not None else self.config.output_attentions

										lowercase :							List[Any]    		=self.backbone.forward_with_filtered_kwargs(
										    A_		,					output_hidden_states=A_		,					output_attentions=A_   )
										lowercase :							Tuple    		=outputs.feature_maps

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

										lowercase :							str    		=None
										if self.auxiliary_head is not None:
																lowercase :							List[Any]    		=self.auxiliary_head(A_   )
																lowercase :							Any    		=nn.functional.interpolate(
																    A_		,					size=pixel_values.shape[2:]		,					mode='''bilinear'''		,					align_corners=A_   )

										lowercase :							Tuple    		=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
																						lowercase :							Optional[int]    		=CrossEntropyLoss(ignore_index=self.config.loss_ignore_index   )
																						lowercase :							List[str]    		=loss_fct(A_		,					A_   )
																						lowercase :							List[str]    		=loss_fct(A_		,					A_   )
																						lowercase :							List[str]    		=main_loss + self.config.auxiliary_loss_weight * auxiliary_loss

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

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












def 				_UpperCAmelCase			(    A     ):




   '''simple docstring'''

   for i in range(len(A     ) - 1				,							0				,							-1     ):
      UpperCAmelCase__						=False

      for j in range(A				,							0				,							-1     ):
         if unsorted[j] < unsorted[j - 1]:
            UpperCAmelCase__			,							UpperCAmelCase__						=unsorted[j - 1], unsorted[j]
            UpperCAmelCase__						=True

      for j in range(A     ):
         if unsorted[j] > unsorted[j + 1]:
            UpperCAmelCase__			,							UpperCAmelCase__						=unsorted[j + 1], unsorted[j]
            UpperCAmelCase__						=True

      if not swapped:
         break
   return unsorted


if __name__ == "__main__":
    import doctest

    doctest.testmod()
    UpperCamelCase_												=	input('Enter numbers separated by a comma:\n').strip()
    UpperCamelCase_												=	[int(item) for item in user_input.split(',')]
    print(f"""{cocktail_shaker_sort(unsorted) = }""")



