


import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin


if is_torch_available():
		import torch

if is_vision_available():
		from PIL import Image

		from transformers import TvltImageProcessor






def 	lowerCamelCase_       (			_a      ,  _a=10      ,  _a=10      ,  _a=False      ,  _a=False			):




		"""simple docstring"""






		lowerCAmelCase__  :     Tuple       	=   []
		for i in range(image_processor_tester.num_frames			):
				video.append(np.random.randint(255      ,  size=(image_processor_tester.num_channels, width, height)      ,  dtype=np.uinta			)			)

		if not numpify and not torchify:
				# PIL expects the channel dimension as last dimension
				lowerCAmelCase__  :     int       	=   [Image.fromarray(np.moveaxis(_a      ,  0      ,  -1			)			) for frame in video]

		if torchify:
				lowerCAmelCase__  :     Optional[Any]       	=   [torch.from_numpy(_a			) for frame in video]

		return video






def 	lowerCamelCase_       (			_a      ,  _a=False      ,  _a=False      ,  _a=False			):




		"""simple docstring"""






		assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

		lowerCAmelCase__  :     Optional[Any]       	=   []
		for i in range(image_processor_tester.batch_size			):
				if equal_resolution:
						lowerCAmelCase__  :     List[str]       	=   image_processor_tester.max_resolution
				else:
						lowerCAmelCase__	,      lowerCAmelCase__  :     Optional[int]       	=   np.random.choice(
						    np.arange(image_processor_tester.min_resolution      ,  image_processor_tester.max_resolution			)      ,  2			)
						lowerCAmelCase__  :     str       	=   prepare_video(
						    image_processor_tester=_a      ,  width=_a      ,  height=_a      ,  numpify=_a      ,  torchify=_a      ,  )
				video_inputs.append(_a			)

		return video_inputs





class    _a				(							unittest.TestCase):




	def __init__(   self		:						List[str]						,   _SCREAMING_SNAKE_CASE		:						Any						,   _SCREAMING_SNAKE_CASE		:						int=7						,   _SCREAMING_SNAKE_CASE		:						Optional[int]=3						,   _SCREAMING_SNAKE_CASE		:						Optional[int]=4						,   _SCREAMING_SNAKE_CASE		:						Tuple=18						,   _SCREAMING_SNAKE_CASE		:						Union[str, Any]=30						,   _SCREAMING_SNAKE_CASE		:						Optional[int]=400						,   _SCREAMING_SNAKE_CASE		:						Dict=True						,   _SCREAMING_SNAKE_CASE		:						Union[str, Any]=None						,   _SCREAMING_SNAKE_CASE		:						Union[str, Any]=True						,   _SCREAMING_SNAKE_CASE		:						List[str]=[0.5, 0.5, 0.5]						,   _SCREAMING_SNAKE_CASE		:						Optional[Any]=[0.5, 0.5, 0.5]						,   _SCREAMING_SNAKE_CASE		:						Optional[int]=True						,   _SCREAMING_SNAKE_CASE		:						List[str]=None						,   )->			List[str]:
			lowerCAmelCase__  :     List[Any]       	=   size if size is not None else {'''shortest_edge''': 18}
			lowerCAmelCase__  :     str       	=   crop_size if crop_size is not None else {'''height''': 18, '''width''': 18}

			lowerCAmelCase__  :     Dict       	=   parent
			lowerCAmelCase__  :     Dict       	=   batch_size
			lowerCAmelCase__  :     Optional[int]       	=   num_channels
			lowerCAmelCase__  :     Tuple       	=   num_frames
			lowerCAmelCase__  :     Optional[Any]       	=   image_size
			lowerCAmelCase__  :     List[Any]       	=   min_resolution
			lowerCAmelCase__  :     Union[str, Any]       	=   max_resolution
			lowerCAmelCase__  :     List[Any]       	=   do_resize
			lowerCAmelCase__  :     Union[str, Any]       	=   size
			lowerCAmelCase__  :     Dict       	=   do_normalize
			lowerCAmelCase__  :     int       	=   image_mean
			lowerCAmelCase__  :     Union[str, Any]       	=   image_std
			lowerCAmelCase__  :     Optional[Any]       	=   do_center_crop
			lowerCAmelCase__  :     int       	=   crop_size




	def 				UpperCAmelCase__(   self		:						List[Any]						)->			str:
			return {
			    "image_mean": self.image_mean,
			    "image_std": self.image_std,
			    "do_normalize": self.do_normalize,
			    "do_resize": self.do_resize,
			    "size": self.size,
			    "do_center_crop": self.do_center_crop,
			    "crop_size": self.crop_size,
			}





