





"""simple docstring"""


import argparse
import logging
import os
from datetime import datetime

import numpy as np
import torch
from torch import nn
from torch.utils.data import DataLoader, SequentialSampler, Subset
from torch.utils.data.distributed import DistributedSampler
from tqdm import tqdm

import transformers
from transformers import (
    AutoConfig,
    AutoModelForSequenceClassification,
    AutoTokenizer,
    GlueDataset,
    default_data_collator,
    glue_compute_metrics,
    glue_output_modes,
    glue_processors,
    set_seed,
)
from transformers.trainer_utils import is_main_process


a__					:     Any							=				logging.getLogger(__name__)





def 							a__			(  _UpperCAmelCase	)    ->  Dict:

 '''simple docstring'''






 snake_case__    							=				p * torch.log(_UpperCAmelCase	)
 snake_case__    							=				0
 return -plogp.sum(dim=-1	)





def 							a__			(  _UpperCAmelCase	)    ->  int:

 '''simple docstring'''






 logger.info("lv, h >\t" + "\t".join(f"{x + 1}" for x in range(len(_UpperCAmelCase	)	)	)	)
 for row in range(len(_UpperCAmelCase	)	):
  if tensor.dtype != torch.long:
   logger.info(f"layer {row + 1}:\t" + "\t".join(f"{x:.5f}" for x in tensor[row].cpu().data	)	)
  else:
   logger.info(f"layer {row + 1}:\t" + "\t".join(f"{x:d}" for x in tensor[row].cpu().data	)	)





def 							a__			(  _UpperCAmelCase	,     _UpperCAmelCase	,     _UpperCAmelCase	,     _UpperCAmelCase=True	,     _UpperCAmelCase=True	,     _UpperCAmelCase=None	,     _UpperCAmelCase=False	)    ->  Optional[Any]:

 '''simple docstring'''






 snake_case__							,   snake_case__    							=				model.config.num_hidden_layers, model.config.num_attention_heads
 snake_case__    							=				torch.zeros(_UpperCAmelCase	,     _UpperCAmelCase	).to(args.device	)
 snake_case__    							=				torch.zeros(_UpperCAmelCase	,     _UpperCAmelCase	).to(args.device	)

 if head_mask is None:
  snake_case__    							=				torch.ones(_UpperCAmelCase	,     _UpperCAmelCase	).to(args.device	)

 head_mask.requires_grad_(requires_grad=_UpperCAmelCase	)
 # If actually pruned attention multi-head, set head mask to None to avoid shape mismatch
 if actually_pruned:
  snake_case__    							=				None

 snake_case__    							=				None
 snake_case__    							=				None
 snake_case__    							=				0.0

 for step, inputs in enumerate(tqdm(_UpperCAmelCase	,     desc="Iteration"	,     disable=args.local_rank not in [-1, 0]	)	):
  for k, v in inputs.items():
   snake_case__    							=				v.to(args.device	)

  # Do a forward pass (not with torch.no_grad() since we need gradients for importance score - see below)
  snake_case__    							=				model(**_UpperCAmelCase	,     head_mask=_UpperCAmelCase	)
  snake_case__							,   snake_case__							,   snake_case__    							=				(
      outputs[0],
      outputs[1],
      outputs[-1],
  )  # Loss and logits are the first, attention the last
  loss.backward()  # Backpropagate to populate the gradients in the head mask

  if compute_entropy:
   for layer, attn in enumerate(_UpperCAmelCase	):
    snake_case__    							=				entropy(attn.detach()	) * inputs["attention_mask"].float().unsqueeze(1	)
    attn_entropy[layer] += masked_entropy.sum(-1	).sum(0	).detach()

  if compute_importance:
   head_importance += head_mask.grad.abs().detach()

  # Also store our logits/labels if we want to compute metrics afterwards
  if preds is None:
   snake_case__    							=				logits.detach().cpu().numpy()
   snake_case__    							=				inputs["labels"].detach().cpu().numpy()
  else:
   snake_case__    							=				np.append(_UpperCAmelCase	,     logits.detach().cpu().numpy()	,     axis=0	)
   snake_case__    							=				np.append(_UpperCAmelCase	,     inputs["labels"].detach().cpu().numpy()	,     axis=0	)

  tot_tokens += inputs["attention_mask"].float().detach().sum().data

 # Normalize
 attn_entropy /= tot_tokens
 head_importance /= tot_tokens
 # Layerwise importance normalization
 if not args.dont_normalize_importance_by_layer:
  snake_case__    							=				2
  snake_case__    							=				torch.pow(torch.pow(_UpperCAmelCase	,     _UpperCAmelCase	).sum(-1	)	,     1 / exponent	)
  head_importance /= norm_by_layer.unsqueeze(-1	) + 1e-20

 if not args.dont_normalize_global_importance:
  snake_case__    							=				(head_importance - head_importance.min()) / (head_importance.max() - head_importance.min())

 # Print/save matrices
 np.save(os.path.join(args.output_dir	,     "attn_entropy.npy"	)	,     attn_entropy.detach().cpu().numpy()	)
 np.save(os.path.join(args.output_dir	,     "head_importance.npy"	)	,     head_importance.detach().cpu().numpy()	)

 logger.info("Attention entropies"	)
 print_ad_tensor(_UpperCAmelCase	)
 logger.info("Head importance scores"	)
 print_ad_tensor(_UpperCAmelCase	)
 logger.info("Head ranked by importance scores"	)
 snake_case__    							=				torch.zeros(head_importance.numel()	,     dtype=torch.long	,     device=args.device	)
 snake_case__    							=				torch.arange(
     head_importance.numel()	,     device=args.device	)
 snake_case__    							=				head_ranks.view_as(_UpperCAmelCase	)
 print_ad_tensor(_UpperCAmelCase	)

 return attn_entropy, head_importance, preds, labels





