


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   snake_case_	(    snake_case	)    ->							Optional[int]:
       lowercase__:  Any         =  p * torch.log(UpperCAmelCase__	)
       lowercase__:  Optional[Any]         =  0
       return -plogp.sum(dim=-1	)




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




def   snake_case_	(    snake_case     ,				snake_case     ,				snake_case     ,				snake_case=True     ,				snake_case=True     ,				snake_case=None     ,				snake_case=False	)    ->							Optional[int]:
       lowercase__     ,		lowercase__:  int         =  model.config.num_hidden_layers, model.config.num_attention_heads
       lowercase__:  Dict         =  torch.zeros(UpperCAmelCase__     ,				UpperCAmelCase__	).to(args.device	)
       lowercase__:  Dict         =  torch.zeros(UpperCAmelCase__     ,				UpperCAmelCase__	).to(args.device	)

       if head_mask is None:
              lowercase__:  List[str]         =  torch.ones(UpperCAmelCase__     ,				UpperCAmelCase__	).to(args.device	)

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

       lowercase__:  Tuple         =  None
       lowercase__:  Any         =  None
       lowercase__:  Any         =  0.0

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

              # Do a forward pass (not with torch.no_grad() since we need gradients for importance score - see below)
              lowercase__:  Tuple         =  model(**UpperCAmelCase__     ,				head_mask=UpperCAmelCase__	)
              lowercase__     ,		lowercase__     ,		lowercase__:  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(UpperCAmelCase__	):
                            lowercase__:  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:
                     lowercase__:  Optional[Any]         =  logits.detach().cpu().numpy()
                     lowercase__:  int         =  inputs['labels'].detach().cpu().numpy()
              else:
                     lowercase__:  Any         =  np.append(UpperCAmelCase__     ,				logits.detach().cpu().numpy()     ,				axis=0	)
                     lowercase__:  Any         =  np.append(UpperCAmelCase__     ,				inputs['labels'].detach().cpu().numpy()     ,				axis=0	)

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

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

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

       return attn_entropy, head_importance, preds, labels




def   snake_case_	(    snake_case     ,				snake_case     ,				snake_case	)    ->							List[str]:
       lowercase__     ,		lowercase__     ,		lowercase__     ,		lowercase__:  List[Any]         =  compute_heads_importance(UpperCAmelCase__     ,				UpperCAmelCase__     ,				UpperCAmelCase__     ,				compute_entropy=UpperCAmelCase__	)
       lowercase__:  Any         =  np.argmax(UpperCAmelCase__     ,				axis=1	) if args.output_mode == 'classification' else np.squeeze(UpperCAmelCase__	)
       lowercase__:  Tuple         =  glue_compute_metrics(args.task_name     ,				UpperCAmelCase__     ,				UpperCAmelCase__	)[args.metric_name]
       logger.info('Pruning: original score: %f, threshold: %f'     ,				UpperCAmelCase__     ,				original_score * args.masking_threshold	)

       lowercase__:  str         =  torch.ones_like(UpperCAmelCase__	)
       lowercase__:  Dict         =  max(1     ,				int(new_head_mask.numel() * args.masking_amount	)	)

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

              if len(UpperCAmelCase__	) <= num_to_mask:
                     break

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

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

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

       return head_mask




