






import dataclasses
import json
import sys
import types
from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser, ArgumentTypeError
from copy import copy
from enum import Enum
from inspect import isclass
from pathlib import Path
from typing import Any, Callable, Dict, Iterable, List, Literal, NewType, Optional, Tuple, Union, get_type_hints

import yaml


UpperCAmelCase__							  =						NewType("DataClass", Any)
UpperCAmelCase__							  =						NewType("DataClassType", Any)
def 		_a       ( a					:List[str]					)				->     Union[str, Any]:
 if isinstance(a      ,				a					):
  return v
 if v.lower() in ("yes", "true", "t", "y", "1"):
  return True
 elif v.lower() in ("no", "false", "f", "n", "0"):
  return False
 else:
  raise ArgumentTypeError(
      F"""Truthy value expected: got {v} but expected one of yes/no, true/false, t/f, y/n, 1/0 (case insensitive)."""					)
def 		_a       ( a					:list					)				->     Callable[[str], Any]:
 a						    = {str(a					): choice for choice in choices}
 return lambda a					: str_to_choice.get(a      ,				a					)
def 		_a       ( *,
    a					:Union[str, List[str]] = None      ,				a					:str = None      ,				a					:Any = dataclasses.MISSING      ,				a					:Callable[[], Any] = dataclasses.MISSING      ,				a					:dict = None      ,				**a					:Tuple      ,				)				->     dataclasses.Field:
 if metadata is None:
  # Important, don't use as default param in function signature because dict is mutable and shared across function calls
  a						    = {}
 if aliases is not None:
  a						    = aliases
 if help is not None:
  a						    = help

 return dataclasses.field(metadata=a      ,				default=a      ,				default_factory=a      ,				**a					)






