

import argparse
import os

import evaluate
import torch
from datasets import load_dataset
from torch.optim import AdamW
from torch.utils.data import DataLoader
from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed

from accelerate import Accelerator, DistributedType


########################################################################
# This is a fully working simple example to use Accelerate,
# specifically showcasing the experiment tracking capability,
# and builds off the `nlp_example.py` script.
#
# This example trains a Bert base model on GLUE MRPC
# in any of the following settings (with the same script):
#   - single CPU or single GPU
#   - multi GPUS (using PyTorch distributed mode)
#   - (multi) TPUs
#   - fp16 (mixed-precision) or fp32 (normal precision)
#
# To help focus on the differences in the code, building `DataLoaders`
# was refactored into its own function.
# New additions from the base script can be found quickly by
# looking for the # New Code # tags
#
# To run it in each of these various modes, follow the instructions
# in the readme for examples:
# https://github.com/huggingface/accelerate/tree/main/examples
#
########################################################################

A_	:			Optional[Any]  	=      16
A_	:			Optional[int]  	=      32

def 						UpperCamelCase (lowercase_:			Accelerator   ,				lowercase_:			int = 16 )					->				Optional[Any]:
	A__							:   Union[str, Any]					       =		AutoTokenizer.from_pretrained("""bert-base-cased""" )
	A__							:   Union[str, Any]					       =		load_dataset("""glue"""   ,				"""mrpc""" )

	def tokenize_function(lowercase_:			Union[str, Any] ):
		# max_length=None => use the model max length (it's actually the default)
		A__							:   Dict					       =		tokenizer(examples["""sentence1"""]   ,				examples["""sentence2"""]   ,				truncation=lowercase_   ,				max_length=lowercase_ )
		return outputs

	# Apply the method we just defined to all the examples in all the splits of the dataset
	# starting with the main process first:
	with accelerator.main_process_first():
		A__							:   Tuple					       =		datasets.map(
		    lowercase_   ,				batched=lowercase_   ,				remove_columns=["""idx""", """sentence1""", """sentence2"""]   ,				)

	# We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
	# transformers library
	A__							:   List[Any]					       =		tokenized_datasets.rename_column("""label"""   ,				"""labels""" )

	def collate_fn(lowercase_:			List[str] ):
		# On TPU it's best to pad everything to the same length or training will be very slow.
		A__							:   int					       =		128 if accelerator.distributed_type == DistributedType.TPU else None
		# When using mixed precision we want round multiples of 8/16
		if accelerator.mixed_precision == "fp8":
			A__							:   int					       =		16
		elif accelerator.mixed_precision != "no":
			A__							:   str					       =		8
		else:
			A__							:   Optional[int]					       =		None

		return tokenizer.pad(
		    lowercase_   ,				padding="""longest"""   ,				max_length=lowercase_   ,				pad_to_multiple_of=lowercase_   ,				return_tensors="""pt"""   ,				)

	# Instantiate dataloaders.
	A__							:   List[Any]					       =		DataLoader(
	    tokenized_datasets["""train"""]   ,				shuffle=lowercase_   ,				collate_fn=lowercase_   ,				batch_size=lowercase_ )
	A__							:   List[str]					       =		DataLoader(
	    tokenized_datasets["""validation"""]   ,				shuffle=lowercase_   ,				collate_fn=lowercase_   ,				batch_size=lowercase_ )

	return train_dataloader, eval_dataloader


# For testing only
if os.environ.get('TESTING_MOCKED_DATALOADERS', None) == "1":
	from accelerate.test_utils.training import mocked_dataloaders

	A_	:			List[str]  	=      mocked_dataloaders  # noqa: F811