def 							a__			(  _UpperCAmelCase	,     _UpperCAmelCase	,     _UpperCAmelCase	)    ->  Tuple:

 '''simple docstring'''






 snake_case__							,   snake_case__							,   snake_case__							,   snake_case__    							=				compute_heads_importance(_UpperCAmelCase	,     _UpperCAmelCase	,     _UpperCAmelCase	,     compute_entropy=_UpperCAmelCase	)
 snake_case__    							=				np.argmax(_UpperCAmelCase	,     axis=1	) if args.output_mode == "classification" else np.squeeze(_UpperCAmelCase	)
 snake_case__    							=				glue_compute_metrics(args.task_name	,     _UpperCAmelCase	,     _UpperCAmelCase	)[args.metric_name]
 logger.info("Pruning: original score: %f, threshold: %f"	,     _UpperCAmelCase	,     original_score * args.masking_threshold	)

 snake_case__    							=				torch.ones_like(_UpperCAmelCase	)
 snake_case__    							=				max(1	,     int(new_head_mask.numel() * args.masking_amount	)	)

 snake_case__    							=				original_score
 while current_score >= original_score * args.masking_threshold:
  snake_case__    							=				new_head_mask.clone()  # save current head mask
  # heads from least important to most - keep only not-masked heads
  snake_case__    							=				float("Inf"	)
  snake_case__    							=				head_importance.view(-1	).sort()[1]

  if len(_UpperCAmelCase	) <= num_to_mask:
   break

  # mask heads
  snake_case__    							=				current_heads_to_mask[:num_to_mask]
  logger.info("Heads to mask: %s"	,     str(current_heads_to_mask.tolist()	)	)
  snake_case__    							=				new_head_mask.view(-1	)
  snake_case__    							=				0.0
  snake_case__    							=				new_head_mask.view_as(_UpperCAmelCase	)
  snake_case__    							=				new_head_mask.clone().detach()
  print_ad_tensor(_UpperCAmelCase	)

  # Compute metric and head importance again
  snake_case__							,   snake_case__							,   snake_case__							,   snake_case__    							=				compute_heads_importance(
      _UpperCAmelCase	,     _UpperCAmelCase	,     _UpperCAmelCase	,     compute_entropy=_UpperCAmelCase	,     head_mask=_UpperCAmelCase	)
  snake_case__    							=				np.argmax(_UpperCAmelCase	,     axis=1	) if args.output_mode == "classification" else np.squeeze(_UpperCAmelCase	)
  snake_case__    							=				glue_compute_metrics(args.task_name	,     _UpperCAmelCase	,     _UpperCAmelCase	)[args.metric_name]
  logger.info(
      "Masking: current score: %f, remaining heads %d (%.1f percents)"	,     _UpperCAmelCase	,     new_head_mask.sum()	,     new_head_mask.sum() / new_head_mask.numel() * 1_0_0	,     )

 logger.info("Final head mask"	)
 print_ad_tensor(_UpperCAmelCase	)
 np.save(os.path.join(args.output_dir	,     "head_mask.npy"	)	,     head_mask.detach().cpu().numpy()	)

 return head_mask





