


import collections.abc
from typing import Optional, Tuple, Union

import torch
import torch.utils.checkpoint
from torch import nn
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss

from ...activations import ACTaFN
from ...modeling_outputs import BaseModelOutputWithNoAttention, ImageClassifierOutputWithNoAttention
from ...modeling_utils import PreTrainedModel
from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging
from .configuration_poolformer import PoolFormerConfig


__snake_case									=		logging.get_logger(__name__)

# General docstring
__snake_case									=		'''PoolFormerConfig'''

# Base docstring
__snake_case									=		'''sail/poolformer_s12'''
__snake_case									=		[1, 5_1_2, 7, 7]

# Image classification docstring
__snake_case									=		'''sail/poolformer_s12'''
__snake_case									=		'''tabby, tabby cat'''

__snake_case									=		[
    '''sail/poolformer_s12''',
    # See all PoolFormer models at https://huggingface.co/models?filter=poolformer
]






def 						_A						(						_lowercase ,   _lowercase = 0.0 ,   _lowercase = False      ) ->      Optional[Any]:


     """simple docstring"""


     if drop_prob == 0.0 or not training:
          return input
     __UpperCamelCase      =       1 - drop_prob
     __UpperCamelCase      =       (input.shape[0],) + (1,) * (input.ndim - 1)  # work with diff dim tensors, not just 2D ConvNets
     __UpperCamelCase      =       keep_prob + torch.rand(snake_case__ ,   dtype=input.dtype ,   device=input.device      )
     random_tensor.floor_()  # binarize
     __UpperCamelCase      =       input.div(snake_case__      ) * random_tensor
     return output



class      __lowerCamelCase       (nn.Module		):







       def __init__(       self:      Dict,A_:      Optional[float] = None ):






            '''simple docstring'''




            super().__init__()
            __UpperCamelCase      =       drop_prob







       def 						snake_case_     (       self:      Tuple,A_:      torch.Tensor ):






            '''simple docstring'''




            return drop_path(SCREAMING_SNAKE_CASE_,self.drop_prob,self.training )







       def 						snake_case_     (       self:      str ):






            '''simple docstring'''




            return "p={}".format(self.drop_prob )



class      __lowerCamelCase       (nn.Module		):







       def __init__(       self:      Tuple,A_:      Optional[int],A_:      Optional[Any],A_:      Any,A_:      Dict,A_:      Dict,A_:      Any=None ):






            '''simple docstring'''




            super().__init__()
            __UpperCamelCase      =       patch_size if isinstance(SCREAMING_SNAKE_CASE_,collections.abc.Iterable ) else (patch_size, patch_size)
            __UpperCamelCase      =       stride if isinstance(SCREAMING_SNAKE_CASE_,collections.abc.Iterable ) else (stride, stride)
            __UpperCamelCase      =       padding if isinstance(SCREAMING_SNAKE_CASE_,collections.abc.Iterable ) else (padding, padding)

            __UpperCamelCase      =       nn.Convad(SCREAMING_SNAKE_CASE_,SCREAMING_SNAKE_CASE_,kernel_size=SCREAMING_SNAKE_CASE_,stride=SCREAMING_SNAKE_CASE_,padding=SCREAMING_SNAKE_CASE_ )
            __UpperCamelCase      =       norm_layer(SCREAMING_SNAKE_CASE_ ) if norm_layer else nn.Identity()







       def 						snake_case_     (       self:      str,A_:      int ):






            '''simple docstring'''




            __UpperCamelCase      =       self.projection(SCREAMING_SNAKE_CASE_ )
            __UpperCamelCase      =       self.norm(SCREAMING_SNAKE_CASE_ )
            return embeddings



class      __lowerCamelCase       (nn.GroupNorm		):







       def __init__(       self:      Union[str, Any],A_:      Optional[Any],**A_:      int ):






            '''simple docstring'''




            super().__init__(1,SCREAMING_SNAKE_CASE_,**SCREAMING_SNAKE_CASE_ )



