





'''simple docstring'''

import argparse
import pathlib

import fairseq
import torch
from fairseq.models.roberta import RobertaModel as FairseqRobertaModel
from fairseq.modules import TransformerSentenceEncoderLayer
from packaging import version

from transformers import XLMRobertaConfig, XLMRobertaXLForMaskedLM, XLMRobertaXLForSequenceClassification
from transformers.models.bert.modeling_bert import (
    BertIntermediate,
    BertLayer,
    BertOutput,
    BertSelfAttention,
    BertSelfOutput,
)
from transformers.models.roberta.modeling_roberta import RobertaAttention
from transformers.utils import logging


if version.parse(fairseq.__version__) < version.parse('1.0.0a'):
  raise Exception('requires fairseq >= 1.0.0a')

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

UpperCAmelCase					:		Dict		=							'Hello world! cécé herlolip'




def    _a    (							lowerCAmelCase_			,      lowerCAmelCase_			,      lowerCAmelCase_	):





      """simple docstring"""



      _snake_case		:	Optional[Any]					     =     FairseqRobertaModel.from_pretrained(lowerCAmelCase_	)
      roberta.eval()  # disable dropout
      _snake_case		:	Optional[int]					     =     roberta.model.encoder.sentence_encoder
      _snake_case		:	Optional[Any]					     =     XLMRobertaConfig(
          vocab_size=roberta_sent_encoder.embed_tokens.num_embeddings			,      hidden_size=roberta.cfg.model.encoder_embed_dim			,      num_hidden_layers=roberta.cfg.model.encoder_layers			,      num_attention_heads=roberta.cfg.model.encoder_attention_heads			,      intermediate_size=roberta.cfg.model.encoder_ffn_embed_dim			,      max_position_embeddings=514			,      type_vocab_size=1			,      layer_norm_eps=1E-5			,      )
      if classification_head:
            _snake_case		:	Dict					     =     roberta.model.classification_heads['''mnli'''].out_proj.weight.shape[0]

      print('''Our RoBERTa config:'''			,      lowerCAmelCase_	)

      _snake_case		:	List[str]					     =     XLMRobertaXLForSequenceClassification(lowerCAmelCase_	) if classification_head else XLMRobertaXLForMaskedLM(lowerCAmelCase_	)
      model.eval()

      # Now let's copy all the weights.
      # Embeddings
      _snake_case		:	int					     =     roberta_sent_encoder.embed_tokens.weight
      _snake_case		:	Union[str, Any]					     =     roberta_sent_encoder.embed_positions.weight
      _snake_case		:	str					     =     torch.zeros_like(
          model.roberta.embeddings.token_type_embeddings.weight	)  # just zero them out b/c RoBERTa doesn't use them.

      _snake_case		:	List[Any]					     =     roberta_sent_encoder.layer_norm.weight
      _snake_case		:	List[Any]					     =     roberta_sent_encoder.layer_norm.bias

      for i in range(config.num_hidden_layers	):
            # Encoder: start of layer
            _snake_case		:	BertLayer					     =     model.roberta.encoder.layer[i]
            _snake_case		:	TransformerSentenceEncoderLayer					     =     roberta_sent_encoder.layers[i]

            _snake_case		:	RobertaAttention					     =     layer.attention
            _snake_case		:	Optional[Any]					     =     roberta_layer.self_attn_layer_norm.weight
            _snake_case		:	List[str]					     =     roberta_layer.self_attn_layer_norm.bias

            # self attention
            _snake_case		:	BertSelfAttention					     =     layer.attention.self
            assert (
                roberta_layer.self_attn.k_proj.weight.data.shape
                == roberta_layer.self_attn.q_proj.weight.data.shape
                == roberta_layer.self_attn.v_proj.weight.data.shape
                == torch.Size((config.hidden_size, config.hidden_size)	)
            )

            _snake_case		:	Optional[Any]					     =     roberta_layer.self_attn.q_proj.weight
            _snake_case		:	int					     =     roberta_layer.self_attn.q_proj.bias
            _snake_case		:	Optional[int]					     =     roberta_layer.self_attn.k_proj.weight
            _snake_case		:	Any					     =     roberta_layer.self_attn.k_proj.bias
            _snake_case		:	List[Any]					     =     roberta_layer.self_attn.v_proj.weight
            _snake_case		:	Any					     =     roberta_layer.self_attn.v_proj.bias

            # self-attention output
            _snake_case		:	BertSelfOutput					     =     layer.attention.output
            assert self_output.dense.weight.shape == roberta_layer.self_attn.out_proj.weight.shape
            _snake_case		:	Optional[Any]					     =     roberta_layer.self_attn.out_proj.weight
            _snake_case		:	Union[str, Any]					     =     roberta_layer.self_attn.out_proj.bias

            # this one is final layer norm
            _snake_case		:	str					     =     roberta_layer.final_layer_norm.weight
            _snake_case		:	Optional[Any]					     =     roberta_layer.final_layer_norm.bias

            # intermediate
            _snake_case		:	BertIntermediate					     =     layer.intermediate
            assert intermediate.dense.weight.shape == roberta_layer.fca.weight.shape
            _snake_case		:	str					     =     roberta_layer.fca.weight
            _snake_case		:	List[Any]					     =     roberta_layer.fca.bias

            # output
            _snake_case		:	BertOutput					     =     layer.output
            assert bert_output.dense.weight.shape == roberta_layer.fca.weight.shape
            _snake_case		:	Optional[int]					     =     roberta_layer.fca.weight
            _snake_case		:	Any					     =     roberta_layer.fca.bias
            # end of layer

      if classification_head:
            _snake_case		:	List[Any]					     =     roberta.model.classification_heads['''mnli'''].dense.weight
            _snake_case		:	Tuple					     =     roberta.model.classification_heads['''mnli'''].dense.bias
            _snake_case		:	int					     =     roberta.model.classification_heads['''mnli'''].out_proj.weight
            _snake_case		:	Any					     =     roberta.model.classification_heads['''mnli'''].out_proj.bias
      else:
            # LM Head
            _snake_case		:	Tuple					     =     roberta.model.encoder.lm_head.dense.weight
            _snake_case		:	Union[str, Any]					     =     roberta.model.encoder.lm_head.dense.bias
            _snake_case		:	int					     =     roberta.model.encoder.lm_head.layer_norm.weight
            _snake_case		:	Dict					     =     roberta.model.encoder.lm_head.layer_norm.bias
            _snake_case		:	int					     =     roberta.model.encoder.lm_head.weight
            _snake_case		:	Union[str, Any]					     =     roberta.model.encoder.lm_head.bias

      # Let's check that we get the same results.
      _snake_case		:	torch.Tensor					     =     roberta.encode(lowerCAmelCase_	).unsqueeze(0	)  # batch of size 1

      _snake_case		:	Any					     =     model(lowerCAmelCase_	)[0]
      if classification_head:
            _snake_case		:	Any					     =     roberta.model.classification_heads['''mnli'''](roberta.extract_features(lowerCAmelCase_	)	)
      else:
            _snake_case		:	Any					     =     roberta.model(lowerCAmelCase_	)[0]
      print(our_output.shape			,      their_output.shape	)
      _snake_case		:	str					     =     torch.max(torch.abs(our_output - their_output	)	).item()
      print(f'''max_absolute_diff = {max_absolute_diff}'''	)  # ~ 1e-7
      _snake_case		:	List[Any]					     =     torch.allclose(lowerCAmelCase_			,      lowerCAmelCase_			,      atol=1E-3	)
      print('''Do both models output the same tensors?'''			,      '''🔥''' if success else '''💩'''	)
      if not success:
            raise Exception('''Something went wRoNg'''	)

      pathlib.Path(lowerCAmelCase_	).mkdir(parents=lowerCAmelCase_			,      exist_ok=lowerCAmelCase_	)
      print(f'''Saving model to {pytorch_dump_folder_path}'''	)
      model.save_pretrained(lowerCAmelCase_	)


