


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, RandomSampler, TensorDataset
from tqdm import tqdm

from transformers import GPTaLMHeadModel


SCREAMING_SNAKE_CASE       :		List[Any]       =				logging.getLogger(__name__)




def     UpperCamelCase    (      _a       ,		_a		)					->							Any:
     '''simple docstring'''





     if os.path.exists(_a		):
          if os.path.exists(os.path.join(_a       ,		'''config.json'''		)		) and os.path.isfile(
              os.path.join(_a       ,		'''config.json'''		)		):
               os.remove(os.path.join(_a       ,		'''config.json'''		)		)
          if os.path.exists(os.path.join(_a       ,		'''pytorch_model.bin'''		)		) and os.path.isfile(
              os.path.join(_a       ,		'''pytorch_model.bin'''		)		):
               os.remove(os.path.join(_a       ,		'''pytorch_model.bin'''		)		)
     else:
          os.makedirs(_a		)
     model.save_pretrained(_a		)




def     UpperCamelCase    (      _a       ,		_a=False		)					->							Optional[int]:
     '''simple docstring'''





     lowercase_       :Optional[Any]     =       2
     if unlogit:
          lowercase_       :Optional[int]     =       torch.pow(_a       ,		_a		)
     lowercase_       :Any     =       p * torch.log(_a		)
     lowercase_       :List[str]     =       0
     return -plogp.sum(dim=-1		)




