



'''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


lowerCamelCase							:Tuple				    =					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'''





			A_	:						Optional[Any]	=     2
			if unlogit:
						A_	:						List[str]	=     torch.pow(lowerCamelCase__						,      lowerCamelCase__    )
			A_	:						Any	=     p * torch.log(lowerCamelCase__    )
			A_	:						Tuple	=     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'''





			A_,    A_	:						Union[str, Any]	=     model.config.num_hidden_layers, model.config.num_attention_heads
			A_	:						Tuple	=     torch.zeros(lowerCamelCase__						,      lowerCamelCase__    ).to(args.device    )
			A_	:						Union[str, Any]	=     torch.zeros(lowerCamelCase__						,      lowerCamelCase__    ).to(args.device    )

			if head_mask is None:
						A_	:						List[str]	=     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:
						A_	:						Tuple	=     None

			A_	:						Optional[Any]	=     0.0
			A_	:						int	=     0.0
			for step, inputs in enumerate(tqdm(lowerCamelCase__						,      desc="""Iteration"""						,      disable=args.local_rank not in [-1, 0]    )    ):
						A_	:						str	=     tuple(t.to(args.device    ) for t in inputs    )
						((A_ ),     )	:						str	=     inputs

						# Do a forward pass (not with torch.no_grad() since we need gradients for importance score - see below)
						A_	:						Optional[Any]	=     model(lowerCamelCase__						,      labels=lowerCamelCase__						,      head_mask=lowerCamelCase__    )
						#  (loss), lm_logits, presents, (all hidden_states), (attentions)
						A_,    A_,    A_	:						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__    ):
												A_	:						List[str]	=     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:
						A_	:						Optional[int]	=     2
						A_	:						Union[str, Any]	=     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:
						A_	:						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"""    )
			A_	:						Optional[Any]	=     torch.zeros(head_importance.numel()						,      dtype=torch.long						,      device=args.device    )
			A_	:						Any	=     torch.arange(
			    head_importance.numel()						,      device=args.device    )
			A_	:						Optional[Any]	=     head_ranks.view_as(lowerCamelCase__    )
			print_ad_tensor(lowerCamelCase__    )
			return attn_entropy, head_importance, total_loss



def 	a			( lowerCamelCase__						,      lowerCamelCase__						,      lowerCamelCase__    ):
			'''simple docstring'''





			A_,    A_,    A_	:						Dict	=     compute_heads_importance(lowerCamelCase__						,      lowerCamelCase__						,      lowerCamelCase__						,      compute_entropy=lowerCamelCase__    )
			A_	:						Dict	=     1 / loss  # instead of downsteam score use the LM loss
			logger.info("""Pruning: original score: %f, threshold: %f"""						,      lowerCamelCase__						,      original_score * args.masking_threshold    )

			A_	:						List[str]	=     torch.ones_like(lowerCamelCase__    )
			A_	:						Tuple	=     max(1						,      int(new_head_mask.numel() * args.masking_amount    )    )

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

						if len(lowerCamelCase__    ) <= num_to_mask:
									print("""BREAK BY num_to_mask"""    )
									break

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

						# Compute metric and head importance again
						A_,    A_,    A_	:						int	=     compute_heads_importance(
						    lowerCamelCase__						,      lowerCamelCase__						,      lowerCamelCase__						,      compute_entropy=lowerCamelCase__						,      head_mask=lowerCamelCase__    )
						A_	:						Any	=     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() * 1_00						,      )

			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'''





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

			A_	:						List[Any]	=     sum(p.numel() for p in model.parameters()    )
			A_	:						Union[str, Any]	=     {
			    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__    ):
									A_	:						Optional[int]	=     [
									    v,
									]

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

			A_	:						List[Any]	=     datetime.now()
			A_,    A_,    A_	:						Tuple	=     compute_heads_importance(
			    lowerCamelCase__						,      lowerCamelCase__						,      lowerCamelCase__						,      compute_entropy=lowerCamelCase__						,      compute_importance=lowerCamelCase__						,      head_mask=lowerCamelCase__						,      actually_pruned=lowerCamelCase__						,      )

			A_	:						Tuple	=     1 / loss
			A_	:						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 * 1_00						,      )
			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 * 1_00    )
			save_model(lowerCamelCase__						,      args.output_dir    )