def 						UpperCamelCase (lowercase_:			Optional[Any]   ,				lowercase_:			Optional[int] )					->				Optional[int]:
	# For testing only
	if os.environ.get("""TESTING_MOCKED_DATALOADERS"""   ,				lowercase_ ) == "1":
		A__							:   Optional[Any]					       =		2
	# Initialize Accelerator

	# New Code #
	# We pass in "all" to `log_with` to grab all available trackers in the environment
	# Note: If using a custom `Tracker` class, should be passed in here such as:
	# >>> log_with = ["all", MyCustomTrackerClassInstance()]
	if args.with_tracking:
		A__							:   Tuple					       =		Accelerator(
		    cpu=args.cpu   ,				mixed_precision=args.mixed_precision   ,				log_with="""all"""   ,				project_dir=args.project_dir )
	else:
		A__							:   Tuple					       =		Accelerator(cpu=args.cpu   ,				mixed_precision=args.mixed_precision )
	# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
	A__							:   Optional[Any]					       =		config["""lr"""]
	A__							:   Optional[int]					       =		int(config["""num_epochs"""] )
	A__							:   int					       =		int(config["""seed"""] )
	A__							:   Union[str, Any]					       =		int(config["""batch_size"""] )
	set_seed(lowercase_ )

	A__       ,       A__							:   str					       =		get_dataloaders(lowercase_   ,				lowercase_ )
	A__							:   List[str]					       =		evaluate.load("""glue"""   ,				"""mrpc""" )

	# If the batch size is too big we use gradient accumulation
	A__							:   int					       =		1
	if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU:
		A__							:   int					       =		batch_size // MAX_GPU_BATCH_SIZE
		A__							:   Tuple					       =		MAX_GPU_BATCH_SIZE

	# Instantiate the model (we build the model here so that the seed also control new weights initialization)
	A__							:   List[Any]					       =		AutoModelForSequenceClassification.from_pretrained("""bert-base-cased"""   ,				return_dict=lowercase_ )

	# We could avoid this line since the accelerator is set with `device_placement=True` (default value).
	# Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
	# creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
	A__							:   Any					       =		model.to(accelerator.device )

	# Instantiate optimizer
	A__							:   int					       =		AdamW(params=model.parameters()   ,				lr=lowercase_ )

	# Instantiate scheduler
	A__							:   Any					       =		get_linear_schedule_with_warmup(
	    optimizer=lowercase_   ,				num_warmup_steps=100   ,				num_training_steps=(len(lowercase_ ) * num_epochs) // gradient_accumulation_steps   ,				)

	# Prepare everything
	# There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
	# prepare method.
	A__       ,       A__       ,       A__       ,       A__       ,       A__							:   Dict					       =		accelerator.prepare(
	    lowercase_   ,				lowercase_   ,				lowercase_   ,				lowercase_   ,				lowercase_ )

	# New Code #
	# We need to initialize the trackers we use. Overall configurations can also be stored
	if args.with_tracking:
		A__							:   Any					       =		os.path.split(lowercase_ )[-1].split(""".""" )[0]
		accelerator.init_trackers(lowercase_   ,				lowercase_ )

	# Now we train the model
	for epoch in range(lowercase_ ):
		model.train()
		# New Code #
		# For our tracking example, we will log the total loss of each epoch
		if args.with_tracking:
			A__							:   Union[str, Any]					       =		0
		for step, batch in enumerate(lowercase_ ):
			# We could avoid this line since we set the accelerator with `device_placement=True`.
			batch.to(accelerator.device )
			A__							:   str					       =		model(**lowercase_ )
			A__							:   Optional[Any]					       =		outputs.loss
			# New Code #
			if args.with_tracking:
				total_loss += loss.detach().float()
			A__							:   List[str]					       =		loss / gradient_accumulation_steps
			accelerator.backward(lowercase_ )
			if step % gradient_accumulation_steps == 0:
				optimizer.step()
				lr_scheduler.step()
				optimizer.zero_grad()

		model.eval()
		for step, batch in enumerate(lowercase_ ):
			# We could avoid this line since we set the accelerator with `device_placement=True` (the default).
			batch.to(accelerator.device )
			with torch.no_grad():
				A__							:   Optional[int]					       =		model(**lowercase_ )
			A__							:   List[Any]					       =		outputs.logits.argmax(dim=-1 )
			A__       ,       A__							:   Any					       =		accelerator.gather_for_metrics((predictions, batch["""labels"""]) )
			metric.add_batch(
			    predictions=lowercase_   ,				references=lowercase_   ,				)

		A__							:   List[str]					       =		metric.compute()
		# Use accelerator.print to print only on the main process.
		accelerator.print(f"""epoch {epoch}:"""   ,				lowercase_ )

		# New Code #
		# To actually log, we call `Accelerator.log`
		# The values passed can be of `str`, `int`, `float` or `dict` of `str` to `float`/`int`
		if args.with_tracking:
			accelerator.log(
			    {
			        """accuracy""": eval_metric["""accuracy"""],
			        """f1""": eval_metric["""f1"""],
			        """train_loss""": total_loss.item() / len(lowercase_ ),
			        """epoch""": epoch,
			    }   ,				step=lowercase_   ,				)

    # New Code #
    # When a run is finished, you should call `accelerator.end_training()`
    # to close all of the open trackers
	if args.with_tracking:
		accelerator.end_training()

def 						UpperCamelCase ()					->				List[Any]:
	A__							:   List[Any]					       =		argparse.ArgumentParser(description="""Simple example of training script.""" )
	parser.add_argument(
	    """--mixed_precision"""   ,				type=lowercase_   ,				default=lowercase_   ,				choices=["""no""", """fp16""", """bf16""", """fp8"""]   ,				help="""Whether to use mixed precision. Choose"""
	    """between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10."""
	    """and an Nvidia Ampere GPU."""   ,				)
	parser.add_argument("""--cpu"""   ,				action="""store_true"""   ,				help="""If passed, will train on the CPU.""" )
	parser.add_argument(
	    """--with_tracking"""   ,				action="""store_true"""   ,				help="""Whether to load in all available experiment trackers from the environment and use them for logging."""   ,				)
	parser.add_argument(
	    """--project_dir"""   ,				type=lowercase_   ,				default="""logs"""   ,				help="""Location on where to store experiment tracking logs` and relevent project information"""   ,				)
	A__							:   Dict					       =		parser.parse_args()
	A__							:   Any					       =		{"""lr""": 2E-5, """num_epochs""": 3, """seed""": 42, """batch_size""": 16}
	training_function(lowercase_   ,				lowercase_ )


if __name__ == "__main__":
	main()






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


					'''simple docstring'''






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






					def   __A      (			self      ):
						A__							:   Any					       =		ids_tensor([self.batch_size, self.seq_length]   ,	self.vocab_size      )

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

						A__							:   str					       =		None

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

						A__							:   Dict					       =		self.get_config()

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






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






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






					def   __A      (			self   ,	A__   ,	A__   ,	A__   ,	A__   ,	A__   ,	A__   ,	A__   ,	A__   ,	A__   ,	):
						A__							:   Union[str, Any]					       =		True
						A__							:   Union[str, Any]					       =		FalconModel(A__      )
						model.to(A__      )
						model.eval()
						A__							:   Tuple					       =		model(
						    A__   ,	attention_mask=A__   ,	encoder_hidden_states=A__   ,	encoder_attention_mask=A__   ,	)
						A__							:   Union[str, Any]					       =		model(
						    A__   ,	attention_mask=A__   ,	encoder_hidden_states=A__   ,	)
						A__							:   List[str]					       =		model(A__   ,	attention_mask=A__      )
						self.parent.assertEqual(result.last_hidden_state.shape   ,	(self.batch_size, self.seq_length, self.hidden_size)      )






					def   __A      (			self   ,	A__   ,	A__   ,	A__   ,	A__   ,	A__   ,	A__   ,	A__   ,	A__   ,	A__   ,	):
						A__							:   Any					       =		FalconForCausalLM(config=A__      )
						model.to(A__      )
						model.eval()
						A__							:   Tuple					       =		model(A__   ,	attention_mask=A__   ,	labels=A__      )
						self.parent.assertEqual(result.logits.shape   ,	(self.batch_size, self.seq_length, self.vocab_size)      )






					def   __A      (			self   ,	A__   ,	A__   ,	A__   ,	A__   ,	A__   ,	A__   ,	A__   ,	A__   ,	A__   ,	):
						A__							:   Optional[Any]					       =		True
						A__							:   Union[str, Any]					       =		True
						A__							:   int					       =		FalconForCausalLM(config=A__      )
						model.to(A__      )
						model.eval()

						# first forward pass
						A__							:   List[Any]					       =		model(
						    A__   ,	attention_mask=A__   ,	encoder_hidden_states=A__   ,	encoder_attention_mask=A__   ,	use_cache=A__   ,	)
						A__							:   Tuple					       =		outputs.past_key_values

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

						# append to next input_ids and
						A__							:   Optional[int]					       =		torch.cat([input_ids, next_tokens]   ,	dim=-1      )
						A__							:   List[str]					       =		torch.cat([input_mask, next_mask]   ,	dim=-1      )

						A__							:   Optional[int]					       =		model(
						    A__   ,	attention_mask=A__   ,	encoder_hidden_states=A__   ,	encoder_attention_mask=A__   ,	output_hidden_states=A__   ,	)["""hidden_states"""][0]
						A__							:   Any					       =		model(
						    A__   ,	attention_mask=A__   ,	encoder_hidden_states=A__   ,	encoder_attention_mask=A__   ,	past_key_values=A__   ,	output_hidden_states=A__   ,	)["""hidden_states"""][0]

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






					def   __A      (			self      ):
						A__							:   List[str]					       =		self.prepare_config_and_inputs()
						(
						    (
						    A__
						)       ,       (
						    A__
						)       ,       (
						    A__
						)       ,       (
						    A__
						)       ,       (
						    A__
						)       ,       (
						    A__
						)       ,       (
						    A__
						)       ,       
						)							:   Tuple					       =		config_and_inputs
						A__							:   List[str]					       =		{"""input_ids""": input_ids, """attention_mask""": input_mask}
						return config, inputs_dict



@require_torch
class    _a						(__magic_name__		,       __magic_name__		,       __magic_name__		,       unittest.TestCase    ):


					'''simple docstring'''






					UpperCAmelCase__:       List[Any]  							=	(
					    (
					        FalconModel,
					        FalconForCausalLM,
					        FalconForSequenceClassification,
					        FalconForTokenClassification,
					        FalconForQuestionAnswering,
					    )
					    if is_torch_available()
					    else ()
					)
					UpperCAmelCase__:       Tuple  							=	(FalconForCausalLM,) if is_torch_available() else ()
					UpperCAmelCase__:       Optional[int]  							=	(
					    {
					        '''feature-extraction''': FalconModel,
					        '''text-classification''': FalconForSequenceClassification,
					        '''text-generation''': FalconForCausalLM,
					        '''question-answering''': FalconForQuestionAnswering,
					        '''token-classification''': FalconForTokenClassification,
					        '''zero-shot''': FalconForSequenceClassification,
					    }
					    if is_torch_available()
					    else {}
					)
					UpperCAmelCase__:       str  							=	False
					UpperCAmelCase__:       int  							=	False






					def   __A      (			self      ):
						A__							:   List[Any]					       =		FalconModelTester(self      )
						A__							:   Union[str, Any]					       =		ConfigTester(self   ,	config_class=A__   ,	hidden_size=37      )






					def   __A      (			self      ):
						self.config_tester.run_common_tests()






					def   __A      (			self      ):
						A__							:   Tuple					       =		self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*A__      )






					def   __A      (			self      ):
						A__       ,       *A__							:   List[Any]					       =		self.model_tester.prepare_config_and_inputs()
						for alibi in [True, False]:
							A__							:   Tuple					       =		alibi
							self.model_tester.create_and_check_model(A__   ,	*A__      )






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






					def   __A      (			self      ):
						A__       ,       A__							:   str					       =		self.model_tester.prepare_config_and_inputs_for_common()
						A__							:   Dict					       =		3
						A__							:   Tuple					       =		"""single_label_classification"""
						A__							:   List[Any]					       =		input_dict["""input_ids"""]
						A__							:   Dict					       =		input_ids.ne(1      ).to(A__      )
						A__							:   Dict					       =		ids_tensor([self.model_tester.batch_size]   ,	self.model_tester.type_sequence_label_size      )
						A__							:   Any					       =		FalconForSequenceClassification(A__      )
						model.to(A__      )
						model.eval()
						A__							:   Any					       =		model(A__   ,	attention_mask=A__   ,	labels=A__      )
						self.assertEqual(result.logits.shape   ,	(self.model_tester.batch_size, self.model_tester.num_labels)      )






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






					def   __A      (			self      ):
						# 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__							:   Tuple					       =		self.model_tester.prepare_config_and_inputs_for_common()

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

							A__							:   Optional[Any]					       =		model_class(A__      ).to(A__      )
							if "use_cache" not in inputs:
								A__							:   Optional[int]					       =		True
							A__							:   List[Any]					       =		model(**A__      )

							# 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__							:   str					       =		(
							    getattr(A__   ,	"""decoder_layers"""   ,	A__      )
							    or getattr(A__   ,	"""num_decoder_layers"""   ,	A__      )
							    or config.num_hidden_layers
							)
							A__							:   Dict					       =		getattr(A__   ,	"""num_kv_heads"""   ,	config.num_attention_heads      )
							A__							:   List[str]					       =		getattr(A__   ,	"""d_model"""   ,	config.hidden_size      )
							A__							:   Union[str, Any]					       =		embed_dim // num_attention_heads

							A__							:   str					       =		outputs["""past_key_values"""]
							self.assertEqual(len(A__      )   ,	A__      )

							A__       ,       A__							:   int					       =		inputs["""input_ids"""].shape
							for i in range(A__      ):
								if config.new_decoder_architecture:
									A__							:   Any					       =		config.num_attention_heads
								elif config.multi_query:
									A__							:   List[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    _a						(unittest.TestCase    ):


					'''simple docstring'''






					@slow
					def   __A      (			self      ):
						A__							:   Dict					       =		AutoTokenizer.from_pretrained("""Rocketknight1/falcon-rw-1b"""      )
						A__							:   List[Any]					       =		FalconForCausalLM.from_pretrained("""Rocketknight1/falcon-rw-1b"""      )
						model.eval()
						model.to(A__      )
						A__							:   Optional[int]					       =		tokenizer("""My favorite food is"""   ,	return_tensors="""pt"""      ).to(A__      )

						A__							:   Optional[Any]					       =		(
						    """My favorite food is pizza. I love it so much that I have a pizza party every year for my birthday."""
						)

						A__							:   Any					       =		model.generate(**A__   ,	do_sample=A__   ,	max_new_tokens=19      )
						A__							:   Optional[int]					       =		tokenizer.batch_decode(A__      )[0]

						self.assertEqual(A__   ,	A__      )






					@slow
					def   __A      (			self      ):
						# 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__							:   Dict					       =		AutoTokenizer.from_pretrained(A__      )
							A__							:   List[str]					       =		FalconForCausalLM.from_pretrained(A__      )
							model.eval()
							model.to(A__      )
							A__							:   Union[str, Any]					       =		tokenizer("""My favorite food is"""   ,	return_tensors="""pt"""      ).to(A__      )

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






					@slow
					def   __A      (			self      ):
						# 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__							:   Dict					       =		AutoTokenizer.from_pretrained(A__      )
								A__							:   Any					       =		FalconForCausalLM.from_pretrained(A__      )
								model.eval()
								model.to(device=A__      )
								A__							:   List[str]					       =		tokenizer("""My favorite food is"""   ,	return_tensors="""pt"""      ).to(A__      )

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



