




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


lowerCAmelCase_						 =					logging.getLogger(__name__)






def    snake_case(							__magic_name__					,						__magic_name__       )					->				int:





     '''simple docstring'''


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






def    snake_case(							__magic_name__					,						__magic_name__=False       )					->				Any:





     '''simple docstring'''


     lowercase   :  Optional[Any]        =					2
     if unlogit:
          lowercase   :  Optional[Any]        =					torch.pow(__snake_case					,						__snake_case       )
     lowercase   :  Tuple        =					p * torch.log(__snake_case       )
     lowercase   :  Any        =					0
     return -plogp.sum(dim=-1       )






def    snake_case(							__magic_name__       )					->				Optional[int]:





     '''simple docstring'''


     logger.info('''lv, h >\t''' + '''\t'''.join(F"""{x + 1}""" for x in range(len(__snake_case       )       )       )       )
     for row in range(len(__snake_case       )       ):
          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(							__magic_name__					,						__magic_name__					,						__magic_name__					,						__magic_name__=True					,						__magic_name__=True					,						__magic_name__=None					,						__magic_name__=False       )					->				Optional[Any]:





     '''simple docstring'''


     lowercase   :  str        =					model.config.num_hidden_layers, model.config.num_attention_heads
     lowercase   :  Dict        =					torch.zeros(__snake_case					,						__snake_case       ).to(args.device       )
     lowercase   :  str        =					torch.zeros(__snake_case					,						__snake_case       ).to(args.device       )

     if head_mask is None:
          lowercase   :  List[Any]        =					torch.ones(__snake_case					,						__snake_case       ).to(args.device       )

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

     lowercase   :  int        =					0.0
     lowercase   :  Optional[Any]        =					0.0
     for step, inputs in enumerate(tqdm(__snake_case					,						desc='''Iteration'''					,						disable=args.local_rank not in [-1, 0]       )       ):
          lowercase   :  Dict        =					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   :  Any        =					model(__snake_case					,						labels=__snake_case					,						head_mask=__snake_case       )
          #  (loss), lm_logits, presents, (all hidden_states), (attentions)
          lowercase   :  Union[str, Any]        =					(
              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(__snake_case       ):
                    lowercase   :  List[Any]        =					entropy(attn.detach()					,						__snake_case       )
                    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(__snake_case       ).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   :  Tuple        =					2
          lowercase   :  Dict        =					torch.pow(torch.pow(__snake_case					,						__snake_case       ).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 matrices
     if compute_entropy:
          logger.info('''Attention entropies'''       )
          print_ad_tensor(__snake_case       )
     if compute_importance:
          logger.info('''Head importance scores'''       )
          print_ad_tensor(__snake_case       )
     logger.info('''Head ranked by importance scores'''       )
     lowercase   :  Any        =					torch.zeros(head_importance.numel()					,						dtype=torch.long					,						device=args.device       )
     lowercase   :  int        =					torch.arange(
         head_importance.numel()					,						device=args.device       )
     lowercase   :  Tuple        =					head_ranks.view_as(__snake_case       )
     print_ad_tensor(__snake_case       )
     return attn_entropy, head_importance, total_loss






def    snake_case(							__magic_name__					,						__magic_name__					,						__magic_name__       )					->				Tuple:





     '''simple docstring'''


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

     lowercase   :  Optional[int]        =					torch.ones_like(__snake_case       )
     lowercase   :  Union[str, Any]        =					max(1					,						int(new_head_mask.numel() * args.masking_amount       )       )

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

          if len(__snake_case       ) <= num_to_mask:
               print('''BREAK BY 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   :  Optional[Any]        =					new_head_mask.view(-1       )
          lowercase   :  Dict        =					0.0
          lowercase   :  Union[str, Any]        =					new_head_mask.view_as(__snake_case       )
          lowercase   :  Optional[Any]        =					new_head_mask.clone().detach()
          print_ad_tensor(__snake_case       )

          # Compute metric and head importance again
          lowercase   :  Tuple        =					compute_heads_importance(
              __snake_case					,						__snake_case					,						__snake_case					,						compute_entropy=__snake_case					,						head_mask=__snake_case       )
          lowercase   :  Tuple        =					1 / loss
          logger.info(
              '''Masking: current score: %f, remaining heads %d (%.1f percents)'''					,						__snake_case					,						new_head_mask.sum()					,						new_head_mask.sum() / new_head_mask.numel() * 1_00					,						)

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

     return head_mask






def    snake_case(							__magic_name__					,						__magic_name__					,						__magic_name__					,						__magic_name__       )					->				int:





     '''simple docstring'''


     lowercase   :  Any        =					datetime.now()
     lowercase   :  Union[str, Any]        =					compute_heads_importance(
         __snake_case					,						__snake_case					,						__snake_case					,						compute_entropy=__snake_case					,						compute_importance=__snake_case					,						head_mask=__snake_case       )
     lowercase   :  Tuple        =					1 / loss
     lowercase   :  str        =					datetime.now() - before_time

     lowercase   :  Union[str, Any]        =					sum(p.numel() for p in model.parameters()       )
     lowercase   :  str        =					{
         layer: (1 - head_mask[layer].long()).nonzero().squeeze().tolist() for layer in range(len(__snake_case       )       )
     }

     for k, v in heads_to_prune.items():
          if isinstance(__snake_case					,						__snake_case       ):
               lowercase   :  Optional[int]        =					[
                   v,
               ]

     assert sum(len(__snake_case       ) for h in heads_to_prune.values()       ) == (1 - head_mask.long()).sum().item()
     model.prune_heads(__snake_case       )
     lowercase   :  int        =					sum(p.numel() for p in model.parameters()       )

     lowercase   :  Dict        =					datetime.now()
     lowercase   :  Any        =					compute_heads_importance(
         __snake_case					,						__snake_case					,						__snake_case					,						compute_entropy=__snake_case					,						compute_importance=__snake_case					,						head_mask=__snake_case					,						actually_pruned=__snake_case					,						)

     lowercase   :  Dict        =					1 / loss
     lowercase   :  Optional[Any]        =					datetime.now() - before_time

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






def    snake_case(							)					->				Optional[int]:





     '''simple docstring'''


     lowercase   :  List[str]        =					argparse.ArgumentParser()
     # Required parameters
     parser.add_argument(
         '''--data_dir'''					,						default=__snake_case					,						type=__snake_case					,						required=__snake_case					,						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=__snake_case					,						type=__snake_case					,						required=__snake_case					,						help='''Path to pretrained model or model identifier from huggingface.co/models'''					,						)
     parser.add_argument(
         '''--output_dir'''					,						default=__snake_case					,						type=__snake_case					,						required=__snake_case					,						help='''The output directory where the model predictions and checkpoints will be written.'''					,						)

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

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

     parser.add_argument('''--seed'''					,						type=__snake_case					,						default=42       )
     parser.add_argument('''--local_rank'''					,						type=__snake_case					,						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=__snake_case					,						default=''''''					,						help='''Can be used for distant debugging.'''       )
     parser.add_argument('''--server_port'''					,						type=__snake_case					,						default=''''''					,						help='''Can be used for distant debugging.'''       )
     lowercase   :  Tuple        =					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=__snake_case       )
          ptvsd.wait_for_attach()

     # Setup devices and distributed training
     if args.local_rank == -1 or args.no_cuda:
          lowercase   :  Optional[int]        =					torch.device('''cuda''' if torch.cuda.is_available() and not args.no_cuda else '''cpu'''       )
          lowercase   :  Optional[Any]        =					0 if args.no_cuda else torch.cuda.device_count()
     else:
          torch.cuda.set_device(args.local_rank       )
          lowercase   :  Dict        =					torch.device('''cuda'''					,						args.local_rank       )
          lowercase   :  int        =					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   :  Optional[Any]        =					GPTaLMHeadModel.from_pretrained(args.model_name_or_path       )

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

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

     # Prepare dataset
     lowercase   :  Any        =					np.concatenate(
         [
             np.loadtxt(args.data_dir					,						dtype=np.intaa       ),
         ]       )
     lowercase   :  List[Any]        =					(torch.from_numpy(__snake_case       ),)
     lowercase   :  List[str]        =					TensorDataset(*__snake_case       )
     lowercase   :  Any        =					RandomSampler(__snake_case       )
     lowercase   :  List[str]        =					DataLoader(__snake_case					,						sampler=__snake_case					,						batch_size=args.batch_size       )

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

     # 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   :  Optional[int]        =					mask_heads(__snake_case					,						__snake_case					,						__snake_case       )
          prune_heads(__snake_case					,						__snake_case					,						__snake_case					,						__snake_case       )


if __name__ == "__main__":
 main()






'''simple docstring'''




import argparse

import torch
from huggingface_hub import hf_hub_download

from transformers import AutoTokenizer, RobertaPreLayerNormConfig, RobertaPreLayerNormForMaskedLM
from transformers.utils import logging


logging.set_verbosity_info()
lowercase__       : Tuple         =       logging.get_logger(__name__)






def 			_lowerCAmelCase     (    __snake_case    :					str					,				__snake_case    :					str     )	->	Union[str, Any]:
     __A		:					int						=			RobertaPreLayerNormConfig.from_pretrained(
         __snake_case					,				architectures=['RobertaPreLayerNormForMaskedLM']     )

     # convert state_dict
     __A		:					Tuple						=			torch.load(hf_hub_download(repo_id=__snake_case					,				filename='pytorch_model.bin'     )     )
     __A		:					str						=			{}
     for tensor_key, tensor_value in original_state_dict.items():
          # The transformer implementation gives the model a unique name, rather than overwiriting 'roberta'
          if tensor_key.startswith('roberta.'     ):
               __A		:					Dict						=			'roberta_prelayernorm.' + tensor_key[len('roberta.'     ) :]

          # The original implementation contains weights which are not used, remove them from the state_dict
          if tensor_key.endswith('.self.LayerNorm.weight'     ) or tensor_key.endswith('.self.LayerNorm.bias'     ):
               continue

          __A		:					str						=			tensor_value

     __A		:					Union[str, Any]						=			RobertaPreLayerNormForMaskedLM.from_pretrained(
         pretrained_model_name_or_path=__snake_case					,				config=__snake_case					,				state_dict=__snake_case     )
     model.save_pretrained(__snake_case     )

     # convert tokenizer
     __A		:					List[Any]						=			AutoTokenizer.from_pretrained(__snake_case     )
     tokenizer.save_pretrained(__snake_case     )


if __name__ == "__main__":
  lowercase__       : Dict         =       argparse.ArgumentParser()
  # Required parameters
  parser.add_argument(
      '''--checkpoint-repo''',
      default=None,
      type=str,
      required=True,
      help='''Path the official PyTorch dump, e.g. \'andreasmadsen/efficient_mlm_m0.40\'.''',
  )
  parser.add_argument(
      '''--pytorch_dump_folder_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.'''
  )
  lowercase__       : Optional[Any]         =       parser.parse_args()
  convert_roberta_prelayernorm_checkpoint_to_pytorch(args.checkpoint_repo, args.pytorch_dump_folder_path)