def 							a__			(  _UpperCAmelCase	,     _UpperCAmelCase	,     _UpperCAmelCase	,     _UpperCAmelCase	)    ->  List[str]:

 '''simple docstring'''






 snake_case__    							=				datetime.now()
 snake_case__							,   snake_case__							,   snake_case__							,   snake_case__    							=				compute_heads_importance(
     _UpperCAmelCase	,     _UpperCAmelCase	,     _UpperCAmelCase	,     compute_entropy=_UpperCAmelCase	,     compute_importance=_UpperCAmelCase	,     head_mask=_UpperCAmelCase	)
 snake_case__    							=				np.argmax(_UpperCAmelCase	,     axis=1	) if args.output_mode == "classification" else np.squeeze(_UpperCAmelCase	)
 snake_case__    							=				glue_compute_metrics(args.task_name	,     _UpperCAmelCase	,     _UpperCAmelCase	)[args.metric_name]
 snake_case__    							=				datetime.now() - before_time

 snake_case__    							=				sum(p.numel() for p in model.parameters()	)
 snake_case__    							=				{
     layer: (1 - head_mask[layer].long()).nonzero().squeeze().tolist() for layer in range(len(_UpperCAmelCase	)	)
 }

 assert sum(len(_UpperCAmelCase	) for h in heads_to_prune.values()	) == (1 - head_mask.long()).sum().item()
 model.prune_heads(_UpperCAmelCase	)
 snake_case__    							=				sum(p.numel() for p in model.parameters()	)

 snake_case__    							=				datetime.now()
 snake_case__							,   snake_case__							,   snake_case__							,   snake_case__    							=				compute_heads_importance(
     _UpperCAmelCase	,     _UpperCAmelCase	,     _UpperCAmelCase	,     compute_entropy=_UpperCAmelCase	,     compute_importance=_UpperCAmelCase	,     head_mask=_UpperCAmelCase	,     actually_pruned=_UpperCAmelCase	,     )
 snake_case__    							=				np.argmax(_UpperCAmelCase	,     axis=1	) if args.output_mode == "classification" else np.squeeze(_UpperCAmelCase	)
 snake_case__    							=				glue_compute_metrics(args.task_name	,     _UpperCAmelCase	,     _UpperCAmelCase	)[args.metric_name]
 snake_case__    							=				datetime.now() - before_time

 logger.info(
     "Pruning: original num of params: %.2e, after pruning %.2e (%.1f percents)"	,     _UpperCAmelCase	,     _UpperCAmelCase	,     pruned_num_params / original_num_params * 1_0_0	,     )
 logger.info("Pruning: score with masking: %f score with pruning: %f"	,     _UpperCAmelCase	,     _UpperCAmelCase	)
 logger.info("Pruning: speed ratio (new timing / original timing): %f percents"	,     original_time / new_time * 1_0_0	)