if __name__ == "__main__":
  UpperCAmelCase					:		Optional[int]		=							argparse.ArgumentParser()
  # Required parameters
  parser.add_argument(
      '--roberta_checkpoint_path', default=None, type=str, required=True, help='Path the official PyTorch dump.'
  )
  parser.add_argument(
      '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.'
  )
  parser.add_argument(
      '--classification_head', action='store_true', help='Whether to convert a final classification head.'
  )
  UpperCAmelCase					:		Dict		=							parser.parse_args()
  convert_xlm_roberta_xl_checkpoint_to_pytorch(
      args.roberta_checkpoint_path, args.pytorch_dump_folder_path, args.classification_head
  )









'''simple docstring'''

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


UpperCAmelCase					:		List[str]		=							logging.getLogger(__name__)




def    _a    (							lowerCAmelCase_			,      lowerCAmelCase_	):





      """simple docstring"""



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




def    _a    (							lowerCAmelCase_			,      lowerCAmelCase_=False	):





      """simple docstring"""



      _snake_case		:	Optional[Any]					     =     2
      if unlogit:
            _snake_case		:	Any					     =     torch.pow(lowerCAmelCase_			,      lowerCAmelCase_	)
      _snake_case		:	Union[str, Any]					     =     p * torch.log(lowerCAmelCase_	)
      _snake_case		:	Optional[Any]					     =     0
      return -plogp.sum(dim=-1	)




