






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


lowercase			  =    logging.get_logger(__name__)

# General docstring
lowercase			  =    '''PoolFormerConfig'''

# Base docstring
lowercase			  =    '''sail/poolformer_s12'''
lowercase			  =    [1, 5_12, 7, 7]

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

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

def      lowerCAmelCase__	(    _a       :			Optional[Any]  ,      _a       :			Optional[Any] = 0.0  ,      _a       :			Any = False    ):
		if drop_prob == 0.0 or not training:
				return input
		snake_case_				:							Optional[Any]						 =       1 - drop_prob
		snake_case_				:							Optional[int]						 =       (input.shape[0],) + (1,) * (input.ndim - 1)  # work with diff dim tensors, not just 2D ConvNets
		snake_case_				:							Any						 =       keep_prob + torch.rand(__lowerCAmelCase  ,      dtype=input.dtype  ,      device=input.device    )
		random_tensor.floor_()  # binarize
		snake_case_				:							List[Any]						 =       input.div(__lowerCAmelCase    ) * random_tensor
		return output




class 		UpperCAmelCase_						(	nn.Module					):


						'''simple docstring'''




						def __init__(	self		,				_SCREAMING_SNAKE_CASE = None				) ->				None:
								super().__init__()
								snake_case_				:							Union[str, Any]						 =       drop_prob






						def       _lowerCAmelCase       (	self		,				_SCREAMING_SNAKE_CASE				) ->				torch.Tensor:
								return drop_path(lowerCamelCase__		,				self.drop_prob		,				self.training				)






						def       _lowerCAmelCase       (	self				) ->				str:
								return "p={}".format(self.drop_prob				)




class 		UpperCAmelCase_						(	nn.Module					):


						'''simple docstring'''




						def __init__(	self		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE=None				) ->				Optional[int]:
								super().__init__()
								snake_case_				:							Dict						 =       patch_size if isinstance(lowerCamelCase__		,				collections.abc.Iterable				) else (patch_size, patch_size)
								snake_case_				:							Optional[int]						 =       stride if isinstance(lowerCamelCase__		,				collections.abc.Iterable				) else (stride, stride)
								snake_case_				:							Any						 =       padding if isinstance(lowerCamelCase__		,				collections.abc.Iterable				) else (padding, padding)

								snake_case_				:							List[Any]						 =       nn.Convad(lowerCamelCase__		,				lowerCamelCase__		,				kernel_size=lowerCamelCase__		,				stride=lowerCamelCase__		,				padding=lowerCamelCase__				)
								snake_case_				:							str						 =       norm_layer(lowerCamelCase__				) if norm_layer else nn.Identity()






						def       _lowerCAmelCase       (	self		,				_SCREAMING_SNAKE_CASE				) ->				List[Any]:
								snake_case_				:							Dict						 =       self.projection(lowerCamelCase__				)
								snake_case_				:							int						 =       self.norm(lowerCamelCase__				)
								return embeddings




class 		UpperCAmelCase_						(	nn.GroupNorm					):


						'''simple docstring'''




						def __init__(	self		,				_SCREAMING_SNAKE_CASE		,				**_SCREAMING_SNAKE_CASE				) ->				Dict:
								super().__init__(1		,				lowerCamelCase__		,				**lowerCamelCase__				)




