


"""simple docstring"""


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 			lowerCamelCase__						:







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







						def __a						(							self   :    Tuple		):
								A					       = ids_tensor([self.batch_size, self.seq_length]			,			self.vocab_size		)

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

								A					       = None

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

								A					       = self.get_config()

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







						def __a						(							self   :    Any		):
								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=_lowercase			,			initializer_range=self.initializer_range			,			pad_token_id=1			,			new_decoder_architecture=_lowercase			,			)







						def __a						(							self   :    Union[str, Any]			,			_lowercase   :    Optional[int]			,			_lowercase   :    List[str]			,			_lowercase   :    Any			,			_lowercase   :    Optional[Any]			,			_lowercase   :    Tuple			,			_lowercase   :    int			,			_lowercase   :    List[str]		):
								A					       = FalconModel(config=_lowercase		)
								model.to(_lowercase		)
								model.eval()
								A					       = model(_lowercase			,			attention_mask=_lowercase		)
								A					       = model(_lowercase		)
								self.parent.assertEqual(result.last_hidden_state.shape			,			(self.batch_size, self.seq_length, self.hidden_size)		)







						def __a						(							self   :    Optional[int]			,			_lowercase   :    str			,			_lowercase   :    Optional[Any]			,			_lowercase   :    Any			,			_lowercase   :    List[str]			,			_lowercase   :    List[str]			,			_lowercase   :    List[str]			,			_lowercase   :    Optional[int]			,			_lowercase   :    Any			,			_lowercase   :    int			,			):
								A					       = True
								A					       = FalconModel(_lowercase		)
								model.to(_lowercase		)
								model.eval()
								A					       = model(
								    _lowercase			,			attention_mask=_lowercase			,			encoder_hidden_states=_lowercase			,			encoder_attention_mask=_lowercase			,			)
								A					       = model(
								    _lowercase			,			attention_mask=_lowercase			,			encoder_hidden_states=_lowercase			,			)
								A					       = model(_lowercase			,			attention_mask=_lowercase		)
								self.parent.assertEqual(result.last_hidden_state.shape			,			(self.batch_size, self.seq_length, self.hidden_size)		)







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







						def __a						(							self   :    List[str]			,			_lowercase   :    Union[str, Any]			,			_lowercase   :    str			,			_lowercase   :    str			,			_lowercase   :    Dict			,			_lowercase   :    str			,			_lowercase   :    Union[str, Any]			,			_lowercase   :    Optional[Any]			,			_lowercase   :    Union[str, Any]			,			_lowercase   :    List[Any]			,			):
								A					       = True
								A					       = True
								A					       = FalconForCausalLM(config=_lowercase		)
								model.to(_lowercase		)
								model.eval()

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

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

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

								A					       = model(
								    _lowercase			,			attention_mask=_lowercase			,			encoder_hidden_states=_lowercase			,			encoder_attention_mask=_lowercase			,			output_hidden_states=_lowercase			,			)['hidden_states'][0]
								A					       = model(
								    _lowercase			,			attention_mask=_lowercase			,			encoder_hidden_states=_lowercase			,			encoder_attention_mask=_lowercase			,			past_key_values=_lowercase			,			output_hidden_states=_lowercase			,			)['hidden_states'][0]

								# select random slice
								A					       = ids_tensor((1,)			,			output_from_past.shape[-1]		).item()
								A					       = output_from_no_past[:, -3:, random_slice_idx].detach()
								A					       = 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(_lowercase			,			_lowercase			,			atol=1e-3		)		)







						def __a						(							self   :    Optional[int]		):
								A					       = self.prepare_config_and_inputs()
								(
								    (
								    A
								)       , (
								    A
								)       , (
								    A
								)       , (
								    A
								)       , (
								    A
								)       , (
								    A
								)       , (
								    A
								)       , 
								)					       = config_and_inputs
								A					       = {'input_ids': input_ids, 'attention_mask': input_mask}
								return config, inputs_dict