def 							a__			(  )    ->  int:

 '''simple docstring'''






 snake_case__    							=				argparse.ArgumentParser()
 # Required parameters
 parser.add_argument(
     "--data_dir"	,     default=_UpperCAmelCase	,     type=_UpperCAmelCase	,     required=_UpperCAmelCase	,     help="The input data dir. Should contain the .tsv files (or other data files) for the task."	,     )
 parser.add_argument(
     "--model_name_or_path"	,     default=_UpperCAmelCase	,     type=_UpperCAmelCase	,     required=_UpperCAmelCase	,     help="Path to pretrained model or model identifier from huggingface.co/models"	,     )
 parser.add_argument(
     "--task_name"	,     default=_UpperCAmelCase	,     type=_UpperCAmelCase	,     required=_UpperCAmelCase	,     help="The name of the task to train selected in the list: " + ", ".join(glue_processors.keys()	)	,     )
 parser.add_argument(
     "--output_dir"	,     default=_UpperCAmelCase	,     type=_UpperCAmelCase	,     required=_UpperCAmelCase	,     help="The output directory where the model predictions and checkpoints will be written."	,     )

 # Other parameters
 parser.add_argument(
     "--config_name"	,     default=""	,     type=_UpperCAmelCase	,     help="Pretrained config name or path if not the same as model_name_or_path"	,     )
 parser.add_argument(
     "--tokenizer_name"	,     default=""	,     type=_UpperCAmelCase	,     help="Pretrained tokenizer name or path if not the same as model_name_or_path"	,     )
 parser.add_argument(
     "--cache_dir"	,     default=_UpperCAmelCase	,     type=_UpperCAmelCase	,     help="Where do you want to store the pre-trained models downloaded from huggingface.co"	,     )
 parser.add_argument(
     "--data_subset"	,     type=_UpperCAmelCase	,     default=-1	,     help="If > 0: limit the data to a subset of data_subset instances."	)
 parser.add_argument(
     "--overwrite_output_dir"	,     action="store_true"	,     help="Whether to overwrite data in output directory"	)
 parser.add_argument(
     "--overwrite_cache"	,     action="store_true"	,     help="Overwrite the cached training and evaluation sets"	)

 parser.add_argument(
     "--dont_normalize_importance_by_layer"	,     action="store_true"	,     help="Don't normalize importance score by layers"	)
 parser.add_argument(
     "--dont_normalize_global_importance"	,     action="store_true"	,     help="Don't normalize all importance scores between 0 and 1"	,     )

 parser.add_argument(
     "--try_masking"	,     action="store_true"	,     help="Whether to try to mask head until a threshold of accuracy."	)
 parser.add_argument(
     "--masking_threshold"	,     default=0.9	,     type=_UpperCAmelCase	,     help="masking threshold in term of metrics (stop masking when metric < threshold * original metric value)."	,     )
 parser.add_argument(
     "--masking_amount"	,     default=0.1	,     type=_UpperCAmelCase	,     help="Amount to heads to masking at each masking step."	)
 parser.add_argument("--metric_name"	,     default="acc"	,     type=_UpperCAmelCase	,     help="Metric to use for head masking."	)

 parser.add_argument(
     "--max_seq_length"	,     default=1_2_8	,     type=_UpperCAmelCase	,     help=(
         "The maximum total input sequence length after WordPiece tokenization. \n"
         "Sequences longer than this will be truncated, sequences shorter padded."
     )	,     )
 parser.add_argument("--batch_size"	,     default=1	,     type=_UpperCAmelCase	,     help="Batch size."	)

 parser.add_argument("--seed"	,     type=_UpperCAmelCase	,     default=4_2	)
 parser.add_argument("--local_rank"	,     type=_UpperCAmelCase	,     default=-1	,     help="local_rank for distributed training on gpus"	)
 parser.add_argument("--no_cuda"	,     action="store_true"	,     help="Whether not to use CUDA when available"	)
 parser.add_argument("--server_ip"	,     type=_UpperCAmelCase	,     default=""	,     help="Can be used for distant debugging."	)
 parser.add_argument("--server_port"	,     type=_UpperCAmelCase	,     default=""	,     help="Can be used for distant debugging."	)
 snake_case__    							=				parser.parse_args()

 if args.server_ip and args.server_port:
  # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script
  import ptvsd

  print("Waiting for debugger attach"	)
  ptvsd.enable_attach(address=(args.server_ip, args.server_port)	,     redirect_output=_UpperCAmelCase	)
  ptvsd.wait_for_attach()

 # Setup devices and distributed training
 if args.local_rank == -1 or args.no_cuda:
  snake_case__    							=				torch.device("cuda" if torch.cuda.is_available() and not args.no_cuda else "cpu"	)
  snake_case__    							=				0 if args.no_cuda else torch.cuda.device_count()
 else:
  torch.cuda.set_device(args.local_rank	)
  snake_case__    							=				torch.device("cuda"	,     args.local_rank	)
  snake_case__    							=				1
  torch.distributed.init_process_group(backend="nccl"	)  # Initializes the distributed backend

 # Setup logging
 logging.basicConfig(level=logging.INFO if args.local_rank in [-1, 0] else logging.WARN	)
 logger.info("device: {} n_gpu: {}, distributed: {}".format(args.device	,     args.n_gpu	,     bool(args.local_rank != -1	)	)	)
 # Set the verbosity to info of the Transformers logger (on main process only):
 if is_main_process(args.local_rank	):
  transformers.utils.logging.set_verbosity_info()
  transformers.utils.logging.enable_default_handler()
  transformers.utils.logging.enable_explicit_format()

 # Set seeds
 set_seed(args.seed	)

 # Prepare GLUE task
 snake_case__    							=				args.task_name.lower()
 if args.task_name not in glue_processors:
  raise ValueError("Task not found: %s" % (args.task_name)	)
 snake_case__    							=				glue_processors[args.task_name]()
 snake_case__    							=				glue_output_modes[args.task_name]
 snake_case__    							=				processor.get_labels()
 snake_case__    							=				len(_UpperCAmelCase	)

 # Load pretrained model and tokenizer
 #
 # Distributed training:
 # The .from_pretrained methods guarantee that only one local process can concurrently
 # download model & vocab.

 snake_case__    							=				AutoConfig.from_pretrained(
     args.config_name if args.config_name else args.model_name_or_path	,     num_labels=_UpperCAmelCase	,     finetuning_task=args.task_name	,     output_attentions=_UpperCAmelCase	,     cache_dir=args.cache_dir	,     )
 snake_case__    							=				AutoTokenizer.from_pretrained(
     args.tokenizer_name if args.tokenizer_name else args.model_name_or_path	,     cache_dir=args.cache_dir	,     )
 snake_case__    							=				AutoModelForSequenceClassification.from_pretrained(
     args.model_name_or_path	,     from_tf=bool(".ckpt" in args.model_name_or_path	)	,     config=_UpperCAmelCase	,     cache_dir=args.cache_dir	,     )

 # Distributed and parallel training
 model.to(args.device	)
 if args.local_rank != -1:
  snake_case__    							=				nn.parallel.DistributedDataParallel(
      _UpperCAmelCase	,     device_ids=[args.local_rank]	,     output_device=args.local_rank	,     find_unused_parameters=_UpperCAmelCase	)
 elif args.n_gpu > 1:
  snake_case__    							=				nn.DataParallel(_UpperCAmelCase	)

 # Print/save training arguments
 os.makedirs(args.output_dir	,     exist_ok=_UpperCAmelCase	)
 torch.save(_UpperCAmelCase	,     os.path.join(args.output_dir	,     "run_args.bin"	)	)
 logger.info("Training/evaluation parameters %s"	,     _UpperCAmelCase	)

 # Prepare dataset for the GLUE task
 snake_case__    							=				GlueDataset(_UpperCAmelCase	,     tokenizer=_UpperCAmelCase	,     mode="dev"	)
 if args.data_subset > 0:
  snake_case__    							=				Subset(_UpperCAmelCase	,     list(range(min(args.data_subset	,     len(_UpperCAmelCase	)	)	)	)	)
 snake_case__    							=				SequentialSampler(_UpperCAmelCase	) if args.local_rank == -1 else DistributedSampler(_UpperCAmelCase	)
 snake_case__    							=				DataLoader(
     _UpperCAmelCase	,     sampler=_UpperCAmelCase	,     batch_size=args.batch_size	,     collate_fn=_UpperCAmelCase	)

 # Compute head entropy and importance score
 compute_heads_importance(_UpperCAmelCase	,     _UpperCAmelCase	,     _UpperCAmelCase	)

 # Try head masking (set heads to zero until the score goes under a threshole)
 # and head pruning (remove masked heads and see the effect on the network)
 if args.try_masking and args.masking_threshold > 0.0 and args.masking_threshold < 1.0:
  snake_case__    							=				mask_heads(_UpperCAmelCase	,     _UpperCAmelCase	,     _UpperCAmelCase	)
  prune_heads(_UpperCAmelCase	,     _UpperCAmelCase	,     _UpperCAmelCase	,     _UpperCAmelCase	)