class 		UpperCAmelCase_						(	nn.Module					):


						'''simple docstring'''




						def __init__(	self		,				_SCREAMING_SNAKE_CASE				) ->				List[Any]:
								super().__init__()
								snake_case_				:							int						 =       nn.AvgPoolad(lowerCamelCase__		,				stride=1		,				padding=pool_size // 2		,				count_include_pad=lowerCamelCase__				)






						def       _lowerCAmelCase       (	self		,				_SCREAMING_SNAKE_CASE				) ->				int:
								return self.pool(lowerCamelCase__				) - hidden_states




class 		UpperCAmelCase_						(	nn.Module					):


						'''simple docstring'''




						def __init__(	self		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE				) ->				Optional[Any]:
								super().__init__()
								snake_case_				:							Optional[Any]						 =       nn.Convad(lowerCamelCase__		,				lowerCamelCase__		,				1				)
								snake_case_				:							Optional[Any]						 =       nn.Convad(lowerCamelCase__		,				lowerCamelCase__		,				1				)
								snake_case_				:							Union[str, Any]						 =       PoolFormerDropPath(lowerCamelCase__				)
								if isinstance(config.hidden_act		,				lowerCamelCase__				):
										snake_case_				:							str						 =       ACTaFN[config.hidden_act]
								else:
										snake_case_				:							int						 =       config.hidden_act






						def       _lowerCAmelCase       (	self		,				_SCREAMING_SNAKE_CASE				) ->				List[str]:
								snake_case_				:							Dict						 =       self.conva(lowerCamelCase__				)
								snake_case_				:							str						 =       self.act_fn(lowerCamelCase__				)
								snake_case_				:							Optional[int]						 =       self.drop(lowerCamelCase__				)
								snake_case_				:							int						 =       self.conva(lowerCamelCase__				)
								snake_case_				:							Tuple						 =       self.drop(lowerCamelCase__				)

								return hidden_states




class 		UpperCAmelCase_						(	nn.Module					):


						'''simple docstring'''




						def __init__(	self		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE				) ->				Optional[Any]:
								super().__init__()
								snake_case_				:							int						 =       PoolFormerPooling(lowerCamelCase__				)
								snake_case_				:							Optional[int]						 =       PoolFormerOutput(lowerCamelCase__		,				lowerCamelCase__		,				lowerCamelCase__		,				lowerCamelCase__				)
								snake_case_				:							Optional[int]						 =       PoolFormerGroupNorm(lowerCamelCase__				)
								snake_case_				:							Optional[Any]						 =       PoolFormerGroupNorm(lowerCamelCase__				)

								# Useful for training neural nets
								snake_case_				:							int						 =       PoolFormerDropPath(lowerCamelCase__				) if drop_path > 0.0 else nn.Identity()
								snake_case_				:							Union[str, Any]						 =       config.use_layer_scale
								if config.use_layer_scale:
										snake_case_				:							Optional[int]						 =       nn.Parameter(
										    config.layer_scale_init_value * torch.ones((lowerCamelCase__)				)		,				requires_grad=lowerCamelCase__				)
										snake_case_				:							Optional[int]						 =       nn.Parameter(
										    config.layer_scale_init_value * torch.ones((lowerCamelCase__)				)		,				requires_grad=lowerCamelCase__				)






						def       _lowerCAmelCase       (	self		,				_SCREAMING_SNAKE_CASE				) ->				str:







								if self.use_layer_scale:
										snake_case_				:							Tuple						 =       self.pooling(self.before_norm(lowerCamelCase__				)				)
										snake_case_				:							Optional[Any]						 =       self.layer_scale_a.unsqueeze(-1				).unsqueeze(-1				) * pooling_output
										# First residual connection
										snake_case_				:							Optional[int]						 =       hidden_states + self.drop_path(lowerCamelCase__				)
										snake_case_				:							Optional[int]						 =       ()

										snake_case_				:							Optional[int]						 =       self.output(self.after_norm(lowerCamelCase__				)				)
										snake_case_				:							Tuple						 =       self.layer_scale_a.unsqueeze(-1				).unsqueeze(-1				) * layer_output
										# Second residual connection
										snake_case_				:							str						 =       hidden_states + self.drop_path(lowerCamelCase__				)

										snake_case_				:							List[Any]						 =       (output,) + outputs
										return outputs

								else:
										snake_case_				:							Dict						 =       self.drop_path(self.pooling(self.before_norm(lowerCamelCase__				)				)				)
										# First residual connection
										snake_case_				:							Tuple						 =       pooling_output + hidden_states
										snake_case_				:							str						 =       ()

										# Second residual connection inside the PoolFormerOutput block
										snake_case_				:							Optional[int]						 =       self.drop_path(self.output(self.after_norm(lowerCamelCase__				)				)				)
										snake_case_				:							int						 =       hidden_states + layer_output

										snake_case_				:							Optional[int]						 =       (output,) + outputs
										return outputs




class 		UpperCAmelCase_						(	nn.Module					):


						'''simple docstring'''




						def __init__(	self		,				_SCREAMING_SNAKE_CASE				) ->				Union[str, Any]:
								super().__init__()
								snake_case_				:							Dict						 =       config
								# stochastic depth decay rule
								snake_case_				:							Optional[int]						 =       [x.item() for x in torch.linspace(0		,				config.drop_path_rate		,				sum(config.depths				)				)]

								# patch embeddings
								snake_case_				:							Any						 =       []
								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]		,				)				)
								snake_case_				:							Tuple						 =       nn.ModuleList(lowerCamelCase__				)

								# Transformer blocks
								snake_case_				:							Any						 =       []
								snake_case_				:							Tuple						 =       0
								for i in range(config.num_encoder_blocks				):
										# each block consists of layers
										snake_case_				:							List[Any]						 =       []
										if i != 0:
												cur += config.depths[i - 1]
										for j in range(config.depths[i]				):
												layers.append(
												    PoolFormerLayer(
												        lowerCamelCase__		,				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(lowerCamelCase__				)				)

								snake_case_				:							List[str]						 =       nn.ModuleList(lowerCamelCase__				)






						def       _lowerCAmelCase       (	self		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE=False		,				_SCREAMING_SNAKE_CASE=True				) ->				List[Any]:
								snake_case_				:							List[str]						 =       () if output_hidden_states else None

								snake_case_				:							List[Any]						 =       pixel_values
								for idx, layers in enumerate(zip(self.patch_embeddings		,				self.block				)				):
										snake_case_				:							Dict						 =       layers
										# Get patch embeddings from hidden_states
										snake_case_				:							List[str]						 =       embedding_layer(lowerCamelCase__				)
										# Send the embeddings through the blocks
										for _, blk in enumerate(lowerCamelCase__				):
												snake_case_				:							Union[str, Any]						 =       blk(lowerCamelCase__				)
												snake_case_				:							str						 =       layer_outputs[0]

										if output_hidden_states:
												snake_case_				:							str						 =       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=lowerCamelCase__		,				hidden_states=lowerCamelCase__				)




