






"""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 						__UpperCamelCase     (     nn.Module						):
					def __init__(							self							:	int     , 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     , )	->       Tuple:
											super().__init__()
											lowerCAmelCase   :int						=			nn.Convad(
											    in_channels=__lowerCamelCase     , out_channels=__lowerCamelCase     , kernel_size=__lowerCamelCase     , padding=__lowerCamelCase     , bias=__lowerCamelCase     , dilation=__lowerCamelCase     , )
											lowerCAmelCase   :Optional[int]						=			nn.BatchNormad(__lowerCamelCase   )
											lowerCAmelCase   :str						=			nn.ReLU()
					def        UpperCAmelCase__ (							self							:	Optional[Any]     , UpperCAmelCase							:	torch.Tensor   )	->       str:
											lowerCAmelCase   :str						=			self.conv(__lowerCamelCase   )
											lowerCAmelCase   :Dict						=			self.batch_norm(__lowerCamelCase   )
											lowerCAmelCase   :Optional[int]						=			self.activation(__lowerCamelCase   )

											return output




class 						__UpperCamelCase     (     nn.Module						):
					def __init__(							self							:	int     , UpperCAmelCase							:	int     , UpperCAmelCase							:	int     , UpperCAmelCase							:	int   )	->       Tuple:
											super().__init__()
											lowerCAmelCase   :Any						=			[
											    nn.AdaptiveAvgPoolad(__lowerCamelCase   ),
											    UperNetConvModule(__lowerCamelCase     , __lowerCamelCase     , kernel_size=1   ),
											]
											for i, layer in enumerate(self.layers   ):
																	self.add_module(str(__lowerCamelCase   )     , __lowerCamelCase   )
					def        UpperCAmelCase__ (							self							:	Any     , UpperCAmelCase							:	torch.Tensor   )	->       Optional[int]:
											lowerCAmelCase   :Union[str, Any]						=			input
											for layer in self.layers:
																	lowerCAmelCase   :Dict						=			layer(__lowerCamelCase   )
											return hidden_state




class 						__UpperCamelCase     (     nn.Module						):
					def __init__(							self							:	Union[str, Any]     , UpperCAmelCase							:	Tuple[int, ...]     , UpperCAmelCase							:	int     , UpperCAmelCase							:	int     , UpperCAmelCase							:	bool   )	->       Tuple:
											super().__init__()
											lowerCAmelCase   :List[str]						=			pool_scales
											lowerCAmelCase   :Dict						=			align_corners
											lowerCAmelCase   :Optional[int]						=			in_channels
											lowerCAmelCase   :int						=			channels
											lowerCAmelCase   :List[str]						=			[]
											for i, pool_scale in enumerate(__lowerCamelCase   ):
																	lowerCAmelCase   :str						=			UperNetPyramidPoolingBlock(pool_scale=__lowerCamelCase     , in_channels=__lowerCamelCase     , channels=__lowerCamelCase   )
																	self.blocks.append(__lowerCamelCase   )
																	self.add_module(str(__lowerCamelCase   )     , __lowerCamelCase   )
					def        UpperCAmelCase__ (							self							:	List[str]     , UpperCAmelCase							:	torch.Tensor   )	->       int:
											lowerCAmelCase   :Union[str, Any]						=			[]
											for ppm in self.blocks:
																	lowerCAmelCase   :Any						=			ppm(__lowerCamelCase   )
																	lowerCAmelCase   :str						=			nn.functional.interpolate(
																	    __lowerCamelCase     , size=x.size()[2:]     , mode='bilinear'     , align_corners=self.align_corners   )
																	ppm_outs.append(__lowerCamelCase   )
											return ppm_outs




class 						__UpperCamelCase     (     nn.Module						):
					def __init__(							self							:	Optional[Any]     , UpperCAmelCase							:	List[Any]     , UpperCAmelCase							:	Optional[int]   )	->       Any:
											super().__init__()

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

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

											lowerCAmelCase   :Union[str, Any]						=			UperNetConvModule(
											    len(self.in_channels   ) * self.channels     , self.channels     , kernel_size=3     , padding=1     , )
					def        UpperCAmelCase__ (							self							:	Dict   )	->       Union[str, Any]:
											self.apply(self._init_weights   )
					def        UpperCAmelCase__ (							self							:	Union[str, Any]     , UpperCAmelCase							:	Optional[Any]   )	->       str:
											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        UpperCAmelCase__ (							self							:	str     , UpperCAmelCase							:	Dict   )	->       Union[str, Any]:
											lowerCAmelCase   :Optional[int]						=			inputs[-1]
											lowerCAmelCase   :str						=			[x]
											psp_outs.extend(self.psp_modules(__lowerCamelCase   )   )
											lowerCAmelCase   :Dict						=			torch.cat(__lowerCamelCase     , dim=1   )
											lowerCAmelCase   :Any						=			self.bottleneck(__lowerCamelCase   )

											return output
					def        UpperCAmelCase__ (							self							:	Any     , UpperCAmelCase							:	torch.Tensor   )	->       Tuple:
											lowerCAmelCase   :Union[str, Any]						=			[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
											lowerCAmelCase   :Tuple						=			len(__lowerCamelCase   )
											for i in range(used_backbone_levels - 1     , 0     , -1   ):
																	lowerCAmelCase   :Union[str, Any]						=			laterals[i - 1].shape[2:]
																	lowerCAmelCase   :Union[str, Any]						=			laterals[i - 1] + nn.functional.interpolate(
																	    laterals[i]     , size=__lowerCamelCase     , mode='bilinear'     , align_corners=self.align_corners   )

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

											return output




class 						__UpperCamelCase     (     nn.Module						):
					def __init__(							self							:	Optional[Any]     , UpperCAmelCase							:	Dict     , UpperCAmelCase							:	int = 2     , UpperCAmelCase							:	int = 3     , UpperCAmelCase							:	Union[int, Tuple[int, int]] = 1   )	->       List[str]:
											super().__init__()

											lowerCAmelCase   :Tuple						=			config
											lowerCAmelCase   :Dict						=			config.auxiliary_in_channels
											lowerCAmelCase   :Optional[int]						=			config.auxiliary_channels
											lowerCAmelCase   :Any						=			config.auxiliary_num_convs
											lowerCAmelCase   :Tuple						=			config.auxiliary_concat_input
											lowerCAmelCase   :Union[str, Any]						=			in_index

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

											lowerCAmelCase   :Any						=			nn.Convad(self.channels     , config.num_labels     , kernel_size=1   )
					def        UpperCAmelCase__ (							self							:	Optional[Any]   )	->       Optional[int]:
											self.apply(self._init_weights   )
					def        UpperCAmelCase__ (							self							:	Union[str, Any]     , UpperCAmelCase							:	int   )	->       Optional[Any]:
											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        UpperCAmelCase__ (							self							:	List[Any]     , UpperCAmelCase							:	torch.Tensor   )	->       Tuple:
											lowerCAmelCase   :List[Any]						=			encoder_hidden_states[self.in_index]
											lowerCAmelCase   :Optional[Any]						=			self.convs(__lowerCamelCase   )
											if self.concat_input:
																	lowerCAmelCase   :str						=			self.conv_cat(torch.cat([hidden_states, output]     , dim=1   )   )
											lowerCAmelCase   :Optional[Any]						=			self.classifier(__lowerCamelCase   )
											return output




class 						__UpperCamelCase     (     __SCREAMING_SNAKE_CASE						):
					lowercase_    :				Optional[int]      =  UperNetConfig
					lowercase_    :				List[str]      =  '''pixel_values'''
					lowercase_    :				List[str]      =  True
					def        UpperCAmelCase__ (							self							:	List[str]     , UpperCAmelCase							:	Dict   )	->       List[str]:
											if isinstance(__lowerCamelCase     , __lowerCamelCase   ):
																	module.backbone.init_weights()
																	module.decode_head.init_weights()
																	module.auxiliary_head.init_weights()
					def        UpperCAmelCase__ (							self							:	int   )	->       Optional[int]:
											self.backbone.init_weights()
											self.decode_head.init_weights()
											self.auxiliary_head.init_weights()
					def        UpperCAmelCase__ (							self							:	Any     , UpperCAmelCase							:	Union[str, Any]     , UpperCAmelCase							:	List[str]=False   )	->       str:
											if isinstance(__lowerCamelCase     , __lowerCamelCase   ):
																	lowerCAmelCase   :Union[str, Any]						=			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."""   ,     __SCREAMING_SNAKE_CASE   ,     )