def    _a    (							lowerCAmelCase_	):





      """simple docstring"""



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




def    _a    (							lowerCAmelCase_			,      lowerCAmelCase_			,      lowerCAmelCase_			,      lowerCAmelCase_=True			,      lowerCAmelCase_=True			,      lowerCAmelCase_=None			,      lowerCAmelCase_=False	):





      """simple docstring"""



      _snake_case     ,							_snake_case		:	Optional[int]					     =     model.config.num_hidden_layers, model.config.num_attention_heads
      _snake_case		:	Tuple					     =     torch.zeros(lowerCAmelCase_			,      lowerCAmelCase_	).to(args.device	)
      _snake_case		:	Union[str, Any]					     =     torch.zeros(lowerCAmelCase_			,      lowerCAmelCase_	).to(args.device	)

      if head_mask is None:
            _snake_case		:	int					     =     torch.ones(lowerCAmelCase_			,      lowerCAmelCase_	).to(args.device	)

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

      _snake_case		:	Dict					     =     0.0
      _snake_case		:	Optional[int]					     =     0.0
      for step, inputs in enumerate(tqdm(lowerCAmelCase_			,      desc='''Iteration'''			,      disable=args.local_rank not in [-1, 0]	)	):
            _snake_case		:	List[Any]					     =     tuple(t.to(args.device	) for t in inputs	)
            ((_snake_case)     ,							)		:	Optional[Any]					     =     inputs

            # Do a forward pass (not with torch.no_grad() since we need gradients for importance score - see below)
            _snake_case		:	Any					     =     model(lowerCAmelCase_			,      labels=lowerCAmelCase_			,      head_mask=lowerCAmelCase_	)
            #  (loss), lm_logits, presents, (all hidden_states), (attentions)
            _snake_case     ,							_snake_case     ,							_snake_case		:	List[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(lowerCAmelCase_	):
                        _snake_case		:	Union[str, Any]					     =     entropy(attn.detach()			,      lowerCAmelCase_	)
                        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(lowerCAmelCase_	).float().detach().sum().data

      # Normalize
      attn_entropy /= tot_tokens
      head_importance /= tot_tokens
      # Layerwise importance normalization
      if not args.dont_normalize_importance_by_layer:
            _snake_case		:	Any					     =     2
            _snake_case		:	List[str]					     =     torch.pow(torch.pow(lowerCAmelCase_			,      lowerCAmelCase_	).sum(-1	)			,      1 / exponent	)
            head_importance /= norm_by_layer.unsqueeze(-1	) + 1E-20

      if not args.dont_normalize_global_importance:
            _snake_case		:	Optional[int]					     =     (head_importance - head_importance.min()) / (head_importance.max() - head_importance.min())

      # Print matrices
      if compute_entropy:
            logger.info('''Attention entropies'''	)
            print_ad_tensor(lowerCAmelCase_	)
      if compute_importance:
            logger.info('''Head importance scores'''	)
            print_ad_tensor(lowerCAmelCase_	)
      logger.info('''Head ranked by importance scores'''	)
      _snake_case		:	str					     =     torch.zeros(head_importance.numel()			,      dtype=torch.long			,      device=args.device	)
      _snake_case		:	List[Any]					     =     torch.arange(
          head_importance.numel()			,      device=args.device	)
      _snake_case		:	List[Any]					     =     head_ranks.view_as(lowerCAmelCase_	)
      print_ad_tensor(lowerCAmelCase_	)
      return attn_entropy, head_importance, total_loss




def    _a    (							lowerCAmelCase_			,      lowerCAmelCase_			,      lowerCAmelCase_	):





      """simple docstring"""



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

      _snake_case		:	int					     =     torch.ones_like(lowerCAmelCase_	)
      _snake_case		:	Optional[Any]					     =     max(1			,      int(new_head_mask.numel() * args.masking_amount	)	)

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

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

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

            # Compute metric and head importance again
            _snake_case     ,							_snake_case     ,							_snake_case		:	Any					     =     compute_heads_importance(
                lowerCAmelCase_			,      lowerCAmelCase_			,      lowerCAmelCase_			,      compute_entropy=lowerCAmelCase_			,      head_mask=lowerCAmelCase_	)
            _snake_case		:	int					     =     1 / loss
            logger.info(
                '''Masking: current score: %f, remaining heads %d (%.1f percents)'''			,      lowerCAmelCase_			,      new_head_mask.sum()			,      new_head_mask.sum() / new_head_mask.numel() * 100			,      )

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

      return head_mask




def    _a    (							lowerCAmelCase_			,      lowerCAmelCase_			,      lowerCAmelCase_			,      lowerCAmelCase_	):





      """simple docstring"""



      _snake_case		:	Optional[Any]					     =     datetime.now()
      _snake_case     ,							_snake_case     ,							_snake_case		:	Union[str, Any]					     =     compute_heads_importance(
          lowerCAmelCase_			,      lowerCAmelCase_			,      lowerCAmelCase_			,      compute_entropy=lowerCAmelCase_			,      compute_importance=lowerCAmelCase_			,      head_mask=lowerCAmelCase_	)
      _snake_case		:	Tuple					     =     1 / loss
      _snake_case		:	Dict					     =     datetime.now() - before_time

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

      for k, v in heads_to_prune.items():
            if isinstance(lowerCAmelCase_			,      lowerCAmelCase_	):
                  _snake_case		:	Union[str, Any]					     =     [
                      v,
                  ]

      assert sum(len(lowerCAmelCase_	) for h in heads_to_prune.values()	) == (1 - head_mask.long()).sum().item()
      model.prune_heads(lowerCAmelCase_	)
      _snake_case		:	List[str]					     =     sum(p.numel() for p in model.parameters()	)

      _snake_case		:	int					     =     datetime.now()
      _snake_case     ,							_snake_case     ,							_snake_case		:	Optional[Any]					     =     compute_heads_importance(
          lowerCAmelCase_			,      lowerCAmelCase_			,      lowerCAmelCase_			,      compute_entropy=lowerCAmelCase_			,      compute_importance=lowerCAmelCase_			,      head_mask=lowerCAmelCase_			,      actually_pruned=lowerCAmelCase_			,      )

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

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




def    _a    (							):





      """simple docstring"""



      _snake_case		:	List[str]					     =     argparse.ArgumentParser()
      # Required parameters
      parser.add_argument(
          '''--data_dir'''			,      default=lowerCAmelCase_			,      type=lowerCAmelCase_			,      required=lowerCAmelCase_			,      help='''The input data dir. Should contain the .tsv files (or other data files) for the task.'''			,      )
      parser.add_argument(
          '''--model_name_or_path'''			,      default=lowerCAmelCase_			,      type=lowerCAmelCase_			,      required=lowerCAmelCase_			,      help='''Path to pretrained model or model identifier from huggingface.co/models'''			,      )
      parser.add_argument(
          '''--output_dir'''			,      default=lowerCAmelCase_			,      type=lowerCAmelCase_			,      required=lowerCAmelCase_			,      help='''The output directory where the model predictions and checkpoints will be written.'''			,      )

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

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

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

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

      parser.add_argument('''--seed'''			,      type=lowerCAmelCase_			,      default=42	)
      parser.add_argument('''--local_rank'''			,      type=lowerCAmelCase_			,      default=-1			,      help='''local_rank for distributed training on gpus'''	)
      parser.add_argument('''--no_cuda'''			,      action='''store_true'''			,      help='''Whether not to use CUDA when available'''	)
      parser.add_argument('''--server_ip'''			,      type=lowerCAmelCase_			,      default=''''''			,      help='''Can be used for distant debugging.'''	)
      parser.add_argument('''--server_port'''			,      type=lowerCAmelCase_			,      default=''''''			,      help='''Can be used for distant debugging.'''	)
      _snake_case		:	Optional[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=lowerCAmelCase_	)
            ptvsd.wait_for_attach()

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

      _snake_case		:	Optional[Any]					     =     GPTaLMHeadModel.from_pretrained(args.model_name_or_path	)

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

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

      # Prepare dataset
      _snake_case		:	Dict					     =     np.concatenate(
          [
              np.loadtxt(args.data_dir			,      dtype=np.intaa	),
          ]	)
      _snake_case		:	int					     =     (torch.from_numpy(lowerCAmelCase_	),)
      _snake_case		:	Tuple					     =     TensorDataset(*lowerCAmelCase_	)
      _snake_case		:	List[str]					     =     RandomSampler(lowerCAmelCase_	)
      _snake_case		:	Dict					     =     DataLoader(lowerCAmelCase_			,      sampler=lowerCAmelCase_			,      batch_size=args.batch_size	)

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

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


if __name__ == "__main__":
   main()