class 						lowercase_   (      lowercase  ):






      '''simple docstring'''




      __snake_case	    =    42







      def __init__( self :		Dict					,   __UpperCAmelCase :		Union[DataClassType, Iterable[DataClassType]]					,   **__UpperCAmelCase :		str    )       ->List[Any]:




       """simple docstring"""


       if "formatter_class" not in kwargs:
        a						    = ArgumentDefaultsHelpFormatter
       super().__init__(**__UpperCAmelCase    )
       if dataclasses.is_dataclass(__UpperCAmelCase    ):
        a						    = [dataclass_types]
       a						    = list(__UpperCAmelCase    )
       for dtype in self.dataclass_types:
        self._add_dataclass_arguments(__UpperCAmelCase    )







      @staticmethod
      def  __lowerCAmelCase   ( __UpperCAmelCase :		ArgumentParser					,   __UpperCAmelCase :		dataclasses.Field    )       ->Union[str, Any]:




       """simple docstring"""


       a						    = F"""--{field.name}"""
       a						    = field.metadata.copy()
       # field.metadata is not used at all by Data Classes,
       # it is provided as a third-party extension mechanism.
       if isinstance(field.type					,   __UpperCAmelCase    ):
        raise RuntimeError(
            '''Unresolved type detected, which should have been done with the help of '''
            '''`typing.get_type_hints` method by default'''    )

       a						    = kwargs.pop('''aliases'''					,   []    )
       if isinstance(__UpperCAmelCase					,   __UpperCAmelCase    ):
        a						    = [aliases]

       a						    = getattr(field.type					,   '''__origin__'''					,   field.type    )
       if origin_type is Union or (hasattr(__UpperCAmelCase					,   '''UnionType'''    ) and isinstance(__UpperCAmelCase					,   types.UnionType    )):
        if str not in field.type.__args__ and (
            len(field.type.__args__    ) != 2 or type(__UpperCAmelCase    ) not in field.type.__args__
        ):
         raise ValueError(
             '''Only `Union[X, NoneType]` (i.e., `Optional[X]`) is allowed for `Union` because'''
             ''' the argument parser only supports one type per argument.'''
             F""" Problem encountered in field '{field.name}'."""    )
        if type(__UpperCAmelCase    ) not in field.type.__args__:
         # filter `str` in Union
         a						    = field.type.__args__[0] if field.type.__args__[1] == str else field.type.__args__[1]
         a						    = getattr(field.type					,   '''__origin__'''					,   field.type    )
        elif bool not in field.type.__args__:
         # filter `NoneType` in Union (except for `Union[bool, NoneType]`)
         a						    = (
             field.type.__args__[0] if isinstance(__UpperCAmelCase					,   field.type.__args__[1]    ) else field.type.__args__[1]
         )
         a						    = getattr(field.type					,   '''__origin__'''					,   field.type    )

        # A variable to store kwargs for a boolean field, if needed
        # so that we can init a `no_*` complement argument (see below)
       a						    = {}
       if origin_type is Literal or (isinstance(field.type					,   __UpperCAmelCase    ) and issubclass(field.type					,   __UpperCAmelCase    )):
        if origin_type is Literal:
         a						    = field.type.__args__
        else:
         a						    = [x.value for x in field.type]

        a						    = make_choice_type_function(kwargs['''choices''']    )

        if field.default is not dataclasses.MISSING:
         a						    = field.default
        else:
         a						    = True
       elif field.type is bool or field.type == Optional[bool]:
        # Copy the currect kwargs to use to instantiate a `no_*` complement argument below.
        # We do not initialize it here because the `no_*` alternative must be instantiated after the real argument
        a						    = copy(__UpperCAmelCase    )

        # Hack because type=bool in argparse does not behave as we want.
        a						    = string_to_bool
        if field.type is bool or (field.default is not None and field.default is not dataclasses.MISSING):
         # Default value is False if we have no default when of type bool.
         a						    = False if field.default is dataclasses.MISSING else field.default
         # This is the value that will get picked if we don't include --field_name in any way
         a						    = default
         # This tells argparse we accept 0 or 1 value after --field_name
         a						    = '''?'''
         # This is the value that will get picked if we do --field_name (without value)
         a						    = True
       elif isclass(__UpperCAmelCase    ) and issubclass(__UpperCAmelCase					,   __UpperCAmelCase    ):
        a						    = field.type.__args__[0]
        a						    = '''+'''
        if field.default_factory is not dataclasses.MISSING:
         a						    = field.default_factory()
        elif field.default is dataclasses.MISSING:
         a						    = True
       else:
        a						    = field.type
        if field.default is not dataclasses.MISSING:
         a						    = field.default
        elif field.default_factory is not dataclasses.MISSING:
         a						    = field.default_factory()
        else:
         a						    = True
       parser.add_argument(__UpperCAmelCase					,   *__UpperCAmelCase					,   **__UpperCAmelCase    )

       # Add a complement `no_*` argument for a boolean field AFTER the initial field has already been added.
       # Order is important for arguments with the same destination!
       # We use a copy of earlier kwargs because the original kwargs have changed a lot before reaching down
       # here and we do not need those changes/additional keys.
       if field.default is True and (field.type is bool or field.type == Optional[bool]):
        a						    = False
        parser.add_argument(F"""--no_{field.name}"""					,   action='''store_false'''					,   dest=field.name					,   **__UpperCAmelCase    )







      def  __lowerCAmelCase   ( self :		Optional[Any]					,   __UpperCAmelCase :		DataClassType    )       ->Optional[Any]:




       """simple docstring"""


       if hasattr(__UpperCAmelCase					,   '''_argument_group_name'''    ):
        a						    = self.add_argument_group(dtype._argument_group_name    )
       else:
        a						    = self

       try:
        a						    = get_type_hints(__UpperCAmelCase    )
       except NameError:
        raise RuntimeError(
            F"""Type resolution failed for {dtype}. Try declaring the class in global scope or """
            '''removing line of `from __future__ import annotations` which opts in Postponed '''
            '''Evaluation of Annotations (PEP 563)'''    )
       except TypeError as ex:
        # Remove this block when we drop Python 3.9 support
        if sys.version_info[:2] < (3, 10) and "unsupported operand type(s) for |" in str(__UpperCAmelCase    ):
         a						    = '''.'''.join(map(__UpperCAmelCase					,   sys.version_info[:3]    )    )
         raise RuntimeError(
             F"""Type resolution failed for {dtype} on Python {python_version}. Try removing """
             '''line of `from __future__ import annotations` which opts in union types as '''
             '''`X | Y` (PEP 604) via Postponed Evaluation of Annotations (PEP 563). To '''
             '''support Python versions that lower than 3.10, you need to use '''
             '''`typing.Union[X, Y]` instead of `X | Y` and `typing.Optional[X]` instead of '''
             '''`X | None`.'''    ) from ex
        raise

       for field in dataclasses.fields(__UpperCAmelCase    ):
        if not field.init:
         continue
        a						    = type_hints[field.name]
        self._parse_dataclass_field(__UpperCAmelCase					,   __UpperCAmelCase    )







      def  __lowerCAmelCase   ( self :		int					,   __UpperCAmelCase :		str=None					,   __UpperCAmelCase :		Optional[Any]=False					,   __UpperCAmelCase :		Tuple=True					,   __UpperCAmelCase :		Tuple=None					,   __UpperCAmelCase :		Any=None					,   )       ->Tuple[DataClass, ...]:




       """simple docstring"""


       if args_file_flag or args_filename or (look_for_args_file and len(sys.argv    )):
        a						    = []

        if args_filename:
         args_files.append(Path(__UpperCAmelCase    )    )
        elif look_for_args_file and len(sys.argv    ):
         args_files.append(Path(sys.argv[0]    ).with_suffix('''.args'''    )    )

        # args files specified via command line flag should overwrite default args files so we add them last
        if args_file_flag:
         # Create special parser just to extract the args_file_flag values
         a						    = ArgumentParser()
         args_file_parser.add_argument(__UpperCAmelCase					,   type=__UpperCAmelCase					,   action='''append'''    )

         # Use only remaining args for further parsing (remove the args_file_flag)
         a    ,	a						    = args_file_parser.parse_known_args(args=__UpperCAmelCase    )
         a						    = vars(__UpperCAmelCase    ).get(args_file_flag.lstrip('''-'''    )					,   __UpperCAmelCase    )

         if cmd_args_file_paths:
          args_files.extend([Path(__UpperCAmelCase    ) for p in cmd_args_file_paths]    )

        a						    = []
        for args_file in args_files:
         if args_file.exists():
          file_args += args_file.read_text().split()

            # in case of duplicate arguments the last one has precedence
            # args specified via the command line should overwrite args from files, so we add them last
        a						    = file_args + args if args is not None else file_args + sys.argv[1:]
       a    ,	a						    = self.parse_known_args(args=__UpperCAmelCase    )
       a						    = []
       for dtype in self.dataclass_types:
        a						    = {f.name for f in dataclasses.fields(__UpperCAmelCase    ) if f.init}
        a						    = {k: v for k, v in vars(__UpperCAmelCase    ).items() if k in keys}
        for k in keys:
         delattr(__UpperCAmelCase					,   __UpperCAmelCase    )
        a						    = dtype(**__UpperCAmelCase    )
        outputs.append(__UpperCAmelCase    )
       if len(namespace.__dict__    ) > 0:
        # additional namespace.
        outputs.append(__UpperCAmelCase    )
       if return_remaining_strings:
        return (*outputs, remaining_args)
       else:
        if remaining_args:
         raise ValueError(F"""Some specified arguments are not used by the HfArgumentParser: {remaining_args}"""    )

        return (*outputs,)







      def  __lowerCAmelCase   ( self :		Tuple					,   __UpperCAmelCase :		Dict[str, Any]					,   __UpperCAmelCase :		bool = False    )       ->Tuple[DataClass, ...]:




       """simple docstring"""


       a						    = set(args.keys()    )
       a						    = []
       for dtype in self.dataclass_types:
        a						    = {f.name for f in dataclasses.fields(__UpperCAmelCase    ) if f.init}
        a						    = {k: v for k, v in args.items() if k in keys}
        unused_keys.difference_update(inputs.keys()    )
        a						    = dtype(**__UpperCAmelCase    )
        outputs.append(__UpperCAmelCase    )
       if not allow_extra_keys and unused_keys:
        raise ValueError(F"""Some keys are not used by the HfArgumentParser: {sorted(__UpperCAmelCase    )}"""    )
       return tuple(__UpperCAmelCase    )







      def  __lowerCAmelCase   ( self :		Optional[Any]					,   __UpperCAmelCase :		str					,   __UpperCAmelCase :		bool = False    )       ->Tuple[DataClass, ...]:




       """simple docstring"""


       with open(Path(__UpperCAmelCase    )					,   encoding='''utf-8'''    ) as open_json_file:
        a						    = json.loads(open_json_file.read()    )
       a						    = self.parse_dict(__UpperCAmelCase					,   allow_extra_keys=__UpperCAmelCase    )
       return tuple(__UpperCAmelCase    )







      def  __lowerCAmelCase   ( self :		List[Any]					,   __UpperCAmelCase :		str					,   __UpperCAmelCase :		bool = False    )       ->Tuple[DataClass, ...]:




       """simple docstring"""


       a						    = self.parse_dict(yaml.safe_load(Path(__UpperCAmelCase    ).read_text()    )					,   allow_extra_keys=__UpperCAmelCase    )
       return tuple(__UpperCAmelCase    )










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__							  =						logging.getLogger(__name__)
def 		_a       ( a					:Union[str, Any]      ,				a					:Tuple					)				->     Optional[Any]:
 # save results
 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 		_a       ( a					:List[Any]      ,				a					:Union[str, Any]=False					)				->     int:
 a						    = 2
 if unlogit:
  a						    = torch.pow(a      ,				a					)
 a						    = p * torch.log(a					)
 a						    = 0
 return -plogp.sum(dim=-1					)