class 		UpperCAmelCase_						(	UpperCAmelCase__					):


						'''simple docstring'''




						A     :   List[Any]						=					PoolFormerConfig
						A     :   Optional[int]						=					"poolformer"
						A     :   Dict						=					"pixel_values"
						A     :   Dict						=					True






						def       _lowerCAmelCase       (	self		,				_SCREAMING_SNAKE_CASE				) ->				List[str]:







								if isinstance(lowerCamelCase__		,				(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(lowerCamelCase__		,				nn.LayerNorm				):
										module.bias.data.zero_()
										module.weight.data.fill_(1.0				)






						def       _lowerCAmelCase       (	self		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE=False				) ->				Any:







								if isinstance(lowerCamelCase__		,				lowerCamelCase__				):
										snake_case_				:							Optional[Any]						 =       value




lowercase			  =    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'''

lowercase			  =    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.'					,  UpperCAmelCase__					,  )
class 		UpperCAmelCase_						(	UpperCAmelCase__					):


						'''simple docstring'''




						def __init__(	self		,				_SCREAMING_SNAKE_CASE				) ->				str:
								super().__init__(lowerCamelCase__				)
								snake_case_				:							Dict						 =       config

								snake_case_				:							int						 =       PoolFormerEncoder(lowerCamelCase__				)

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






						def       _lowerCAmelCase       (	self				) ->				Dict:
								return self.embeddings.patch_embeddings






						@add_start_docstrings_to_model_forward(lowerCamelCase__				)
						@add_code_sample_docstrings(
						    checkpoint=_CHECKPOINT_FOR_DOC		,				output_type=lowerCamelCase__		,				config_class=_CONFIG_FOR_DOC		,				modality="vision"		,				expected_output=_EXPECTED_OUTPUT_SHAPE		,				)
						def       _lowerCAmelCase       (	self		,				_SCREAMING_SNAKE_CASE = None		,				_SCREAMING_SNAKE_CASE = None		,				_SCREAMING_SNAKE_CASE = None		,				) ->				Union[Tuple, BaseModelOutputWithNoAttention]:
								snake_case_				:							int						 =       (
								    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
								)
								snake_case_				:							Dict						 =       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"				)

								snake_case_				:							List[str]						 =       self.encoder(
								    lowerCamelCase__		,				output_hidden_states=lowerCamelCase__		,				return_dict=lowerCamelCase__		,				)
								snake_case_				:							int						 =       encoder_outputs[0]

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

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




class 		UpperCAmelCase_						(	nn.Module					):


						'''simple docstring'''




						def __init__(	self		,				_SCREAMING_SNAKE_CASE				) ->				Tuple:
								super().__init__()
								snake_case_				:							List[Any]						 =       nn.Linear(config.hidden_size		,				config.hidden_size				)






						def       _lowerCAmelCase       (	self		,				_SCREAMING_SNAKE_CASE				) ->				List[str]:
								snake_case_				:							Optional[Any]						 =       self.dense(lowerCamelCase__				)
								return output




@add_start_docstrings(
    '\n    PoolFormer Model transformer with an image classification head on top\n    '					,  UpperCAmelCase__					,  )
class 		UpperCAmelCase_						(	UpperCAmelCase__					):


						'''simple docstring'''




						def __init__(	self		,				_SCREAMING_SNAKE_CASE				) ->				Tuple:
								super().__init__(lowerCamelCase__				)
								snake_case_				:							List[Any]						 =       config.num_labels
								snake_case_				:							str						 =       PoolFormerModel(lowerCamelCase__				)

								# Final norm
								snake_case_				:							List[str]						 =       PoolFormerGroupNorm(config.hidden_sizes[-1]				)
								# Classifier head
								snake_case_				:							Union[str, Any]						 =       (
								    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(lowerCamelCase__				)
						@add_code_sample_docstrings(
						    checkpoint=_IMAGE_CLASS_CHECKPOINT		,				output_type=lowerCamelCase__		,				config_class=_CONFIG_FOR_DOC		,				expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT		,				)
						def       _lowerCAmelCase       (	self		,				_SCREAMING_SNAKE_CASE = None		,				_SCREAMING_SNAKE_CASE = None		,				_SCREAMING_SNAKE_CASE = None		,				_SCREAMING_SNAKE_CASE = None		,				) ->				Union[Tuple, ImageClassifierOutputWithNoAttention]:
								snake_case_				:							Optional[int]						 =       return_dict if return_dict is not None else self.config.use_return_dict

								snake_case_				:							Any						 =       self.poolformer(
								    lowerCamelCase__		,				output_hidden_states=lowerCamelCase__		,				return_dict=lowerCamelCase__		,				)

								snake_case_				:							List[Any]						 =       outputs[0]

								snake_case_				:							Optional[int]						 =       self.classifier(self.norm(lowerCamelCase__				).mean([-2, -1]				)				)

								snake_case_				:							int						 =       None
								if labels is not None:
										if self.config.problem_type is None:
												if self.num_labels == 1:
														snake_case_				:							Optional[int]						 =       "regression"
												elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
														snake_case_				:							List[Any]						 =       "single_label_classification"
												else:
														snake_case_				:							Any						 =       "multi_label_classification"

										if self.config.problem_type == "regression":
												snake_case_				:							Union[str, Any]						 =       MSELoss()
												if self.num_labels == 1:
														snake_case_				:							List[Any]						 =       loss_fct(logits.squeeze()		,				labels.squeeze()				)
												else:
														snake_case_				:							Optional[int]						 =       loss_fct(lowerCamelCase__		,				lowerCamelCase__				)
										elif self.config.problem_type == "single_label_classification":
												snake_case_				:							Optional[int]						 =       CrossEntropyLoss()
												snake_case_				:							Union[str, Any]						 =       loss_fct(logits.view(-1		,				self.num_labels				)		,				labels.view(-1				)				)
										elif self.config.problem_type == "multi_label_classification":
												snake_case_				:							int						 =       BCEWithLogitsLoss()
												snake_case_				:							Optional[Any]						 =       loss_fct(lowerCamelCase__		,				lowerCamelCase__				)

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

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








import fire

from transformers import AutoConfig, AutoModelForSeqaSeqLM, AutoTokenizer

def      lowerCAmelCase__	(    _a       :			str  ,      _a       :			str  ,      **_a       :			Optional[int]    ):
		snake_case_				:							Any						 =       AutoConfig.from_pretrained(_a  ,      **_a    )
		snake_case_				:							str						 =       AutoModelForSeqaSeqLM.from_config(_a    )
		model.save_pretrained(_a    )
		AutoTokenizer.from_pretrained(_a    ).save_pretrained(_a    )
		return model


if __name__ == "__main__":
							fire.Fire(save_randomly_initialized_version)
