




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  __magic_name__						:
				'''simple docstring'''







				def __init__(							self:   str		,					_lowerCamelCase:   Dict		,					_lowerCamelCase:   Union[str, Any]=3		,					_lowerCamelCase:   int=7		,					_lowerCamelCase:   Union[str, Any]=True		,					_lowerCamelCase:   int=True		,					_lowerCamelCase:   Optional[int]=False		,					_lowerCamelCase:   Optional[Any]=True		,					_lowerCamelCase:   Tuple=99		,					_lowerCamelCase:   List[str]=32		,					_lowerCamelCase:   Optional[int]=5		,					_lowerCamelCase:   Optional[Any]=4		,					_lowerCamelCase:   Any=37		,					_lowerCamelCase:   List[Any]="gelu"		,					_lowerCamelCase:   List[Any]=0.1		,					_lowerCamelCase:   str=0.1		,					_lowerCamelCase:   List[str]=5_12		,					_lowerCamelCase:   Union[str, Any]=16		,					_lowerCamelCase:   Optional[Any]=2		,					_lowerCamelCase:   Optional[int]=0.02		,					_lowerCamelCase:   List[Any]=3		,					_lowerCamelCase:   Dict=4		,					_lowerCamelCase:   Optional[Any]=None		,					):
											SCREAMING_SNAKE_CASE_   	=    parent
											SCREAMING_SNAKE_CASE_   	=    batch_size
											SCREAMING_SNAKE_CASE_   	=    seq_length
											SCREAMING_SNAKE_CASE_   	=    is_training
											SCREAMING_SNAKE_CASE_   	=    use_input_mask
											SCREAMING_SNAKE_CASE_   	=    use_token_type_ids
											SCREAMING_SNAKE_CASE_   	=    use_labels
											SCREAMING_SNAKE_CASE_   	=    vocab_size
											SCREAMING_SNAKE_CASE_   	=    hidden_size
											SCREAMING_SNAKE_CASE_   	=    num_hidden_layers
											SCREAMING_SNAKE_CASE_   	=    num_attention_heads
											SCREAMING_SNAKE_CASE_   	=    intermediate_size
											SCREAMING_SNAKE_CASE_   	=    hidden_act
											SCREAMING_SNAKE_CASE_   	=    hidden_dropout_prob
											SCREAMING_SNAKE_CASE_   	=    attention_probs_dropout_prob
											SCREAMING_SNAKE_CASE_   	=    max_position_embeddings
											SCREAMING_SNAKE_CASE_   	=    type_vocab_size
											SCREAMING_SNAKE_CASE_   	=    type_sequence_label_size
											SCREAMING_SNAKE_CASE_   	=    initializer_range
											SCREAMING_SNAKE_CASE_   	=    num_labels
											SCREAMING_SNAKE_CASE_   	=    num_choices
											SCREAMING_SNAKE_CASE_   	=    scope


				def     _A							(							self:   List[str]		):
											SCREAMING_SNAKE_CASE_   	=    ids_tensor([self.batch_size, self.seq_length]		,					self.vocab_size		)

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

											SCREAMING_SNAKE_CASE_   	=    None

											SCREAMING_SNAKE_CASE_   	=    None
											SCREAMING_SNAKE_CASE_   	=    None
											SCREAMING_SNAKE_CASE_   	=    None
											if self.use_labels:
																		SCREAMING_SNAKE_CASE_   	=    ids_tensor([self.batch_size]		,					self.type_sequence_label_size		)
																		SCREAMING_SNAKE_CASE_   	=    ids_tensor([self.batch_size, self.seq_length]		,					self.num_labels		)
																		SCREAMING_SNAKE_CASE_   	=    ids_tensor([self.batch_size]		,					self.num_choices		)

											SCREAMING_SNAKE_CASE_   	=    self.get_config()

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


				def     _A							(							self:   str		):
											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     _A							(							self:   Any		,					_lowerCamelCase:   str		,					_lowerCamelCase:   Optional[Any]		,					_lowerCamelCase:   Any		,					_lowerCamelCase:   int		,					_lowerCamelCase:   Dict		,					_lowerCamelCase:   Dict		,					_lowerCamelCase:   Dict		):
											SCREAMING_SNAKE_CASE_   	=    FalconModel(config=_lowerCamelCase		)
											model.to(_lowerCamelCase		)
											model.eval()
											SCREAMING_SNAKE_CASE_   	=    model(_lowerCamelCase		,					attention_mask=_lowerCamelCase		)
											SCREAMING_SNAKE_CASE_   	=    model(_lowerCamelCase		)
											self.parent.assertEqual(result.last_hidden_state.shape		,					(self.batch_size, self.seq_length, self.hidden_size)		)


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


				def     _A							(							self:   List[str]		,					_lowerCamelCase:   str		,					_lowerCamelCase:   List[str]		,					_lowerCamelCase:   Union[str, Any]		,					_lowerCamelCase:   Union[str, Any]		,					_lowerCamelCase:   Optional[int]		,					_lowerCamelCase:   Optional[Any]		,					_lowerCamelCase:   Tuple		,					_lowerCamelCase:   Dict		,					_lowerCamelCase:   Dict		,					):
											SCREAMING_SNAKE_CASE_   	=    FalconForCausalLM(config=_lowerCamelCase		)
											model.to(_lowerCamelCase		)
											model.eval()
											SCREAMING_SNAKE_CASE_   	=    model(_lowerCamelCase		,					attention_mask=_lowerCamelCase		,					labels=_lowerCamelCase		)
											self.parent.assertEqual(result.logits.shape		,					(self.batch_size, self.seq_length, self.vocab_size)		)


				def     _A							(							self:   List[str]		,					_lowerCamelCase:   Tuple		,					_lowerCamelCase:   Optional[Any]		,					_lowerCamelCase:   Tuple		,					_lowerCamelCase:   int		,					_lowerCamelCase:   List[Any]		,					_lowerCamelCase:   int		,					_lowerCamelCase:   Dict		,					_lowerCamelCase:   int		,					_lowerCamelCase:   Union[str, Any]		,					):
											SCREAMING_SNAKE_CASE_   	=    True
											SCREAMING_SNAKE_CASE_   	=    True
											SCREAMING_SNAKE_CASE_   	=    FalconForCausalLM(config=_lowerCamelCase		)
											model.to(_lowerCamelCase		)
											model.eval()

											# first forward pass
											SCREAMING_SNAKE_CASE_   	=    model(
											    _lowerCamelCase		,					attention_mask=_lowerCamelCase		,					encoder_hidden_states=_lowerCamelCase		,					encoder_attention_mask=_lowerCamelCase		,					use_cache=_lowerCamelCase		,					)
											SCREAMING_SNAKE_CASE_   	=    outputs.past_key_values

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

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

											SCREAMING_SNAKE_CASE_   	=    model(
											    _lowerCamelCase		,					attention_mask=_lowerCamelCase		,					encoder_hidden_states=_lowerCamelCase		,					encoder_attention_mask=_lowerCamelCase		,					output_hidden_states=_lowerCamelCase		,					)['''hidden_states'''][0]
											SCREAMING_SNAKE_CASE_   	=    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_   	=    ids_tensor((1,)		,					output_from_past.shape[-1]		).item()
											SCREAMING_SNAKE_CASE_   	=    output_from_no_past[:, -3:, random_slice_idx].detach()
											SCREAMING_SNAKE_CASE_   	=    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     _A							(							self:   Optional[Any]		):
											SCREAMING_SNAKE_CASE_   	=    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_
											)	,	
											)   	=    config_and_inputs
											SCREAMING_SNAKE_CASE_   	=    {'''input_ids''': input_ids, '''attention_mask''': input_mask}
											return config, inputs_dict






