

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


UpperCAmelCase      :						Union[str, Any]    =		logging.getLogger(__name__)






def   __lowerCamelCase	(       lowerCamelCase__		:	List[Any]			):





			'''simple docstring'''




			lowerCamelCase								=     p * torch.log(lowerCamelCase__			)
			lowerCamelCase								=     0
			return -plogp.sum(dim=-1			)






def   __lowerCamelCase	(       lowerCamelCase__		:	Dict			):





			'''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	(       lowerCamelCase__		:	Union[str, Any]     ,       lowerCamelCase__		:	Dict     ,       lowerCamelCase__		:	Any     ,       lowerCamelCase__		:	Optional[int]=True     ,       lowerCamelCase__		:	Dict=True     ,       lowerCamelCase__		:	List[str]=None     ,       lowerCamelCase__		:	Optional[int]=False			):





			'''simple docstring'''




			lowerCamelCase								=     model.config.num_hidden_layers, model.config.num_attention_heads
			lowerCamelCase								=     torch.zeros(lowerCamelCase__     ,       lowerCamelCase__			).to(args.device			)
			lowerCamelCase								=     torch.zeros(lowerCamelCase__     ,       lowerCamelCase__			).to(args.device			)

			if head_mask is None:
						lowerCamelCase								=     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:
						lowerCamelCase								=     None

			lowerCamelCase								=     None
			lowerCamelCase								=     None
			lowerCamelCase								=     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():
									lowerCamelCase								=     v.to(args.device			)

						# Do a forward pass (not with torch.no_grad() since we need gradients for importance score - see below)
						lowerCamelCase								=     model(**lowerCamelCase__     ,       head_mask=lowerCamelCase__			)
						lowerCamelCase								=     (
						    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__			):
												lowerCamelCase								=     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:
									lowerCamelCase								=     logits.detach().cpu().numpy()
									lowerCamelCase								=     inputs["labels"].detach().cpu().numpy()
						else:
									lowerCamelCase								=     np.append(lowerCamelCase__     ,       logits.detach().cpu().numpy()     ,       axis=0			)
									lowerCamelCase								=     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:
						lowerCamelCase								=     2
						lowerCamelCase								=     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:
						lowerCamelCase								=     (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"""			)
			lowerCamelCase								=     torch.zeros(head_importance.numel()     ,       dtype=torch.long     ,       device=args.device			)
			lowerCamelCase								=     torch.arange(
			    head_importance.numel()     ,       device=args.device			)
			lowerCamelCase								=     head_ranks.view_as(lowerCamelCase__			)
			print_ad_tensor(lowerCamelCase__			)

			return attn_entropy, head_importance, preds, labels






def   __lowerCamelCase	(       lowerCamelCase__		:	Optional[Any]     ,       lowerCamelCase__		:	str     ,       lowerCamelCase__		:	int			):





			'''simple docstring'''




			lowerCamelCase								=     compute_heads_importance(lowerCamelCase__     ,       lowerCamelCase__     ,       lowerCamelCase__     ,       compute_entropy=lowerCamelCase__			)
			lowerCamelCase								=     np.argmax(lowerCamelCase__     ,       axis=1			) if args.output_mode == "classification" else np.squeeze(lowerCamelCase__			)
			lowerCamelCase								=     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			)

			lowerCamelCase								=     torch.ones_like(lowerCamelCase__			)
			lowerCamelCase								=     max(1     ,       int(new_head_mask.numel() * args.masking_amount			)			)

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

						if len(lowerCamelCase__			) <= num_to_mask:
									break

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

						# Compute metric and head importance again
						lowerCamelCase								=     compute_heads_importance(
						    lowerCamelCase__     ,       lowerCamelCase__     ,       lowerCamelCase__     ,       compute_entropy=lowerCamelCase__     ,       head_mask=lowerCamelCase__			)
						lowerCamelCase								=     np.argmax(lowerCamelCase__     ,       axis=1			) if args.output_mode == "classification" else np.squeeze(lowerCamelCase__			)
						lowerCamelCase								=     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	(       lowerCamelCase__		:	Any     ,       lowerCamelCase__		:	List[str]     ,       lowerCamelCase__		:	int     ,       lowerCamelCase__		:	Any			):





			'''simple docstring'''




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

			lowerCamelCase								=     sum(p.numel() for p in model.parameters()			)
			lowerCamelCase								=     {
			    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__			)
			lowerCamelCase								=     sum(p.numel() for p in model.parameters()			)

			lowerCamelCase								=     datetime.now()
			lowerCamelCase								=     compute_heads_importance(
			    lowerCamelCase__     ,       lowerCamelCase__     ,       lowerCamelCase__     ,       compute_entropy=lowerCamelCase__     ,       compute_importance=lowerCamelCase__     ,       head_mask=lowerCamelCase__     ,       actually_pruned=lowerCamelCase__     ,       )
			lowerCamelCase								=     np.argmax(lowerCamelCase__     ,       axis=1			) if args.output_mode == "classification" else np.squeeze(lowerCamelCase__			)
			lowerCamelCase								=     glue_compute_metrics(args.task_name     ,       lowerCamelCase__     ,       lowerCamelCase__			)[args.metric_name]
			lowerCamelCase								=     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'''




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

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

			lowerCamelCase								=     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     ,       )
			lowerCamelCase								=     AutoTokenizer.from_pretrained(
			    args.tokenizer_name if args.tokenizer_name else args.model_name_or_path     ,       cache_dir=args.cache_dir     ,       )
			lowerCamelCase								=     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:
						lowerCamelCase								=     nn.parallel.DistributedDataParallel(
						    lowerCamelCase__     ,       device_ids=[args.local_rank]     ,       output_device=args.local_rank     ,       find_unused_parameters=lowerCamelCase__			)
			elif args.n_gpu > 1:
						lowerCamelCase								=     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
			lowerCamelCase								=     GlueDataset(lowerCamelCase__     ,       tokenizer=lowerCamelCase__     ,       mode="""dev"""			)
			if args.data_subset > 0:
						lowerCamelCase								=     Subset(lowerCamelCase__     ,       list(range(min(args.data_subset     ,       len(lowerCamelCase__			)			)			)			)			)
			lowerCamelCase								=     SequentialSampler(lowerCamelCase__			) if args.local_rank == -1 else DistributedSampler(lowerCamelCase__			)
			lowerCamelCase								=     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:
						lowerCamelCase								=     mask_heads(lowerCamelCase__     ,       lowerCamelCase__     ,       lowerCamelCase__			)
						prune_heads(lowerCamelCase__     ,       lowerCamelCase__     ,       lowerCamelCase__     ,       lowerCamelCase__			)