def 	a			( ):
			'''simple docstring'''





			A_	:						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=1_28						,      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."""    )
			A_	:						int	=     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:
						A_	:						List[Any]	=     torch.device("""cuda""" if torch.cuda.is_available() and not args.no_cuda else """cpu"""    )
						A_	:						int	=     0 if args.no_cuda else torch.cuda.device_count()
			else:
						torch.cuda.set_device(args.local_rank    )
						A_	:						Union[str, Any]	=     torch.device("""cuda"""						,      args.local_rank    )
						A_	:						Dict	=     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_	:						str	=     GPTaLMHeadModel.from_pretrained(args.model_name_or_path    )

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


if __name__ == "__main__":
						main()
"""simple docstring"""


from sklearn.metrics import recall_score

import datasets


UpperCAmelCase__     						=  """
Recall is the fraction of the positive examples that were correctly labeled by the model as positive. It can be computed with the equation:
Recall = TP / (TP + FN)
Where TP is the true positives and FN is the false negatives.
"""


UpperCAmelCase__     						=  """
Args:
- **predictions** (`list` of `int`): The predicted labels.
- **references** (`list` of `int`): The ground truth labels.
- **labels** (`list` of `int`): The set of labels to include when `average` is not set to `binary`, and their order when average is `None`. Labels present in the data can be excluded in this input, for example to calculate a multiclass average ignoring a majority negative class, while labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in y_true and y_pred are used in sorted order. Defaults to None.
- **pos_label** (`int`): The class label to use as the 'positive class' when calculating the recall. Defaults to `1`.
- **average** (`string`): This parameter is required for multiclass/multilabel targets. If None, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `'binary'`.
    - `'binary'`: Only report results for the class specified by `pos_label`. This is applicable only if the target labels and predictions are binary.
    - `'micro'`: Calculate metrics globally by counting the total true positives, false negatives, and false positives.
    - `'macro'`: Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account.
    - `'weighted'`: Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters `'macro'` to account for label imbalance. Note that it can result in an F-score that is not between precision and recall.
    - `'samples'`: Calculate metrics for each instance, and find their average (only meaningful for multilabel classification).
- **sample_weight** (`list` of `float`): Sample weights Defaults to `None`.
- **zero_division** (): Sets the value to return when there is a zero division. Defaults to .
    - `'warn'`: If there is a zero division, the return value is `0`, but warnings are also raised.
    - `0`: If there is a zero division, the return value is `0`.
    - `1`: If there is a zero division, the return value is `1`.

Returns:
- **recall** (`float`, or `array` of `float`): Either the general recall score, or the recall scores for individual classes, depending on the values input to `labels` and `average`. Minimum possible value is 0. Maximum possible value is 1. A higher recall means that more of the positive examples have been labeled correctly. Therefore, a higher recall is generally considered better.

Examples:

    Example 1-A simple example with some errors
        >>> recall_metric = datasets.load_metric('recall')
        >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1])
        >>> print(results)
        {'recall': 0.6666666666666666}

    Example 2-The same example as Example 1, but with `pos_label=0` instead of the default `pos_label=1`.
        >>> recall_metric = datasets.load_metric('recall')
        >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1], pos_label=0)
        >>> print(results)
        {'recall': 0.5}

    Example 3-The same example as Example 1, but with `sample_weight` included.
        >>> recall_metric = datasets.load_metric('recall')
        >>> sample_weight = [0.9, 0.2, 0.9, 0.3, 0.8]
        >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1], sample_weight=sample_weight)
        >>> print(results)
        {'recall': 0.55}

    Example 4-A multiclass example, using different averages.
        >>> recall_metric = datasets.load_metric('recall')
        >>> predictions = [0, 2, 1, 0, 0, 1]
        >>> references = [0, 1, 2, 0, 1, 2]
        >>> results = recall_metric.compute(predictions=predictions, references=references, average='macro')
        >>> print(results)
        {'recall': 0.3333333333333333}
        >>> results = recall_metric.compute(predictions=predictions, references=references, average='micro')
        >>> print(results)
        {'recall': 0.3333333333333333}
        >>> results = recall_metric.compute(predictions=predictions, references=references, average='weighted')
        >>> print(results)
        {'recall': 0.3333333333333333}
        >>> results = recall_metric.compute(predictions=predictions, references=references, average=None)
        >>> print(results)
        {'recall': array([1., 0., 0.])}
"""


UpperCAmelCase__     						=  """
@article{scikit-learn, title={Scikit-learn: Machine Learning in {P}ython}, author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V. and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P. and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.}, journal={Journal of Machine Learning Research}, volume={12}, pages={2825--2830}, year={2011}
"""


@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION		,							_KWARGS_DESCRIPTION      )
class 				a (						datasets.Metric      ):


    def    lowerCAmelCase_     (    self		:     Tuple    ):
      return datasets.MetricInfo(
          description=_DESCRIPTION      , citation=_CITATION      , inputs_description=_KWARGS_DESCRIPTION      , features=datasets.Features(
              {
                  """predictions""": datasets.Sequence(datasets.Value("""int32"""    )    ),
                  """references""": datasets.Sequence(datasets.Value("""int32"""    )    ),
              }
              if self.config_name == """multilabel"""
              else {
                  """predictions""": datasets.Value("""int32"""    ),
                  """references""": datasets.Value("""int32"""    ),
              }    )      , reference_urls=["""https://scikit-learn.org/stable/modules/generated/sklearn.metrics.recall_score.html"""]      , )


    def    lowerCAmelCase_     (    self		:     List[Any]      , __lowerCAmelCase		:     int      , __lowerCAmelCase		:     Optional[Any]      , __lowerCAmelCase		:     int=None      , __lowerCAmelCase		:     Dict=1      , __lowerCAmelCase		:     List[str]="binary"      , __lowerCAmelCase		:     Any=None      , __lowerCAmelCase		:     int="warn"      , ):
      _UpperCAmelCase         =					recall_score(
          __lowerCAmelCase      , __lowerCAmelCase      , labels=__lowerCAmelCase      , pos_label=__lowerCAmelCase      , average=__lowerCAmelCase      , sample_weight=__lowerCAmelCase      , zero_division=__lowerCAmelCase      , )
      return {"recall": float(__lowerCAmelCase    ) if score.size == 1 else score}