@require_torch
class  __magic_name__						(  __UpperCAmelCase    ,  __UpperCAmelCase    ,  __UpperCAmelCase    ,  unittest.TestCase):
				'''simple docstring'''







				SCREAMING_SNAKE_CASE__					:							Dict	      =					(
				    (
				        FalconModel,
				        FalconForCausalLM,
				        FalconForSequenceClassification,
				        FalconForTokenClassification,
				        FalconForQuestionAnswering,
				    )
				    if is_torch_available()
				    else ()
				)
				SCREAMING_SNAKE_CASE__					:							Union[str, Any]	      =					(FalconForCausalLM,) if is_torch_available() else ()
				SCREAMING_SNAKE_CASE__					:							str	      =					(
				    {
				        "feature-extraction": FalconModel,
				        "text-classification": FalconForSequenceClassification,
				        "text-generation": FalconForCausalLM,
				        "question-answering": FalconForQuestionAnswering,
				        "token-classification": FalconForTokenClassification,
				        "zero-shot": FalconForSequenceClassification,
				    }
				    if is_torch_available()
				    else {}
				)
				SCREAMING_SNAKE_CASE__					:							List[str]	      =					False
				SCREAMING_SNAKE_CASE__					:							List[Any]	      =					False


				def     _A							(							self:   Optional[int]		):
											SCREAMING_SNAKE_CASE_   	=    FalconModelTester(self		)
											SCREAMING_SNAKE_CASE_   	=    ConfigTester(self		,					config_class=_lowerCamelCase		,					hidden_size=37		)


				def     _A							(							self:   int		):
											self.config_tester.run_common_tests()


				def     _A							(							self:   Optional[Any]		):
											SCREAMING_SNAKE_CASE_   	=    self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_model(*_lowerCamelCase		)


				def     _A							(							self:   str		):
											SCREAMING_SNAKE_CASE_	,	*SCREAMING_SNAKE_CASE_   	=    self.model_tester.prepare_config_and_inputs()
											for alibi in [True, False]:
																		SCREAMING_SNAKE_CASE_   	=    alibi
																		self.model_tester.create_and_check_model(_lowerCamelCase		,					*_lowerCamelCase		)


				def     _A							(							self:   List[str]		):
											SCREAMING_SNAKE_CASE_	,	SCREAMING_SNAKE_CASE_   	=    self.model_tester.prepare_config_and_inputs_for_common()
											SCREAMING_SNAKE_CASE_   	=    3
											SCREAMING_SNAKE_CASE_   	=    input_dict['''input_ids''']
											SCREAMING_SNAKE_CASE_   	=    input_ids.ne(1		).to(_lowerCamelCase		)
											SCREAMING_SNAKE_CASE_   	=    ids_tensor([self.model_tester.batch_size]		,					self.model_tester.type_sequence_label_size		)
											SCREAMING_SNAKE_CASE_   	=    FalconForSequenceClassification(_lowerCamelCase		)
											model.to(_lowerCamelCase		)
											model.eval()
											SCREAMING_SNAKE_CASE_   	=    model(_lowerCamelCase		,					attention_mask=_lowerCamelCase		,					labels=_lowerCamelCase		)
											self.assertEqual(result.logits.shape		,					(self.model_tester.batch_size, self.model_tester.num_labels)		)


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


				def     _A							(							self:   Any		):
											SCREAMING_SNAKE_CASE_	,	SCREAMING_SNAKE_CASE_   	=    self.model_tester.prepare_config_and_inputs_for_common()
											SCREAMING_SNAKE_CASE_   	=    input_dict['''input_ids''']
											SCREAMING_SNAKE_CASE_   	=    FalconForCausalLM(_lowerCamelCase		)
											model.to(_lowerCamelCase		)
											model.eval()
											SCREAMING_SNAKE_CASE_   	=    model(_lowerCamelCase		,					use_cache=_lowerCamelCase		)
											SCREAMING_SNAKE_CASE_   	=    input_ids.shape[0]
											SCREAMING_SNAKE_CASE_   	=    model._convert_to_rw_cache(result.past_key_values		)
											SCREAMING_SNAKE_CASE_   	=    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     _A							(							self:   Any		):
											SCREAMING_SNAKE_CASE_	,	SCREAMING_SNAKE_CASE_   	=    self.model_tester.prepare_config_and_inputs_for_common()
											SCREAMING_SNAKE_CASE_   	=    3
											SCREAMING_SNAKE_CASE_   	=    '''multi_label_classification'''
											SCREAMING_SNAKE_CASE_   	=    input_dict['''input_ids''']
											SCREAMING_SNAKE_CASE_   	=    input_ids.ne(1		).to(_lowerCamelCase		)
											SCREAMING_SNAKE_CASE_   	=    ids_tensor(
											    [self.model_tester.batch_size, config.num_labels]		,					self.model_tester.type_sequence_label_size		).to(torch.float		)
											SCREAMING_SNAKE_CASE_   	=    FalconForSequenceClassification(_lowerCamelCase		)
											model.to(_lowerCamelCase		)
											model.eval()
											SCREAMING_SNAKE_CASE_   	=    model(_lowerCamelCase		,					attention_mask=_lowerCamelCase		,					labels=_lowerCamelCase		)
											self.assertEqual(result.logits.shape		,					(self.model_tester.batch_size, self.model_tester.num_labels)		)





				def     _A							(							self:   int		):
											# Falcon can have different numbers of KV-heads than the number of query heads, so we need
											# to override this test to use the right head counts.
											for model_class in self.all_generative_model_classes:
																		SCREAMING_SNAKE_CASE_	,	SCREAMING_SNAKE_CASE_   	=    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_   	=    model_class(_lowerCamelCase		).to(_lowerCamelCase		)
																		if "use_cache" not in inputs:
																									SCREAMING_SNAKE_CASE_   	=    True
																		SCREAMING_SNAKE_CASE_   	=    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_   	=    (
																		    getattr(_lowerCamelCase		,					'''decoder_layers'''		,					_lowerCamelCase		)
																		    or getattr(_lowerCamelCase		,					'''num_decoder_layers'''		,					_lowerCamelCase		)
																		    or config.num_hidden_layers
																		)
																		SCREAMING_SNAKE_CASE_   	=    getattr(_lowerCamelCase		,					'''num_kv_heads'''		,					config.num_attention_heads		)
																		SCREAMING_SNAKE_CASE_   	=    getattr(_lowerCamelCase		,					'''d_model'''		,					config.hidden_size		)
																		SCREAMING_SNAKE_CASE_   	=    embed_dim // num_attention_heads

																		SCREAMING_SNAKE_CASE_   	=    outputs['''past_key_values''']
																		self.assertEqual(len(_lowerCamelCase		)		,					_lowerCamelCase		)

																		SCREAMING_SNAKE_CASE_	,	SCREAMING_SNAKE_CASE_   	=    inputs['''input_ids'''].shape
																		for i in range(_lowerCamelCase		):
																									if config.new_decoder_architecture:
																																SCREAMING_SNAKE_CASE_   	=    config.num_attention_heads
																									elif config.multi_query:
																																SCREAMING_SNAKE_CASE_   	=    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  __magic_name__						(  unittest.TestCase):
				'''simple docstring'''







				@slow
				def     _A							(							self:   List[str]		):
											SCREAMING_SNAKE_CASE_   	=    AutoTokenizer.from_pretrained('''Rocketknight1/falcon-rw-1b'''		)
											SCREAMING_SNAKE_CASE_   	=    FalconForCausalLM.from_pretrained('''Rocketknight1/falcon-rw-1b'''		)
											model.eval()
											model.to(_lowerCamelCase		)
											SCREAMING_SNAKE_CASE_   	=    tokenizer('''My favorite food is'''		,					return_tensors='''pt'''		).to(_lowerCamelCase		)

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

											SCREAMING_SNAKE_CASE_   	=    model.generate(**_lowerCamelCase		,					do_sample=_lowerCamelCase		,					max_new_tokens=19		)
											SCREAMING_SNAKE_CASE_   	=    tokenizer.batch_decode(_lowerCamelCase		)[0]

											self.assertEqual(_lowerCamelCase		,					_lowerCamelCase		)


				@slow
				def     _A							(							self:   Any		):
											# The big models are way too big for the CI, so we use tiny random models that resemble their
											# architectures but with much smaller and fewer layers
											for repo in ["Rocketknight1/tiny-random-falcon-7b", "Rocketknight1/tiny-random-falcon-40b"]:
																		SCREAMING_SNAKE_CASE_   	=    AutoTokenizer.from_pretrained(_lowerCamelCase		)
																		SCREAMING_SNAKE_CASE_   	=    FalconForCausalLM.from_pretrained(_lowerCamelCase		)
																		model.eval()
																		model.to(_lowerCamelCase		)
																		SCREAMING_SNAKE_CASE_   	=    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     _A							(							self:   Dict		):
											# The big models are way too big for the CI, so we use tiny random models that resemble their
											# architectures but with much smaller and fewer layers
											with torch.no_grad():
																		for repo in [
																		    "Rocketknight1/falcon-rw-1b",
																		    "Rocketknight1/tiny-random-falcon-7b",
																		    "Rocketknight1/tiny-random-falcon-40b",
																		]:
																									SCREAMING_SNAKE_CASE_   	=    AutoTokenizer.from_pretrained(_lowerCamelCase		)
																									SCREAMING_SNAKE_CASE_   	=    FalconForCausalLM.from_pretrained(_lowerCamelCase		)
																									model.eval()
																									model.to(device=_lowerCamelCase		)
																									SCREAMING_SNAKE_CASE_   	=    tokenizer('''My favorite food is'''		,					return_tensors='''pt'''		).to(_lowerCamelCase		)

																									# Test results are the same with and without cache
																									SCREAMING_SNAKE_CASE_   	=    model.generate(**_lowerCamelCase		,					do_sample=_lowerCamelCase		,					max_new_tokens=20		,					use_cache=_lowerCamelCase		)
																									SCREAMING_SNAKE_CASE_   	=    model.generate(**_lowerCamelCase		,					do_sample=_lowerCamelCase		,					max_new_tokens=20		,					use_cache=_lowerCamelCase		)
																									self.assertTrue((outputs_cache - outputs_no_cache).sum().item() == 0		)