@require_torch
@require_vision
class    _a				(							_lowercase	,		unittest.TestCase):
	_a    :    Any        =				TvltImageProcessor if is_vision_available() else None




	def 				UpperCAmelCase__(   self		:						int						)->			int:
			lowerCAmelCase__  :     str       	=   TvltImageProcessorTester(self						)




	@property
	def 				UpperCAmelCase__(   self		:						Union[str, Any]						)->			Union[str, Any]:
			return self.image_processor_tester.prepare_image_processor_dict()




	def 				UpperCAmelCase__(   self		:						Dict						)->			Union[str, Any]:
			lowerCAmelCase__  :     List[str]       	=   self.image_processing_class(**self.image_processor_dict						)
			self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE						,   '''image_mean'''						)						)
			self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE						,   '''image_std'''						)						)
			self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE						,   '''do_normalize'''						)						)
			self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE						,   '''do_resize'''						)						)
			self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE						,   '''do_center_crop'''						)						)
			self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE						,   '''size'''						)						)




	def 				UpperCAmelCase__(   self		:						Tuple						)->			List[Any]:
			# Initialize image_processor
			lowerCAmelCase__  :     Dict       	=   self.image_processing_class(**self.image_processor_dict						)
			# create random PIL videos
			lowerCAmelCase__  :     str       	=   prepare_video_inputs(self.image_processor_tester						,   equal_resolution=_SCREAMING_SNAKE_CASE						)
			for video in video_inputs:
					self.assertIsInstance(_SCREAMING_SNAKE_CASE						,   _SCREAMING_SNAKE_CASE						)
					self.assertIsInstance(video[0]						,   Image.Image						)

			# Test not batched input
			lowerCAmelCase__  :     Any       	=   image_processor(video_inputs[0]						,   return_tensors='''pt'''						).pixel_values
			self.assertEqual(
			    encoded_videos.shape						,   (
			        1,
			        self.image_processor_tester.num_frames,
			        self.image_processor_tester.num_channels,
			        self.image_processor_tester.crop_size['''height'''],
			        self.image_processor_tester.crop_size['''width'''],
			    )						,   )

			# Test batched
			lowerCAmelCase__  :     Optional[int]       	=   image_processor(_SCREAMING_SNAKE_CASE						,   return_tensors='''pt'''						).pixel_values
			self.assertEqual(
			    encoded_videos.shape						,   (
			        self.image_processor_tester.batch_size,
			        self.image_processor_tester.num_frames,
			        self.image_processor_tester.num_channels,
			        self.image_processor_tester.crop_size['''height'''],
			        self.image_processor_tester.crop_size['''width'''],
			    )						,   )




	def 				UpperCAmelCase__(   self		:						int						)->			Optional[int]:
			# Initialize image_processor
			lowerCAmelCase__  :     Tuple       	=   self.image_processing_class(**self.image_processor_dict						)
			# create random numpy tensors
			lowerCAmelCase__  :     List[str]       	=   prepare_video_inputs(self.image_processor_tester						,   equal_resolution=_SCREAMING_SNAKE_CASE						,   numpify=_SCREAMING_SNAKE_CASE						)
			for video in video_inputs:
					self.assertIsInstance(_SCREAMING_SNAKE_CASE						,   _SCREAMING_SNAKE_CASE						)
					self.assertIsInstance(video[0]						,   np.ndarray						)

			# Test not batched input
			lowerCAmelCase__  :     Optional[Any]       	=   image_processor(video_inputs[0]						,   return_tensors='''pt'''						).pixel_values
			self.assertEqual(
			    encoded_videos.shape						,   (
			        1,
			        self.image_processor_tester.num_frames,
			        self.image_processor_tester.num_channels,
			        self.image_processor_tester.crop_size['''height'''],
			        self.image_processor_tester.crop_size['''width'''],
			    )						,   )

			# Test batched
			lowerCAmelCase__  :     Tuple       	=   image_processor(_SCREAMING_SNAKE_CASE						,   return_tensors='''pt'''						).pixel_values
			self.assertEqual(
			    encoded_videos.shape						,   (
			        self.image_processor_tester.batch_size,
			        self.image_processor_tester.num_frames,
			        self.image_processor_tester.num_channels,
			        self.image_processor_tester.crop_size['''height'''],
			        self.image_processor_tester.crop_size['''width'''],
			    )						,   )




	def 				UpperCAmelCase__(   self		:						Any						)->			List[str]:
			# Initialize image_processor
			lowerCAmelCase__  :     Union[str, Any]       	=   self.image_processing_class(**self.image_processor_dict						)
			# create random PyTorch tensors
			lowerCAmelCase__  :     List[Any]       	=   prepare_video_inputs(self.image_processor_tester						,   equal_resolution=_SCREAMING_SNAKE_CASE						,   torchify=_SCREAMING_SNAKE_CASE						)
			for video in video_inputs:
					self.assertIsInstance(_SCREAMING_SNAKE_CASE						,   _SCREAMING_SNAKE_CASE						)
					self.assertIsInstance(video[0]						,   torch.Tensor						)

			# Test not batched input
			lowerCAmelCase__  :     List[str]       	=   image_processor(video_inputs[0]						,   return_tensors='''pt'''						).pixel_values
			self.assertEqual(
			    encoded_videos.shape						,   (
			        1,
			        self.image_processor_tester.num_frames,
			        self.image_processor_tester.num_channels,
			        self.image_processor_tester.crop_size['''height'''],
			        self.image_processor_tester.crop_size['''width'''],
			    )						,   )

			# Test batched
			lowerCAmelCase__  :     Optional[int]       	=   image_processor(_SCREAMING_SNAKE_CASE						,   return_tensors='''pt'''						).pixel_values
			self.assertEqual(
			    encoded_videos.shape						,   (
			        self.image_processor_tester.batch_size,
			        self.image_processor_tester.num_frames,
			        self.image_processor_tester.num_channels,
			        self.image_processor_tester.crop_size['''height'''],
			        self.image_processor_tester.crop_size['''width'''],
			    )						,   )








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