def 		_a       ( a					:List[str]					)				->     Union[str, Any]:
 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 		_a       ( a					:Optional[int]      ,				a					:Dict      ,				a					:Tuple      ,				a					:Tuple=True      ,				a					:Union[str, Any]=True      ,				a					:str=None      ,				a					:Union[str, Any]=False					)				->     int:
 a    ,	a						    = model.config.num_hidden_layers, model.config.num_attention_heads
 a						    = torch.zeros(a      ,				a					).to(args.device					)
 a						    = torch.zeros(a      ,				a					).to(args.device					)

 if head_mask is None:
  a						    = 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:
  a						    = None

 a						    = 0.0
 a						    = 0.0
 for step, inputs in enumerate(tqdm(a      ,				desc='''Iteration'''      ,				disable=args.local_rank not in [-1, 0]					)					):
  a						    = tuple(t.to(args.device					) for t in inputs					)
  ((a)    ,	)						    = inputs

  # Do a forward pass (not with torch.no_grad() since we need gradients for importance score - see below)
  a						    = model(a      ,				labels=a      ,				head_mask=a					)
  #  (loss), lm_logits, presents, (all hidden_states), (attentions)
  a    ,	a    ,	a						    = (
      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					):
    a						    = 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:
  a						    = 2
  a						    = 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:
  a						    = (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'''					)
 a						    = torch.zeros(head_importance.numel()      ,				dtype=torch.long      ,				device=args.device					)
 a						    = torch.arange(
     head_importance.numel()      ,				device=args.device					)
 a						    = head_ranks.view_as(a					)
 print_ad_tensor(a					)
 return attn_entropy, head_importance, total_loss
def 		_a       ( a					:Optional[Any]      ,				a					:List[Any]      ,				a					:str					)				->     Optional[Any]:
 a    ,	a    ,	a						    = compute_heads_importance(a      ,				a      ,				a      ,				compute_entropy=a					)
 a						    = 1 / loss  # instead of downsteam score use the LM loss
 logger.info('''Pruning: original score: %f, threshold: %f'''      ,				a      ,				original_score * args.masking_threshold					)

 a						    = torch.ones_like(a					)
 a						    = max(1      ,				int(new_head_mask.numel() * args.masking_amount					)					)

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

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

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

  # Compute metric and head importance again
  a    ,	a    ,	a						    = compute_heads_importance(
      a      ,				a      ,				a      ,				compute_entropy=a      ,				head_mask=a					)
  a						    = 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() * 100      ,				)

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

 return head_mask
def 		_a       ( a					:List[Any]      ,				a					:Optional[int]      ,				a					:Tuple      ,				a					:List[str]					)				->     List[str]:
 a						    = datetime.now()
 a    ,	a    ,	a						    = compute_heads_importance(
     a      ,				a      ,				a      ,				compute_entropy=a      ,				compute_importance=a      ,				head_mask=a					)
 a						    = 1 / loss
 a						    = datetime.now() - before_time

 a						    = sum(p.numel() for p in model.parameters()					)
 a						    = {
     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					):
   a						    = [
       v,
   ]

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

 a						    = datetime.now()
 a    ,	a    ,	a						    = compute_heads_importance(
     a      ,				a      ,				a      ,				compute_entropy=a      ,				compute_importance=a      ,				head_mask=a      ,				actually_pruned=a      ,				)

 a						    = 1 / loss
 a						    = datetime.now() - before_time

 logger.info(
     '''Pruning: original num of params: %.2e, after pruning %.2e (%.1f percents)'''      ,				a      ,				a      ,				pruned_num_params / original_num_params * 100      ,				)
 logger.info('''Pruning: score with masking: %f score with pruning: %f'''      ,				a      ,				a					)
 logger.info('''Pruning: speed ratio (original timing / new timing): %f percents'''      ,				original_time / new_time * 100					)
 save_model(a      ,				args.output_dir					)
def 		_a       ( )				->     int:
 a						    = 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=128      ,				type=a      ,				help=(
         '''The maximum total input sequence length after WordPiece tokenization. \n'''
         '''Sequences longer than this will be truncated, sequences shorter padded.'''
     )      ,				)
 parser.add_argument('''--batch_size'''      ,				default=1      ,				type=a      ,				help='''Batch size.'''					)

 parser.add_argument('''--seed'''      ,				type=a      ,				default=42					)
 parser.add_argument('''--local_rank'''      ,				type=a      ,				default=-1      ,				help='''local_rank for distributed training on gpus'''					)
 parser.add_argument('''--no_cuda'''      ,				action='''store_true'''      ,				help='''Whether not to use CUDA when available'''					)
 parser.add_argument('''--server_ip'''      ,				type=a      ,				default=''''''      ,				help='''Can be used for distant debugging.'''					)
 parser.add_argument('''--server_port'''      ,				type=a      ,				default=''''''      ,				help='''Can be used for distant debugging.'''					)
 a						    = 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:
  a						    = torch.device('''cuda''' if torch.cuda.is_available() and not args.no_cuda else '''cpu'''					)
  a						    = 0 if args.no_cuda else torch.cuda.device_count()
 else:
  torch.cuda.set_device(args.local_rank					)
  a						    = torch.device('''cuda'''      ,				args.local_rank					)
  a						    = 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					)					)					)

 a						    = GPTaLMHeadModel.from_pretrained(args.model_name_or_path					)

 # Distributed and parallel training
 model.to(args.device					)
 if args.local_rank != -1:
  a						    = nn.parallel.DistributedDataParallel(
      a      ,				device_ids=[args.local_rank]      ,				output_device=args.local_rank      ,				find_unused_parameters=a					)
 elif args.n_gpu > 1:
  a						    = 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
 a						    = np.concatenate(
     [
         np.loadtxt(args.data_dir      ,				dtype=np.intaa					),
     ]					)
 a						    = (torch.from_numpy(a					),)
 a						    = TensorDataset(*a					)
 a						    = RandomSampler(a					)
 a						    = 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:
  a						    = mask_heads(a      ,				a      ,				a					)
  prune_heads(a      ,				a      ,				a      ,				a					)


if __name__ == "__main__":
     main()