class      __lowerCamelCase       (nn.Module		):







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






            '''simple docstring'''




            super().__init__()
            __UpperCamelCase      =       nn.AvgPoolad(SCREAMING_SNAKE_CASE_,stride=1,padding=pool_size // 2,count_include_pad=SCREAMING_SNAKE_CASE_ )







       def 						snake_case_     (       self:      Optional[Any],A_:      Dict ):






            '''simple docstring'''




            return self.pool(SCREAMING_SNAKE_CASE_ ) - hidden_states



class      __lowerCamelCase       (nn.Module		):







       def __init__(       self:      List[Any],A_:      List[Any],A_:      Dict,A_:      Any,A_:      Optional[int] ):






            '''simple docstring'''




            super().__init__()
            __UpperCamelCase      =       nn.Convad(SCREAMING_SNAKE_CASE_,SCREAMING_SNAKE_CASE_,1 )
            __UpperCamelCase      =       nn.Convad(SCREAMING_SNAKE_CASE_,SCREAMING_SNAKE_CASE_,1 )
            __UpperCamelCase      =       PoolFormerDropPath(SCREAMING_SNAKE_CASE_ )
            if isinstance(config.hidden_act,SCREAMING_SNAKE_CASE_ ):
                 __UpperCamelCase      =       ACTaFN[config.hidden_act]
            else:
                 __UpperCamelCase      =       config.hidden_act







       def 						snake_case_     (       self:      List[str],A_:      Tuple ):






            '''simple docstring'''




            __UpperCamelCase      =       self.conva(SCREAMING_SNAKE_CASE_ )
            __UpperCamelCase      =       self.act_fn(SCREAMING_SNAKE_CASE_ )
            __UpperCamelCase      =       self.drop(SCREAMING_SNAKE_CASE_ )
            __UpperCamelCase      =       self.conva(SCREAMING_SNAKE_CASE_ )
            __UpperCamelCase      =       self.drop(SCREAMING_SNAKE_CASE_ )

            return hidden_states



class      __lowerCamelCase       (nn.Module		):







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






            '''simple docstring'''




            super().__init__()
            __UpperCamelCase      =       PoolFormerPooling(SCREAMING_SNAKE_CASE_ )
            __UpperCamelCase      =       PoolFormerOutput(SCREAMING_SNAKE_CASE_,SCREAMING_SNAKE_CASE_,SCREAMING_SNAKE_CASE_,SCREAMING_SNAKE_CASE_ )
            __UpperCamelCase      =       PoolFormerGroupNorm(SCREAMING_SNAKE_CASE_ )
            __UpperCamelCase      =       PoolFormerGroupNorm(SCREAMING_SNAKE_CASE_ )

            # Useful for training neural nets
            __UpperCamelCase      =       PoolFormerDropPath(SCREAMING_SNAKE_CASE_ ) if drop_path > 0.0 else nn.Identity()
            __UpperCamelCase      =       config.use_layer_scale
            if config.use_layer_scale:
                 __UpperCamelCase      =       nn.Parameter(
                     config.layer_scale_init_value * torch.ones((SCREAMING_SNAKE_CASE_) ),requires_grad=SCREAMING_SNAKE_CASE_ )
                 __UpperCamelCase      =       nn.Parameter(
                     config.layer_scale_init_value * torch.ones((SCREAMING_SNAKE_CASE_) ),requires_grad=SCREAMING_SNAKE_CASE_ )







       def 						snake_case_     (       self:      List[str],A_:      Union[str, Any] ):






            '''simple docstring'''




            if self.use_layer_scale:
                 __UpperCamelCase      =       self.pooling(self.before_norm(SCREAMING_SNAKE_CASE_ ) )
                 __UpperCamelCase      =       self.layer_scale_a.unsqueeze(-1 ).unsqueeze(-1 ) * pooling_output
                 # First residual connection
                 __UpperCamelCase      =       hidden_states + self.drop_path(SCREAMING_SNAKE_CASE_ )
                 __UpperCamelCase      =       ()

                 __UpperCamelCase      =       self.output(self.after_norm(SCREAMING_SNAKE_CASE_ ) )
                 __UpperCamelCase      =       self.layer_scale_a.unsqueeze(-1 ).unsqueeze(-1 ) * layer_output
                 # Second residual connection
                 __UpperCamelCase      =       hidden_states + self.drop_path(SCREAMING_SNAKE_CASE_ )

                 __UpperCamelCase      =       (output,) + outputs
                 return outputs

            else:
                 __UpperCamelCase      =       self.drop_path(self.pooling(self.before_norm(SCREAMING_SNAKE_CASE_ ) ) )
                 # First residual connection
                 __UpperCamelCase      =       pooling_output + hidden_states
                 __UpperCamelCase      =       ()

                 # Second residual connection inside the PoolFormerOutput block
                 __UpperCamelCase      =       self.drop_path(self.output(self.after_norm(SCREAMING_SNAKE_CASE_ ) ) )
                 __UpperCamelCase      =       hidden_states + layer_output

                 __UpperCamelCase      =       (output,) + outputs
                 return outputs



class      __lowerCamelCase       (nn.Module		):







       def __init__(       self:      List[str],A_:      Optional[int] ):






            '''simple docstring'''




            super().__init__()
            __UpperCamelCase      =       config
            # stochastic depth decay rule
            __UpperCamelCase      =       [x.item() for x in torch.linspace(0,config.drop_path_rate,sum(config.depths ) )]

            # patch embeddings
            __UpperCamelCase      =       []
            for i in range(config.num_encoder_blocks ):
                 embeddings.append(
                     PoolFormerEmbeddings(
                         patch_size=config.patch_sizes[i],stride=config.strides[i],padding=config.padding[i],num_channels=config.num_channels if i == 0 else config.hidden_sizes[i - 1],hidden_size=config.hidden_sizes[i],) )
            __UpperCamelCase      =       nn.ModuleList(SCREAMING_SNAKE_CASE_ )

            # Transformer blocks
            __UpperCamelCase      =       []
            __UpperCamelCase      =       0
            for i in range(config.num_encoder_blocks ):
                 # each block consists of layers
                 __UpperCamelCase      =       []
                 if i != 0:
                      cur += config.depths[i - 1]
                 for j in range(config.depths[i] ):
                      layers.append(
                          PoolFormerLayer(
                              SCREAMING_SNAKE_CASE_,num_channels=config.hidden_sizes[i],pool_size=config.pool_size,hidden_size=config.hidden_sizes[i],intermediate_size=int(config.hidden_sizes[i] * config.mlp_ratio ),drop_path=dpr[cur + j],) )
                 blocks.append(nn.ModuleList(SCREAMING_SNAKE_CASE_ ) )

            __UpperCamelCase      =       nn.ModuleList(SCREAMING_SNAKE_CASE_ )







       def 						snake_case_     (       self:      Optional[int],A_:      Optional[int],A_:      Optional[Any]=False,A_:      int=True ):






            '''simple docstring'''




            __UpperCamelCase      =       () if output_hidden_states else None

            __UpperCamelCase      =       pixel_values
            for idx, layers in enumerate(zip(self.patch_embeddings,self.block ) ):
                 __UpperCamelCase,  __UpperCamelCase      =       layers
                 # Get patch embeddings from hidden_states
                 __UpperCamelCase      =       embedding_layer(SCREAMING_SNAKE_CASE_ )
                 # Send the embeddings through the blocks
                 for _, blk in enumerate(SCREAMING_SNAKE_CASE_ ):
                      __UpperCamelCase      =       blk(SCREAMING_SNAKE_CASE_ )
                      __UpperCamelCase      =       layer_outputs[0]

                 if output_hidden_states:
                      __UpperCamelCase      =       all_hidden_states + (hidden_states,)

            if not return_dict:
                 return tuple(v for v in [hidden_states, all_hidden_states] if v is not None )

            return BaseModelOutputWithNoAttention(last_hidden_state=SCREAMING_SNAKE_CASE_,hidden_states=SCREAMING_SNAKE_CASE_ )



class      __lowerCamelCase       (_a		):
       _lowercase											=			PoolFormerConfig
       _lowercase											=			'poolformer'
       _lowercase											=			'pixel_values'
       _lowercase											=			True







       def 						snake_case_     (       self:      List[str],A_:      Any ):






            '''simple docstring'''




            if isinstance(SCREAMING_SNAKE_CASE_,(nn.Linear, nn.Convad) ):
                 module.weight.data.normal_(mean=0.0,std=self.config.initializer_range )
                 if module.bias is not None:
                      module.bias.data.zero_()
            elif isinstance(SCREAMING_SNAKE_CASE_,nn.LayerNorm ):
                 module.bias.data.zero_()
                 module.weight.data.fill_(1.0 )







       def 						snake_case_     (       self:      Dict,A_:      str,A_:      List[str]=False ):






            '''simple docstring'''




            if isinstance(SCREAMING_SNAKE_CASE_,SCREAMING_SNAKE_CASE_ ):
                 __UpperCamelCase      =       value



__snake_case									=		r'''\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\n    Parameters:\n        config ([`PoolFormerConfig`]): 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'''

__snake_case									=		r'''\n    Args:\n        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n            Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n            [`PoolFormerImageProcessor.__call__`] for details.\n'''



@add_start_docstrings(
    """The bare PoolFormer Model transformer outputting raw hidden-states without any specific head on top."""							,	_a							,	)
class      __lowerCamelCase       (_a		):







       def __init__(       self:      List[str],A_:      int ):






            '''simple docstring'''




            super().__init__(SCREAMING_SNAKE_CASE_ )
            __UpperCamelCase      =       config

            __UpperCamelCase      =       PoolFormerEncoder(SCREAMING_SNAKE_CASE_ )

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







       def 						snake_case_     (       self:      Dict ):






            '''simple docstring'''




            return self.embeddings.patch_embeddings







       @add_start_docstrings_to_model_forward(SCREAMING_SNAKE_CASE_ )
       @add_code_sample_docstrings(
           checkpoint=_CHECKPOINT_FOR_DOC,output_type=SCREAMING_SNAKE_CASE_,config_class=_CONFIG_FOR_DOC,modality='vision',expected_output=_EXPECTED_OUTPUT_SHAPE,)
       def 						snake_case_     (       self:      int,A_:      Optional[torch.FloatTensor] = None,A_:      Optional[bool] = None,A_:      Optional[bool] = None,):






            '''simple docstring'''




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

            if pixel_values is None:
                 raise ValueError('You have to specify pixel_values' )

            __UpperCamelCase      =       self.encoder(
                SCREAMING_SNAKE_CASE_,output_hidden_states=SCREAMING_SNAKE_CASE_,return_dict=SCREAMING_SNAKE_CASE_,)
            __UpperCamelCase      =       encoder_outputs[0]

            if not return_dict:
                 return (sequence_output, None) + encoder_outputs[1:]

            return BaseModelOutputWithNoAttention(
                last_hidden_state=SCREAMING_SNAKE_CASE_,hidden_states=encoder_outputs.hidden_states,)



class      __lowerCamelCase       (nn.Module		):







       def __init__(       self:      List[str],A_:      List[str] ):






            '''simple docstring'''




            super().__init__()
            __UpperCamelCase      =       nn.Linear(config.hidden_size,config.hidden_size )







       def 						snake_case_     (       self:      str,A_:      Union[str, Any] ):






            '''simple docstring'''




            __UpperCamelCase      =       self.dense(SCREAMING_SNAKE_CASE_ )
            return output



@add_start_docstrings(
    """\n    PoolFormer Model transformer with an image classification head on top\n    """							,	_a							,	)
class      __lowerCamelCase       (_a		):







       def __init__(       self:      Dict,A_:      str ):






            '''simple docstring'''




            super().__init__(SCREAMING_SNAKE_CASE_ )
            __UpperCamelCase      =       config.num_labels
            __UpperCamelCase      =       PoolFormerModel(SCREAMING_SNAKE_CASE_ )

            # Final norm
            __UpperCamelCase      =       PoolFormerGroupNorm(config.hidden_sizes[-1] )
            # Classifier head
            __UpperCamelCase      =       (
                nn.Linear(config.hidden_sizes[-1],config.num_labels ) if config.num_labels > 0 else nn.Identity()
            )

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







       @add_start_docstrings_to_model_forward(SCREAMING_SNAKE_CASE_ )
       @add_code_sample_docstrings(
           checkpoint=_IMAGE_CLASS_CHECKPOINT,output_type=SCREAMING_SNAKE_CASE_,config_class=_CONFIG_FOR_DOC,expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT,)
       def 						snake_case_     (       self:      List[Any],A_:      Optional[torch.FloatTensor] = None,A_:      Optional[torch.LongTensor] = None,A_:      Optional[bool] = None,A_:      Optional[bool] = None,):






            '''simple docstring'''




            __UpperCamelCase      =       return_dict if return_dict is not None else self.config.use_return_dict

            __UpperCamelCase      =       self.poolformer(
                SCREAMING_SNAKE_CASE_,output_hidden_states=SCREAMING_SNAKE_CASE_,return_dict=SCREAMING_SNAKE_CASE_,)

            __UpperCamelCase      =       outputs[0]

            __UpperCamelCase      =       self.classifier(self.norm(SCREAMING_SNAKE_CASE_ ).mean([-2, -1] ) )

            __UpperCamelCase      =       None
            if labels is not None:
                 if self.config.problem_type is None:
                      if self.num_labels == 1:
                           __UpperCamelCase      =       'regression'
                      elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
                           __UpperCamelCase      =       'single_label_classification'
                      else:
                           __UpperCamelCase      =       'multi_label_classification'

                 if self.config.problem_type == "regression":
                      __UpperCamelCase      =       MSELoss()
                      if self.num_labels == 1:
                           __UpperCamelCase      =       loss_fct(logits.squeeze(),labels.squeeze() )
                      else:
                           __UpperCamelCase      =       loss_fct(SCREAMING_SNAKE_CASE_,SCREAMING_SNAKE_CASE_ )
                 elif self.config.problem_type == "single_label_classification":
                      __UpperCamelCase      =       CrossEntropyLoss()
                      __UpperCamelCase      =       loss_fct(logits.view(-1,self.num_labels ),labels.view(-1 ) )
                 elif self.config.problem_type == "multi_label_classification":
                      __UpperCamelCase      =       BCEWithLogitsLoss()
                      __UpperCamelCase      =       loss_fct(SCREAMING_SNAKE_CASE_,SCREAMING_SNAKE_CASE_ )

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

            return ImageClassifierOutputWithNoAttention(loss=SCREAMING_SNAKE_CASE_,logits=SCREAMING_SNAKE_CASE_,hidden_states=outputs.hidden_states )




def 				a						(							snake_case__:					list					):


				'''simple docstring'''

				if len(snake_case__					) <= 1:
								return [tuple(snake_case__					)]

				lowercase_       =					[]

				def generate(snake_case__:					int						,   snake_case__:					list					):
								if k == 1:
												res.append(tuple(arr[:]					)					)
												return

								generate(k - 1						,   snake_case__					)

								for i in range(k - 1					):
												if k % 2 == 0:  # k is even
																lowercase_  ,	lowercase_       =					arr[k - 1], arr[i]
												else:  # k is odd
																lowercase_  ,	lowercase_       =					arr[k - 1], arr[0]
												generate(k - 1						,   snake_case__					)

				generate(len(snake_case__					)						,   snake_case__					)
				return res


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