if __name__ == "__main__":
		main()





import inspect
import unittest

from transformers import EfficientNetConfig
from transformers.testing_utils import is_pipeline_test, 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 EfficientNetForImageClassification, EfficientNetModel
		from transformers.models.efficientnet.modeling_efficientnet import EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
		from PIL import Image

		from transformers import AutoImageProcessor







class 					__lowercase					:



		"""simple docstring"""

		def __init__(   self		,			A		,			A=13		,			A=32		,			A=3		,			A=[3, 3, 5]		,			A=[32, 16, 24]		,			A=[16, 24, 40]		,			A=[1, 1, 2]		,			A=[1, 1, 2]		,			A=[1, 6, 6]		,			A=True		,			A=True		,			A=37		,			A="gelu"		,			A=10		,			)     ->   Dict:







					'''simple docstring'''







					lowerCamelCase								=     parent
					lowerCamelCase								=     batch_size
					lowerCamelCase								=     image_size
					lowerCamelCase								=     num_channels
					lowerCamelCase								=     kernel_sizes
					lowerCamelCase								=     in_channels
					lowerCamelCase								=     out_channels
					lowerCamelCase								=     strides
					lowerCamelCase								=     num_block_repeats
					lowerCamelCase								=     expand_ratios
					lowerCamelCase								=     is_training
					lowerCamelCase								=     hidden_act
					lowerCamelCase								=     num_labels
					lowerCamelCase								=     use_labels







		def 				__A      (   self  )     ->   Optional[Any]:







					'''simple docstring'''







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

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

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







		def 				__A      (   self  )     ->   Optional[int]:







					'''simple docstring'''







					return EfficientNetConfig(
					    num_channels=self.num_channels		,			kernel_sizes=self.kernel_sizes		,			in_channels=self.in_channels		,			out_channels=self.out_channels		,			strides=self.strides		,			num_block_repeats=self.num_block_repeats		,			expand_ratios=self.expand_ratios		,			hidden_act=self.hidden_act		,			num_labels=self.num_labels		,			)







		def 				__A      (   self		,			A		,			A		,			A  )     ->   List[Any]:







					'''simple docstring'''







					lowerCamelCase								=     EfficientNetModel(config=A  )
					model.to(A  )
					model.eval()
					lowerCamelCase								=     model(A  )
					# expected last hidden states: B, C, H // 4, W // 4
					self.parent.assertEqual(
					    result.last_hidden_state.shape		,			(self.batch_size, config.hidden_dim, self.image_size // 4, self.image_size // 4)		,			)







		def 				__A      (   self		,			A		,			A		,			A  )     ->   Optional[int]:







					'''simple docstring'''







					lowerCamelCase								=     EfficientNetForImageClassification(A  )
					model.to(A  )
					model.eval()
					lowerCamelCase								=     model(A		,			labels=A  )
					self.parent.assertEqual(result.logits.shape		,			(self.batch_size, self.num_labels)  )







		def 				__A      (   self  )     ->   Any:







					'''simple docstring'''







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







@require_torch
class 					__lowercase					(       a_ ,       a_ ,       unittest.TestCase     ):



		"""simple docstring"""

		UpperCamelCase    :				str 					=		(EfficientNetModel, EfficientNetForImageClassification) if is_torch_available() else ()
		UpperCamelCase    :				List[Any] 					=		(
		    {"feature-extraction": EfficientNetModel, "image-classification": EfficientNetForImageClassification}
		    if is_torch_available()
		    else {}
		)

		UpperCamelCase    :				Any 					=		False
		UpperCamelCase    :				Dict 					=		False
		UpperCamelCase    :				Optional[int] 					=		False
		UpperCamelCase    :				str 					=		False
		UpperCamelCase    :				Optional[Any] 					=		False







		def 				__A      (   self  )     ->   str:







					'''simple docstring'''







					lowerCamelCase								=     EfficientNetModelTester(self  )
					lowerCamelCase								=     ConfigTester(
					    self		,			config_class=A		,			has_text_modality=A		,			hidden_size=37  )







		def 				__A      (   self  )     ->   Optional[Any]:







					'''simple docstring'''







					self.create_and_test_config_common_properties()
					self.config_tester.create_and_test_config_to_json_string()
					self.config_tester.create_and_test_config_to_json_file()
					self.config_tester.create_and_test_config_from_and_save_pretrained()
					self.config_tester.create_and_test_config_with_num_labels()
					self.config_tester.check_config_can_be_init_without_params()
					self.config_tester.check_config_arguments_init()







		def 				__A      (   self  )     ->   Union[str, Any]:







					'''simple docstring'''







					return







		@unittest.skip(reason="""EfficientNet does not use inputs_embeds"""  )
		def 				__A      (   self  )     ->   Optional[Any]:







					'''simple docstring'''







					pass







		@unittest.skip(reason="""EfficientNet does not support input and output embeddings"""  )
		def 				__A      (   self  )     ->   Any:







					'''simple docstring'''







					pass







		@unittest.skip(reason="""EfficientNet does not use feedforward chunking"""  )
		def 				__A      (   self  )     ->   List[Any]:







					'''simple docstring'''







					pass







		def 				__A      (   self  )     ->   Optional[int]:







					'''simple docstring'''







					lowerCamelCase		,		lowerCamelCase								=     self.model_tester.prepare_config_and_inputs_for_common()

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

								lowerCamelCase								=     ["""pixel_values"""]
								self.assertListEqual(arg_names[:1]		,			A  )







		def 				__A      (   self  )     ->   Dict:







					'''simple docstring'''







					lowerCamelCase								=     self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_model(*A  )







		def 				__A      (   self  )     ->   Tuple:







					'''simple docstring'''







					def check_hidden_states_output(A		,			A		,			A  ):
								lowerCamelCase								=     model_class(A  )
								model.to(A  )
								model.eval()

								with torch.no_grad():
											lowerCamelCase								=     model(**self._prepare_for_class(A		,			A  )  )

								lowerCamelCase								=     outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states
								lowerCamelCase								=     sum(config.num_block_repeats  ) * 4
								self.assertEqual(len(A  )		,			A  )

								# EfficientNet's feature maps are of shape (batch_size, num_channels, height, width)
								self.assertListEqual(
								    list(hidden_states[0].shape[-2:]  )		,			[self.model_tester.image_size // 2, self.model_tester.image_size // 2]		,			)

					lowerCamelCase		,		lowerCamelCase								=     self.model_tester.prepare_config_and_inputs_for_common()

					for model_class in self.all_model_classes:
								lowerCamelCase								=     True
								check_hidden_states_output(A		,			A		,			A  )

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

								check_hidden_states_output(A		,			A		,			A  )







		def 				__A      (   self  )     ->   int:







					'''simple docstring'''







					lowerCamelCase								=     self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_for_image_classification(*A  )







		@unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests."""  )
		def 				__A      (   self  )     ->   Union[str, Any]:







					'''simple docstring'''







					pass







		@slow
		def 				__A      (   self  )     ->   Any:







					'''simple docstring'''







					for model_name in EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
								lowerCamelCase								=     EfficientNetModel.from_pretrained(A  )
								self.assertIsNotNone(A  )







		@is_pipeline_test
		@require_vision
		@slow
		def 				__A      (   self  )     ->   Optional[Any]:







					'''simple docstring'''







					super().test_pipeline_image_classification()






def   __lowerCamelCase	(       ):





			'''simple docstring'''




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







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



		"""simple docstring"""

		@cached_property
		def 				__A      (   self  )     ->   Dict:







					'''simple docstring'''







					return AutoImageProcessor.from_pretrained("""google/efficientnet-b7"""  ) if is_vision_available() else None







		@slow
		def 				__A      (   self  )     ->   List[str]:







					'''simple docstring'''







					lowerCamelCase								=     EfficientNetForImageClassification.from_pretrained("""google/efficientnet-b7"""  ).to(A  )

					lowerCamelCase								=     self.default_image_processor
					lowerCamelCase								=     prepare_img()
					lowerCamelCase								=     image_processor(images=A		,			return_tensors="""pt"""  ).to(A  )

					# forward pass
					with torch.no_grad():
								lowerCamelCase								=     model(**A  )

					# verify the logits
					lowerCamelCase								=     torch.Size((1, 10_00)  )
					self.assertEqual(outputs.logits.shape		,			A  )

					lowerCamelCase								=     torch.tensor([0.0001, 0.0002, 0.0002]  ).to(A  )
					self.assertTrue(torch.allclose(outputs.logits[0, :3]		,			A		,			atol=1e-4  )  )

