
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


__magic_name__  							=	logging.get_logger(__name__)

# General docstring
__magic_name__  							=	'''PoolFormerConfig'''

# Base docstring
__magic_name__  							=	'''sail/poolformer_s12'''
__magic_name__  							=	[1, 512, 7, 7]

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

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





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




class        _SCREAMING_SNAKE_CASE	(   nn.Module			):
      def __init__(      self		,						lowerCamelCase = None			):
          super().__init__()
          snake_case__    =					drop_prob
      def A_      (      self		,						lowerCamelCase			):
          return drop_path(lowerCamelCase		,						self.drop_prob		,						self.training			)



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





class        _SCREAMING_SNAKE_CASE	(   nn.Module			):
      def __init__(      self		,						lowerCamelCase		,						lowerCamelCase		,						lowerCamelCase		,						lowerCamelCase		,						lowerCamelCase		,						lowerCamelCase=None			):
          super().__init__()
          snake_case__    =					patch_size if isinstance(lowerCamelCase		,						collections.abc.Iterable			) else (patch_size, patch_size)
          snake_case__    =					stride if isinstance(lowerCamelCase		,						collections.abc.Iterable			) else (stride, stride)
          snake_case__    =					padding if isinstance(lowerCamelCase		,						collections.abc.Iterable			) else (padding, padding)

          snake_case__    =					nn.Convad(lowerCamelCase		,						lowerCamelCase		,						kernel_size=lowerCamelCase		,						stride=lowerCamelCase		,						padding=lowerCamelCase			)
          snake_case__    =					norm_layer(lowerCamelCase			) if norm_layer else nn.Identity()



      def A_      (      self		,						lowerCamelCase			):
          snake_case__    =					self.projection(lowerCamelCase			)
          snake_case__    =					self.norm(lowerCamelCase			)
          return embeddings





class        _SCREAMING_SNAKE_CASE	(   nn.GroupNorm			):
      def __init__(      self		,						lowerCamelCase		,						**lowerCamelCase			):
          super().__init__(1		,						lowerCamelCase		,						**lowerCamelCase			)