if __name__ == "__main__":
   main()








"""simple docstring"""


import inspect
import unittest

from transformers import is_torch_available, is_vision_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
   import torch

   from transformers import MODEL_MAPPING, PoolFormerConfig, PoolFormerForImageClassification, PoolFormerModel
   from transformers.models.poolformer.modeling_poolformer import POOLFORMER_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
   from PIL import Image

   from transformers import PoolFormerImageProcessor



class      lowercase_				(     __lowerCAmelCase							):

       def 		_SCREAMING_SNAKE_CASE(			self     ):






        '''simple docstring'''

        snake_case__    							=				self.config_class(**self.inputs_dict     )
        self.parent.assertTrue(hasattr(__SCREAMING_SNAKE_CASE   ,					"hidden_sizes"     )     )
        self.parent.assertTrue(hasattr(__SCREAMING_SNAKE_CASE   ,					"num_encoder_blocks"     )     )



class      lowercase_				:

       def __init__(			self   ,					__SCREAMING_SNAKE_CASE   ,					__SCREAMING_SNAKE_CASE=13   ,					__SCREAMING_SNAKE_CASE=64   ,					__SCREAMING_SNAKE_CASE=3   ,					__SCREAMING_SNAKE_CASE=4   ,					__SCREAMING_SNAKE_CASE=[2, 2, 2, 2]   ,					__SCREAMING_SNAKE_CASE=[8, 4, 2, 1]   ,					__SCREAMING_SNAKE_CASE=[16, 32, 64, 128]   ,					__SCREAMING_SNAKE_CASE=[1, 4, 8, 16]   ,					__SCREAMING_SNAKE_CASE=False   ,					__SCREAMING_SNAKE_CASE=True   ,					__SCREAMING_SNAKE_CASE="gelu"   ,					__SCREAMING_SNAKE_CASE=0.1   ,					__SCREAMING_SNAKE_CASE=0.02   ,					__SCREAMING_SNAKE_CASE=3   ,					__SCREAMING_SNAKE_CASE=None   ,					):






        '''simple docstring'''

        snake_case__    							=				parent
        snake_case__    							=				batch_size
        snake_case__    							=				image_size
        snake_case__    							=				num_channels
        snake_case__    							=				num_encoder_blocks
        snake_case__    							=				sr_ratios
        snake_case__    							=				depths
        snake_case__    							=				hidden_sizes
        snake_case__    							=				downsampling_rates
        snake_case__    							=				is_training
        snake_case__    							=				use_labels
        snake_case__    							=				hidden_act
        snake_case__    							=				hidden_dropout_prob
        snake_case__    							=				initializer_range
        snake_case__    							=				num_labels
        snake_case__    							=				scope

       def 		_SCREAMING_SNAKE_CASE(			self     ):






        '''simple docstring'''

        snake_case__    							=				floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]     )

        snake_case__    							=				None
        if self.use_labels:
         snake_case__    							=				ids_tensor([self.batch_size, self.image_size, self.image_size]   ,					self.num_labels     )

        snake_case__    							=				PoolFormerConfig(
            image_size=self.image_size   ,					num_channels=self.num_channels   ,					num_encoder_blocks=self.num_encoder_blocks   ,					depths=self.depths   ,					hidden_sizes=self.hidden_sizes   ,					hidden_act=self.hidden_act   ,					hidden_dropout_prob=self.hidden_dropout_prob   ,					initializer_range=self.initializer_range   ,					)

        return config, pixel_values, labels

       def 		_SCREAMING_SNAKE_CASE(			self   ,					__SCREAMING_SNAKE_CASE   ,					__SCREAMING_SNAKE_CASE   ,					__SCREAMING_SNAKE_CASE     ):






        '''simple docstring'''

        snake_case__    							=				PoolFormerModel(config=__SCREAMING_SNAKE_CASE     )
        model.to(__SCREAMING_SNAKE_CASE     )
        model.eval()
        snake_case__    							=				model(__SCREAMING_SNAKE_CASE     )
        snake_case__    							=				snake_case__    							=				self.image_size // 32.0
        self.parent.assertEqual(
            result.last_hidden_state.shape   ,					(self.batch_size, self.hidden_sizes[-1], expected_height, expected_width)     )

       def 		_SCREAMING_SNAKE_CASE(			self     ):






        '''simple docstring'''

        snake_case__    							=				self.prepare_config_and_inputs()
        snake_case__							,   snake_case__							,   snake_case__    							=				config_and_inputs
        snake_case__    							=				{"pixel_values": pixel_values}
        return config, inputs_dict