class 						__UpperCamelCase     (     __SCREAMING_SNAKE_CASE						):
					def __init__(							self							:	List[str]     , UpperCAmelCase							:	Dict   )	->       str:
											super().__init__(__lowerCamelCase   )

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

											# Semantic segmentation head(s)
											lowerCAmelCase   :Dict						=			UperNetHead(__lowerCamelCase     , in_channels=self.backbone.channels   )
											lowerCAmelCase   :Optional[Any]						=			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        UpperCAmelCase__ (							self							:	Optional[Any]     , UpperCAmelCase							:	Optional[torch.Tensor] = None     , UpperCAmelCase							:	Optional[bool] = None     , UpperCAmelCase							:	Optional[bool] = None     , UpperCAmelCase							:	Optional[torch.Tensor] = None     , UpperCAmelCase							:	Optional[bool] = None     , )	->       Any:
											lowerCAmelCase   :Optional[int]						=			return_dict if return_dict is not None else self.config.use_return_dict
											lowerCAmelCase   :str						=			(
											    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
											)
											lowerCAmelCase   :Optional[int]						=			output_attentions if output_attentions is not None else self.config.output_attentions

											lowerCAmelCase   :List[str]						=			self.backbone.forward_with_filtered_kwargs(
											    __lowerCamelCase     , output_hidden_states=__lowerCamelCase     , output_attentions=__lowerCamelCase   )
											lowerCAmelCase   :List[str]						=			outputs.feature_maps

											lowerCAmelCase   :Tuple						=			self.decode_head(__lowerCamelCase   )
											lowerCAmelCase   :Optional[int]						=			nn.functional.interpolate(__lowerCamelCase     , size=pixel_values.shape[2:]     , mode='bilinear'     , align_corners=__lowerCamelCase   )

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

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

											if not return_dict:
																	if output_hidden_states:
																							lowerCAmelCase   :Union[str, Any]						=			(logits,) + outputs[1:]
																	else:
																							lowerCAmelCase   :Optional[int]						=			(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     , )




