





'''simple docstring'''






import coval  # From: git+https://github.com/ns-moosavi/coval.git # noqa: F401
from coval.conll import reader, util
from coval.eval import evaluator

import datasets


A   : Tuple             =			datasets.logging.get_logger(__name__)


A   : Tuple             =			'\\n@InProceedings{moosavi2019minimum,\n    author = { Nafise Sadat Moosavi, Leo Born, Massimo Poesio and Michael Strube},\n    title = {Using Automatically Extracted Minimum Spans to Disentangle Coreference Evaluation from Boundary Detection},\n    year = {2019},\n    booktitle = {Proceedings of the 57th Annual Meeting of\n        the Association for Computational Linguistics (Volume 1: Long Papers)},\n    publisher = {Association for Computational Linguistics},\n    address = {Florence, Italy},\n}\n\n@inproceedings{10.3115/1072399.1072405,\nauthor = {Vilain, Marc and Burger, John and Aberdeen, John and Connolly, Dennis and Hirschman, Lynette},\ntitle = {A Model-Theoretic Coreference Scoring Scheme},\nyear = {1995},\nisbn = {1558604022},\npublisher = {Association for Computational Linguistics},\naddress = {USA},\nurl = {https://doi.org/10.3115/1072399.1072405},\ndoi = {10.3115/1072399.1072405},\nbooktitle = {Proceedings of the 6th Conference on Message Understanding},\npages = {45–52},\nnumpages = {8},\nlocation = {Columbia, Maryland},\nseries = {MUC6 ’95}\n}\n\n@INPROCEEDINGS{Bagga98algorithmsfor,\n    author = {Amit Bagga and Breck Baldwin},\n    title = {Algorithms for Scoring Coreference Chains},\n    booktitle = {In The First International Conference on Language Resources and Evaluation Workshop on Linguistics Coreference},\n    year = {1998},\n    pages = {563--566}\n}\n\n@INPROCEEDINGS{Luo05oncoreference,\n    author = {Xiaoqiang Luo},\n    title = {On coreference resolution performance metrics},\n    booktitle = {In Proc. of HLT/EMNLP},\n    year = {2005},\n    pages = {25--32},\n    publisher = {URL}\n}\n\n@inproceedings{moosavi-strube-2016-coreference,\n    title = "Which Coreference Evaluation Metric Do You Trust? A Proposal for a Link-based Entity Aware Metric",\n    author = "Moosavi, Nafise Sadat  and\n      Strube, Michael",\n    booktitle = "Proceedings of the 54th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)",\n    month = aug,\n    year = "2016",\n    address = "Berlin, Germany",\n    publisher = "Association for Computational Linguistics",\n    url = "https://www.aclweb.org/anthology/P16-1060",\n    doi = "10.18653/v1/P16-1060",\n    pages = "632--642",\n}\n\n'

A   : Tuple             =			'\\nCoVal is a coreference evaluation tool for the CoNLL and ARRAU datasets which\nimplements of the common evaluation metrics including MUC [Vilain et al, 1995],\nB-cubed [Bagga and Baldwin, 1998], CEAFe [Luo et al., 2005],\nLEA [Moosavi and Strube, 2016] and the averaged CoNLL score\n(the average of the F1 values of MUC, B-cubed and CEAFe)\n[Denis and Baldridge, 2009a; Pradhan et al., 2011].\n\nThis wrapper of CoVal currently only work with CoNLL line format:\nThe CoNLL format has one word per line with all the annotation for this word in column separated by spaces:\nColumn	Type	Description\n1	Document ID	This is a variation on the document filename\n2	Part number	Some files are divided into multiple parts numbered as 000, 001, 002, ... etc.\n3	Word number\n4	Word itself	This is the token as segmented/tokenized in the Treebank. Initially the *_skel file contain the placeholder [WORD] which gets replaced by the actual token from the Treebank which is part of the OntoNotes release.\n5	Part-of-Speech\n6	Parse bit	This is the bracketed structure broken before the first open parenthesis in the parse, and the word/part-of-speech leaf replaced with a *. The full parse can be created by substituting the asterix with the "([pos] [word])" string (or leaf) and concatenating the items in the rows of that column.\n7	Predicate lemma	The predicate lemma is mentioned for the rows for which we have semantic role information. All other rows are marked with a "-"\n8	Predicate Frameset ID	This is the PropBank frameset ID of the predicate in Column 7.\n9	Word sense	This is the word sense of the word in Column 3.\n10	Speaker/Author	This is the speaker or author name where available. Mostly in Broadcast Conversation and Web Log data.\n11	Named Entities	These columns identifies the spans representing various named entities.\n12:N	Predicate Arguments	There is one column each of predicate argument structure information for the predicate mentioned in Column 7.\nN	Coreference	Coreference chain information encoded in a parenthesis structure.\nMore informations on the format can be found here (section "*_conll File Format"): http://www.conll.cemantix.org/2012/data.html\n\nDetails on the evaluation on CoNLL can be found here: https://github.com/ns-moosavi/coval/blob/master/conll/README.md\n\nCoVal code was written by @ns-moosavi.\nSome parts are borrowed from https://github.com/clarkkev/deep-coref/blob/master/evaluation.py\nThe test suite is taken from https://github.com/conll/reference-coreference-scorers/\nMention evaluation and the test suite are added by @andreasvc.\nParsing CoNLL files is developed by Leo Born.\n'