def     UpperCamelCase    (      _a		)					->							Optional[Any]:
     '''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     UpperCamelCase    (      _a       ,		_a       ,		_a       ,		_a=True       ,		_a=True       ,		_a=None       ,		_a=False		)					->							int:
     '''simple docstring'''





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

     if head_mask is None:
          lowercase_       :Optional[int]     =       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:
          lowercase_       :Union[str, Any]     =       None

     lowercase_       :Tuple     =       0.0
     lowercase_       :List[str]     =       0.0
     for step, inputs in enumerate(tqdm(_a       ,		desc='''Iteration'''       ,		disable=args.local_rank not in [-1, 0]		)		):
          lowercase_       :Union[str, Any]     =       tuple(t.to(args.device		) for t in inputs		)
          (lowercase_      )       :Union[str, Any]     =       inputs

          # Do a forward pass (not with torch.no_grad() since we need gradients for importance score - see below)
          lowercase_       :List[str]     =       model(_a       ,		labels=_a       ,		head_mask=_a		)
          #  (loss), lm_logits, presents, (all hidden_states), (attentions)
          lowercase_       :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
          total_loss += loss.detach().cpu().numpy()
          if compute_entropy:
               for layer, attn in enumerate(_a		):
                    lowercase_       :Optional[int]     =       entropy(attn.detach()       ,		_a		)
                    attn_entropy[layer] += masked_entropy.sum(-1		).sum(0		).sum(0		).detach()

          if compute_importance:
               head_importance += head_mask.grad.abs().detach()
          tot_tokens += torch.ones_like(_a		).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_       :str     =       2
          lowercase_       :Tuple     =       torch.pow(torch.pow(_a       ,		_a		).sum(-1		)       ,		1 / exponent		)
          head_importance /= norm_by_layer.unsqueeze(-1		) + 1E-20

     if not args.dont_normalize_global_importance:
          lowercase_       :List[str]     =       (head_importance - head_importance.min()) / (head_importance.max() - head_importance.min())

     # Print matrices
     if compute_entropy:
          logger.info('''Attention entropies'''		)
          print_ad_tensor(_a		)
     if compute_importance:
          logger.info('''Head importance scores'''		)
          print_ad_tensor(_a		)
     logger.info('''Head ranked by importance scores'''		)
     lowercase_       :Any     =       torch.zeros(head_importance.numel()       ,		dtype=torch.long       ,		device=args.device		)
     lowercase_       :Dict     =       torch.arange(
         head_importance.numel()       ,		device=args.device		)
     lowercase_       :int     =       head_ranks.view_as(_a		)
     print_ad_tensor(_a		)
     return attn_entropy, head_importance, total_loss




def     UpperCamelCase    (      _a       ,		_a       ,		_a		)					->							Optional[Any]:
     '''simple docstring'''





     lowercase_       :Any     =       compute_heads_importance(_a       ,		_a       ,		_a       ,		compute_entropy=_a		)
     lowercase_       :List[Any]     =       1 / loss  # instead of downsteam score use the LM loss
     logger.info('''Pruning: original score: %f, threshold: %f'''       ,		_a       ,		original_score * args.masking_threshold		)

     lowercase_       :Any     =       torch.ones_like(_a		)
     lowercase_       :str     =       max(1       ,		int(new_head_mask.numel() * args.masking_amount		)		)

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

          if len(_a		) <= num_to_mask:
               print('''BREAK BY num_to_mask'''		)
               break

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

          # Compute metric and head importance again
          lowercase_       :Union[str, Any]     =       compute_heads_importance(
              _a       ,		_a       ,		_a       ,		compute_entropy=_a       ,		head_mask=_a		)
          lowercase_       :Union[str, Any]     =       1 / loss
          logger.info(
              '''Masking: current score: %f, remaining heads %d (%.1f percents)'''       ,		_a       ,		new_head_mask.sum()       ,		new_head_mask.sum() / new_head_mask.numel() * 1_0_0       ,		)

     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     UpperCamelCase    (      _a       ,		_a       ,		_a       ,		_a		)					->							Optional[int]:
     '''simple docstring'''





     lowercase_       :Optional[int]     =       datetime.now()
     lowercase_       :Tuple     =       compute_heads_importance(
         _a       ,		_a       ,		_a       ,		compute_entropy=_a       ,		compute_importance=_a       ,		head_mask=_a		)
     lowercase_       :Any     =       1 / loss
     lowercase_       :Any     =       datetime.now() - before_time

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

     for k, v in heads_to_prune.items():
          if isinstance(_a       ,		_a		):
               lowercase_       :List[Any]     =       [
                   v,
               ]

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

     lowercase_       :Tuple     =       datetime.now()
     lowercase_       :Optional[Any]     =       compute_heads_importance(
         _a       ,		_a       ,		_a       ,		compute_entropy=_a       ,		compute_importance=_a       ,		head_mask=_a       ,		actually_pruned=_a       ,		)

     lowercase_       :List[Any]     =       1 / loss
     lowercase_       :List[str]     =       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 * 1_0_0       ,		)
     logger.info('''Pruning: score with masking: %f score with pruning: %f'''       ,		_a       ,		_a		)
     logger.info('''Pruning: speed ratio (original timing / new timing): %f percents'''       ,		original_time / new_time * 1_0_0		)
     save_model(_a       ,		args.output_dir		)




def     UpperCamelCase    (      )					->							Tuple:
     '''simple docstring'''





     lowercase_       :Union[str, Any]     =       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(
         '''--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 s3'''       ,		)
     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=1_2_8       ,		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=4_2		)
     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.'''		)
     lowercase_       :Union[str, 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=_a		)
          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_       :Tuple     =       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		)		)		)

     lowercase_       :str     =       GPTaLMHeadModel.from_pretrained(args.model_name_or_path		)

     # Distributed and parallel training
     model.to(args.device		)
     if args.local_rank != -1:
          lowercase_       :str     =       nn.parallel.DistributedDataParallel(
              _a       ,		device_ids=[args.local_rank]       ,		output_device=args.local_rank       ,		find_unused_parameters=_a		)
     elif args.n_gpu > 1:
          lowercase_       :List[Any]     =       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
     lowercase_       :Tuple     =       np.concatenate(
         [
             np.loadtxt(args.data_dir       ,		dtype=np.intaa		),
         ]		)
     lowercase_       :Optional[int]     =       (torch.from_numpy(_a		),)
     lowercase_       :str     =       TensorDataset(*_a		)
     lowercase_       :Any     =       RandomSampler(_a		)
     lowercase_       :Any     =       DataLoader(_a       ,		sampler=_a       ,		batch_size=args.batch_size		)

     # 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:
          lowercase_       :int     =       mask_heads(_a       ,		_a       ,		_a		)
          prune_heads(_a       ,		_a       ,		_a       ,		_a		)


if __name__ == "__main__":
   main()





from typing import Dict

from transformers import EvalPrediction, HfArgumentParser, TrainingArguments, is_torch_available
from transformers.testing_utils import (
    TestCasePlus,
    execute_subprocess_async,
    get_torch_dist_unique_port,
    require_torch_multi_gpu,
    require_torch_neuroncore,
)
from transformers.training_args import ParallelMode
from transformers.utils import logging


SCREAMING_SNAKE_CASE       :		List[str]         =				logging.get_logger(__name__)


if is_torch_available():
   import torch
   from torch import nn
   from torch.utils.data import Dataset

   from transformers import Trainer






   class      UpperCamelCase					(		lowercase__     ):


      '''simple docstring'''







      def __init__(     self   ,							UpperCamelCase_ = 101		):
           lowercase_       :Tuple     =       length
      def __len__(     self		):
           return self.length




      def __getitem__(     self   ,							UpperCamelCase_		):
           return i






   class      UpperCamelCase					:


      '''simple docstring'''







      def __call__(     self   ,							UpperCamelCase_		):
           return {"input_ids": torch.tensor(UpperCamelCase_		), "labels": torch.tensor(UpperCamelCase_		)}






   class      UpperCamelCase					(		nn.Module     ):


      '''simple docstring'''







      def __init__(     self		):
           super().__init__()
           # Add some (unused) params otherwise DDP will complain.
           lowercase_       :List[Any]     =       nn.Linear(120   ,							80		)




      def 		UpperCamelCase  (     self   ,							UpperCamelCase_   ,							UpperCamelCase_=None		):
           if labels is not None:
                return torch.tensor(0.0   ,							device=input_ids.device		), input_ids
           else:
                return input_ids






