
"""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


__magic_name__		       =				logging.getLogger(__name__)




def     __lowerCamelCase  (		UpperCamelCase__      ):


	"""simple docstring"""






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




def     __lowerCamelCase  (		UpperCamelCase__      ):


	"""simple docstring"""






	logger.info("lv, h >\t" + "\t".join(f"{x + 1}" for x in range(len(__lowerCamelCase      )      )      )      )
	for row in range(len(__lowerCamelCase      )      ):
		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     __lowerCamelCase  (		UpperCamelCase__				,     UpperCamelCase__				,     UpperCamelCase__				,     UpperCamelCase__=True				,     UpperCamelCase__=True				,     UpperCamelCase__=None				,     UpperCamelCase__=False      ):


	"""simple docstring"""






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

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

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

	_UpperCAmelCase =						None
	_UpperCAmelCase =						None
	_UpperCAmelCase =						0.0

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

		# Do a forward pass (not with torch.no_grad() since we need gradients for importance score - see below)
		_UpperCAmelCase =						model(**__lowerCamelCase				,     head_mask=__lowerCamelCase      )
		_UpperCAmelCase ,      _UpperCAmelCase ,      _UpperCAmelCase =						(
		    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(__lowerCamelCase      ):
				_UpperCAmelCase =						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:
			_UpperCAmelCase =						logits.detach().cpu().numpy()
			_UpperCAmelCase =						inputs["labels"].detach().cpu().numpy()
		else:
			_UpperCAmelCase =						np.append(__lowerCamelCase				,     logits.detach().cpu().numpy()				,     axis=0      )
			_UpperCAmelCase =						np.append(__lowerCamelCase				,     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:
		_UpperCAmelCase =						2
		_UpperCAmelCase =						torch.pow(torch.pow(__lowerCamelCase				,     __lowerCamelCase      ).sum(-1      )				,     1 / exponent      )
		head_importance /= norm_by_layer.unsqueeze(-1      ) + 1E-20

	if not args.dont_normalize_global_importance:
		_UpperCAmelCase =						(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(__lowerCamelCase      )
	logger.info("Head importance scores"      )
	print_ad_tensor(__lowerCamelCase      )
	logger.info("Head ranked by importance scores"      )
	_UpperCAmelCase =						torch.zeros(head_importance.numel()				,     dtype=torch.long				,     device=args.device      )
	_UpperCAmelCase =						torch.arange(
	    head_importance.numel()				,     device=args.device      )
	_UpperCAmelCase =						head_ranks.view_as(__lowerCamelCase      )
	print_ad_tensor(__lowerCamelCase      )

	return attn_entropy, head_importance, preds, labels




def     __lowerCamelCase  (		UpperCamelCase__				,     UpperCamelCase__				,     UpperCamelCase__      ):


	"""simple docstring"""






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

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

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

		if len(__lowerCamelCase      ) <= num_to_mask:
			break

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

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

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

	return head_mask




def     __lowerCamelCase  (		UpperCamelCase__				,     UpperCamelCase__				,     UpperCamelCase__				,     UpperCamelCase__      ):


	"""simple docstring"""






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

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

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

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

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




def     __lowerCamelCase  (		):


	"""simple docstring"""






	_UpperCAmelCase =						argparse.ArgumentParser()
	# Required parameters
	parser.add_argument(
	    "--data_dir"				,     default=__lowerCamelCase				,     type=__lowerCamelCase				,     required=__lowerCamelCase				,     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=__lowerCamelCase				,     type=__lowerCamelCase				,     required=__lowerCamelCase				,     help="Path to pretrained model or model identifier from huggingface.co/models"				,     )
	parser.add_argument(
	    "--task_name"				,     default=__lowerCamelCase				,     type=__lowerCamelCase				,     required=__lowerCamelCase				,     help="The name of the task to train selected in the list: " + ", ".join(glue_processors.keys()      )				,     )
	parser.add_argument(
	    "--output_dir"				,     default=__lowerCamelCase				,     type=__lowerCamelCase				,     required=__lowerCamelCase				,     help="The output directory where the model predictions and checkpoints will be written."				,     )

	# Other parameters
	parser.add_argument(
	    "--config_name"				,     default=""				,     type=__lowerCamelCase				,     help="Pretrained config name or path if not the same as model_name_or_path"				,     )
	parser.add_argument(
	    "--tokenizer_name"				,     default=""				,     type=__lowerCamelCase				,     help="Pretrained tokenizer name or path if not the same as model_name_or_path"				,     )
	parser.add_argument(
	    "--cache_dir"				,     default=__lowerCamelCase				,     type=__lowerCamelCase				,     help="Where do you want to store the pre-trained models downloaded from huggingface.co"				,     )
	parser.add_argument(
	    "--data_subset"				,     type=__lowerCamelCase				,     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=__lowerCamelCase				,     help="masking threshold in term of metrics (stop masking when metric < threshold * original metric value)."				,     )
	parser.add_argument(
	    "--masking_amount"				,     default=0.1				,     type=__lowerCamelCase				,     help="Amount to heads to masking at each masking step."      )
	parser.add_argument("--metric_name"				,     default="acc"				,     type=__lowerCamelCase				,     help="Metric to use for head masking."      )

	parser.add_argument(
	    "--max_seq_length"				,     default=128				,     type=__lowerCamelCase				,     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=__lowerCamelCase				,     help="Batch size."      )

	parser.add_argument("--seed"				,     type=__lowerCamelCase				,     default=42      )
	parser.add_argument("--local_rank"				,     type=__lowerCamelCase				,     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=__lowerCamelCase				,     default=""				,     help="Can be used for distant debugging."      )
	parser.add_argument("--server_port"				,     type=__lowerCamelCase				,     default=""				,     help="Can be used for distant debugging."      )
	_UpperCAmelCase =						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=__lowerCamelCase      )
		ptvsd.wait_for_attach()

	# Setup devices and distributed training
	if args.local_rank == -1 or args.no_cuda:
		_UpperCAmelCase =						torch.device("cuda" if torch.cuda.is_available() and not args.no_cuda else "cpu"      )
		_UpperCAmelCase =						0 if args.no_cuda else torch.cuda.device_count()
	else:
		torch.cuda.set_device(args.local_rank      )
		_UpperCAmelCase =						torch.device("cuda"				,     args.local_rank      )
		_UpperCAmelCase =						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
	_UpperCAmelCase =						args.task_name.lower()
	if args.task_name not in glue_processors:
		raise ValueError("Task not found: %s" % (args.task_name)      )
	_UpperCAmelCase =						glue_processors[args.task_name]()
	_UpperCAmelCase =						glue_output_modes[args.task_name]
	_UpperCAmelCase =						processor.get_labels()
	_UpperCAmelCase =						len(__lowerCamelCase      )

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

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

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

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

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

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

	# 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:
		_UpperCAmelCase =						mask_heads(__lowerCamelCase				,     __lowerCamelCase				,     __lowerCamelCase      )
		prune_heads(__lowerCamelCase				,     __lowerCamelCase				,     __lowerCamelCase				,     __lowerCamelCase      )


if __name__ == "__main__":
			main()






"""simple docstring"""
import inspect
import unittest
import warnings
from typing import List

from transformers import EfficientFormerConfig
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

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_FOR_IMAGE_CLASSIFICATION_MAPPING,
			    MODEL_MAPPING,
			    EfficientFormerForImageClassification,
			    EfficientFormerForImageClassificationWithTeacher,
			    EfficientFormerModel,
			)
			from transformers.models.efficientformer.modeling_efficientformer import (
			    EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
			)


if is_vision_available():
			from PIL import Image

			from transformers import EfficientFormerImageProcessor


class    _lowerCAmelCase						:



							def __init__(      self ,						a_ ,						a_ = 13 ,						a_ = 64 ,						a_ = 2 ,						a_ = 3 ,						a_ = 3 ,						a_ = True ,						a_ = True ,						a_ = 128 ,						a_=[16, 32, 64, 128] ,						a_ = 7 ,						a_ = 4 ,						a_ = 37 ,						a_ = "gelu" ,						a_ = 0.1 ,						a_ = 0.1 ,						a_ = 10 ,						a_ = 0.02 ,						a_ = 2 ,						a_ = 1 ,						a_ = 128 ,						a_ = [2, 2, 2, 2] ,						a_ = 2 ,						a_ = 2 ,						)							->							Tuple:
								_UpperCAmelCase =						parent
								_UpperCAmelCase =						batch_size
								_UpperCAmelCase =						image_size
								_UpperCAmelCase =						patch_size
								_UpperCAmelCase =						num_channels
								_UpperCAmelCase =						is_training
								_UpperCAmelCase =						use_labels
								_UpperCAmelCase =						hidden_size
								_UpperCAmelCase =						num_hidden_layers
								_UpperCAmelCase =						num_attention_heads
								_UpperCAmelCase =						intermediate_size
								_UpperCAmelCase =						hidden_act
								_UpperCAmelCase =						hidden_dropout_prob
								_UpperCAmelCase =						attention_probs_dropout_prob
								_UpperCAmelCase =						type_sequence_label_size
								_UpperCAmelCase =						initializer_range
								_UpperCAmelCase =						encoder_stride
								_UpperCAmelCase =						num_attention_outputs
								_UpperCAmelCase =						embed_dim
								_UpperCAmelCase =						embed_dim + 1
								_UpperCAmelCase =						resolution
								_UpperCAmelCase =						depths
								_UpperCAmelCase =						hidden_sizes
								_UpperCAmelCase =						dim
								_UpperCAmelCase =						mlp_expansion_ratio



							def       _a   (      self   )							->							Tuple:
								_UpperCAmelCase =						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]   )

								_UpperCAmelCase =						None
								if self.use_labels:
									_UpperCAmelCase =						ids_tensor([self.batch_size] ,						self.type_sequence_label_size   )

								_UpperCAmelCase =						self.get_config()
								return config, pixel_values, labels



							def       _a   (      self   )							->							Optional[int]:
								return EfficientFormerConfig(
								    image_size=self.image_size ,						patch_size=self.patch_size ,						num_channels=self.num_channels ,						hidden_size=self.hidden_size ,						num_hidden_layers=self.num_hidden_layers ,						num_attention_heads=self.num_attention_heads ,						intermediate_size=self.intermediate_size ,						hidden_act=self.hidden_act ,						hidden_dropout_prob=self.hidden_dropout_prob ,						attention_probs_dropout_prob=self.attention_probs_dropout_prob ,						is_decoder=a_ ,						initializer_range=self.initializer_range ,						encoder_stride=self.encoder_stride ,						resolution=self.resolution ,						depths=self.depths ,						hidden_sizes=self.hidden_sizes ,						dim=self.dim ,						mlp_expansion_ratio=self.mlp_expansion_ratio ,						)



							def       _a   (      self ,						a_ ,						a_ ,						a_   )							->							int:
								_UpperCAmelCase =						EfficientFormerModel(config=a_   )
								model.to(a_   )
								model.eval()
								_UpperCAmelCase =						model(a_   )
								self.parent.assertEqual(result.last_hidden_state.shape ,						(self.batch_size, self.seq_length, self.hidden_size)   )



							def       _a   (      self ,						a_ ,						a_ ,						a_   )							->							str:
								_UpperCAmelCase =						self.type_sequence_label_size
								_UpperCAmelCase =						EfficientFormerForImageClassification(a_   )
								model.to(a_   )
								model.eval()
								_UpperCAmelCase =						model(a_ ,						labels=a_   )
								self.parent.assertEqual(result.logits.shape ,						(self.batch_size, self.type_sequence_label_size)   )

								# test greyscale images
								_UpperCAmelCase =						1
								_UpperCAmelCase =						EfficientFormerForImageClassification(a_   )
								model.to(a_   )
								model.eval()

								_UpperCAmelCase =						floats_tensor([self.batch_size, 1, self.image_size, self.image_size]   )
								_UpperCAmelCase =						model(a_   )
								self.parent.assertEqual(result.logits.shape ,						(self.batch_size, self.type_sequence_label_size)   )



							def       _a   (      self   )							->							Optional[int]:
								_UpperCAmelCase =						self.prepare_config_and_inputs()
								(
								    (
								    _UpperCAmelCase
								) ,      (
								    _UpperCAmelCase
								) ,      (
								    _UpperCAmelCase
								) ,      
								) =						config_and_inputs
								_UpperCAmelCase =						{"pixel_values": pixel_values}
								return config, inputs_dict





@require_torch
class    _lowerCAmelCase						(						lowerCamelCase    ,       lowerCamelCase    ,       unittest.TestCase						):
							lowercase_     :     List[Any]       =							(
							    (
							        EfficientFormerModel,
							        EfficientFormerForImageClassificationWithTeacher,
							        EfficientFormerForImageClassification,
							    )
							    if is_torch_available()
							    else ()
							)
							lowercase_     :     Optional[Any]       =							(
							    {
							        '''feature-extraction''': EfficientFormerModel,
							        '''image-classification''': (
							            EfficientFormerForImageClassification,
							            EfficientFormerForImageClassificationWithTeacher,
							        ),
							    }
							    if is_torch_available()
							    else {}
							)
							lowercase_     :     List[str]       =							False

							lowercase_     :     Dict       =							False
							lowercase_     :     List[str]       =							False
							lowercase_     :     List[str]       =							False



							def       _a   (      self   )							->							Dict:
								_UpperCAmelCase =						EfficientFormerModelTester(self   )
								_UpperCAmelCase =						ConfigTester(
								    self ,						config_class=a_ ,						has_text_modality=a_ ,						hidden_size=37   )



							def       _a   (      self   )							->							List[Any]:
								self.config_tester.run_common_tests()



							@unittest.skip(reason="EfficientFormer does not use inputs_embeds"   )
							def       _a   (      self   )							->							Tuple:
								pass



							@unittest.skip(reason="EfficientFormer does not support input and output embeddings"   )
							def       _a   (      self   )							->							Optional[int]:
								pass



							def       _a   (      self   )							->							Optional[Any]:
								_UpperCAmelCase ,      _UpperCAmelCase =						self.model_tester.prepare_config_and_inputs_for_common()

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

									_UpperCAmelCase =						["pixel_values"]
									self.assertListEqual(arg_names[:1] ,						a_   )



							def       _a   (      self   )							->							int:
								def check_hidden_states_output(a_ ,						a_ ,						a_   ):
									_UpperCAmelCase =						model_class(a_   )
									model.to(a_   )
									model.eval()

									with torch.no_grad():
										_UpperCAmelCase =						model(**self._prepare_for_class(a_ ,						a_   )   )

									_UpperCAmelCase =						outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

									_UpperCAmelCase =						getattr(
									    self.model_tester ,						"expected_num_hidden_layers" ,						self.model_tester.num_hidden_layers + 1   )
									self.assertEqual(len(a_   ) ,						a_   )

									if hasattr(self.model_tester ,						"encoder_seq_length"   ):
										_UpperCAmelCase =						self.model_tester.encoder_seq_length
										if hasattr(self.model_tester ,						"chunk_length"   ) and self.model_tester.chunk_length > 1:
											_UpperCAmelCase =						seq_length * self.model_tester.chunk_length
									else:
										_UpperCAmelCase =						self.model_tester.seq_length

									self.assertListEqual(
									    list(hidden_states[-1].shape[-2:]   ) ,						[seq_length, self.model_tester.hidden_size] ,						)

									if config.is_encoder_decoder:
										_UpperCAmelCase =						outputs.decoder_hidden_states

										self.assertIsInstance(a_ ,						(list, tuple)   )
										self.assertEqual(len(a_   ) ,						a_   )
										_UpperCAmelCase =						getattr(self.model_tester ,						"seq_length" ,						a_   )
										_UpperCAmelCase =						getattr(self.model_tester ,						"decoder_seq_length" ,						a_   )

										self.assertListEqual(
										    list(hidden_states[-1].shape[-2:]   ) ,						[decoder_seq_length, self.model_tester.hidden_size] ,						)

								_UpperCAmelCase ,      _UpperCAmelCase =						self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
									_UpperCAmelCase =						True
									check_hidden_states_output(a_ ,						a_ ,						a_   )

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

									check_hidden_states_output(a_ ,						a_ ,						a_   )



							def       _a   (      self ,						a_ ,						a_ ,						a_=False   )							->							Optional[Any]:
								_UpperCAmelCase =						super()._prepare_for_class(a_ ,						a_ ,						return_labels=a_   )

								if return_labels:
									if model_class.__name__ == "EfficientFormerForImageClassificationWithTeacher":
										del inputs_dict["labels"]

								return inputs_dict



							def       _a   (      self   )							->							int:
								_UpperCAmelCase =						self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*a_   )



							@unittest.skip(reason="EfficientFormer does not implement masked image modeling yet"   )
							def       _a   (      self   )							->							int:
								_UpperCAmelCase =						self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_masked_image_modeling(*a_   )



							def       _a   (      self   )							->							int:
								_UpperCAmelCase =						self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_image_classification(*a_   )



							def       _a   (      self   )							->							str:
								if not self.model_tester.is_training:
									return

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

								for model_class in self.all_model_classes:
									# EfficientFormerForImageClassificationWithTeacher supports inference-only
									if (
									    model_class in get_values(a_   )
									    or model_class.__name__ == "EfficientFormerForImageClassificationWithTeacher"
									):
										continue
									_UpperCAmelCase =						model_class(a_   )
									model.to(a_   )
									model.train()
									_UpperCAmelCase =						self._prepare_for_class(a_ ,						a_ ,						return_labels=a_   )
									_UpperCAmelCase =						model(**a_   ).loss
									loss.backward()



							def       _a   (      self   )							->							Tuple:
								_UpperCAmelCase ,      _UpperCAmelCase =						self.model_tester.prepare_config_and_inputs_for_common()

								_UpperCAmelCase =						[
								    {"title": "multi_label_classification", "num_labels": 2, "dtype": torch.float},
								    {"title": "single_label_classification", "num_labels": 1, "dtype": torch.long},
								    {"title": "regression", "num_labels": 1, "dtype": torch.float},
								]

								for model_class in self.all_model_classes:
									if (
									    model_class
									    not in [
									        *get_values(a_   ),
									    ]
									    or model_class.__name__ == "EfficientFormerForImageClassificationWithTeacher"
									):
										continue

									for problem_type in problem_types:
										with self.subTest(msg=f"Testing {model_class} with {problem_type['title']}"   ):
											_UpperCAmelCase =						problem_type["title"]
											_UpperCAmelCase =						problem_type["num_labels"]

											_UpperCAmelCase =						model_class(a_   )
											model.to(a_   )
											model.train()

											_UpperCAmelCase =						self._prepare_for_class(a_ ,						a_ ,						return_labels=a_   )

											if problem_type["num_labels"] > 1:
												_UpperCAmelCase =						inputs["labels"].unsqueeze(1   ).repeat(1 ,						problem_type["num_labels"]   )

											_UpperCAmelCase =						inputs["labels"].to(problem_type["dtype"]   )

											# This tests that we do not trigger the warning form PyTorch "Using a target size that is different
											# to the input size. This will likely lead to incorrect results due to broadcasting. Please ensure
											# they have the same size." which is a symptom something in wrong for the regression problem.
											# See https://github.com/huggingface/transformers/issues/11780
											with warnings.catch_warnings(record=a_   ) as warning_list:
												_UpperCAmelCase =						model(**a_   ).loss
											for w in warning_list:
												if "Using a target size that is different to the input size" in str(w.message   ):
													raise ValueError(
													    f"Something is going wrong in the regression problem: intercepted {w.message}"   )

											loss.backward()



							@slow
							def       _a   (      self   )							->							Tuple:
								for model_name in EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
									_UpperCAmelCase =						EfficientFormerModel.from_pretrained(a_   )
									self.assertIsNotNone(a_   )



							def       _a   (      self   )							->							Union[str, Any]:
								_UpperCAmelCase ,      _UpperCAmelCase =						self.model_tester.prepare_config_and_inputs_for_common()
								_UpperCAmelCase =						True

								_UpperCAmelCase =						getattr(self.model_tester ,						"seq_length" ,						a_   )
								_UpperCAmelCase =						getattr(self.model_tester ,						"encoder_seq_length" ,						a_   )
								_UpperCAmelCase =						getattr(self.model_tester ,						"key_length" ,						a_   )
								_UpperCAmelCase =						getattr(self.model_tester ,						"chunk_length" ,						a_   )

								if chunk_length is not None and hasattr(self.model_tester ,						"num_hashes"   ):
									_UpperCAmelCase =						encoder_seq_length * self.model_tester.num_hashes

								for model_class in self.all_model_classes:
									_UpperCAmelCase =						True
									_UpperCAmelCase =						False
									_UpperCAmelCase =						True
									_UpperCAmelCase =						model_class(a_   )
									model.to(a_   )
									model.eval()
									with torch.no_grad():
										_UpperCAmelCase =						model(**self._prepare_for_class(a_ ,						a_   )   )
									_UpperCAmelCase =						outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions
									self.assertEqual(len(a_   ) ,						self.model_tester.num_attention_outputs   )

									# check that output_attentions also work using config
									del inputs_dict["output_attentions"]
									_UpperCAmelCase =						True
									_UpperCAmelCase =						model_class(a_   )
									model.to(a_   )
									model.eval()
									with torch.no_grad():
										_UpperCAmelCase =						model(**self._prepare_for_class(a_ ,						a_   )   )
									_UpperCAmelCase =						outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions
									self.assertEqual(len(a_   ) ,						self.model_tester.num_attention_outputs   )

									if chunk_length is not None:
										self.assertListEqual(
										    list(attentions[0].shape[-4:]   ) ,						[self.model_tester.num_attention_heads, encoder_seq_length, chunk_length, encoder_key_length] ,						)
									else:
										self.assertListEqual(
										    list(attentions[0].shape[-3:]   ) ,						[self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length] ,						)





def     __lowerCamelCase  (		):


	"""simple docstring"""






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



@require_torch
@require_vision
class    _lowerCAmelCase						(						unittest.TestCase						):



							@cached_property
							def       _a   (      self   )							->							Optional[Any]:
								return (
								    EfficientFormerImageProcessor.from_pretrained("snap-research/efficientformer-l1-300"   )
								    if is_vision_available()
								    else None
								)



							@slow
							def       _a   (      self   )							->							Tuple:
								_UpperCAmelCase =						EfficientFormerForImageClassification.from_pretrained("snap-research/efficientformer-l1-300"   ).to(
								    a_   )

								_UpperCAmelCase =						self.default_image_processor
								_UpperCAmelCase =						prepare_img()
								_UpperCAmelCase =						image_processor(images=a_ ,						return_tensors="pt"   ).to(a_   )

								# forward pass
								with torch.no_grad():
									_UpperCAmelCase =						model(**a_   )

								# verify the logits
								_UpperCAmelCase =						(1, 1000)
								self.assertEqual(outputs.logits.shape ,						a_   )

								_UpperCAmelCase =						torch.tensor([-0.0555, 0.4825, -0.0852]   ).to(a_   )
								self.assertTrue(torch.allclose(outputs.logits[0][:3] ,						a_ ,						atol=1e-4   )   )



							@slow
							def       _a   (      self   )							->							Tuple:
								_UpperCAmelCase =						EfficientFormerForImageClassificationWithTeacher.from_pretrained(
								    "snap-research/efficientformer-l1-300"   ).to(a_   )

								_UpperCAmelCase =						self.default_image_processor
								_UpperCAmelCase =						prepare_img()
								_UpperCAmelCase =						image_processor(images=a_ ,						return_tensors="pt"   ).to(a_   )

								# forward pass
								with torch.no_grad():
									_UpperCAmelCase =						model(**a_   )

								# verify the logits
								_UpperCAmelCase =						(1, 1000)
								self.assertEqual(outputs.logits.shape ,						a_   )

								_UpperCAmelCase =						torch.tensor([-0.1312, 0.4353, -1.0499]   ).to(a_   )
								self.assertTrue(torch.allclose(outputs.logits[0][:3] ,						a_ ,						atol=1e-4   )   )