A   : str             =			'\nCalculates coreference evaluation metrics.\nArgs:\n    predictions: list of sentences. Each sentence is a list of word predictions to score in the CoNLL format.\n        Each prediction is a word with its annotations as a string made of columns joined with spaces.\n        Only columns 4, 5, 6 and the last column are used (word, POS, Pars and coreference annotation)\n        See the details on the format in the description of the metric.\n    references: list of sentences. Each sentence is a list of word reference to score in the CoNLL format.\n        Each reference is a word with its annotations as a string made of columns joined with spaces.\n        Only columns 4, 5, 6 and the last column are used (word, POS, Pars and coreference annotation)\n        See the details on the format in the description of the metric.\n    keep_singletons: After extracting all mentions of key or system files,\n        mentions whose corresponding coreference chain is of size one,\n        are considered as singletons. The default evaluation mode will include\n        singletons in evaluations if they are included in the key or the system files.\n        By setting \'keep_singletons=False\', all singletons in the key and system files\n        will be excluded from the evaluation.\n    NP_only: Most of the recent coreference resolvers only resolve NP mentions and\n        leave out the resolution of VPs. By setting the \'NP_only\' option, the scorer will only evaluate the resolution of NPs.\n    min_span: By setting \'min_span\', the scorer reports the results based on automatically detected minimum spans.\n        Minimum spans are determined using the MINA algorithm.\n\nReturns:\n    \'mentions\': mentions\n    \'muc\': MUC metric [Vilain et al, 1995]\n    \'bcub\': B-cubed [Bagga and Baldwin, 1998]\n    \'ceafe\': CEAFe [Luo et al., 2005]\n    \'lea\': LEA [Moosavi and Strube, 2016]\n    \'conll_score\': averaged CoNLL score (the average of the F1 values of MUC, B-cubed and CEAFe)\n\nExamples:\n\n    >>> coval = datasets.load_metric(\'coval\')\n    >>> words = [\'bc/cctv/00/cctv_0005   0   0       Thank   VBP  (TOP(S(VP*    thank  01   1    Xu_li  *           (V*)        *       -\',\n    ... \'bc/cctv/00/cctv_0005   0   1         you   PRP        (NP*)      -    -   -    Xu_li  *        (ARG1*)   (ARG0*)   (116)\',\n    ... \'bc/cctv/00/cctv_0005   0   2    everyone    NN        (NP*)      -    -   -    Xu_li  *    (ARGM-DIS*)        *    (116)\',\n    ... \'bc/cctv/00/cctv_0005   0   3         for    IN        (PP*       -    -   -    Xu_li  *        (ARG2*         *       -\',\n    ... \'bc/cctv/00/cctv_0005   0   4    watching   VBG   (S(VP*))))   watch  01   1    Xu_li  *             *)      (V*)      -\',\n    ... \'bc/cctv/00/cctv_0005   0   5           .     .          *))      -    -   -    Xu_li  *             *         *       -\']\n    >>> references = [words]\n    >>> predictions = [words]\n    >>> results = coval.compute(predictions=predictions, references=references)\n    >>> print(results) # doctest:+ELLIPSIS\n    {\'mentions/recall\': 1.0,[...] \'conll_score\': 100.0}\n'





def       lowercase_      (		lowercase__				,  lowercase__				,  lowercase__=False				,  lowercase__=False				,  lowercase__=True				,  lowercase__=False				,  lowercase__="dummy_doc"						)   ->str:
						_snake_case:   List[str]  					=		{doc: key_lines}
						_snake_case:   int  					=		{doc: sys_lines}

						_snake_case:   int  					=		{}

						_snake_case:   List[str]  					=		0
						_snake_case:   Dict  					=		0
						_snake_case:   List[str]  					=		0
						_snake_case:   int  					=		0
						_snake_case:   int  					=		0
						_snake_case:   int  					=		0

						_snake_case					,						_snake_case:   List[str]  					=		reader.get_doc_mentions(lowercase__				,  key_doc_lines[doc]				,  lowercase__						)
						key_singletons_num += singletons_num

						if NP_only or min_span:
												_snake_case:   Any  					=		reader.set_annotated_parse_trees(lowercase__				,  key_doc_lines[doc]				,  lowercase__				,  lowercase__						)

						_snake_case					,						_snake_case:   Dict  					=		reader.get_doc_mentions(lowercase__				,  sys_doc_lines[doc]				,  lowercase__						)
						sys_singletons_num += singletons_num

						if NP_only or min_span:
												_snake_case:   Dict  					=		reader.set_annotated_parse_trees(lowercase__				,  key_doc_lines[doc]				,  lowercase__				,  lowercase__						)

						if remove_nested:
												_snake_case					,						_snake_case:   List[Any]  					=		reader.remove_nested_coref_mentions(lowercase__				,  lowercase__						)
												key_nested_coref_num += nested_mentions
												key_removed_nested_clusters += removed_clusters

												_snake_case					,						_snake_case:   str  					=		reader.remove_nested_coref_mentions(lowercase__				,  lowercase__						)
												sys_nested_coref_num += nested_mentions
												sys_removed_nested_clusters += removed_clusters

						_snake_case:   Tuple  					=		reader.get_mention_assignments(lowercase__				,  lowercase__						)
						_snake_case:   List[str]  					=		reader.get_mention_assignments(lowercase__				,  lowercase__						)

						_snake_case:   Tuple  					=		(key_clusters, sys_clusters, key_mention_sys_cluster, sys_mention_key_cluster)

						if remove_nested:
												logger.info(
												    'Number of removed nested coreferring mentions in the key '
												    F'''annotation: {key_nested_coref_num}; and system annotation: {sys_nested_coref_num}'''						)
												logger.info(
												    'Number of resulting singleton clusters in the key '
												    F'''annotation: {key_removed_nested_clusters}; and system annotation: {sys_removed_nested_clusters}'''						)

						if not keep_singletons:
												logger.info(
												    F'''{key_singletons_num:d} and {sys_singletons_num:d} singletons are removed from the key and system '''
												    'files, respectively'						)

						return doc_coref_infos