class      UpperCamelCase					(		lowercase__     ):


   '''simple docstring'''







   @require_torch_neuroncore
   def 		UpperCamelCase  (     self		):
        lowercase_       :int     =       f"--nproc_per_node=2\n            --master_port={get_torch_dist_unique_port()}\n            {self.test_file_dir}/test_trainer_distributed.py\n        ".split()
        lowercase_       :List[str]     =       self.get_auto_remove_tmp_dir()
        lowercase_       :List[str]     =       f"--output_dir {output_dir}".split()
        lowercase_       :Any     =       ['''torchrun'''] + distributed_args + args
        execute_subprocess_async(UpperCamelCase_   ,							env=self.get_env()		)
        # successful return here == success - any errors would have caused an error in the sub-call






class      UpperCamelCase					(		lowercase__     ):


   '''simple docstring'''







   @require_torch_multi_gpu
   def 		UpperCamelCase  (     self		):
        lowercase_       :Any     =       f"--nproc_per_node={torch.cuda.device_count()}\n            --master_port={get_torch_dist_unique_port()}\n            {self.test_file_dir}/test_trainer_distributed.py\n        ".split()
        lowercase_       :str     =       self.get_auto_remove_tmp_dir()
        lowercase_       :List[str]     =       f"--output_dir {output_dir}".split()
        lowercase_       :Dict     =       ['''torchrun'''] + distributed_args + args
        execute_subprocess_async(UpperCamelCase_   ,							env=self.get_env()		)
        # successful return here == success - any errors would have caused an error in the sub-call


if __name__ == "__main__":
   # The script below is meant to be run under torch.distributed, on a machine with multiple GPUs:
   #
   # PYTHONPATH="src" python -m torch.distributed.run --nproc_per_node 2 --output_dir output_dir ./tests/test_trainer_distributed.py

   SCREAMING_SNAKE_CASE       :		Optional[int]         =				HfArgumentParser((TrainingArguments,))
   SCREAMING_SNAKE_CASE       :		Optional[int]         =				parser.parse_args_into_dataclasses()[0]

   logger.warning(
       f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}, "
       f"distributed training: {training_args.parallel_mode != ParallelMode.NOT_DISTRIBUTED}"
   )

   # Essentially, what we want to verify in the distributed case is that we get all samples back,
   # in the right order. (this is crucial for prediction for instance)
   for dataset_length in [101, 40, 7]:
      SCREAMING_SNAKE_CASE       :		Dict         =				DummyDataset(dataset_length)




      def     UpperCamelCase    (      _a		)					->							Dict:
           '''simple docstring'''





           lowercase_       :Optional[Any]     =       list(range(len(_a		)		)		)
           lowercase_       :Optional[Any]     =       p.predictions.tolist() == sequential and p.label_ids.tolist() == sequential
           if not success and training_args.local_rank == 0:
                logger.warning(
                    '''Predictions and/or labels do not match expected results:\n  - predictions: '''
                    f"{p.predictions.tolist()}\n  - labels: {p.label_ids.tolist()}\n  - expected: {sequential}"		)
           return {"success": success}

      SCREAMING_SNAKE_CASE       :		Optional[Any]         =				Trainer(
          model=DummyModel(),
          args=training_args,
          data_collator=DummyDataCollator(),
          eval_dataset=dataset,
          compute_metrics=compute_metrics,
      )
      SCREAMING_SNAKE_CASE       :		Any         =				trainer.evaluate()
      logger.info(metrics)
      if metrics["eval_success"] is not True:
         logger.error(metrics)
         exit(1)

      SCREAMING_SNAKE_CASE       :		Optional[int]         =				trainer.predict(dataset)
      logger.info(p.metrics)
      if p.metrics["test_success"] is not True:
         logger.error(p.metrics)
         exit(1)

      SCREAMING_SNAKE_CASE       :		Union[str, Any]         =				2

      SCREAMING_SNAKE_CASE       :		Any         =				trainer.evaluate()
      logger.info(metrics)
      if metrics["eval_success"] is not True:
         logger.error(metrics)
         exit(1)

      SCREAMING_SNAKE_CASE       :		List[str]         =				trainer.predict(dataset)
      logger.info(p.metrics)
      if p.metrics["test_success"] is not True:
         logger.error(p.metrics)
         exit(1)
      SCREAMING_SNAKE_CASE       :		Optional[int]         =				None

