


import unittest

from transformers import AutoTokenizer, FalconConfig, is_torch_available
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 (
				    FalconForCausalLM,
				    FalconForQuestionAnswering,
				    FalconForSequenceClassification,
				    FalconForTokenClassification,
				    FalconModel,
				)







class 	__lowercase    :





							"""simple docstring"""







							def __init__(      self			,						lowerCAmelCase__			,						lowerCAmelCase__=3			,						lowerCAmelCase__=7			,						lowerCAmelCase__=True			,						lowerCAmelCase__=True			,						lowerCAmelCase__=False			,						lowerCAmelCase__=True			,						lowerCAmelCase__=9_9			,						lowerCAmelCase__=3_2			,						lowerCAmelCase__=5			,						lowerCAmelCase__=4			,						lowerCAmelCase__=3_7			,						lowerCAmelCase__="gelu"			,						lowerCAmelCase__=0.1			,						lowerCAmelCase__=0.1			,						lowerCAmelCase__=5_1_2			,						lowerCAmelCase__=1_6			,						lowerCAmelCase__=2			,						lowerCAmelCase__=0.02			,						lowerCAmelCase__=3			,						lowerCAmelCase__=4			,						lowerCAmelCase__=None			,						):





										"""simple docstring"""




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






							def 					UpperCamelCase__     (      self       ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_		:     Optional[int]					=					ids_tensor([self.batch_size, self.seq_length]			,						self.vocab_size       )

										SCREAMING_SNAKE_CASE_		:     Union[str, Any]					=					None
										if self.use_input_mask:
													SCREAMING_SNAKE_CASE_		:     Any					=					random_attention_mask([self.batch_size, self.seq_length]       )

										SCREAMING_SNAKE_CASE_		:     List[Any]					=					None

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

										SCREAMING_SNAKE_CASE_		:     List[str]					=					self.get_config()

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






							def 					UpperCamelCase__     (      self       ):





										"""simple docstring"""




										return FalconConfig(
										    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=lowerCAmelCase__			,						initializer_range=self.initializer_range			,						pad_token_id=1			,						new_decoder_architecture=lowerCAmelCase__			,						)






							def 					UpperCamelCase__     (      self			,						lowerCAmelCase__			,						lowerCAmelCase__			,						lowerCAmelCase__			,						lowerCAmelCase__			,						lowerCAmelCase__			,						lowerCAmelCase__			,						lowerCAmelCase__       ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_		:     Dict					=					FalconModel(config=lowerCAmelCase__       )
										model.to(lowerCAmelCase__       )
										model.eval()
										SCREAMING_SNAKE_CASE_		:     Any					=					model(lowerCAmelCase__			,						attention_mask=lowerCAmelCase__       )
										SCREAMING_SNAKE_CASE_		:     List[Any]					=					model(lowerCAmelCase__       )
										self.parent.assertEqual(result.last_hidden_state.shape			,						(self.batch_size, self.seq_length, self.hidden_size)       )






							def 					UpperCamelCase__     (      self			,						lowerCAmelCase__			,						lowerCAmelCase__			,						lowerCAmelCase__			,						lowerCAmelCase__			,						lowerCAmelCase__			,						lowerCAmelCase__			,						lowerCAmelCase__			,						lowerCAmelCase__			,						lowerCAmelCase__			,						):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_		:     int					=					True
										SCREAMING_SNAKE_CASE_		:     int					=					FalconModel(lowerCAmelCase__       )
										model.to(lowerCAmelCase__       )
										model.eval()
										SCREAMING_SNAKE_CASE_		:     Tuple					=					model(
										    lowerCAmelCase__			,						attention_mask=lowerCAmelCase__			,						encoder_hidden_states=lowerCAmelCase__			,						encoder_attention_mask=lowerCAmelCase__			,						)
										SCREAMING_SNAKE_CASE_		:     Dict					=					model(
										    lowerCAmelCase__			,						attention_mask=lowerCAmelCase__			,						encoder_hidden_states=lowerCAmelCase__			,						)
										SCREAMING_SNAKE_CASE_		:     Union[str, Any]					=					model(lowerCAmelCase__			,						attention_mask=lowerCAmelCase__       )
										self.parent.assertEqual(result.last_hidden_state.shape			,						(self.batch_size, self.seq_length, self.hidden_size)       )






							def 					UpperCamelCase__     (      self			,						lowerCAmelCase__			,						lowerCAmelCase__			,						lowerCAmelCase__			,						lowerCAmelCase__			,						lowerCAmelCase__			,						lowerCAmelCase__			,						lowerCAmelCase__			,						lowerCAmelCase__			,						lowerCAmelCase__			,						):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_		:     Any					=					FalconForCausalLM(config=lowerCAmelCase__       )
										model.to(lowerCAmelCase__       )
										model.eval()
										SCREAMING_SNAKE_CASE_		:     Dict					=					model(lowerCAmelCase__			,						attention_mask=lowerCAmelCase__			,						labels=lowerCAmelCase__       )
										self.parent.assertEqual(result.logits.shape			,						(self.batch_size, self.seq_length, self.vocab_size)       )






							def 					UpperCamelCase__     (      self			,						lowerCAmelCase__			,						lowerCAmelCase__			,						lowerCAmelCase__			,						lowerCAmelCase__			,						lowerCAmelCase__			,						lowerCAmelCase__			,						lowerCAmelCase__			,						lowerCAmelCase__			,						lowerCAmelCase__			,						):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_		:     int					=					True
										SCREAMING_SNAKE_CASE_		:     Optional[Any]					=					True
										SCREAMING_SNAKE_CASE_		:     Union[str, Any]					=					FalconForCausalLM(config=lowerCAmelCase__       )
										model.to(lowerCAmelCase__       )
										model.eval()

										# first forward pass
										SCREAMING_SNAKE_CASE_		:     str					=					model(
										    lowerCAmelCase__			,						attention_mask=lowerCAmelCase__			,						encoder_hidden_states=lowerCAmelCase__			,						encoder_attention_mask=lowerCAmelCase__			,						use_cache=lowerCAmelCase__			,						)
										SCREAMING_SNAKE_CASE_		:     Optional[int]					=					outputs.past_key_values

										# create hypothetical multiple next token and extent to next_input_ids
										SCREAMING_SNAKE_CASE_		:     Optional[Any]					=					ids_tensor((self.batch_size, 3)			,						config.vocab_size       )
										SCREAMING_SNAKE_CASE_		:     int					=					ids_tensor((self.batch_size, 3)			,						vocab_size=2       )

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

										SCREAMING_SNAKE_CASE_		:     List[str]					=					model(
										    lowerCAmelCase__			,						attention_mask=lowerCAmelCase__			,						encoder_hidden_states=lowerCAmelCase__			,						encoder_attention_mask=lowerCAmelCase__			,						output_hidden_states=lowerCAmelCase__			,						)['hidden_states'][0]
										SCREAMING_SNAKE_CASE_		:     Any					=					model(
										    lowerCAmelCase__			,						attention_mask=lowerCAmelCase__			,						encoder_hidden_states=lowerCAmelCase__			,						encoder_attention_mask=lowerCAmelCase__			,						past_key_values=lowerCAmelCase__			,						output_hidden_states=lowerCAmelCase__			,						)['hidden_states'][0]

										# select random slice
										SCREAMING_SNAKE_CASE_		:     List[Any]					=					ids_tensor((1,)			,						output_from_past.shape[-1]       ).item()
										SCREAMING_SNAKE_CASE_		:     str					=					output_from_no_past[:, -3:, random_slice_idx].detach()
										SCREAMING_SNAKE_CASE_		:     str					=					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(lowerCAmelCase__			,						lowerCAmelCase__			,						atol=1E-3       )       )






							def 					UpperCamelCase__     (      self       ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_		:     Any					=					self.prepare_config_and_inputs()
										(
										    (
										    SCREAMING_SNAKE_CASE_
										)		,      (
										    SCREAMING_SNAKE_CASE_
										)		,      (
										    SCREAMING_SNAKE_CASE_
										)		,      (
										    SCREAMING_SNAKE_CASE_
										)		,      (
										    SCREAMING_SNAKE_CASE_
										)		,      (
										    SCREAMING_SNAKE_CASE_
										)		,      (
										    SCREAMING_SNAKE_CASE_
										)		,      
										)		:     Any					=					config_and_inputs
										SCREAMING_SNAKE_CASE_		:     str					=					{'input_ids': input_ids, 'attention_mask': input_mask}
										return config, inputs_dict







@require_torch
class 	__lowercase    (__SCREAMING_SNAKE_CASE	,       __SCREAMING_SNAKE_CASE	,       __SCREAMING_SNAKE_CASE	,       unittest.TestCase  ):





							"""simple docstring"""







							_UpperCAmelCase      =						(
							    (
							        FalconModel,
							        FalconForCausalLM,
							        FalconForSequenceClassification,
							        FalconForTokenClassification,
							        FalconForQuestionAnswering,
							    )
							    if is_torch_available()
							    else ()
							)
							_UpperCAmelCase      =						(FalconForCausalLM,) if is_torch_available() else ()
							_UpperCAmelCase      =						(
							    {
							        """feature-extraction""": FalconModel,
							        """text-classification""": FalconForSequenceClassification,
							        """text-generation""": FalconForCausalLM,
							        """question-answering""": FalconForQuestionAnswering,
							        """token-classification""": FalconForTokenClassification,
							        """zero-shot""": FalconForSequenceClassification,
							    }
							    if is_torch_available()
							    else {}
							)
							_UpperCAmelCase      =						False
							_UpperCAmelCase      =						False






							def 					UpperCamelCase__     (      self       ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_		:     Dict					=					FalconModelTester(self       )
										SCREAMING_SNAKE_CASE_		:     Any					=					ConfigTester(self			,						config_class=lowerCAmelCase__			,						hidden_size=3_7       )






							def 					UpperCamelCase__     (      self       ):





										"""simple docstring"""




										self.config_tester.run_common_tests()






							def 					UpperCamelCase__     (      self       ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_		:     Dict					=					self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*lowerCAmelCase__       )






							def 					UpperCamelCase__     (      self       ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_		,      *SCREAMING_SNAKE_CASE_		:     Union[str, Any]					=					self.model_tester.prepare_config_and_inputs()
										for alibi in [True, False]:
													SCREAMING_SNAKE_CASE_		:     Dict					=					alibi
													self.model_tester.create_and_check_model(lowerCAmelCase__			,						*lowerCAmelCase__       )






							def 					UpperCamelCase__     (      self       ):





										"""simple docstring"""




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






							def 					UpperCamelCase__     (      self       ):





										"""simple docstring"""




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






							def 					UpperCamelCase__     (      self       ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_		,      SCREAMING_SNAKE_CASE_		:     List[Any]					=					self.model_tester.prepare_config_and_inputs_for_common()
										SCREAMING_SNAKE_CASE_		:     Dict					=					input_dict['input_ids']
										SCREAMING_SNAKE_CASE_		:     Dict					=					FalconForCausalLM(lowerCAmelCase__       )
										model.to(lowerCAmelCase__       )
										model.eval()
										SCREAMING_SNAKE_CASE_		:     str					=					model(lowerCAmelCase__			,						use_cache=lowerCAmelCase__       )
										SCREAMING_SNAKE_CASE_		:     Any					=					input_ids.shape[0]
										SCREAMING_SNAKE_CASE_		:     Optional[int]					=					model._convert_to_rw_cache(result.past_key_values       )
										SCREAMING_SNAKE_CASE_		:     Optional[int]					=					model._convert_cache_to_standard_format(lowerCAmelCase__			,						lowerCAmelCase__       )
										for layer in range(len(lowerCAmelCase__       )       ):
													for tensor_idx in range(2       ):
																self.assertTrue(rw_cache[layer][tensor_idx].ndim == 3       )
																self.assertTrue(result.past_key_values[layer][tensor_idx].ndim == 4       )
																self.assertTrue(
																    torch.all(result.past_key_values[layer][tensor_idx] == standard_cache[layer][tensor_idx]       )       )






							def 					UpperCamelCase__     (      self       ):





										"""simple docstring"""




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






							def 					UpperCamelCase__     (      self       ):





										"""simple docstring"""




										for model_class in self.all_generative_model_classes:
													SCREAMING_SNAKE_CASE_		,      SCREAMING_SNAKE_CASE_		:     List[str]					=					self.model_tester.prepare_config_and_inputs_for_common()

													# If it doesn't support cache, pass the test
													if not hasattr(lowerCAmelCase__			,						'use_cache'       ):
																return

													SCREAMING_SNAKE_CASE_		:     Dict					=					model_class(lowerCAmelCase__       ).to(lowerCAmelCase__       )
													if "use_cache" not in inputs:
																SCREAMING_SNAKE_CASE_		:     Union[str, Any]					=					True
													SCREAMING_SNAKE_CASE_		:     Any					=					model(**lowerCAmelCase__       )

													# If "past_key_values" is not returned, pass the test (e.g. RWKV uses a different cache name and format)
													if "past_key_values" not in outputs:
																return

													SCREAMING_SNAKE_CASE_		:     Optional[Any]					=					(
													    getattr(lowerCAmelCase__			,						'decoder_layers'			,						lowerCAmelCase__       )
													    or getattr(lowerCAmelCase__			,						'num_decoder_layers'			,						lowerCAmelCase__       )
													    or config.num_hidden_layers
													)
													SCREAMING_SNAKE_CASE_		:     List[str]					=					getattr(lowerCAmelCase__			,						'num_kv_heads'			,						config.num_attention_heads       )
													SCREAMING_SNAKE_CASE_		:     str					=					getattr(lowerCAmelCase__			,						'd_model'			,						config.hidden_size       )
													SCREAMING_SNAKE_CASE_		:     List[str]					=					embed_dim // num_attention_heads

													SCREAMING_SNAKE_CASE_		:     List[Any]					=					outputs['past_key_values']
													self.assertEqual(len(lowerCAmelCase__       )			,						lowerCAmelCase__       )

													SCREAMING_SNAKE_CASE_		,      SCREAMING_SNAKE_CASE_		:     Optional[Any]					=					inputs['input_ids'].shape
													for i in range(lowerCAmelCase__       ):
																if config.new_decoder_architecture:
																			SCREAMING_SNAKE_CASE_		:     Any					=					config.num_attention_heads
																elif config.multi_query:
																			SCREAMING_SNAKE_CASE_		:     Any					=					1
																self.assertEqual(len(past_kv[0]       )			,						2       )  # K V for the decoder = 2
																self.assertEqual(
																    past_kv[i][0].shape			,						(batch_size, num_attention_heads, seq_length, per_head_embed_dim)       )
																self.assertEqual(
																    past_kv[i][1].shape			,						(batch_size, num_attention_heads, seq_length, per_head_embed_dim)       )







@require_torch
class 	__lowercase    (unittest.TestCase  ):





							"""simple docstring"""







							@slow
							def 					UpperCamelCase__     (      self       ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_		:     Union[str, Any]					=					AutoTokenizer.from_pretrained('Rocketknight1/falcon-rw-1b'       )
										SCREAMING_SNAKE_CASE_		:     Optional[Any]					=					FalconForCausalLM.from_pretrained('Rocketknight1/falcon-rw-1b'       )
										model.eval()
										model.to(lowerCAmelCase__       )
										SCREAMING_SNAKE_CASE_		:     Dict					=					tokenizer('My favorite food is'			,						return_tensors='pt'       ).to(lowerCAmelCase__       )

										SCREAMING_SNAKE_CASE_		:     List[str]					=					(
										    'My favorite food is pizza. I love it so much that I have a pizza party every year for my birthday.'
										)

										SCREAMING_SNAKE_CASE_		:     Dict					=					model.generate(**lowerCAmelCase__			,						do_sample=lowerCAmelCase__			,						max_new_tokens=1_9       )
										SCREAMING_SNAKE_CASE_		:     List[Any]					=					tokenizer.batch_decode(lowerCAmelCase__       )[0]

										self.assertEqual(lowerCAmelCase__			,						lowerCAmelCase__       )






							@slow
							def 					UpperCamelCase__     (      self       ):





										"""simple docstring"""




										for repo in ["Rocketknight1/tiny-random-falcon-7b", "Rocketknight1/tiny-random-falcon-40b"]:
													SCREAMING_SNAKE_CASE_		:     int					=					AutoTokenizer.from_pretrained(lowerCAmelCase__       )
													SCREAMING_SNAKE_CASE_		:     Tuple					=					FalconForCausalLM.from_pretrained(lowerCAmelCase__       )
													model.eval()
													model.to(lowerCAmelCase__       )
													SCREAMING_SNAKE_CASE_		:     int					=					tokenizer('My favorite food is'			,						return_tensors='pt'       ).to(lowerCAmelCase__       )

													# We just test that these run without errors - the models are randomly initialized
													# and so the actual text outputs will be garbage
													model.generate(**lowerCAmelCase__			,						do_sample=lowerCAmelCase__			,						max_new_tokens=4       )
													model.generate(**lowerCAmelCase__			,						do_sample=lowerCAmelCase__			,						max_new_tokens=4       )
													model.generate(**lowerCAmelCase__			,						num_beams=2			,						max_new_tokens=4       )






							@slow
							def 					UpperCamelCase__     (      self       ):





										"""simple docstring"""




										with torch.no_grad():
													for repo in [
													    "Rocketknight1/falcon-rw-1b",
													    "Rocketknight1/tiny-random-falcon-7b",
													    "Rocketknight1/tiny-random-falcon-40b",
													]:
																SCREAMING_SNAKE_CASE_		:     List[str]					=					AutoTokenizer.from_pretrained(lowerCAmelCase__       )
																SCREAMING_SNAKE_CASE_		:     int					=					FalconForCausalLM.from_pretrained(lowerCAmelCase__       )
																model.eval()
																model.to(device=lowerCAmelCase__       )
																SCREAMING_SNAKE_CASE_		:     Tuple					=					tokenizer('My favorite food is'			,						return_tensors='pt'       ).to(lowerCAmelCase__       )

																# Test results are the same with and without cache
																SCREAMING_SNAKE_CASE_		:     Optional[Any]					=					model.generate(**lowerCAmelCase__			,						do_sample=lowerCAmelCase__			,						max_new_tokens=2_0			,						use_cache=lowerCAmelCase__       )
																SCREAMING_SNAKE_CASE_		:     Any					=					model.generate(**lowerCAmelCase__			,						do_sample=lowerCAmelCase__			,						max_new_tokens=2_0			,						use_cache=lowerCAmelCase__       )
																self.assertTrue((outputs_cache - outputs_no_cache).sum().item() == 0       )







"""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_    							=					datasets.logging.get_logger(__name__)


A_    							=					"""\
@InProceedings{moosavi2019minimum,
    author = { Nafise Sadat Moosavi, Leo Born, Massimo Poesio and Michael Strube},
    title = {Using Automatically Extracted Minimum Spans to Disentangle Coreference Evaluation from Boundary Detection},
    year = {2019},
    booktitle = {Proceedings of the 57th Annual Meeting of
        the Association for Computational Linguistics (Volume 1: Long Papers)},
    publisher = {Association for Computational Linguistics},
    address = {Florence, Italy},
}

@inproceedings{10.3115/1072399.1072405,
author = {Vilain, Marc and Burger, John and Aberdeen, John and Connolly, Dennis and Hirschman, Lynette},
title = {A Model-Theoretic Coreference Scoring Scheme},
year = {1995},
isbn = {1558604022},
publisher = {Association for Computational Linguistics},
address = {USA},
url = {https://doi.org/10.3115/1072399.1072405},
doi = {10.3115/1072399.1072405},
booktitle = {Proceedings of the 6th Conference on Message Understanding},
pages = {45–52},
numpages = {8},
location = {Columbia, Maryland},
series = {MUC6 ’95}
}

@INPROCEEDINGS{Bagga98algorithmsfor,
    author = {Amit Bagga and Breck Baldwin},
    title = {Algorithms for Scoring Coreference Chains},
    booktitle = {In The First International Conference on Language Resources and Evaluation Workshop on Linguistics Coreference},
    year = {1998},
    pages = {563--566}
}

@INPROCEEDINGS{Luo05oncoreference,
    author = {Xiaoqiang Luo},
    title = {On coreference resolution performance metrics},
    booktitle = {In Proc. of HLT/EMNLP},
    year = {2005},
    pages = {25--32},
    publisher = {URL}
}

@inproceedings{moosavi-strube-2016-coreference,
    title = \"Which Coreference Evaluation Metric Do You Trust? A Proposal for a Link-based Entity Aware Metric\",
    author = \"Moosavi, Nafise Sadat  and
      Strube, Michael\",
    booktitle = \"Proceedings of the 54th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)\",
    month = aug,
    year = \"2016\",
    address = \"Berlin, Germany\",
    publisher = \"Association for Computational Linguistics\",
    url = \"https://www.aclweb.org/anthology/P16-1060\",
    doi = \"10.18653/v1/P16-1060\",
    pages = \"632--642\",
}

"""

A_    							=					"""\
CoVal is a coreference evaluation tool for the CoNLL and ARRAU datasets which
implements of the common evaluation metrics including MUC [Vilain et al, 1995],
B-cubed [Bagga and Baldwin, 1998], CEAFe [Luo et al., 2005],
LEA [Moosavi and Strube, 2016] and the averaged CoNLL score
(the average of the F1 values of MUC, B-cubed and CEAFe)
[Denis and Baldridge, 2009a; Pradhan et al., 2011].

This wrapper of CoVal currently only work with CoNLL line format:
The CoNLL format has one word per line with all the annotation for this word in column separated by spaces:
Column	Type	Description
1	Document ID	This is a variation on the document filename
2	Part number	Some files are divided into multiple parts numbered as 000, 001, 002, ... etc.
3	Word number
4	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.
5	Part-of-Speech
6	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.
7	Predicate lemma	The predicate lemma is mentioned for the rows for which we have semantic role information. All other rows are marked with a \"-\"
8	Predicate Frameset ID	This is the PropBank frameset ID of the predicate in Column 7.
9	Word sense	This is the word sense of the word in Column 3.
10	Speaker/Author	This is the speaker or author name where available. Mostly in Broadcast Conversation and Web Log data.
11	Named Entities	These columns identifies the spans representing various named entities.
12:N	Predicate Arguments	There is one column each of predicate argument structure information for the predicate mentioned in Column 7.
N	Coreference	Coreference chain information encoded in a parenthesis structure.
More informations on the format can be found here (section \"*_conll File Format\"): http://www.conll.cemantix.org/2012/data.html

Details on the evaluation on CoNLL can be found here: https://github.com/ns-moosavi/coval/blob/master/conll/README.md

CoVal code was written by @ns-moosavi.
Some parts are borrowed from https://github.com/clarkkev/deep-coref/blob/master/evaluation.py
The test suite is taken from https://github.com/conll/reference-coreference-scorers/
Mention evaluation and the test suite are added by @andreasvc.
Parsing CoNLL files is developed by Leo Born.
"""

A_    							=					"""
Calculates coreference evaluation metrics.
Args:
    predictions: list of sentences. Each sentence is a list of word predictions to score in the CoNLL format.
        Each prediction is a word with its annotations as a string made of columns joined with spaces.
        Only columns 4, 5, 6 and the last column are used (word, POS, Pars and coreference annotation)
        See the details on the format in the description of the metric.
    references: list of sentences. Each sentence is a list of word reference to score in the CoNLL format.
        Each reference is a word with its annotations as a string made of columns joined with spaces.
        Only columns 4, 5, 6 and the last column are used (word, POS, Pars and coreference annotation)
        See the details on the format in the description of the metric.
    keep_singletons: After extracting all mentions of key or system files,
        mentions whose corresponding coreference chain is of size one,
        are considered as singletons. The default evaluation mode will include
        singletons in evaluations if they are included in the key or the system files.
        By setting 'keep_singletons=False', all singletons in the key and system files
        will be excluded from the evaluation.
    NP_only: Most of the recent coreference resolvers only resolve NP mentions and
        leave out the resolution of VPs. By setting the 'NP_only' option, the scorer will only evaluate the resolution of NPs.
    min_span: By setting 'min_span', the scorer reports the results based on automatically detected minimum spans.
        Minimum spans are determined using the MINA algorithm.

Returns:
    'mentions': mentions
    'muc': MUC metric [Vilain et al, 1995]
    'bcub': B-cubed [Bagga and Baldwin, 1998]
    'ceafe': CEAFe [Luo et al., 2005]
    'lea': LEA [Moosavi and Strube, 2016]
    'conll_score': averaged CoNLL score (the average of the F1 values of MUC, B-cubed and CEAFe)

Examples:

    >>> coval = datasets.load_metric('coval')
    >>> words = ['bc/cctv/00/cctv_0005   0   0       Thank   VBP  (TOP(S(VP*    thank  01   1    Xu_li  *           (V*)        *       -',
    ... 'bc/cctv/00/cctv_0005   0   1         you   PRP        (NP*)      -    -   -    Xu_li  *        (ARG1*)   (ARG0*)   (116)',
    ... 'bc/cctv/00/cctv_0005   0   2    everyone    NN        (NP*)      -    -   -    Xu_li  *    (ARGM-DIS*)        *    (116)',
    ... 'bc/cctv/00/cctv_0005   0   3         for    IN        (PP*       -    -   -    Xu_li  *        (ARG2*         *       -',
    ... 'bc/cctv/00/cctv_0005   0   4    watching   VBG   (S(VP*))))   watch  01   1    Xu_li  *             *)      (V*)      -',
    ... 'bc/cctv/00/cctv_0005   0   5           .     .          *))      -    -   -    Xu_li  *             *         *       -']
    >>> references = [words]
    >>> predictions = [words]
    >>> results = coval.compute(predictions=predictions, references=references)
    >>> print(results) # doctest:+ELLIPSIS
    {'mentions/recall': 1.0,[...] 'conll_score': 100.0}
"""






def  lowercase						(	lowerCAmelCase__	,lowerCAmelCase__	,lowerCAmelCase__=False	,lowerCAmelCase__=False	,lowerCAmelCase__=True	,lowerCAmelCase__=False	,lowerCAmelCase__="dummy_doc"						):
			lowerCamelCase_					=  {doc: key_lines}
			lowerCamelCase_					=  {doc: sys_lines}

			lowerCamelCase_					=  {}

			lowerCamelCase_					=  0
			lowerCamelCase_					=  0
			lowerCamelCase_					=  0
			lowerCamelCase_					=  0
			lowerCamelCase_					=  0
			lowerCamelCase_					=  0

			lowerCamelCase_		, lowerCamelCase_					=  reader.get_doc_mentions(lowerCAmelCase__	,key_doc_lines[doc]	,lowerCAmelCase__						)
			key_singletons_num += singletons_num

			if NP_only or min_span:
						lowerCamelCase_					=  reader.set_annotated_parse_trees(lowerCAmelCase__	,key_doc_lines[doc]	,lowerCAmelCase__	,lowerCAmelCase__						)

			lowerCamelCase_		, lowerCamelCase_					=  reader.get_doc_mentions(lowerCAmelCase__	,sys_doc_lines[doc]	,lowerCAmelCase__						)
			sys_singletons_num += singletons_num

			if NP_only or min_span:
						lowerCamelCase_					=  reader.set_annotated_parse_trees(lowerCAmelCase__	,key_doc_lines[doc]	,lowerCAmelCase__	,lowerCAmelCase__						)

			if remove_nested:
						lowerCamelCase_		, lowerCamelCase_					=  reader.remove_nested_coref_mentions(lowerCAmelCase__	,lowerCAmelCase__						)
						key_nested_coref_num += nested_mentions
						key_removed_nested_clusters += removed_clusters

						lowerCamelCase_		, lowerCamelCase_					=  reader.remove_nested_coref_mentions(lowerCAmelCase__	,lowerCAmelCase__						)
						sys_nested_coref_num += nested_mentions
						sys_removed_nested_clusters += removed_clusters

			lowerCamelCase_					=  reader.get_mention_assignments(lowerCAmelCase__	,lowerCAmelCase__						)
			lowerCamelCase_					=  reader.get_mention_assignments(lowerCAmelCase__	,lowerCAmelCase__						)

			lowerCamelCase_					=  (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						(	lowerCAmelCase__	,lowerCAmelCase__	,lowerCAmelCase__	,lowerCAmelCase__	,lowerCAmelCase__	,lowerCAmelCase__	,lowerCAmelCase__						):
			lowerCamelCase_					=  get_coref_infos(lowerCAmelCase__	,lowerCAmelCase__	,lowerCAmelCase__	,lowerCAmelCase__	,lowerCAmelCase__	,lowerCAmelCase__						)

			lowerCamelCase_					=  {}
			lowerCamelCase_					=  0
			lowerCamelCase_					=  0

			for name, metric in metrics:
						lowerCamelCase_		, lowerCamelCase_		, lowerCamelCase_					=  evaluator.evaluate_documents(lowerCAmelCase__	,lowerCAmelCase__	,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:
						lowerCamelCase_					=  (conll / 3) * 100
						logger.info(f"CoNLL score: {conll:.2f}"						)
						output_scores.update({'''conll_score''': conll}						)

			return output_scores






def  lowercase						(	lowerCAmelCase__						):
			lowerCamelCase_					=  False
			for line in key_lines:
						if not line.startswith('''#'''						):
									if len(line.split()						) > 6:
												lowerCamelCase_					=  line.split()[5]
												if not parse_col == "-":
															lowerCamelCase_					=  True
															break
												else:
															break
			return has_gold_parse




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




				def        UpperCAmelCase__						(				self   ):
							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        UpperCAmelCase__						(				self							,						UpperCAmelCase							,						UpperCAmelCase							,						UpperCAmelCase=True							,						UpperCAmelCase=False							,						UpperCAmelCase=False							,						UpperCAmelCase=False   ):
							lowerCamelCase_					=  [
							    ('''mentions''', evaluator.mentions),
							    ('''muc''', evaluator.muc),
							    ('''bcub''', evaluator.b_cubed),
							    ('''ceafe''', evaluator.ceafe),
							    ('''lea''', evaluator.lea),
							]

							if min_span:
										lowerCamelCase_					=  util.check_gold_parse_annotation(UpperCAmelCase   )
										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"

							lowerCamelCase_					=  evaluate(
							    key_lines=UpperCAmelCase							,						sys_lines=UpperCAmelCase							,						metrics=UpperCAmelCase							,						NP_only=UpperCAmelCase							,						remove_nested=UpperCAmelCase							,						keep_singletons=UpperCAmelCase							,						min_span=UpperCAmelCase							,						)

							return score