def   snake_case_	(    snake_case     ,				snake_case     ,				snake_case     ,				snake_case	)    ->							Any:
       lowercase__:  str         =  datetime.now()
       lowercase__     ,		lowercase__     ,		lowercase__     ,		lowercase__:  Union[str, Any]         =  compute_heads_importance(
           UpperCAmelCase__     ,				UpperCAmelCase__     ,				UpperCAmelCase__     ,				compute_entropy=UpperCAmelCase__     ,				compute_importance=UpperCAmelCase__     ,				head_mask=UpperCAmelCase__	)
       lowercase__:  Union[str, Any]         =  np.argmax(UpperCAmelCase__     ,				axis=1	) if args.output_mode == 'classification' else np.squeeze(UpperCAmelCase__	)
       lowercase__:  Optional[Any]         =  glue_compute_metrics(args.task_name     ,				UpperCAmelCase__     ,				UpperCAmelCase__	)[args.metric_name]
       lowercase__:  Any         =  datetime.now() - before_time

       lowercase__:  List[str]         =  sum(p.numel() for p in model.parameters()	)
       lowercase__:  Optional[Any]         =  {
           layer: (1 - head_mask[layer].long()).nonzero().squeeze().tolist() for layer in range(len(UpperCAmelCase__	)	)
       }

       assert sum(len(UpperCAmelCase__	) for h in heads_to_prune.values()	) == (1 - head_mask.long()).sum().item()
       model.prune_heads(UpperCAmelCase__	)
       lowercase__:  Union[str, Any]         =  sum(p.numel() for p in model.parameters()	)

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

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




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

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

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

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

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

       parser.add_argument('--seed'     ,				type=UpperCAmelCase__     ,				default=42	)
       parser.add_argument('--local_rank'     ,				type=UpperCAmelCase__     ,				default=-1     ,				help='local_rank for distributed training on gpus'	)
       parser.add_argument('--no_cuda'     ,				action='store_true'     ,				help='Whether not to use CUDA when available'	)
       parser.add_argument('--server_ip'     ,				type=UpperCAmelCase__     ,				default=''     ,				help='Can be used for distant debugging.'	)
       parser.add_argument('--server_port'     ,				type=UpperCAmelCase__     ,				default=''     ,				help='Can be used for distant debugging.'	)
       lowercase__:  Any         =  parser.parse_args()

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

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

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

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

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

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

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

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

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

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


if __name__ == "__main__":
 main()







from __future__ import annotations

import copy
import os
import tempfile
from importlib import import_module
from math import isnan

from transformers import is_tf_available
from transformers.models.auto import get_values
from transformers.testing_utils import _tf_gpu_memory_limit, require_tf, slow

from ..test_modeling_tf_common import ids_tensor


if is_tf_available():
     import numpy as np
     import tensorflow as tf

     from transformers import (
         TF_MODEL_FOR_CAUSAL_LM_MAPPING,
         TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING,
         TF_MODEL_FOR_MASKED_LM_MAPPING,
         TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING,
         TF_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING,
         TF_MODEL_FOR_PRETRAINING_MAPPING,
         TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING,
         TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
         TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
         TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING,
         TFSharedEmbeddings,
     )

     if _tf_gpu_memory_limit is not None:
          A_		:  List[Any]										=  tf.config.list_physical_devices('''GPU''')
          for gpu in gpus:
               # Restrict TensorFlow to only allocate x GB of memory on the GPUs
               try:
                    tf.config.set_logical_device_configuration(
                        gpu, [tf.config.LogicalDeviceConfiguration(memory_limit=_tf_gpu_memory_limit)]
                    )
                    A_		:  List[Any]										=  tf.config.list_logical_devices('''GPU''')
                    print('''Logical GPUs''', logical_gpus)
               except RuntimeError as e:
                    # Virtual devices must be set before GPUs have been initialized
                    print(e)