def       lowercase_      (		lowercase__				,  lowercase__				,  lowercase__				,  lowercase__				,  lowercase__				,  lowercase__				,  lowercase__						)   ->int:
						_snake_case:   Optional[int]  					=		get_coref_infos(lowercase__				,  lowercase__				,  lowercase__				,  lowercase__				,  lowercase__				,  lowercase__						)

						_snake_case:   Optional[Any]  					=		{}
						_snake_case:   str  					=		0
						_snake_case:   str  					=		0

						for name, metric in metrics:
												_snake_case					,						_snake_case					,						_snake_case:   List[Any]  					=		evaluator.evaluate_documents(lowercase__				,  lowercase__				,  beta=1						)
												if name in ["muc", "bcub", "ceafe"]:
																		conll += fa
																		conll_subparts_num += 1
												output_scores.update({F'''{name}/recall''': recall, F'''{name}/precision''': precision, F'''{name}/f1''': fa}						)

												logger.info(
												    name.ljust(10						)				,  F'''Recall: {recall * 100:.2f}'''				,  F''' Precision: {precision * 100:.2f}'''				,  F''' F1: {fa * 100:.2f}'''				,  )

						if conll_subparts_num == 3:
												_snake_case:   List[str]  					=		(conll / 3) * 100
												logger.info(F'''CoNLL score: {conll:.2f}'''						)
												output_scores.update({'conll_score': conll}						)

						return output_scores





def       lowercase_      (		lowercase__						)   ->int:
						_snake_case:   Dict  					=		False
						for line in key_lines:
												if not line.startswith('#'						):
																		if len(line.split()						) > 6:
																								_snake_case:   Dict  					=		line.split()[5]
																								if not parse_col == "-":
																														_snake_case:   Optional[Any]  					=		True
																														break
																								else:
																														break
						return has_gold_parse







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


					def    SCREAMING_SNAKE_CASE_		(					self	:  str       ):





											'''simple docstring'''





											return datasets.MetricInfo(
											    description=_DESCRIPTION       ,     citation=_CITATION       ,     inputs_description=_KWARGS_DESCRIPTION       ,     features=datasets.Features(
											        {
											            'predictions': datasets.Sequence(datasets.Value('string'       )       ),
											            'references': datasets.Sequence(datasets.Value('string'       )       ),
											        }       )       ,     codebase_urls=['https://github.com/ns-moosavi/coval']       ,     reference_urls=[
											        'https://github.com/ns-moosavi/coval',
											        'https://www.aclweb.org/anthology/P16-1060',
											        'http://www.conll.cemantix.org/2012/data.html',
											    ]       ,     )




					def    SCREAMING_SNAKE_CASE_		(					self	:  Dict       ,     __snake_case	:  Any       ,     __snake_case	:  str       ,     __snake_case	:  int=True       ,     __snake_case	:  Tuple=False       ,     __snake_case	:  int=False       ,     __snake_case	:  Dict=False       ):





											'''simple docstring'''





											_snake_case:   Any  					=		[
											    ('mentions', evaluator.mentions),
											    ('muc', evaluator.muc),
											    ('bcub', evaluator.b_cubed),
											    ('ceafe', evaluator.ceafe),
											    ('lea', evaluator.lea),
											]

											if min_span:
																	_snake_case:   int  					=		util.check_gold_parse_annotation(__snake_case       )
																	if not has_gold_parse:
																							raise NotImplementedError('References should have gold parse annotation to use \'min_span\'.'       )
																							# util.parse_key_file(key_file)
																							# key_file = key_file + ".parsed"

											_snake_case:   Tuple  					=		evaluate(
											    key_lines=__snake_case       ,     sys_lines=__snake_case       ,     metrics=__snake_case       ,     NP_only=__snake_case       ,     remove_nested=__snake_case       ,     keep_singletons=__snake_case       ,     min_span=__snake_case       ,     )

											return score












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