class        _SCREAMING_SNAKE_CASE	(   nn.Module			):
      def __init__(      self		,						lowerCamelCase			):
          super().__init__()
          snake_case__    =					nn.AvgPoolad(lowerCamelCase		,						stride=1		,						padding=pool_size // 2		,						count_include_pad=lowerCamelCase			)



      def A_      (      self		,						lowerCamelCase			):
          return self.pool(lowerCamelCase			) - hidden_states





class        _SCREAMING_SNAKE_CASE	(   nn.Module			):
      def __init__(      self		,						lowerCamelCase		,						lowerCamelCase		,						lowerCamelCase		,						lowerCamelCase			):
          super().__init__()
          snake_case__    =					nn.Convad(lowerCamelCase		,						lowerCamelCase		,						1			)
          snake_case__    =					nn.Convad(lowerCamelCase		,						lowerCamelCase		,						1			)
          snake_case__    =					PoolFormerDropPath(lowerCamelCase			)
          if isinstance(config.hidden_act		,						lowerCamelCase			):
              snake_case__    =					ACTaFN[config.hidden_act]
          else:
              snake_case__    =					config.hidden_act



      def A_      (      self		,						lowerCamelCase			):
          snake_case__    =					self.conva(lowerCamelCase			)
          snake_case__    =					self.act_fn(lowerCamelCase			)
          snake_case__    =					self.drop(lowerCamelCase			)
          snake_case__    =					self.conva(lowerCamelCase			)
          snake_case__    =					self.drop(lowerCamelCase			)

          return hidden_states





class        _SCREAMING_SNAKE_CASE	(   nn.Module			):
      def __init__(      self		,						lowerCamelCase		,						lowerCamelCase		,						lowerCamelCase		,						lowerCamelCase		,						lowerCamelCase		,						lowerCamelCase			):
          super().__init__()
          snake_case__    =					PoolFormerPooling(lowerCamelCase			)
          snake_case__    =					PoolFormerOutput(lowerCamelCase		,						lowerCamelCase		,						lowerCamelCase		,						lowerCamelCase			)
          snake_case__    =					PoolFormerGroupNorm(lowerCamelCase			)
          snake_case__    =					PoolFormerGroupNorm(lowerCamelCase			)

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



      def A_      (      self		,						lowerCamelCase			):
          if self.use_layer_scale:
              snake_case__    =					self.pooling(self.before_norm(lowerCamelCase			)			)
              snake_case__    =					self.layer_scale_a.unsqueeze(-1			).unsqueeze(-1			) * pooling_output
              # First residual connection
              snake_case__    =					hidden_states + self.drop_path(lowerCamelCase			)
              snake_case__    =					()

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

              snake_case__    =					(output,) + outputs
              return outputs

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

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

              snake_case__    =					(output,) + outputs
              return outputs





class        _SCREAMING_SNAKE_CASE	(   nn.Module			):
      def __init__(      self		,						lowerCamelCase			):
          super().__init__()
          snake_case__    =					config
          # stochastic depth decay rule
          snake_case__    =					[x.item() for x in torch.linspace(0		,						config.drop_path_rate		,						sum(config.depths			)			)]

          # patch embeddings
          snake_case__    =					[]
          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__    =					nn.ModuleList(lowerCamelCase			)

          # Transformer blocks
          snake_case__    =					[]
          snake_case__    =					0
          for i in range(config.num_encoder_blocks			):
              # each block consists of layers
              snake_case__    =					[]
              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__    =					nn.ModuleList(lowerCamelCase			)



      def A_      (      self		,						lowerCamelCase		,						lowerCamelCase=False		,						lowerCamelCase=True			):
          snake_case__    =					() if output_hidden_states else None

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

              if output_hidden_states:
                  snake_case__    =					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        _SCREAMING_SNAKE_CASE	(   __UpperCamelCase			):
      _A    :		Union[str, Any]     						=  PoolFormerConfig
      _A    :		Optional[Any]     						=  'poolformer'
      _A    :		Optional[Any]     						=  'pixel_values'
      _A    :		Optional[int]     						=  True
      def A_      (      self		,						lowerCamelCase			):
          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 A_      (      self		,						lowerCamelCase		,						lowerCamelCase=False			):
          if isinstance(lowerCamelCase		,						lowerCamelCase			):
              snake_case__    =					value





__magic_name__  							=	r'''
    This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use
    it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
    behavior.

    Parameters:
        config ([`PoolFormerConfig`]): Model configuration class with all the parameters of the model.
            Initializing with a config file does not load the weights associated with the model, only the
            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
'''

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




@add_start_docstrings(
    'The bare PoolFormer Model transformer outputting raw hidden-states without any specific head on top.'							,       __UpperCamelCase							,       )
class        _SCREAMING_SNAKE_CASE	(   __UpperCamelCase			):
      def __init__(      self		,						lowerCamelCase			):
          super().__init__(lowerCamelCase			)
          snake_case__    =					config

          snake_case__    =					PoolFormerEncoder(lowerCamelCase			)

          # Initialize weights and apply final processing
          self.post_init()
      def A_      (      self			):
          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 A_      (      self		,						lowerCamelCase = None		,						lowerCamelCase = None		,						lowerCamelCase = None		,						):
          snake_case__    =					(
              output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
          )
          snake_case__    =					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__    =					self.encoder(
              lowerCamelCase		,						output_hidden_states=lowerCamelCase		,						return_dict=lowerCamelCase		,						)
          snake_case__    =					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        _SCREAMING_SNAKE_CASE	(   nn.Module			):
      def __init__(      self		,						lowerCamelCase			):
          super().__init__()
          snake_case__    =					nn.Linear(config.hidden_size		,						config.hidden_size			)



      def A_      (      self		,						lowerCamelCase			):
          snake_case__    =					self.dense(lowerCamelCase			)
          return output





@add_start_docstrings(
    '\n    PoolFormer Model transformer with an image classification head on top\n    '							,       __UpperCamelCase							,       )
class        _SCREAMING_SNAKE_CASE	(   __UpperCamelCase			):
      def __init__(      self		,						lowerCamelCase			):
          super().__init__(lowerCamelCase			)
          snake_case__    =					config.num_labels
          snake_case__    =					PoolFormerModel(lowerCamelCase			)

          # Final norm
          snake_case__    =					PoolFormerGroupNorm(config.hidden_sizes[-1]			)
          # Classifier head
          snake_case__    =					(
              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 A_      (      self		,						lowerCamelCase = None		,						lowerCamelCase = None		,						lowerCamelCase = None		,						lowerCamelCase = None		,						):
          snake_case__    =					return_dict if return_dict is not None else self.config.use_return_dict

          snake_case__    =					self.poolformer(
              lowerCamelCase		,						output_hidden_states=lowerCamelCase		,						return_dict=lowerCamelCase		,						)

          snake_case__    =					outputs[0]

          snake_case__    =					self.classifier(self.norm(lowerCamelCase			).mean([-2, -1]			)			)

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

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

          if not return_dict:
              snake_case__    =					(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 shutil
import tempfile
import unittest

import numpy as np
import pytest

from transformers import is_speech_available, is_vision_available
from transformers.testing_utils import require_torch


if is_vision_available():
     from transformers import TvltImageProcessor

if is_speech_available():
     from transformers import TvltFeatureExtractor

from transformers import TvltProcessor




@require_torch
class        _SCREAMING_SNAKE_CASE	(   unittest.TestCase			):
      def A_      (      self			):
          snake_case__    =					"ZinengTang/tvlt-base"
          snake_case__    =					tempfile.mkdtemp()
      def A_      (      self		,						**lowerCamelCase			):
          return TvltImageProcessor.from_pretrained(self.checkpoint		,						**lowerCamelCase			)
      def A_      (      self		,						**lowerCamelCase			):
          return TvltFeatureExtractor.from_pretrained(self.checkpoint		,						**lowerCamelCase			)
      def A_      (      self			):
          shutil.rmtree(self.tmpdirname			)
      def A_      (      self			):
          snake_case__    =					self.get_image_processor()
          snake_case__    =					self.get_feature_extractor()

          snake_case__    =					TvltProcessor(image_processor=lowerCamelCase		,						feature_extractor=lowerCamelCase			)
          processor.save_pretrained(self.tmpdirname			)
          snake_case__    =					TvltProcessor.from_pretrained(self.tmpdirname			)

          self.assertIsInstance(processor.feature_extractor		,						lowerCamelCase			)
          self.assertIsInstance(processor.image_processor		,						lowerCamelCase			)
      def A_      (      self			):
          snake_case__    =					self.get_image_processor()
          snake_case__    =					self.get_feature_extractor()

          snake_case__    =					TvltProcessor(image_processor=lowerCamelCase		,						feature_extractor=lowerCamelCase			)

          snake_case__    =					np.ones([1_20_00]			)

          snake_case__    =					feature_extractor(lowerCamelCase		,						return_tensors="np"			)
          snake_case__    =					processor(audio=lowerCamelCase		,						return_tensors="np"			)

          for key in audio_dict.keys():
              self.assertAlmostEqual(audio_dict[key].sum()		,						input_processor[key].sum()		,						delta=1e-2			)
      def A_      (      self			):
          snake_case__    =					self.get_image_processor()
          snake_case__    =					self.get_feature_extractor()

          snake_case__    =					TvltProcessor(image_processor=lowerCamelCase		,						feature_extractor=lowerCamelCase			)

          snake_case__    =					np.ones([3, 2_24, 2_24]			)

          snake_case__    =					image_processor(lowerCamelCase		,						return_tensors="np"			)
          snake_case__    =					processor(images=lowerCamelCase		,						return_tensors="np"			)

          for key in image_dict.keys():
              self.assertAlmostEqual(image_dict[key].sum()		,						input_processor[key].sum()		,						delta=1e-2			)
      def A_      (      self			):
          snake_case__    =					self.get_image_processor()
          snake_case__    =					self.get_feature_extractor()

          snake_case__    =					TvltProcessor(image_processor=lowerCamelCase		,						feature_extractor=lowerCamelCase			)

          snake_case__    =					np.ones([1_20_00]			)
          snake_case__    =					np.ones([3, 2_24, 2_24]			)

          snake_case__    =					processor(audio=lowerCamelCase		,						images=lowerCamelCase			)

          self.assertListEqual(list(inputs.keys()			)		,						["audio_values", "audio_mask", "pixel_values", "pixel_mask"]			)

          # test if it raises when no input is passed
          with pytest.raises(lowerCamelCase			):
              processor()



      def A_      (      self			):
          snake_case__    =					self.get_image_processor()
          snake_case__    =					self.get_feature_extractor()

          snake_case__    =					TvltProcessor(image_processor=lowerCamelCase		,						feature_extractor=lowerCamelCase			)

          self.assertListEqual(
              processor.model_input_names		,						image_processor.model_input_names + feature_extractor.model_input_names		,						msg="`processor` and `image_processor`+`feature_extractor` model input names do not match"		,						)



