




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


A   : Union[str, Any]             =			logging.getLogger(__name__)





def       lowercase_      (		lowercase__				,  lowercase__						)   ->Union[str, Any]:





						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       lowercase_      (		lowercase__				,  lowercase__=False						)   ->Any:
						_snake_case:   str  					=		2
						if unlogit:
												_snake_case:   Tuple  					=		torch.pow(_lowerCamelCase				,  _lowerCamelCase						)
						_snake_case:   Optional[int]  					=		p * torch.log(_lowerCamelCase						)
						_snake_case:   Optional[int]  					=		0
						return -plogp.sum(dim=-1						)





def       lowercase_      (		lowercase__						)   ->Union[str, Any]:
						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       lowercase_      (		lowercase__				,  lowercase__				,  lowercase__				,  lowercase__=True				,  lowercase__=True				,  lowercase__=None				,  lowercase__=False						)   ->int:
						_snake_case:   List[Any]  					=		model.config.num_hidden_layers, model.config.num_attention_heads
						_snake_case:   Optional[Any]  					=		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:   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:
												_snake_case:   Optional[Any]  					=		None

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

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





def       lowercase_      (		lowercase__				,  lowercase__				,  lowercase__						)   ->str:
						_snake_case:   Tuple  					=		compute_heads_importance(_lowerCamelCase				,  _lowerCamelCase				,  _lowerCamelCase				,  compute_entropy=_lowerCamelCase						)
						_snake_case:   int  					=		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:   List[str]  					=		max(1				,  int(new_head_mask.numel() * args.masking_amount						)						)

						_snake_case:   Dict  					=		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:   Optional[int]  					=		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:   Tuple  					=		current_heads_to_mask[:num_to_mask]
												logger.info('Heads to mask: %s'				,  str(current_heads_to_mask.tolist()						)						)
												_snake_case:   int  					=		new_head_mask.view(-1						)
												_snake_case:   Optional[Any]  					=		0.0
												_snake_case:   Optional[Any]  					=		new_head_mask.view_as(_lowerCamelCase						)
												_snake_case:   Any  					=		new_head_mask.clone().detach()
												print_ad_tensor(_lowerCamelCase						)

												# Compute metric and head importance again
												_snake_case:   Union[str, Any]  					=		compute_heads_importance(
												    _lowerCamelCase				,  _lowerCamelCase				,  _lowerCamelCase				,  compute_entropy=_lowerCamelCase				,  head_mask=_lowerCamelCase						)
												_snake_case:   Optional[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() * 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       lowercase_      (		lowercase__				,  lowercase__				,  lowercase__				,  lowercase__						)   ->str:
						_snake_case:   int  					=		datetime.now()
						_snake_case:   List[str]  					=		compute_heads_importance(
						    _lowerCamelCase				,  _lowerCamelCase				,  _lowerCamelCase				,  compute_entropy=_lowerCamelCase				,  compute_importance=_lowerCamelCase				,  head_mask=_lowerCamelCase						)
						_snake_case:   int  					=		1 / loss
						_snake_case:   Optional[Any]  					=		datetime.now() - before_time

						_snake_case:   Tuple  					=		sum(p.numel() for p in model.parameters()						)
						_snake_case:   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						):
																		_snake_case:   Optional[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:   Union[str, Any]  					=		sum(p.numel() for p in model.parameters()						)

						_snake_case:   Dict  					=		datetime.now()
						_snake_case:   List[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:   Optional[int]  					=		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       lowercase_      (		)   ->Dict:
						_snake_case:   Optional[int]  					=		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:   Dict  					=		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:   List[str]  					=		torch.device('cuda' if torch.cuda.is_available() and not args.no_cuda else 'cpu'						)
												_snake_case:   List[Any]  					=		0 if args.no_cuda else torch.cuda.device_count()
						else:
												torch.cuda.set_device(args.local_rank						)
												_snake_case:   Optional[Any]  					=		torch.device('cuda'				,  args.local_rank						)
												_snake_case:   Optional[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:   List[str]  					=		GPTaLMHeadModel.from_pretrained(args.model_name_or_path						)

						# Distributed and parallel training
						model.to(args.device						)
						if args.local_rank != -1:
												_snake_case:   List[Any]  					=		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:   Union[str, 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:   Union[str, Any]  					=		np.concatenate(
						    [
						        np.loadtxt(args.data_dir				,  dtype=np.intaa						),
						    ]						)
						_snake_case:   str  					=		(torch.from_numpy(_lowerCamelCase						),)
						_snake_case:   int  					=		TensorDataset(*_lowerCamelCase						)
						_snake_case:   Union[str, Any]  					=		RandomSampler(_lowerCamelCase						)
						_snake_case:   List[str]  					=		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:   int  					=		mask_heads(_lowerCamelCase				,  _lowerCamelCase				,  _lowerCamelCase						)
												prune_heads(_lowerCamelCase				,  _lowerCamelCase				,  _lowerCamelCase				,  _lowerCamelCase						)


if __name__ == "__main__":
		main()












'''simple docstring'''






import unittest

from parameterized import parameterized

from transformers import LlamaConfig, is_torch_available, set_seed
from transformers.testing_utils import require_torch, slow, torch_device

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
		import torch

		from transformers import LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaTokenizer







class 			lowerCamelCase					:


					def __init__(					self	:  Optional[int]       ,     __snake_case	:  int       ,     __snake_case	:  Tuple=13       ,     __snake_case	:  Any=7       ,     __snake_case	:  Union[str, Any]=True       ,     __snake_case	:  List[str]=True       ,     __snake_case	:  Optional[int]=False       ,     __snake_case	:  List[Any]=True       ,     __snake_case	:  str=99       ,     __snake_case	:  Optional[int]=32       ,     __snake_case	:  Any=5       ,     __snake_case	:  Tuple=4       ,     __snake_case	:  List[Any]=37       ,     __snake_case	:  Union[str, Any]="gelu"       ,     __snake_case	:  List[str]=0.1       ,     __snake_case	:  int=0.1       ,     __snake_case	:  Any=5_12       ,     __snake_case	:  Dict=16       ,     __snake_case	:  int=2       ,     __snake_case	:  Any=0.02       ,     __snake_case	:  Any=3       ,     __snake_case	:  str=4       ,     __snake_case	:  int=None       ,     ):





											'''simple docstring'''





											_snake_case:   Dict  					=		parent
											_snake_case:   Optional[int]  					=		batch_size
											_snake_case:   List[Any]  					=		seq_length
											_snake_case:   Union[str, Any]  					=		is_training
											_snake_case:   Optional[Any]  					=		use_input_mask
											_snake_case:   Dict  					=		use_token_type_ids
											_snake_case:   Any  					=		use_labels
											_snake_case:   Optional[Any]  					=		vocab_size
											_snake_case:   List[Any]  					=		hidden_size
											_snake_case:   int  					=		num_hidden_layers
											_snake_case:   List[str]  					=		num_attention_heads
											_snake_case:   List[Any]  					=		intermediate_size
											_snake_case:   Optional[Any]  					=		hidden_act
											_snake_case:   str  					=		hidden_dropout_prob
											_snake_case:   List[str]  					=		attention_probs_dropout_prob
											_snake_case:   Dict  					=		max_position_embeddings
											_snake_case:   Optional[Any]  					=		type_vocab_size
											_snake_case:   List[Any]  					=		type_sequence_label_size
											_snake_case:   List[str]  					=		initializer_range
											_snake_case:   List[str]  					=		num_labels
											_snake_case:   Tuple  					=		num_choices
											_snake_case:   Dict  					=		scope


					def    SCREAMING_SNAKE_CASE_		(					self	:  List[str]       ):





											'''simple docstring'''





											_snake_case:   str  					=		ids_tensor([self.batch_size, self.seq_length]       ,     self.vocab_size       )

											_snake_case:   int  					=		None
											if self.use_input_mask:
																	_snake_case:   List[Any]  					=		random_attention_mask([self.batch_size, self.seq_length]       )

											_snake_case:   List[Any]  					=		None
											if self.use_token_type_ids:
																	_snake_case:   str  					=		ids_tensor([self.batch_size, self.seq_length]       ,     self.type_vocab_size       )

											_snake_case:   Optional[int]  					=		None
											_snake_case:   Tuple  					=		None
											_snake_case:   Union[str, Any]  					=		None
											if self.use_labels:
																	_snake_case:   Any  					=		ids_tensor([self.batch_size]       ,     self.type_sequence_label_size       )
																	_snake_case:   Optional[int]  					=		ids_tensor([self.batch_size, self.seq_length]       ,     self.num_labels       )
																	_snake_case:   Optional[int]  					=		ids_tensor([self.batch_size]       ,     self.num_choices       )

											_snake_case:   Union[str, Any]  					=		self.get_config()

											return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels


					def    SCREAMING_SNAKE_CASE_		(					self	:  Optional[int]       ):





											'''simple docstring'''





											return LlamaConfig(
											    vocab_size=self.vocab_size       ,     hidden_size=self.hidden_size       ,     num_hidden_layers=self.num_hidden_layers       ,     num_attention_heads=self.num_attention_heads       ,     intermediate_size=self.intermediate_size       ,     hidden_act=self.hidden_act       ,     hidden_dropout_prob=self.hidden_dropout_prob       ,     attention_probs_dropout_prob=self.attention_probs_dropout_prob       ,     max_position_embeddings=self.max_position_embeddings       ,     type_vocab_size=self.type_vocab_size       ,     is_decoder=__snake_case       ,     initializer_range=self.initializer_range       ,     )


					def    SCREAMING_SNAKE_CASE_		(					self	:  Optional[int]       ,     __snake_case	:  List[Any]       ,     __snake_case	:  Any       ,     __snake_case	:  Any       ,     __snake_case	:  Union[str, Any]       ,     __snake_case	:  Optional[Any]       ,     __snake_case	:  Tuple       ,     __snake_case	:  int       ):





											'''simple docstring'''





											_snake_case:   Optional[Any]  					=		LlamaModel(config=__snake_case       )
											model.to(__snake_case       )
											model.eval()
											_snake_case:   Optional[Any]  					=		model(__snake_case       ,     attention_mask=__snake_case       )
											_snake_case:   Tuple  					=		model(__snake_case       )
											self.parent.assertEqual(result.last_hidden_state.shape       ,     (self.batch_size, self.seq_length, self.hidden_size)       )


					def    SCREAMING_SNAKE_CASE_		(					self	:  Union[str, Any]       ,     __snake_case	:  Any       ,     __snake_case	:  Tuple       ,     __snake_case	:  Tuple       ,     __snake_case	:  Dict       ,     __snake_case	:  str       ,     __snake_case	:  int       ,     __snake_case	:  List[str]       ,     __snake_case	:  Union[str, Any]       ,     __snake_case	:  Any       ,     ):





											'''simple docstring'''





											_snake_case:   str  					=		True
											_snake_case:   int  					=		LlamaModel(__snake_case       )
											model.to(__snake_case       )
											model.eval()
											_snake_case:   int  					=		model(
											    __snake_case       ,     attention_mask=__snake_case       ,     encoder_hidden_states=__snake_case       ,     encoder_attention_mask=__snake_case       ,     )
											_snake_case:   Optional[int]  					=		model(
											    __snake_case       ,     attention_mask=__snake_case       ,     encoder_hidden_states=__snake_case       ,     )
											_snake_case:   List[str]  					=		model(__snake_case       ,     attention_mask=__snake_case       )
											self.parent.assertEqual(result.last_hidden_state.shape       ,     (self.batch_size, self.seq_length, self.hidden_size)       )


					def    SCREAMING_SNAKE_CASE_		(					self	:  int       ,     __snake_case	:  List[str]       ,     __snake_case	:  Dict       ,     __snake_case	:  Dict       ,     __snake_case	:  List[str]       ,     __snake_case	:  Optional[int]       ,     __snake_case	:  int       ,     __snake_case	:  int       ,     __snake_case	:  List[Any]       ,     __snake_case	:  Union[str, Any]       ,     ):





											'''simple docstring'''





											_snake_case:   Union[str, Any]  					=		LlamaForCausalLM(config=__snake_case       )
											model.to(__snake_case       )
											model.eval()
											_snake_case:   str  					=		model(__snake_case       ,     attention_mask=__snake_case       ,     labels=__snake_case       )
											self.parent.assertEqual(result.logits.shape       ,     (self.batch_size, self.seq_length, self.vocab_size)       )


					def    SCREAMING_SNAKE_CASE_		(					self	:  int       ,     __snake_case	:  Dict       ,     __snake_case	:  List[Any]       ,     __snake_case	:  Optional[Any]       ,     __snake_case	:  Optional[int]       ,     __snake_case	:  Optional[Any]       ,     __snake_case	:  Optional[Any]       ,     __snake_case	:  Union[str, Any]       ,     __snake_case	:  Optional[int]       ,     __snake_case	:  Any       ,     ):





											'''simple docstring'''





											_snake_case:   Any  					=		True
											_snake_case:   Optional[int]  					=		True
											_snake_case:   List[str]  					=		LlamaForCausalLM(config=__snake_case       )
											model.to(__snake_case       )
											model.eval()

											# first forward pass
											_snake_case:   Dict  					=		model(
											    __snake_case       ,     attention_mask=__snake_case       ,     encoder_hidden_states=__snake_case       ,     encoder_attention_mask=__snake_case       ,     use_cache=__snake_case       ,     )
											_snake_case:   Optional[int]  					=		outputs.past_key_values

											# create hypothetical multiple next token and extent to next_input_ids
											_snake_case:   Any  					=		ids_tensor((self.batch_size, 3)       ,     config.vocab_size       )
											_snake_case:   str  					=		ids_tensor((self.batch_size, 3)       ,     vocab_size=2       )

											# append to next input_ids and
											_snake_case:   Tuple  					=		torch.cat([input_ids, next_tokens]       ,     dim=-1       )
											_snake_case:   Tuple  					=		torch.cat([input_mask, next_mask]       ,     dim=-1       )

											_snake_case:   Tuple  					=		model(
											    __snake_case       ,     attention_mask=__snake_case       ,     encoder_hidden_states=__snake_case       ,     encoder_attention_mask=__snake_case       ,     output_hidden_states=__snake_case       ,     )['hidden_states'][0]
											_snake_case:   Dict  					=		model(
											    __snake_case       ,     attention_mask=__snake_case       ,     encoder_hidden_states=__snake_case       ,     encoder_attention_mask=__snake_case       ,     past_key_values=__snake_case       ,     output_hidden_states=__snake_case       ,     )['hidden_states'][0]

											# select random slice
											_snake_case:   List[Any]  					=		ids_tensor((1,)       ,     output_from_past.shape[-1]       ).item()
											_snake_case:   str  					=		output_from_no_past[:, -3:, random_slice_idx].detach()
											_snake_case:   Tuple  					=		output_from_past[:, :, random_slice_idx].detach()

											self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1]       )

											# test that outputs are equal for slice
											self.parent.assertTrue(torch.allclose(__snake_case       ,     __snake_case       ,     atol=1e-3       )       )




					def    SCREAMING_SNAKE_CASE_		(					self	:  Tuple       ):





											'''simple docstring'''





											_snake_case:   List[str]  					=		self.prepare_config_and_inputs()
											(
											    (
											    _snake_case
											)					,						(
											    _snake_case
											)					,						(
											    _snake_case
											)					,						(
											    _snake_case
											)					,						(
											    _snake_case
											)					,						(
											    _snake_case
											)					,						(
											    _snake_case
											)					,						
											):   Dict  					=		config_and_inputs
											_snake_case:   Any  					=		{'input_ids': input_ids, 'attention_mask': input_mask}
											return config, inputs_dict







@require_torch
class 			lowerCamelCase					(						__UpperCAmelCase     ,							__UpperCAmelCase     ,							__UpperCAmelCase     ,							unittest.TestCase  ):
					_SCREAMING_SNAKE_CASE							   =    (LlamaModel, LlamaForCausalLM, LlamaForSequenceClassification) if is_torch_available() else ()
					_SCREAMING_SNAKE_CASE							   =    (LlamaForCausalLM,) if is_torch_available() else ()
					_SCREAMING_SNAKE_CASE							   =    (
					    {
					        "feature-extraction": LlamaModel,
					        "text-classification": LlamaForSequenceClassification,
					        "text-generation": LlamaForCausalLM,
					        "zero-shot": LlamaForSequenceClassification,
					    }
					    if is_torch_available()
					    else {}
					)
					_SCREAMING_SNAKE_CASE							   =    False
					_SCREAMING_SNAKE_CASE							   =    False


					def    SCREAMING_SNAKE_CASE_		(					self	:  str       ):





											'''simple docstring'''





											_snake_case:   Optional[int]  					=		LlamaModelTester(self       )
											_snake_case:   Dict  					=		ConfigTester(self       ,     config_class=__snake_case       ,     hidden_size=37       )


					def    SCREAMING_SNAKE_CASE_		(					self	:  List[str]       ):





											'''simple docstring'''





											self.config_tester.run_common_tests()


					def    SCREAMING_SNAKE_CASE_		(					self	:  Optional[Any]       ):





											'''simple docstring'''





											_snake_case:   str  					=		self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_model(*__snake_case       )


					def    SCREAMING_SNAKE_CASE_		(					self	:  str       ):





											'''simple docstring'''





											_snake_case:   Optional[Any]  					=		self.model_tester.prepare_config_and_inputs()
											for type in ["absolute", "relative_key", "relative_key_query"]:
																	_snake_case:   Union[str, Any]  					=		type
																	self.model_tester.create_and_check_model(*__snake_case       )


					def    SCREAMING_SNAKE_CASE_		(					self	:  List[Any]       ):





											'''simple docstring'''





											_snake_case					,						_snake_case:   Optional[Any]  					=		self.model_tester.prepare_config_and_inputs_for_common()
											_snake_case:   int  					=		3
											_snake_case:   Optional[Any]  					=		input_dict['input_ids']
											_snake_case:   Tuple  					=		input_ids.ne(1       ).to(__snake_case       )
											_snake_case:   Optional[Any]  					=		ids_tensor([self.model_tester.batch_size]       ,     self.model_tester.type_sequence_label_size       )
											_snake_case:   Union[str, Any]  					=		LlamaForSequenceClassification(__snake_case       )
											model.to(__snake_case       )
											model.eval()
											_snake_case:   str  					=		model(__snake_case       ,     attention_mask=__snake_case       ,     labels=__snake_case       )
											self.assertEqual(result.logits.shape       ,     (self.model_tester.batch_size, self.model_tester.num_labels)       )


					def    SCREAMING_SNAKE_CASE_		(					self	:  List[Any]       ):





											'''simple docstring'''





											_snake_case					,						_snake_case:   List[Any]  					=		self.model_tester.prepare_config_and_inputs_for_common()
											_snake_case:   Dict  					=		3
											_snake_case:   str  					=		'single_label_classification'
											_snake_case:   List[str]  					=		input_dict['input_ids']
											_snake_case:   Optional[int]  					=		input_ids.ne(1       ).to(__snake_case       )
											_snake_case:   List[str]  					=		ids_tensor([self.model_tester.batch_size]       ,     self.model_tester.type_sequence_label_size       )
											_snake_case:   Optional[Any]  					=		LlamaForSequenceClassification(__snake_case       )
											model.to(__snake_case       )
											model.eval()
											_snake_case:   Optional[Any]  					=		model(__snake_case       ,     attention_mask=__snake_case       ,     labels=__snake_case       )
											self.assertEqual(result.logits.shape       ,     (self.model_tester.batch_size, self.model_tester.num_labels)       )


					def    SCREAMING_SNAKE_CASE_		(					self	:  Union[str, Any]       ):





											'''simple docstring'''





											_snake_case					,						_snake_case:   int  					=		self.model_tester.prepare_config_and_inputs_for_common()
											_snake_case:   Any  					=		3
											_snake_case:   Optional[int]  					=		'multi_label_classification'
											_snake_case:   Tuple  					=		input_dict['input_ids']
											_snake_case:   Optional[Any]  					=		input_ids.ne(1       ).to(__snake_case       )
											_snake_case:   List[str]  					=		ids_tensor(
											    [self.model_tester.batch_size, config.num_labels]       ,     self.model_tester.type_sequence_label_size       ).to(torch.float       )
											_snake_case:   Union[str, Any]  					=		LlamaForSequenceClassification(__snake_case       )
											model.to(__snake_case       )
											model.eval()
											_snake_case:   Optional[int]  					=		model(__snake_case       ,     attention_mask=__snake_case       ,     labels=__snake_case       )
											self.assertEqual(result.logits.shape       ,     (self.model_tester.batch_size, self.model_tester.num_labels)       )


					@unittest.skip('LLaMA buffers include complex numbers, which breaks this test'       )
					def    SCREAMING_SNAKE_CASE_		(					self	:  Optional[int]       ):





											'''simple docstring'''





											pass




					@parameterized.expand([('linear',), ('dynamic',)]       )
					def    SCREAMING_SNAKE_CASE_		(					self	:  List[Any]       ,     __snake_case	:  Union[str, Any]       ):





											'''simple docstring'''





											_snake_case					,						_snake_case:   int  					=		self.model_tester.prepare_config_and_inputs_for_common()
											_snake_case:   Optional[int]  					=		ids_tensor([1, 10]       ,     config.vocab_size       )
											_snake_case:   Union[str, Any]  					=		ids_tensor([1, int(config.max_position_embeddings * 1.5       )]       ,     config.vocab_size       )

											set_seed(42       )  # Fixed seed at init time so the two models get the same random weights
											_snake_case:   Tuple  					=		LlamaModel(__snake_case       )
											original_model.to(__snake_case       )
											original_model.eval()
											_snake_case:   List[Any]  					=		original_model(__snake_case       ).last_hidden_state
											_snake_case:   List[str]  					=		original_model(__snake_case       ).last_hidden_state

											set_seed(42       )  # Fixed seed at init time so the two models get the same random weights
											_snake_case:   Tuple  					=		{'type': scaling_type, 'factor': 10.0}
											_snake_case:   List[Any]  					=		LlamaModel(__snake_case       )
											scaled_model.to(__snake_case       )
											scaled_model.eval()
											_snake_case:   Dict  					=		scaled_model(__snake_case       ).last_hidden_state
											_snake_case:   str  					=		scaled_model(__snake_case       ).last_hidden_state

											# Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original
											# maximum sequence length, so the outputs for the short input should match.
											if scaling_type == "dynamic":
																	self.assertTrue(torch.allclose(__snake_case       ,     __snake_case       ,     atol=1e-5       )       )
											else:
																	self.assertFalse(torch.allclose(__snake_case       ,     __snake_case       ,     atol=1e-5       )       )

											# The output should be different for long inputs
											self.assertFalse(torch.allclose(__snake_case       ,     __snake_case       ,     atol=1e-5       )       )







@require_torch
class 			lowerCamelCase					(						unittest.TestCase  ):


					@unittest.skip('Logits are not exactly the same, once we fix the instabalities somehow, will update!'       )
					@slow
					def    SCREAMING_SNAKE_CASE_		(					self	:  str       ):





											'''simple docstring'''





											_snake_case:   List[str]  					=		[1, 3_06, 46_58, 2_78, 65_93, 3_10, 28_34, 3_38]
											_snake_case:   Optional[int]  					=		LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-7b-hf'       ,     device_map='auto'       )
											_snake_case:   Optional[int]  					=		model(torch.tensor([input_ids]       )       )
											# Expected mean on dim = -1
											_snake_case:   List[Any]  					=		torch.tensor([[-6.6_550, -4.1_227, -4.9_859, -3.2_406, 0.8_262, -3.0_033, 1.2_964, -3.3_699]]       )
											torch.testing.assert_close(out.mean(-1       )       ,     __snake_case       ,     atol=1e-2       ,     rtol=1e-2       )
											# slicing logits[0, 0, 0:30]
											# fmt: off
											_snake_case:   Tuple  					=		torch.tensor([-12.8_281, -7.4_453, -0.4_639, -8.0_625, -7.2_500, -8.0_000, -6.4_883, -7.7_695, -7.8_438, -7.0_312, -6.2_188, -7.1_328, -1.8_496, 1.9_961, -8.6_250, -6.7_227, -12.8_281, -6.9_492, -7.0_742, -7.7_852, -7.5_820, -7.9_062, -6.9_375, -7.9_805, -8.3_438, -8.1_562, -8.0_469, -7.6_250, -7.7_422, -7.3_398,]       )
											# fmt: on
											torch.testing.assert_close(out[0, 0, :30]       ,     __snake_case       ,     atol=1e-5       ,     rtol=1e-5       )


					@unittest.skip('Logits are not exactly the same, once we fix the instabalities somehow, will update!'       )
					@slow
					def    SCREAMING_SNAKE_CASE_		(					self	:  Union[str, Any]       ):





											'''simple docstring'''





											_snake_case:   Union[str, Any]  					=		[1, 3_06, 46_58, 2_78, 65_93, 3_10, 28_34, 3_38]
											_snake_case:   Any  					=		LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-13b-hf'       ,     device_map='auto'       )
											_snake_case:   int  					=		model(torch.tensor(__snake_case       )       )
											# Expected mean on dim = -1
											_snake_case:   List[Any]  					=		torch.tensor([[-2.0_622, -1.2_794, -1.1_638, -0.9_788, -1.4_603, -1.0_238, -1.7_893, -1.4_411]]       )
											torch.testing.assert_close(out.mean(-1       )       ,     __snake_case       ,     atol=1e-2       ,     rtol=1e-2       )
											# slicing logits[0, 0, 0:30]
											# fmt: off
											_snake_case:   Optional[Any]  					=		torch.tensor([-8.1_406, -8.0_547, 2.7_461, -1.2_344, -0.1_448, -1.8_262, -1.0_020, -1.8_154, -1.6_895, -1.8_516, -2.3_574, -0.9_277, 3.7_598, 6.5_742, -1.2_998, -0.1_177, -8.1_406, -2.9_688, -2.9_199, -3.1_699, -3.5_254, -2.3_555, -2.7_988, -3.4_141, -2.8_262, -4.5_195, -3.3_379, -3.3_164, -2.7_832, -3.0_273]       )
											# fmt: on
											torch.testing.assert_close(out[0, 0, :30]       ,     __snake_case       ,     atol=1e-5       ,     rtol=1e-5       )


					@unittest.skip('Logits are not exactly the same, once we fix the instabalities somehow, will update!'       )
					@slow
					def    SCREAMING_SNAKE_CASE_		(					self	:  int       ):





											'''simple docstring'''





											_snake_case:   List[Any]  					=		[1, 3_06, 46_58, 2_78, 65_93, 3_10, 28_34, 3_38]
											_snake_case:   Any  					=		LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-13b-chat-hf'       ,     device_map='auto'       )
											_snake_case:   List[str]  					=		model(torch.tensor(__snake_case       )       )
											# Expected mean on dim = -1
											_snake_case:   List[Any]  					=		torch.tensor([[-0.8_562, -1.8_520, -0.7_551, -0.4_162, -1.5_161, -1.2_038, -2.4_823, -2.3_254]]       )
											torch.testing.assert_close(out.mean(-1       )       ,     __snake_case       ,     atol=1e-2       ,     rtol=1e-2       )
											# slicing logits[0, 0, 0:30]
											# fmt: off
											_snake_case:   Optional[int]  					=		torch.tensor([-2.2_227, 4.8_828, 0.9_023, -0.4_578, -0.7_871, -0.1_033, -0.6_221, -0.5_786, -0.7_803, -1.0_674, -1.2_920, -0.1_570, 0.8_008, 2.0_723, -0.9_497, 0.2_771, -2.2_227, -0.7_612, -1.4_346, -1.2_061, -1.6_426, -0.3_000, -0.7_139, -1.1_934, -1.8_691, -1.6_973, -1.5_947, -1.2_705, -0.3_523, -0.5_513]       )
											# fmt: on
											torch.testing.assert_close(out.mean(-1       )       ,     __snake_case       ,     atol=1e-2       ,     rtol=1e-2       )


					@unittest.skip(
					    'Logits are not exactly the same, once we fix the instabalities somehow, will update! Also it is gonna be a `too_slow` test'       )
					@slow
					def    SCREAMING_SNAKE_CASE_		(					self	:  str       ):





											'''simple docstring'''





											_snake_case:   int  					=		[1, 3_06, 46_58, 2_78, 65_93, 3_10, 28_34, 3_38]
											_snake_case:   Any  					=		LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-70b-hf'       ,     device_map='auto'       )
											_snake_case:   Dict  					=		model(torch.tensor(__snake_case       )       )

											_snake_case:   Optional[Any]  					=		torch.tensor(
											    [[-4.2_327, -3.3_360, -4.6_665, -4.7_631, -1.8_180, -3.4_170, -1.4_211, -3.1_810]]       ,     dtype=torch.floataa       )
											torch.testing.assert_close(out.mean(-1       )       ,     __snake_case       ,     atol=1e-2       ,     rtol=1e-2       )
											# fmt: off
											_snake_case:   str  					=		torch.tensor([-9.4_922, -3.9_551, 1.7_998, -5.6_758, -5.1_055, -5.8_984, -4.8_320, -6.8_086, -6.5_391, -5.6_172, -5.5_820, -5.5_352, 1.7_881, 3.6_289, -6.5_117, -3.4_785, -9.5_000, -6.0_352, -6.8_125, -6.0_195, -6.6_836, -5.4_727, -6.2_812, -6.0_391, -7.3_398, -7.4_297, -7.4_844, -6.5_820, -5.8_789, -5.5_312]       )
											# fmt: on
											torch.testing.assert_close(out[0, 0, :30]       ,     __snake_case       ,     atol=1e-5       ,     rtol=1e-5       )




					@unittest.skip('Model is curently gated'       )
					@slow
					def    SCREAMING_SNAKE_CASE_		(					self	:  int       ):





											'''simple docstring'''





											_snake_case:   Dict  					=		'Simply put, the theory of relativity states that 1) the laws of physics are the same everywhere in the universe and 2) the passage of time and the length of objects can vary depending on the observer\'s frame of reference.\n\nThe first part of the theory, that the laws of physics are the same everywhere, is known as the "princi'
											_snake_case:   Dict  					=		'Simply put, the theory of relativity states that '
											_snake_case:   List[str]  					=		LlamaTokenizer.from_pretrained('meta-llama/Llama-2-13b-chat-hf'       )
											_snake_case:   Optional[Any]  					=		tokenizer.encode(__snake_case       ,     return_tensors='pt'       )
											_snake_case:   Optional[int]  					=		LlamaForCausalLM.from_pretrained(
											    'meta-llama/Llama-2-13b-chat-hf'       ,     device_map='sequential'       ,     use_safetensors=__snake_case       )

											# greedy generation outputs
											_snake_case:   List[Any]  					=		model.generate(__snake_case       ,     max_new_tokens=64       ,     top_p=__snake_case       ,     temperature=1       ,     do_sample=__snake_case       )
											_snake_case:   Dict  					=		tokenizer.decode(generated_ids[0]       ,     skip_special_tokens=__snake_case       )
											self.assertEqual(__snake_case       ,     __snake_case       )