lowerCamelCase		=						logging.getLogger(__name__)






def 	lowerCamelCase_       (			_a			):




		"""simple docstring"""






		lowerCAmelCase__  :     str       	=   p * torch.log(_a			)
		lowerCAmelCase__  :     List[str]       	=   0
		return -plogp.sum(dim=-1			)






def 	lowerCamelCase_       (			_a			):




		"""simple docstring"""






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




		"""simple docstring"""






		lowerCAmelCase__	,      lowerCAmelCase__  :     int       	=   model.config.num_hidden_layers, model.config.num_attention_heads
		lowerCAmelCase__  :     Optional[int]       	=   torch.zeros(_a      ,  _a			).to(args.device			)
		lowerCAmelCase__  :     Optional[int]       	=   torch.zeros(_a      ,  _a			).to(args.device			)

		if head_mask is None:
				lowerCAmelCase__  :     Union[str, Any]       	=   torch.ones(_a      ,  _a			).to(args.device			)

		head_mask.requires_grad_(requires_grad=_a			)
		# If actually pruned attention multi-head, set head mask to None to avoid shape mismatch
		if actually_pruned:
				lowerCAmelCase__  :     Optional[int]       	=   None

		lowerCAmelCase__  :     List[str]       	=   None
		lowerCAmelCase__  :     Any       	=   None
		lowerCAmelCase__  :     Optional[Any]       	=   0.0

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

				# Do a forward pass (not with torch.no_grad() since we need gradients for importance score - see below)
				lowerCAmelCase__  :     Optional[int]       	=   model(**_a      ,  head_mask=_a			)
				lowerCAmelCase__	,      lowerCAmelCase__	,      lowerCAmelCase__  :     Optional[int]       	=   (
				    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(_a			):
								lowerCAmelCase__  :     List[str]       	=   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__  :     str       	=   logits.detach().cpu().numpy()
						lowerCAmelCase__  :     Any       	=   inputs['''labels'''].detach().cpu().numpy()
				else:
						lowerCAmelCase__  :     Tuple       	=   np.append(_a      ,  logits.detach().cpu().numpy()      ,  axis=0			)
						lowerCAmelCase__  :     Any       	=   np.append(_a      ,  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__  :     str       	=   2
				lowerCAmelCase__  :     List[str]       	=   torch.pow(torch.pow(_a      ,  _a			).sum(-1			)      ,  1 / exponent			)
				head_importance /= norm_by_layer.unsqueeze(-1			) + 1e-2_0

		if not args.dont_normalize_global_importance:
				lowerCAmelCase__  :     Union[str, Any]       	=   (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(_a			)
		logger.info('''Head importance scores'''			)
		print_ad_tensor(_a			)
		logger.info('''Head ranked by importance scores'''			)
		lowerCAmelCase__  :     Any       	=   torch.zeros(head_importance.numel()      ,  dtype=torch.long      ,  device=args.device			)
		lowerCAmelCase__  :     Union[str, Any]       	=   torch.arange(
		    head_importance.numel()      ,  device=args.device			)
		lowerCAmelCase__  :     Tuple       	=   head_ranks.view_as(_a			)
		print_ad_tensor(_a			)

		return attn_entropy, head_importance, preds, labels






def 	lowerCamelCase_       (			_a      ,  _a      ,  _a			):




		"""simple docstring"""






		lowerCAmelCase__	,      lowerCAmelCase__	,      lowerCAmelCase__	,      lowerCAmelCase__  :     Optional[int]       	=   compute_heads_importance(_a      ,  _a      ,  _a      ,  compute_entropy=_a			)
		lowerCAmelCase__  :     Dict       	=   np.argmax(_a      ,  axis=1			) if args.output_mode == '''classification''' else np.squeeze(_a			)
		lowerCAmelCase__  :     int       	=   glue_compute_metrics(args.task_name      ,  _a      ,  _a			)[args.metric_name]
		logger.info('''Pruning: original score: %f, threshold: %f'''      ,  _a      ,  original_score * args.masking_threshold			)

		lowerCAmelCase__  :     int       	=   torch.ones_like(_a			)
		lowerCAmelCase__  :     List[Any]       	=   max(1      ,  int(new_head_mask.numel() * args.masking_amount			)			)

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

				if len(_a			) <= num_to_mask:
						break

				# mask heads
				lowerCAmelCase__  :     List[Any]       	=   current_heads_to_mask[:num_to_mask]
				logger.info('''Heads to mask: %s'''      ,  str(current_heads_to_mask.tolist()			)			)
				lowerCAmelCase__  :     int       	=   new_head_mask.view(-1			)
				lowerCAmelCase__  :     int       	=   0.0
				lowerCAmelCase__  :     int       	=   new_head_mask.view_as(_a			)
				lowerCAmelCase__  :     Dict       	=   new_head_mask.clone().detach()
				print_ad_tensor(_a			)

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

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

		return head_mask






def 	lowerCamelCase_       (			_a      ,  _a      ,  _a      ,  _a			):




		"""simple docstring"""






		lowerCAmelCase__  :     int       	=   datetime.now()
		lowerCAmelCase__	,      lowerCAmelCase__	,      lowerCAmelCase__	,      lowerCAmelCase__  :     Optional[int]       	=   compute_heads_importance(
		    _a      ,  _a      ,  _a      ,  compute_entropy=_a      ,  compute_importance=_a      ,  head_mask=_a			)
		lowerCAmelCase__  :     str       	=   np.argmax(_a      ,  axis=1			) if args.output_mode == '''classification''' else np.squeeze(_a			)
		lowerCAmelCase__  :     Union[str, Any]       	=   glue_compute_metrics(args.task_name      ,  _a      ,  _a			)[args.metric_name]
		lowerCAmelCase__  :     Tuple       	=   datetime.now() - before_time

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

		assert sum(len(_a			) for h in heads_to_prune.values()			) == (1 - head_mask.long()).sum().item()
		model.prune_heads(_a			)
		lowerCAmelCase__  :     Tuple       	=   sum(p.numel() for p in model.parameters()			)

		lowerCAmelCase__  :     Tuple       	=   datetime.now()
		lowerCAmelCase__	,      lowerCAmelCase__	,      lowerCAmelCase__	,      lowerCAmelCase__  :     List[Any]       	=   compute_heads_importance(
		    _a      ,  _a      ,  _a      ,  compute_entropy=_a      ,  compute_importance=_a      ,  head_mask=_a      ,  actually_pruned=_a      ,  )
		lowerCAmelCase__  :     Optional[int]       	=   np.argmax(_a      ,  axis=1			) if args.output_mode == '''classification''' else np.squeeze(_a			)
		lowerCAmelCase__  :     Any       	=   glue_compute_metrics(args.task_name      ,  _a      ,  _a			)[args.metric_name]
		lowerCAmelCase__  :     Dict       	=   datetime.now() - before_time

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






def 	lowerCamelCase_       (			):




		"""simple docstring"""






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

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

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

		parser.add_argument('''--seed'''      ,  type=_a      ,  default=42			)
		parser.add_argument('''--local_rank'''      ,  type=_a      ,  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=_a      ,  default=''''''      ,  help='''Can be used for distant debugging.'''			)
		parser.add_argument('''--server_port'''      ,  type=_a      ,  default=''''''      ,  help='''Can be used for distant debugging.'''			)
		lowerCAmelCase__  :     Optional[int]       	=   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=_a			)
				ptvsd.wait_for_attach()

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

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

		lowerCAmelCase__  :     List[str]       	=   AutoConfig.from_pretrained(
		    args.config_name if args.config_name else args.model_name_or_path      ,  num_labels=_a      ,  finetuning_task=args.task_name      ,  output_attentions=_a      ,  cache_dir=args.cache_dir      ,  )
		lowerCAmelCase__  :     Union[str, Any]       	=   AutoTokenizer.from_pretrained(
		    args.tokenizer_name if args.tokenizer_name else args.model_name_or_path      ,  cache_dir=args.cache_dir      ,  )
		lowerCAmelCase__  :     str       	=   AutoModelForSequenceClassification.from_pretrained(
		    args.model_name_or_path      ,  from_tf=bool('''.ckpt''' in args.model_name_or_path			)      ,  config=_a      ,  cache_dir=args.cache_dir      ,  )

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

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

		# Prepare dataset for the GLUE task
		lowerCAmelCase__  :     Dict       	=   GlueDataset(_a      ,  tokenizer=_a      ,  mode='''dev'''			)
		if args.data_subset > 0:
				lowerCAmelCase__  :     Union[str, Any]       	=   Subset(_a      ,  list(range(min(args.data_subset      ,  len(_a			)			)			)			)			)
		lowerCAmelCase__  :     Any       	=   SequentialSampler(_a			) if args.local_rank == -1 else DistributedSampler(_a			)
		lowerCAmelCase__  :     int       	=   DataLoader(
		    _a      ,  sampler=_a      ,  batch_size=args.batch_size      ,  collate_fn=_a			)

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

		# 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__  :     List[str]       	=   mask_heads(_a      ,  _a      ,  _a			)
				prune_heads(_a      ,  _a      ,  _a      ,  _a			)


if __name__ == "__main__":
		main()