"""simple docstring"""






import operator




def 			snake_case		(		lowerCAmelCase_  ,						lowerCAmelCase_ = False  ,						lowerCAmelCase_ = None	)						->				list:
  _snake_case   	=      operator.lt if reverse else operator.gt
  _snake_case   	=      solution or []

  if not arr:
    return solution

  _snake_case   	=      [arr.pop(0	)]
  for i, item in enumerate(lowerCAmelCase_	):
    if _operator(lowerCAmelCase_  ,						sublist[-1]	):
      sublist.append(lowerCAmelCase_	)
      arr.pop(lowerCAmelCase_	)

    #  merging sublist into solution list
  if not solution:
    solution.extend(lowerCAmelCase_	)
  else:
    while sublist:
      _snake_case   	=      sublist.pop(0	)
      for i, xx in enumerate(lowerCAmelCase_	):
        if not _operator(lowerCAmelCase_  ,						lowerCAmelCase_	):
          solution.insert(lowerCAmelCase_  ,						lowerCAmelCase_	)
          break
      else:
        solution.append(lowerCAmelCase_	)

  strand_sort(lowerCAmelCase_  ,						lowerCAmelCase_  ,						lowerCAmelCase_	)
  return solution


if __name__ == "__main__":
     assert strand_sort([4, 3, 5, 1, 2]) == [1, 2, 3, 4, 5]
     assert strand_sort([4, 3, 5, 1, 2], reverse=True) == [5, 4, 3, 2, 1]