@require_torch
class 			lowerCamelCase__						(   UpperCAmelCase_							,    UpperCAmelCase_							,    UpperCAmelCase_							,    unittest.TestCase			):
						lowerCAmelCase       =     (
						    (
						        FalconModel,
						        FalconForCausalLM,
						        FalconForSequenceClassification,
						        FalconForTokenClassification,
						        FalconForQuestionAnswering,
						    )
						    if is_torch_available()
						    else ()
						)
						lowerCAmelCase       =     (FalconForCausalLM,) if is_torch_available() else ()
						lowerCAmelCase       =     (
						    {
						        """feature-extraction""": FalconModel,
						        """text-classification""": FalconForSequenceClassification,
						        """text-generation""": FalconForCausalLM,
						        """question-answering""": FalconForQuestionAnswering,
						        """token-classification""": FalconForTokenClassification,
						        """zero-shot""": FalconForSequenceClassification,
						    }
						    if is_torch_available()
						    else {}
						)
						lowerCAmelCase       =     False
						lowerCAmelCase       =     False







						def __a						(							self   :    Union[str, Any]		):
								A					       = FalconModelTester(self		)
								A					       = ConfigTester(self			,			config_class=_lowercase			,			hidden_size=37		)







						def __a						(							self   :    Any		):
								self.config_tester.run_common_tests()







						def __a						(							self   :    Tuple		):
								A					       = self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*_lowercase		)







						def __a						(							self   :    List[Any]		):
								A       , *A					       = self.model_tester.prepare_config_and_inputs()
								for alibi in [True, False]:
										A					       = alibi
										self.model_tester.create_and_check_model(_lowercase			,			*_lowercase		)







						def __a						(							self   :    Optional[int]		):
								A       , A					       = self.model_tester.prepare_config_and_inputs_for_common()
								A					       = 3
								A					       = input_dict['input_ids']
								A					       = input_ids.ne(1		).to(_lowercase		)
								A					       = ids_tensor([self.model_tester.batch_size]			,			self.model_tester.type_sequence_label_size		)
								A					       = FalconForSequenceClassification(_lowercase		)
								model.to(_lowercase		)
								model.eval()
								A					       = model(_lowercase			,			attention_mask=_lowercase			,			labels=_lowercase		)
								self.assertEqual(result.logits.shape			,			(self.model_tester.batch_size, self.model_tester.num_labels)		)







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







						def __a						(							self   :    Tuple		):
								A       , A					       = self.model_tester.prepare_config_and_inputs_for_common()
								A					       = input_dict['input_ids']
								A					       = FalconForCausalLM(_lowercase		)
								model.to(_lowercase		)
								model.eval()
								A					       = model(_lowercase			,			use_cache=_lowercase		)
								A					       = input_ids.shape[0]
								A					       = model._convert_to_rw_cache(result.past_key_values		)
								A					       = model._convert_cache_to_standard_format(_lowercase			,			_lowercase		)
								for layer in range(len(_lowercase		)		):
										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   :    Union[str, Any]		):
								A       , A					       = self.model_tester.prepare_config_and_inputs_for_common()
								A					       = 3
								A					       = 'multi_label_classification'
								A					       = input_dict['input_ids']
								A					       = input_ids.ne(1		).to(_lowercase		)
								A					       = ids_tensor(
								    [self.model_tester.batch_size, config.num_labels]			,			self.model_tester.type_sequence_label_size		).to(torch.float		)
								A					       = FalconForSequenceClassification(_lowercase		)
								model.to(_lowercase		)
								model.eval()
								A					       = model(_lowercase			,			attention_mask=_lowercase			,			labels=_lowercase		)
								self.assertEqual(result.logits.shape			,			(self.model_tester.batch_size, self.model_tester.num_labels)		)







						def __a						(							self   :    Optional[Any]		):
								# 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:
										A       , A					       = self.model_tester.prepare_config_and_inputs_for_common()

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

										A					       = model_class(_lowercase		).to(_lowercase		)
										if "use_cache" not in inputs:
												A					       = True
										A					       = model(**_lowercase		)

										# 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

										A					       = (
										    getattr(_lowercase			,			'decoder_layers'			,			_lowercase		)
										    or getattr(_lowercase			,			'num_decoder_layers'			,			_lowercase		)
										    or config.num_hidden_layers
										)
										A					       = getattr(_lowercase			,			'num_kv_heads'			,			config.num_attention_heads		)
										A					       = getattr(_lowercase			,			'd_model'			,			config.hidden_size		)
										A					       = embed_dim // num_attention_heads

										A					       = outputs['past_key_values']
										self.assertEqual(len(_lowercase		)			,			_lowercase		)

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







						@slow
						def __a						(							self   :    int		):
								A					       = AutoTokenizer.from_pretrained('Rocketknight1/falcon-rw-1b'		)
								A					       = FalconForCausalLM.from_pretrained('Rocketknight1/falcon-rw-1b'		)
								model.eval()
								model.to(_lowercase		)
								A					       = tokenizer('My favorite food is'			,			return_tensors='pt'		).to(_lowercase		)

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

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

								self.assertEqual(_lowercase			,			_lowercase		)







						@slow
						def __a						(							self   :    Union[str, 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"]:
										A					       = AutoTokenizer.from_pretrained(_lowercase		)
										A					       = FalconForCausalLM.from_pretrained(_lowercase		)
										model.eval()
										model.to(_lowercase		)
										A					       = tokenizer('My favorite food is'			,			return_tensors='pt'		).to(_lowercase		)

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







						@slow
						def __a						(							self   :    int		):
								# 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",
										]:
												A					       = AutoTokenizer.from_pretrained(_lowercase		)
												A					       = FalconForCausalLM.from_pretrained(_lowercase		)
												model.eval()
												model.to(device=_lowercase		)
												A					       = tokenizer('My favorite food is'			,			return_tensors='pt'		).to(_lowercase		)

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









"""simple docstring"""


import os
import unittest

from transformers.models.transfo_xl.tokenization_transfo_xl import VOCAB_FILES_NAMES, TransfoXLTokenizer

from ...test_tokenization_common import TokenizerTesterMixin



class 			lowerCamelCase__						(   UpperCAmelCase_							,    unittest.TestCase			):
						lowerCAmelCase       =     TransfoXLTokenizer
						lowerCAmelCase       =     False
						lowerCAmelCase       =     False







						def __a						(							self   :    Union[str, Any]		):
								super().setUp()

								A					       = [
								    '<unk>',
								    '[CLS]',
								    '[SEP]',
								    'want',
								    'unwanted',
								    'wa',
								    'un',
								    'running',
								    ',',
								    'low',
								    'l',
								]
								A					       = os.path.join(self.tmpdirname			,			VOCAB_FILES_NAMES['vocab_file']		)
								with open(self.vocab_file			,			'w'			,			encoding='utf-8'		) as vocab_writer:
										vocab_writer.write(''.join([x + '\n' for x in vocab_tokens]		)		)







						def __a						(							self   :    int			,			**_lowercase   :    List[str]		):
								A					       = True
								return TransfoXLTokenizer.from_pretrained(self.tmpdirname			,			**_lowercase		)







						def __a						(							self   :    int			,			_lowercase   :    List[Any]		):
								A					       = '<unk> UNwanted , running'
								A					       = '<unk> unwanted, running'
								return input_text, output_text







						def __a						(							self   :    List[str]		):
								A					       = TransfoXLTokenizer(vocab_file=self.vocab_file			,			lower_case=_lowercase		)

								A					       = tokenizer.tokenize('<unk> UNwanted , running'		)
								self.assertListEqual(_lowercase			,			['<unk>', 'unwanted', ',', 'running']		)

								self.assertListEqual(tokenizer.convert_tokens_to_ids(_lowercase		)			,			[0, 4, 8, 7]		)







						def __a						(							self   :    int		):
								A					       = TransfoXLTokenizer(lower_case=_lowercase		)

								self.assertListEqual(
								    tokenizer.tokenize(' \tHeLLo ! how  \n Are yoU ?  '		)			,			['hello', '!', 'how', 'are', 'you', '?']		)







						def __a						(							self   :    Optional[Any]		):
								A					       = TransfoXLTokenizer(lower_case=_lowercase		)

								self.assertListEqual(
								    tokenizer.tokenize(' \tHeLLo ! how  \n Are yoU ?  '		)			,			['HeLLo', '!', 'how', 'Are', 'yoU', '?']		)







						def __a						(							self   :    str		):
								A					       = TransfoXLTokenizer(lower_case=_lowercase		)
								A					       = 'Hello (bracket) and side-scrolled [and] Henry\'s $5,000 with 3.34 m. What\'s up!?'
								A					       = [
								    'Hello',
								    '(',
								    'bracket',
								    ')',
								    'and',
								    'side',
								    '@-@',
								    'scrolled',
								    '[',
								    'and',
								    ']',
								    'Henry',
								    '\'s',
								    '$',
								    '5',
								    '@,@',
								    '000',
								    'with',
								    '3',
								    '@.@',
								    '34',
								    'm',
								    '.',
								    'What',
								    '\'s',
								    'up',
								    '!',
								    '?',
								]

								self.assertListEqual(tokenizer.tokenize(_lowercase		)			,			_lowercase		)

								self.assertEqual(tokenizer.convert_tokens_to_string(_lowercase		)			,			_lowercase		)







						def __a						(							self   :    Dict		):
								A					       = self.get_tokenizer()
								A					       = len(_lowercase		)

								tokenizer.add_tokens(['new1', 'new2']		)
								tokenizer.move_added_token('new1'			,			1		)

								# Check that moved token is not copied (duplicate)
								self.assertEqual(len(_lowercase		)			,			original_len + 2		)
								# Check that token is moved to specified id
								self.assertEqual(tokenizer.encode('new1'		)			,			[1]		)
								self.assertEqual(tokenizer.decode([1]		)			,			'new1'		)