@require_torch
class      lowercase_				(     __lowerCAmelCase				,__lowerCAmelCase				,unittest.TestCase							):
       snake_case__				:							Optional[Any]											=     (PoolFormerModel, PoolFormerForImageClassification) if is_torch_available() else ()
       snake_case__				:							Dict											=     (
           {"""feature-extraction""": PoolFormerModel, """image-classification""": PoolFormerForImageClassification}
           if is_torch_available()
           else {}
       )

       snake_case__				:							Optional[int]											=     False
       snake_case__				:							Optional[Any]											=     False
       snake_case__				:							List[Any]											=     False
       snake_case__				:							Any											=     False
       snake_case__				:							Tuple											=     False

       def 		_SCREAMING_SNAKE_CASE(			self     ):






        '''simple docstring'''

        snake_case__    							=				PoolFormerModelTester(self     )
        snake_case__    							=				PoolFormerConfigTester(self   ,					config_class=__SCREAMING_SNAKE_CASE     )

       def 		_SCREAMING_SNAKE_CASE(			self     ):






        '''simple docstring'''

        self.config_tester.run_common_tests()

       def 		_SCREAMING_SNAKE_CASE(			self     ):






        '''simple docstring'''

        snake_case__    							=				self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE     )

       @unittest.skip("PoolFormer does not use inputs_embeds"     )
       def 		_SCREAMING_SNAKE_CASE(			self     ):






        '''simple docstring'''

        pass

       @unittest.skip("PoolFormer does not have get_input_embeddings method and get_output_embeddings methods"     )
       def 		_SCREAMING_SNAKE_CASE(			self     ):






        '''simple docstring'''

        pass

       def 		_SCREAMING_SNAKE_CASE(			self     ):






        '''simple docstring'''

        def check_hidden_states_output(__SCREAMING_SNAKE_CASE   ,					__SCREAMING_SNAKE_CASE   ,					__SCREAMING_SNAKE_CASE     ):
         snake_case__    							=				model_class(__SCREAMING_SNAKE_CASE     )
         model.to(__SCREAMING_SNAKE_CASE     )
         model.eval()

         with torch.no_grad():
          snake_case__    							=				model(**self._prepare_for_class(__SCREAMING_SNAKE_CASE   ,					__SCREAMING_SNAKE_CASE     )     )

         snake_case__    							=				outputs.hidden_states

         snake_case__    							=				self.model_tester.num_encoder_blocks
         self.assertEqual(len(__SCREAMING_SNAKE_CASE     )   ,					__SCREAMING_SNAKE_CASE     )

         # verify the first hidden states (first block)
         self.assertListEqual(
             list(hidden_states[0].shape[-3:]     )   ,					[
                 self.model_tester.hidden_sizes[0],
                 self.model_tester.image_size // 4,
                 self.model_tester.image_size // 4,
             ]   ,					)

        snake_case__							,   snake_case__    							=				self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
         snake_case__    							=				True
         check_hidden_states_output(__SCREAMING_SNAKE_CASE   ,					__SCREAMING_SNAKE_CASE   ,					__SCREAMING_SNAKE_CASE     )

         # check that output_hidden_states also work using config
         del inputs_dict["output_hidden_states"]
         snake_case__    							=				True

         check_hidden_states_output(__SCREAMING_SNAKE_CASE   ,					__SCREAMING_SNAKE_CASE   ,					__SCREAMING_SNAKE_CASE     )

       def 		_SCREAMING_SNAKE_CASE(			self     ):






        '''simple docstring'''

        if not self.model_tester.is_training:
         return

        snake_case__							,   snake_case__    							=				self.model_tester.prepare_config_and_inputs_for_common()
        snake_case__    							=				True

        for model_class in self.all_model_classes:
         if model_class in get_values(__SCREAMING_SNAKE_CASE     ):
          continue
         snake_case__    							=				model_class(__SCREAMING_SNAKE_CASE     )
         model.to(__SCREAMING_SNAKE_CASE     )
         model.train()
         snake_case__    							=				self._prepare_for_class(__SCREAMING_SNAKE_CASE   ,					__SCREAMING_SNAKE_CASE   ,					return_labels=__SCREAMING_SNAKE_CASE     )
         snake_case__    							=				model(**__SCREAMING_SNAKE_CASE     ).loss
         loss.backward()

       def 		_SCREAMING_SNAKE_CASE(			self     ):






        '''simple docstring'''

        snake_case__							,   snake_case__    							=				self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
         snake_case__    							=				model_class(__SCREAMING_SNAKE_CASE     )
         snake_case__    							=				inspect.signature(model.forward     )
         # signature.parameters is an OrderedDict => so arg_names order is deterministic
         snake_case__    							=				[*signature.parameters.keys()]

         snake_case__    							=				["pixel_values"]
         self.assertListEqual(arg_names[:1]   ,					__SCREAMING_SNAKE_CASE     )

       @slow
       def 		_SCREAMING_SNAKE_CASE(			self     ):






        '''simple docstring'''

        for model_name in POOLFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
         snake_case__    							=				PoolFormerModel.from_pretrained(__SCREAMING_SNAKE_CASE     )
         self.assertIsNotNone(__SCREAMING_SNAKE_CASE     )





