





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      lowerCamelCase_						(				_UpperCamelCase ,				_UpperCamelCase )		->						Any:






				"""simple docstring"""


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






def      lowerCamelCase_						(				_UpperCamelCase ,				_UpperCamelCase=False )		->						str:






				"""simple docstring"""


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






def      lowerCamelCase_						(				_UpperCamelCase )		->						int:






				"""simple docstring"""


				logger.info('''lv, h >\t''' + '''\t'''.join(f'''{x + 1}''' for x in range(len(_UpperCamelCase ) ) ) )
				for row in range(len(_UpperCamelCase ) ):
								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      lowerCamelCase_						(				_UpperCamelCase ,				_UpperCamelCase ,				_UpperCamelCase ,				_UpperCamelCase=True ,				_UpperCamelCase=True ,				_UpperCamelCase=None ,				_UpperCamelCase=False )		->						Tuple:






				"""simple docstring"""


				snake_case_			,							snake_case_						:    Optional[int]				=  model.config.num_hidden_layers, model.config.num_attention_heads
				snake_case_						:    Optional[int]				=  torch.zeros(_UpperCamelCase ,				_UpperCamelCase ).to(args.device )
				snake_case_						:    Tuple				=  torch.zeros(_UpperCamelCase ,				_UpperCamelCase ).to(args.device )

				if head_mask is None:
								snake_case_						:    Optional[Any]				=  torch.ones(_UpperCamelCase ,				_UpperCamelCase ).to(args.device )

				head_mask.requires_grad_(requires_grad=_UpperCamelCase )
				# If actually pruned attention multi-head, set head mask to None to avoid shape mismatch
				if actually_pruned:
								snake_case_						:    Optional[int]				=  None

				snake_case_						:    Dict				=  0.0
				snake_case_						:    Tuple				=  0.0
				for step, inputs in enumerate(tqdm(_UpperCamelCase ,				desc='''Iteration''' ,				disable=args.local_rank not in [-1, 0] ) ):
								snake_case_						:    List[str]				=  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_						:    List[str]				=  model(_UpperCamelCase ,				labels=_UpperCamelCase ,				head_mask=_UpperCamelCase )
								#  (loss), lm_logits, presents, (all hidden_states), (attentions)
								snake_case_			,							snake_case_			,							snake_case_						:    str				=  (
								    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(_UpperCamelCase ):
																snake_case_						:    List[Any]				=  entropy(attn.detach() ,				_UpperCamelCase )
																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(_UpperCamelCase ).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_						:    Optional[int]				=  2
								snake_case_						:    List[Any]				=  torch.pow(torch.pow(_UpperCamelCase ,				_UpperCamelCase ).sum(-1 ) ,				1 / exponent )
								head_importance /= norm_by_layer.unsqueeze(-1 ) + 1E-20

				if not args.dont_normalize_global_importance:
								snake_case_						:    Dict				=  (head_importance - head_importance.min()) / (head_importance.max() - head_importance.min())

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






def      lowerCamelCase_						(				_UpperCamelCase ,				_UpperCamelCase ,				_UpperCamelCase )		->						List[str]:






				"""simple docstring"""


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

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

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

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

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

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

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

				return head_mask






def      lowerCamelCase_						(				_UpperCamelCase ,				_UpperCamelCase ,				_UpperCamelCase ,				_UpperCamelCase )		->						Optional[int]:






				"""simple docstring"""


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

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

				for k, v in heads_to_prune.items():
								if isinstance(_UpperCamelCase ,				_UpperCamelCase ):
												snake_case_						:    Dict				=  [
												    v,
												]

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

				snake_case_						:    str				=  datetime.now()
				snake_case_			,							snake_case_			,							snake_case_						:    Tuple				=  compute_heads_importance(
				    _UpperCamelCase ,				_UpperCamelCase ,				_UpperCamelCase ,				compute_entropy=_UpperCamelCase ,				compute_importance=_UpperCamelCase ,				head_mask=_UpperCamelCase ,				actually_pruned=_UpperCamelCase ,				)

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

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






def      lowerCamelCase_						(				)		->						Optional[Any]:






				"""simple docstring"""


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

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

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

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

				# Setup devices and distributed training
				if args.local_rank == -1 or args.no_cuda:
								snake_case_						:    Optional[int]				=  torch.device('''cuda''' if torch.cuda.is_available() and not args.no_cuda else '''cpu''' )
								snake_case_						:    List[str]				=  0 if args.no_cuda else torch.cuda.device_count()
				else:
								torch.cuda.set_device(args.local_rank )
								snake_case_						:    Union[str, Any]				=  torch.device('''cuda''' ,				args.local_rank )
								snake_case_						:    Tuple				=  1
								torch.distributed.init_process_group(backend='''nccl''' )  # Initializes the distributed backend

				# Setup logging
				logging.basicConfig(level=logging.INFO if args.local_rank in [-1, 0] else logging.WARN )
				logger.info('''device: {} n_gpu: {}, distributed: {}'''.format(args.device ,				args.n_gpu ,				bool(args.local_rank != -1 ) ) )

				snake_case_						:    Optional[int]				=  GPTaLMHeadModel.from_pretrained(args.model_name_or_path )

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

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

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

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

				# 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_						:    Any				=  mask_heads(_UpperCamelCase ,				_UpperCamelCase ,				_UpperCamelCase )
								prune_heads(_UpperCamelCase ,				_UpperCamelCase ,				_UpperCamelCase ,				_UpperCamelCase )


if __name__ == "__main__":
	main()







def      lowerCamelCase_						(				_UpperCamelCase ,				_UpperCamelCase )		->						List[str]:






				"""simple docstring"""


				print('''\nThe shortest path matrix using Floyd Warshall algorithm\n''' )
				for i in range(_UpperCamelCase ):
								for j in range(_UpperCamelCase ):
												if dist[i][j] != float('''inf''' ):
																print(int(dist[i][j] ) ,				end='''\t''' )
												else:
																print('''INF''' ,				end='''\t''' )
								print()






def      lowerCamelCase_						(				_UpperCamelCase ,				_UpperCamelCase )		->						Union[str, Any]:






				"""simple docstring"""


				snake_case_						:    int				=  [[float('''inf''' ) for _ in range(_UpperCamelCase )] for _ in range(_UpperCamelCase )]

				for i in range(_UpperCamelCase ):
								for j in range(_UpperCamelCase ):
												snake_case_						:    Dict				=  graph[i][j]

												# check vertex k against all other vertices (i, j)
				for k in range(_UpperCamelCase ):
								# looping through rows of graph array
								for i in range(_UpperCamelCase ):
												# looping through columns of graph array
												for j in range(_UpperCamelCase ):
																if (
																    dist[i][k] != float('''inf''' )
																    and dist[k][j] != float('''inf''' )
																    and dist[i][k] + dist[k][j] < dist[i][j]
																):
																				snake_case_						:    List[Any]				=  dist[i][k] + dist[k][j]

				_print_dist(_UpperCamelCase ,				_UpperCamelCase )
				return dist, v


if __name__ == "__main__":
	lowerCAmelCase_    =				int(input('''Enter number of vertices: '''))
	lowerCAmelCase_    =				int(input('''Enter number of edges: '''))

	lowerCAmelCase_    =				[[float('''inf''') for i in range(v)] for j in range(v)]

	for i in range(v):
		lowerCAmelCase_    =				0.0

		# src and dst are indices that must be within the array size graph[e][v]
		# failure to follow this will result in an error
	for i in range(e):
		print('''\nEdge ''', i + 1)
		lowerCAmelCase_    =				int(input('''Enter source:'''))
		lowerCAmelCase_    =				int(input('''Enter destination:'''))
		lowerCAmelCase_    =				float(input('''Enter weight:'''))
		lowerCAmelCase_    =				weight

	floyd_warshall(graph, v)

	# Example Input
	# Enter number of vertices: 3
	# Enter number of edges: 2

	# # generated graph from vertex and edge inputs
	# [[inf, inf, inf], [inf, inf, inf], [inf, inf, inf]]
	# [[0.0, inf, inf], [inf, 0.0, inf], [inf, inf, 0.0]]

	# specify source, destination and weight for edge #1
	# Edge  1
	# Enter source:1
	# Enter destination:2
	# Enter weight:2

	# specify source, destination and weight for edge #2
	# Edge  2
	# Enter source:2
	# Enter destination:1
	# Enter weight:1

	# # Expected Output from the vertice, edge and src, dst, weight inputs!!
	# 0		INF	INF
	# INF	0	2
	# INF	1	0