@require_tf
class 		_lowercase		:
   _UpperCAmelCase  						=      None
   _UpperCAmelCase  						=      ()
   _UpperCAmelCase  						=      ()
   _UpperCAmelCase  						=      True
   _UpperCAmelCase  						=      True
   _UpperCAmelCase  						=      True
   _UpperCAmelCase  						=      False

   def 		A				(   self      :							Dict				, __lowerCAmelCase      :							List[str]				, __lowerCAmelCase      :							List[Any]				, __lowerCAmelCase      :							Union[str, Any]=False				)							->					dict:


    """simple docstring"""






    a							=		copy.deepcopy(__lowerCAmelCase				)

    if model_class in get_values(__lowerCAmelCase				):
     a							=		{
         k: tf.tile(tf.expand_dims(__lowerCAmelCase				, 1				)				, (1, self.model_tester.num_choices) + (1,) * (v.ndim - 1)				)
         if isinstance(__lowerCAmelCase				, tf.Tensor				) and v.ndim > 0
         else v
         for k, v in inputs_dict.items()
     }

    if return_labels:
     if model_class in get_values(__lowerCAmelCase				):
      a							=		tf.ones(self.model_tester.batch_size				, dtype=tf.intaa				)
     elif model_class in get_values(__lowerCAmelCase				):
      a							=		tf.zeros(self.model_tester.batch_size				, dtype=tf.intaa				)
      a							=		tf.zeros(self.model_tester.batch_size				, dtype=tf.intaa				)
     elif model_class in [
         *get_values(__lowerCAmelCase				),
         *get_values(__lowerCAmelCase				),
     ]:
      a							=		tf.zeros(self.model_tester.batch_size				, dtype=tf.intaa				)
     elif model_class in get_values(__lowerCAmelCase				):
      a							=		tf.zeros(self.model_tester.batch_size				, dtype=tf.intaa				)
     elif model_class in [
         *get_values(__lowerCAmelCase				),
         *get_values(__lowerCAmelCase				),
         *get_values(__lowerCAmelCase				),
         *get_values(__lowerCAmelCase				),
         *get_values(__lowerCAmelCase				),
     ]:
      a							=		tf.zeros(
          (self.model_tester.batch_size, self.model_tester.seq_length)				, dtype=tf.intaa				)
    return inputs_dict

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


    """simple docstring"""






    a		,	a							=		self.model_tester.prepare_config_and_inputs_for_common()
    for model_class in self.all_model_classes[:2]:
     a							=		self._prepare_for_class(__lowerCAmelCase				, __lowerCAmelCase				)
     a							=		model_class(__lowerCAmelCase				)

     @tf.function
     def run_in_graph_mode():
      return model(__lowerCAmelCase				)

     a							=		run_in_graph_mode()
     self.assertIsNotNone(__lowerCAmelCase				)

   @slow
   def 		A				(   self      :							Optional[int]				)							->					Union[str, Any]:


    """simple docstring"""






    a		,	a							=		self.model_tester.prepare_config_and_inputs_for_common()
    for model_class in self.all_model_classes[:2]:
     a							=		self._prepare_for_class(__lowerCAmelCase				, __lowerCAmelCase				)
     a							=		model_class(__lowerCAmelCase				)

     @tf.function(experimental_compile=__lowerCAmelCase				)
     def run_in_graph_mode():
      return model(__lowerCAmelCase				)

     a							=		run_in_graph_mode()
     self.assertIsNotNone(__lowerCAmelCase				)

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


    """simple docstring"""






    a		,	a							=		self.model_tester.prepare_config_and_inputs_for_common()
    for model_class in self.all_model_classes[:2]:
     a							=		model_class(__lowerCAmelCase				)
     if getattr(__lowerCAmelCase				, "hf_compute_loss"				, __lowerCAmelCase				):
      # Test that model correctly compute the loss with kwargs
      a							=		self._prepare_for_class(inputs_dict.copy()				, __lowerCAmelCase				, return_labels=__lowerCAmelCase				)
      # Is there a better way to remove these decoder inputs?
      a							=		{
          key: val
          for key, val in prepared_for_class.items()
          if key not in ("head_mask", "decoder_head_mask", "cross_attn_head_mask", "decoder_input_ids")
      }

      a							=		{
          "labels",
          "label",
          "label_ids",
          "start_positions",
          "start_position",
          "end_positions",
          "end_position",
          "next_sentence_label",
      }
      a							=		possible_label_cols.intersection(set(__lowerCAmelCase				)				)
      self.assertGreater(len(__lowerCAmelCase				)				, 0				, msg="No matching label names found!"				)
      a							=		{key: val for key, val in prepared_for_class.items() if key in label_names}
      a							=		{key: val for key, val in prepared_for_class.items() if key not in label_names}
      self.assertGreater(len(__lowerCAmelCase				)				, 0				)

      # Make sure it works with XLA!
      model.compile(optimizer=tf.keras.optimizers.SGD(0.0				)				, jit_compile=__lowerCAmelCase				)
      # Make sure the model fits without crashing regardless of where we pass the labels
      a							=		model.fit(
          __lowerCAmelCase				, validation_data=__lowerCAmelCase				, steps_per_epoch=1				, validation_steps=1				, shuffle=__lowerCAmelCase				, verbose=0				, )
      a							=		history.history["loss"][0]
      self.assertTrue(not isnan(__lowerCAmelCase				)				)
      a							=		history.history["val_loss"][0]
      self.assertTrue(not isnan(__lowerCAmelCase				)				)

      # Now test it with separate labels, to make sure that path works in XLA too.
      a							=		model_class(__lowerCAmelCase				)
      model.compile(optimizer=tf.keras.optimizers.SGD(0.0				)				, jit_compile=__lowerCAmelCase				)
      a							=		model.fit(
          __lowerCAmelCase				, __lowerCAmelCase				, validation_data=(inputs_minus_labels, labels)				, steps_per_epoch=1				, validation_steps=1				, shuffle=__lowerCAmelCase				, verbose=0				, )

      a							=		history.history["loss"][0]
      self.assertTrue(not isnan(__lowerCAmelCase				)				)
      a							=		history.history["val_loss"][0]
      self.assertTrue(not isnan(__lowerCAmelCase				)				)

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


    """simple docstring"""






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

    if hasattr(__lowerCAmelCase				, "use_cache"				):
     a							=		True

    a							=		getattr(self.model_tester				, "encoder_seq_length"				, self.model_tester.seq_length				)
    a							=		getattr(self.model_tester				, "key_length"				, __lowerCAmelCase				)

    for model_class in self.all_model_classes[:2]:
     a							=		self._prepare_for_class(__lowerCAmelCase				, __lowerCAmelCase				)
     a							=		model_class(__lowerCAmelCase				)
     model.build()
     a							=		len(model(__lowerCAmelCase				)				)

     for key in list(class_inputs_dict.keys()				):
      # Remove keys not in the serving signature, as the SavedModel will not be compiled to deal with them
      if key not in model.input_signature:
       del class_inputs_dict[key]
      # Check it's a tensor, in case the inputs dict has some bools in it too
      elif isinstance(class_inputs_dict[key]				, tf.Tensor				) and class_inputs_dict[key].dtype.is_integer:
       a							=		tf.cast(class_inputs_dict[key]				, tf.intaa				)

     if set(class_inputs_dict.keys()				) != set(model.input_signature.keys()				):
      continue  # Some models have inputs that the preparation functions don't create, we skip those

     with tempfile.TemporaryDirectory() as tmpdirname:
      model.save_pretrained(__lowerCAmelCase				, saved_model=__lowerCAmelCase				)
      a							=		os.path.join(__lowerCAmelCase				, "saved_model"				, "1"				)
      a							=		tf.keras.models.load_model(__lowerCAmelCase				)
      a							=		model(__lowerCAmelCase				)

      if self.is_encoder_decoder:
       a							=		outputs["encoder_hidden_states"]
       a							=		outputs["encoder_attentions"]
      else:
       a							=		outputs["hidden_states"]
       a							=		outputs["attentions"]

      self.assertEqual(len(__lowerCAmelCase				)				, __lowerCAmelCase				)

      a							=		getattr(
          self.model_tester				, "expected_num_hidden_layers"				, self.model_tester.num_hidden_layers + 1				)

      self.assertEqual(len(__lowerCAmelCase				)				, __lowerCAmelCase				)
      self.assertListEqual(
          list(output_hidden_states[0].shape[-2:]				)				, [self.model_tester.seq_length, self.model_tester.hidden_size]				, )

      self.assertEqual(len(__lowerCAmelCase				)				, self.model_tester.num_hidden_layers				)
      self.assertListEqual(
          list(output_attentions[0].shape[-3:]				)				, [self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length]				, )

   @slow
   def 		A				(   self      :							Optional[int]				)							->					Tuple:


    """simple docstring"""






    tf.keras.mixed_precision.set_global_policy("mixed_float16"				)

    # try/finally block to ensure subsequent tests run in float32
    try:
     a		,	a							=		self.model_tester.prepare_config_and_inputs_for_common()
     for model_class in self.all_model_classes[:2]:
      a							=		self._prepare_for_class(__lowerCAmelCase				, __lowerCAmelCase				)
      a							=		model_class(__lowerCAmelCase				)
      a							=		model(__lowerCAmelCase				)

      self.assertIsNotNone(__lowerCAmelCase				)
    finally:
     tf.keras.mixed_precision.set_global_policy("float32"				)

   @slow
   def 		A				(   self      :							Optional[int]				)							->					Dict:


    """simple docstring"""






    a		,	a							=		self.model_tester.prepare_config_and_inputs_for_common()
    # head_mask and decoder_head_mask has different shapes than other input args
    if "head_mask" in inputs_dict:
     del inputs_dict["head_mask"]
    if "decoder_head_mask" in inputs_dict:
     del inputs_dict["decoder_head_mask"]
    if "cross_attn_head_mask" in inputs_dict:
     del inputs_dict["cross_attn_head_mask"]
    a							=		{
        module_member
        for model_class in self.all_model_classes
        for module in (import_module(model_class.__module__				),)
        for module_member_name in dir(__lowerCAmelCase				)
        if module_member_name.endswith("MainLayer"				)
        for module_member in (getattr(__lowerCAmelCase				, __lowerCAmelCase				),)
        if isinstance(__lowerCAmelCase				, __lowerCAmelCase				)
        and tf.keras.layers.Layer in module_member.__bases__
        and getattr(__lowerCAmelCase				, "_keras_serializable"				, __lowerCAmelCase				)
    }

    for main_layer_class in tf_main_layer_classes:
     # T5MainLayer needs an embed_tokens parameter when called without the inputs_embeds parameter
     if "T5" in main_layer_class.__name__:
      # Take the same values than in TFT5ModelTester for this shared layer
      a							=		TFSharedEmbeddings(self.model_tester.vocab_size				, self.model_tester.hidden_size				, name="shared"				)
      a							=		False
      a							=		main_layer_class(__lowerCAmelCase				, embed_tokens=__lowerCAmelCase				)
     else:
      a							=		main_layer_class(__lowerCAmelCase				)

     a							=		{
         name: tf.keras.Input(tensor.shape[1:]				, dtype=tensor.dtype				) for name, tensor in inputs_dict.items()
     }

     if hasattr(self.model_tester				, "num_labels"				):
      a							=		self.model_tester.num_labels
     else:
      a							=		2

     a							=		tf.data.Dataset.from_tensor_slices(
         (inputs_dict, np.ones((self.model_tester.batch_size, self.model_tester.seq_length, num_labels, 1)				))				).batch(1				)

     a							=		main_layer(__lowerCAmelCase				)[0]
     a							=		tf.keras.layers.Dense(__lowerCAmelCase				, activation="softmax"				, name="outputs"				)(__lowerCAmelCase				)
     a							=		tf.keras.models.Model(inputs=__lowerCAmelCase				, outputs=[outputs]				)

     model.compile(loss="binary_crossentropy"				, optimizer="adam"				, metrics=["binary_accuracy"]				)
     model.fit(__lowerCAmelCase				, epochs=1				)

     with tempfile.TemporaryDirectory() as tmpdirname:
      a							=		os.path.join(__lowerCAmelCase				, "keras_model.h5"				)
      model.save(__lowerCAmelCase				)
      if "T5" in main_layer_class.__name__:
       a							=		tf.keras.models.load_model(
           __lowerCAmelCase				, custom_objects={
               main_layer_class.__name__: main_layer_class,
               "TFSharedEmbeddings": TFSharedEmbeddings,
           }				, )
      else:
       a							=		tf.keras.models.load_model(
           __lowerCAmelCase				, custom_objects={main_layer_class.__name__: main_layer_class}				)
      assert isinstance(__lowerCAmelCase				, tf.keras.Model				)
      model(__lowerCAmelCase				)

   @slow
   def 		A				(   self      :							Any				)							->					Union[str, Any]:


    """simple docstring"""






    a		,	a							=		self.model_tester.prepare_config_and_inputs_for_common()

    for model_class in self.all_model_classes[:2]:
     a							=		model_class(__lowerCAmelCase				)

     a							=		copy.deepcopy(__lowerCAmelCase				)

     if not self.is_encoder_decoder:
      a							=		inputs["input_ids"]
      del inputs["input_ids"]
     else:
      a							=		inputs["input_ids"]
      a							=		inputs.get("decoder_input_ids"				, __lowerCAmelCase				)
      del inputs["input_ids"]
      inputs.pop("decoder_input_ids"				, __lowerCAmelCase				)

     if not self.is_encoder_decoder:
      a							=		model.get_input_embeddings()(__lowerCAmelCase				)
     else:
      a							=		model.get_input_embeddings()(__lowerCAmelCase				)
      a							=		model.get_input_embeddings()(__lowerCAmelCase				)

     a							=		self._prepare_for_class(__lowerCAmelCase				, __lowerCAmelCase				)

     @tf.function
     def run_in_graph_mode():
      return model(__lowerCAmelCase				)

     a							=		run_in_graph_mode()
     self.assertIsNotNone(__lowerCAmelCase				)

   def 		A				(   self      :							Union[str, Any]				, __lowerCAmelCase      :							Dict				, __lowerCAmelCase      :							List[str]				)							->					List[str]:


    """simple docstring"""






    a							=		[]
    if model.config.bos_token_id is not None:
     special_tokens.append(model.config.bos_token_id				)
    if model.config.pad_token_id is not None:
     special_tokens.append(model.config.pad_token_id				)
    if model.config.eos_token_id is not None:
     special_tokens.append(model.config.eos_token_id				)

    # create random bad tokens that are not special tokens
    a							=		[]
    while len(__lowerCAmelCase				) < num_bad_tokens:
     a							=		tf.squeeze(ids_tensor((1, 1)				, self.model_tester.vocab_size				)				, 0				).numpy()[0]
     if token not in special_tokens:
      bad_tokens.append(__lowerCAmelCase				)
    return bad_tokens

   def 		A				(   self      :							int				, __lowerCAmelCase      :							int				)							->					int:


    """simple docstring"""






    for token_id in output_ids[0].numpy().tolist():
     self.assertGreaterEqual(__lowerCAmelCase				, 0				)
     self.assertLess(__lowerCAmelCase				, self.model_tester.vocab_size				)




   def 		A				(   self      :							Optional[Any]				, __lowerCAmelCase      :							List[str]				, __lowerCAmelCase      :							Any				)							->					int:


    """simple docstring"""






    for bad_word_ids in bad_words_ids:
     # for all slices in batch
     for generated_ids_slice in generated_ids:
      # for all word idx
      for i in range(len(__lowerCAmelCase				)				, len(__lowerCAmelCase				)				):
       # if tokens match
       if generated_ids_slice[i - len(__lowerCAmelCase				) : i] == bad_word_ids:
        return True
    return False