def 							a__			(  )    ->  int:

 '''simple docstring'''






 snake_case__    							=				Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"	)
 return image



@require_torch
class      lowercase_				(     unittest.TestCase							):

       @slow
       def 		_SCREAMING_SNAKE_CASE(			self     ):






        '''simple docstring'''

        snake_case__    							=				PoolFormerImageProcessor()
        snake_case__    							=				PoolFormerForImageClassification.from_pretrained("sail/poolformer_s12"     ).to(__SCREAMING_SNAKE_CASE     )

        snake_case__    							=				image_processor(images=prepare_img()   ,					return_tensors="pt"     ).to(__SCREAMING_SNAKE_CASE     )

        # forward pass
        with torch.no_grad():
         snake_case__    							=				model(**__SCREAMING_SNAKE_CASE     )

        # verify the logits
        snake_case__    							=				torch.Size((1, 1000)     )
        self.assertEqual(outputs.logits.shape   ,					__SCREAMING_SNAKE_CASE     )

        snake_case__    							=				torch.tensor([-0.6113, 0.1685, -0.0492]     ).to(__SCREAMING_SNAKE_CASE     )
        self.assertTrue(torch.allclose(outputs.logits[0, :3]   ,					__SCREAMING_SNAKE_CASE   ,					atol=1e-4     )     )