import math
import time
from typing import Dict, List, Optional

from torch.utils.data import Dataset

from transformers import SeqaSeqTrainer, is_torch_tpu_available
from transformers.trainer_utils import PredictionOutput, speed_metrics


if is_torch_tpu_available(check_device=False):
			import torch_xla.core.xla_model as xm
			import torch_xla.debug.metrics as met






class  __magic_name__						(  __UpperCAmelCase):
				'''simple docstring'''







				def __init__(							self:   List[Any]		,					*_lowerCamelCase:   Tuple		,					_lowerCamelCase:   Optional[Any]=None		,					_lowerCamelCase:   Dict=None		,					**_lowerCamelCase:   Dict		):
											super().__init__(*_lowerCamelCase		,					**_lowerCamelCase		)
											SCREAMING_SNAKE_CASE_   	=    eval_examples
											SCREAMING_SNAKE_CASE_   	=    post_process_function


				def     _A							(							self:   Tuple		,					_lowerCamelCase:   Optional[Dataset] = None		,					_lowerCamelCase:   List[str]=None		,					_lowerCamelCase:   Optional[List[str]] = None		,					_lowerCamelCase:   str = "eval"		,					**_lowerCamelCase:   Union[str, Any]		,					):
											SCREAMING_SNAKE_CASE_   	=    gen_kwargs.copy()
											SCREAMING_SNAKE_CASE_   	=    (
											    gen_kwargs['''max_length'''] if gen_kwargs.get('''max_length'''		) is not None else self.args.generation_max_length
											)
											SCREAMING_SNAKE_CASE_   	=    (
											    gen_kwargs['''num_beams'''] if gen_kwargs.get('''num_beams'''		) is not None else self.args.generation_num_beams
											)
											SCREAMING_SNAKE_CASE_   	=    gen_kwargs

											SCREAMING_SNAKE_CASE_   	=    self.eval_dataset if eval_dataset is None else eval_dataset
											SCREAMING_SNAKE_CASE_   	=    self.get_eval_dataloader(_lowerCamelCase		)
											SCREAMING_SNAKE_CASE_   	=    self.eval_examples if eval_examples is None else eval_examples

											# Temporarily disable metric computation, we will do it in the loop here.
											SCREAMING_SNAKE_CASE_   	=    self.compute_metrics
											SCREAMING_SNAKE_CASE_   	=    None
											SCREAMING_SNAKE_CASE_   	=    time.time()
											SCREAMING_SNAKE_CASE_   	=    self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
											try:
																		SCREAMING_SNAKE_CASE_   	=    eval_loop(
																		    _lowerCamelCase		,					description='''Evaluation'''		,					prediction_loss_only=True if compute_metrics is None else None		,					ignore_keys=_lowerCamelCase		,					metric_key_prefix=_lowerCamelCase		,					)
											finally:
																		SCREAMING_SNAKE_CASE_   	=    compute_metrics
											SCREAMING_SNAKE_CASE_   	=    self.args.eval_batch_size * self.args.world_size
											if f"{metric_key_prefix}_jit_compilation_time" in output.metrics:
																		start_time += output.metrics[f"{metric_key_prefix}_jit_compilation_time"]
											output.metrics.update(
											    speed_metrics(
											        _lowerCamelCase		,					_lowerCamelCase		,					num_samples=output.num_samples		,					num_steps=math.ceil(output.num_samples / total_batch_size		)		,					)		)

											if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save:
																		# Only the main node write the results by default
																		SCREAMING_SNAKE_CASE_   	=    self.post_process_function(_lowerCamelCase		,					_lowerCamelCase		,					_lowerCamelCase		)
																		SCREAMING_SNAKE_CASE_   	=    self.compute_metrics(_lowerCamelCase		)

																		# Prefix all keys with metric_key_prefix + '_'
																		for key in list(metrics.keys()		):
																									if not key.startswith(f"{metric_key_prefix}_"		):
																																SCREAMING_SNAKE_CASE_   	=    metrics.pop(_lowerCamelCase		)

																		metrics.update(output.metrics		)
											else:
																		SCREAMING_SNAKE_CASE_   	=    output.metrics

											if self.args.should_log:
																		# Only the main node log the results by default
																		self.log(_lowerCamelCase		)

											if self.args.tpu_metrics_debug or self.args.debug:
																		# tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.)
																		xm.master_print(met.metrics_report()		)

											SCREAMING_SNAKE_CASE_   	=    self.callback_handler.on_evaluate(self.args		,					self.state		,					self.control		,					_lowerCamelCase		)
											return metrics





				def     _A							(							self:   List[str]		,					_lowerCamelCase:   int		,					_lowerCamelCase:   List[str]		,					_lowerCamelCase:   Optional[int]=None		,					_lowerCamelCase:   str = "test"		,					**_lowerCamelCase:   str		):
											SCREAMING_SNAKE_CASE_   	=    gen_kwargs.copy()

											SCREAMING_SNAKE_CASE_   	=    self.get_test_dataloader(_lowerCamelCase		)

											# Temporarily disable metric computation, we will do it in the loop here.
											SCREAMING_SNAKE_CASE_   	=    self.compute_metrics
											SCREAMING_SNAKE_CASE_   	=    None
											SCREAMING_SNAKE_CASE_   	=    time.time()
											SCREAMING_SNAKE_CASE_   	=    self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
											try:
																		SCREAMING_SNAKE_CASE_   	=    eval_loop(
																		    _lowerCamelCase		,					description='''Prediction'''		,					prediction_loss_only=True if compute_metrics is None else None		,					ignore_keys=_lowerCamelCase		,					metric_key_prefix=_lowerCamelCase		,					)
											finally:
																		SCREAMING_SNAKE_CASE_   	=    compute_metrics

											SCREAMING_SNAKE_CASE_   	=    self.args.eval_batch_size * self.args.world_size
											if f"{metric_key_prefix}_jit_compilation_time" in output.metrics:
																		start_time += output.metrics[f"{metric_key_prefix}_jit_compilation_time"]
											output.metrics.update(
											    speed_metrics(
											        _lowerCamelCase		,					_lowerCamelCase		,					num_samples=output.num_samples		,					num_steps=math.ceil(output.num_samples / total_batch_size		)		,					)		)
											if self.post_process_function is None or self.compute_metrics is None:
																		return output

											SCREAMING_SNAKE_CASE_   	=    self.post_process_function(_lowerCamelCase		,					_lowerCamelCase		,					_lowerCamelCase		,					'''predict'''		)
											SCREAMING_SNAKE_CASE_   	=    self.compute_metrics(_lowerCamelCase		)

											# Prefix all keys with metric_key_prefix + '_'
											for key in list(metrics.keys()		):
																		if not key.startswith(f"{metric_key_prefix}_"		):
																									SCREAMING_SNAKE_CASE_   	=    metrics.pop(_lowerCamelCase		)
											metrics.update(output.metrics		)
											return PredictionOutput(predictions=predictions.predictions		,					label_ids=predictions.label_ids		,					metrics=_lowerCamelCase		)


