

import json
import os
import re
import shutil
import tempfile
import unittest
from typing import Tuple

from transformers import AddedToken, BatchEncoding, ByTaTokenizer
from transformers.utils import cached_property, is_tf_available, is_torch_available

from ...test_tokenization_common import TokenizerTesterMixin


if is_torch_available():
 A_	:			Optional[Any]  	=      '''pt'''
elif is_tf_available():
 A_	:			str  	=      '''tf'''
else:
 A_	:			Any  	=      '''jax'''



class    _a						(SCREAMING_SNAKE_CASE__		,       unittest.TestCase    ):


     '''simple docstring'''






     UpperCAmelCase__:       Any  							=	ByTaTokenizer
     UpperCAmelCase__:       Union[str, Any]  							=	False






     def   __A      (			self      ):
      super().setUp()
      A__							:   Dict					       =		ByTaTokenizer()
      tokenizer.save_pretrained(self.tmpdirname      )






     @cached_property
     def   __A      (			self      ):
      return ByTaTokenizer.from_pretrained("""google/byt5-small"""      )






     def   __A      (			self   ,	**A__      ):
      return self.tokenizer_class.from_pretrained(self.tmpdirname   ,	**_SCREAMING_SNAKE_CASE      )






     def   __A      (			self   ,	A__   ,	A__=False   ,	A__=20   ,	A__=5      ):
      # XXX The default common tokenizer tests assume that every ID is decodable on its own.
      # This assumption is invalid for ByT5 because single bytes might not be
      # valid utf-8 (byte 128 for instance).
      # Here we're overriding the smallest possible method to provide
      # a clean sequence without making the same assumption.

      A__							:   Union[str, Any]					       =		[]
      for i in range(len(_SCREAMING_SNAKE_CASE      )      ):
       try:
        A__							:   List[Any]					       =		tokenizer.decode([i]   ,	clean_up_tokenization_spaces=_SCREAMING_SNAKE_CASE      )
       except UnicodeDecodeError:
        pass
       toks.append((i, tok)      )

      A__							:   Dict					       =		list(filter(lambda A__      : re.match(r"""^[ a-zA-Z]+$"""   ,	t[1]      )   ,	_SCREAMING_SNAKE_CASE      )      )
      A__							:   List[Any]					       =		list(filter(lambda A__      : [t[0]] == tokenizer.encode(t[1]   ,	add_special_tokens=_SCREAMING_SNAKE_CASE      )   ,	_SCREAMING_SNAKE_CASE      )      )
      if max_length is not None and len(_SCREAMING_SNAKE_CASE      ) > max_length:
       A__							:   Optional[int]					       =		toks[:max_length]
      if min_length is not None and len(_SCREAMING_SNAKE_CASE      ) < min_length and len(_SCREAMING_SNAKE_CASE      ) > 0:
       while len(_SCREAMING_SNAKE_CASE      ) < min_length:
        A__							:   Optional[Any]					       =		toks + toks
        # toks_str = [t[1] for t in toks]
      A__							:   Optional[int]					       =		[t[0] for t in toks]

      # Ensure consistency
      A__							:   Tuple					       =		tokenizer.decode(_SCREAMING_SNAKE_CASE   ,	clean_up_tokenization_spaces=_SCREAMING_SNAKE_CASE      )
      if " " not in output_txt and len(_SCREAMING_SNAKE_CASE      ) > 1:
       A__							:   Optional[Any]					       =		(
           tokenizer.decode([toks_ids[0]]   ,	clean_up_tokenization_spaces=_SCREAMING_SNAKE_CASE      )
           + " "
           + tokenizer.decode(toks_ids[1:]   ,	clean_up_tokenization_spaces=_SCREAMING_SNAKE_CASE      )
       )
      if with_prefix_space:
       A__							:   int					       =		" " + output_txt
      A__							:   Dict					       =		tokenizer.encode(_SCREAMING_SNAKE_CASE   ,	add_special_tokens=_SCREAMING_SNAKE_CASE      )
      return output_txt, output_ids






     def   __A      (			self      ):
      A__							:   str					       =		self.ta_base_tokenizer
      A__							:   List[Any]					       =		tokenizer(["""hi</s>""", """I went to the gym</s>""", """</s>"""]      )
      A__							:   Any					       =		tokenizer(["""hi""", """I went to the gym""", """"""]      )
      self.assertListEqual(batch_with_eos_added["""input_ids"""]   ,	batch_without_eos_added["""input_ids"""]      )






     def   __A      (			self      ):
      A__							:   Optional[int]					       =		self.ta_base_tokenizer
      A__							:   Any					       =		"Unicode €."
      A__							:   Union[str, Any]					       =		tokenizer(_SCREAMING_SNAKE_CASE      )
      A__							:   Tuple					       =		[88, 113, 108, 102, 114, 103, 104, 35, 229, 133, 175, 49, 1]
      self.assertEqual(encoded["""input_ids"""]   ,	_SCREAMING_SNAKE_CASE      )

      # decoding
      A__							:   List[Any]					       =		tokenizer.decode(_SCREAMING_SNAKE_CASE      )
      self.assertEqual(_SCREAMING_SNAKE_CASE   ,	"""Unicode €.</s>"""      )

      A__							:   Optional[Any]					       =		tokenizer("""e è é ê ë"""      )
      A__							:   Any					       =		[104, 35, 198, 171, 35, 198, 172, 35, 198, 173, 35, 198, 174, 1]
      self.assertEqual(encoded["""input_ids"""]   ,	_SCREAMING_SNAKE_CASE      )
      # decoding
      A__							:   Optional[Any]					       =		tokenizer.decode(_SCREAMING_SNAKE_CASE      )
      self.assertEqual(_SCREAMING_SNAKE_CASE   ,	"""e è é ê ë</s>"""      )

      # encode/decode, but with `encode` instead of `__call__`
      self.assertEqual(tokenizer.decode(tokenizer.encode("""e è é ê ë"""      )      )   ,	"""e è é ê ë</s>"""      )






     def   __A      (			self      ):
      A__							:   int					       =		self.ta_base_tokenizer
      A__							:   Any					       =		["A long paragraph for summarization.", "Another paragraph for summarization."]
      # fmt: off
      A__							:   Union[str, Any]					       =		[68, 35, 111, 114, 113, 106, 35, 115, 100, 117, 100, 106, 117, 100, 115, 107, 35, 105, 114, 117, 35, 118, 120, 112, 112, 100, 117, 108, 125, 100, 119, 108, 114, 113, 49, 1, 0]
      # fmt: on
      A__							:   Tuple					       =		tokenizer(_SCREAMING_SNAKE_CASE   ,	padding=_SCREAMING_SNAKE_CASE   ,	return_tensors=_SCREAMING_SNAKE_CASE      )
      self.assertIsInstance(_SCREAMING_SNAKE_CASE   ,	_SCREAMING_SNAKE_CASE      )

      if FRAMEWORK != "jax":
       A__							:   Optional[Any]					       =		list(batch.input_ids.numpy()[0]      )
      else:
       A__							:   Optional[int]					       =		list(batch.input_ids.tolist()[0]      )

      self.assertListEqual(_SCREAMING_SNAKE_CASE   ,	_SCREAMING_SNAKE_CASE      )

      self.assertEqual((2, 37)   ,	batch.input_ids.shape      )
      self.assertEqual((2, 37)   ,	batch.attention_mask.shape      )






     def   __A      (			self      ):
      A__							:   Tuple					       =		self.ta_base_tokenizer
      A__							:   Any					       =		["A long paragraph for summarization.", "Another paragraph for summarization."]
      A__							:   Optional[int]					       =		tokenizer(_SCREAMING_SNAKE_CASE   ,	padding=_SCREAMING_SNAKE_CASE   ,	return_tensors=_SCREAMING_SNAKE_CASE      )
      # check if input_ids are returned and no decoder_input_ids
      self.assertIn("""input_ids"""   ,	_SCREAMING_SNAKE_CASE      )
      self.assertIn("""attention_mask"""   ,	_SCREAMING_SNAKE_CASE      )
      self.assertNotIn("""decoder_input_ids"""   ,	_SCREAMING_SNAKE_CASE      )
      self.assertNotIn("""decoder_attention_mask"""   ,	_SCREAMING_SNAKE_CASE      )






     def   __A      (			self      ):
      A__							:   Any					       =		self.ta_base_tokenizer
      A__							:   Union[str, Any]					       =		[
          "Summary of the text.",
          "Another summary.",
      ]
      A__							:   Optional[int]					       =		tokenizer(
          text_target=_SCREAMING_SNAKE_CASE   ,	max_length=32   ,	padding="""max_length"""   ,	truncation=_SCREAMING_SNAKE_CASE   ,	return_tensors=_SCREAMING_SNAKE_CASE      )
      self.assertEqual(32   ,	targets["""input_ids"""].shape[1]      )






     def   __A      (			self      ):
      A__							:   List[Any]					       =		self.ta_base_tokenizer
      A__							:   int					       =		["A long paragraph for summarization. </s>"]
      A__							:   List[str]					       =		["Summary of the text. </s>"]
      # fmt: off
      A__							:   Any					       =		[68, 35, 111, 114, 113, 106, 35, 115, 100, 117, 100, 106, 117, 100, 115, 107, 35, 105, 114, 117, 35, 118, 120, 112, 112, 100, 117, 108, 125, 100, 119, 108, 114, 113, 49, 35, 1]
      A__							:   List[str]					       =		[86, 120, 112, 112, 100, 117, 124, 35, 114, 105, 35, 119, 107, 104, 35, 119, 104, 123, 119, 49, 35, 1]
      # fmt: on

      A__							:   int					       =		tokenizer(_SCREAMING_SNAKE_CASE   ,	text_target=_SCREAMING_SNAKE_CASE      )

      self.assertEqual(_SCREAMING_SNAKE_CASE   ,	batch["""input_ids"""][0]      )
      self.assertEqual(_SCREAMING_SNAKE_CASE   ,	batch["""labels"""][0]      )






     def   __A      (			self      ):
      # safety check on max_len default value so we are sure the test works
      A__							:   Union[str, Any]					       =		self.get_tokenizers()
      for tokenizer in tokenizers:
       with self.subTest(F"""{tokenizer.__class__.__name__}"""      ):
        self.assertNotEqual(tokenizer.model_max_length   ,	42      )

        # Now let's start the test
      A__							:   List[Any]					       =		self.get_tokenizers()
      for tokenizer in tokenizers:
       with self.subTest(F"""{tokenizer.__class__.__name__}"""      ):
        # Isolate this from the other tests because we save additional tokens/etc
        A__							:   Dict					       =		tempfile.mkdtemp()

        A__							:   List[Any]					       =		" He is very happy, UNwant\u00E9d,running"
        A__							:   Tuple					       =		tokenizer.encode(_SCREAMING_SNAKE_CASE   ,	add_special_tokens=_SCREAMING_SNAKE_CASE      )
        tokenizer.save_pretrained(_SCREAMING_SNAKE_CASE      )

        A__							:   List[Any]					       =		tokenizer.__class__.from_pretrained(_SCREAMING_SNAKE_CASE      )
        A__							:   Union[str, Any]					       =		after_tokenizer.encode(_SCREAMING_SNAKE_CASE   ,	add_special_tokens=_SCREAMING_SNAKE_CASE      )
        self.assertListEqual(_SCREAMING_SNAKE_CASE   ,	_SCREAMING_SNAKE_CASE      )

        shutil.rmtree(_SCREAMING_SNAKE_CASE      )

      A__							:   List[str]					       =		self.get_tokenizers(model_max_length=42      )
      for tokenizer in tokenizers:
       with self.subTest(F"""{tokenizer.__class__.__name__}"""      ):
        # Isolate this from the other tests because we save additional tokens/etc
        A__							:   str					       =		tempfile.mkdtemp()

        A__							:   int					       =		" He is very happy, UNwant\u00E9d,running"
        tokenizer.add_tokens(["""bim""", """bambam"""]      )
        A__							:   Optional[int]					       =		tokenizer.additional_special_tokens
        additional_special_tokens.append("""new_additional_special_token"""      )
        tokenizer.add_special_tokens({"""additional_special_tokens""": additional_special_tokens}      )
        A__							:   Tuple					       =		tokenizer.encode(_SCREAMING_SNAKE_CASE   ,	add_special_tokens=_SCREAMING_SNAKE_CASE      )
        tokenizer.save_pretrained(_SCREAMING_SNAKE_CASE      )

        A__							:   str					       =		tokenizer.__class__.from_pretrained(_SCREAMING_SNAKE_CASE      )
        A__							:   Tuple					       =		after_tokenizer.encode(_SCREAMING_SNAKE_CASE   ,	add_special_tokens=_SCREAMING_SNAKE_CASE      )
        self.assertListEqual(_SCREAMING_SNAKE_CASE   ,	_SCREAMING_SNAKE_CASE      )
        self.assertIn("""new_additional_special_token"""   ,	after_tokenizer.additional_special_tokens      )
        self.assertEqual(after_tokenizer.model_max_length   ,	42      )

        A__							:   List[str]					       =		tokenizer.__class__.from_pretrained(_SCREAMING_SNAKE_CASE   ,	model_max_length=43      )
        self.assertEqual(tokenizer.model_max_length   ,	43      )

        shutil.rmtree(_SCREAMING_SNAKE_CASE      )






     def   __A      (			self      ):
      A__							:   List[Any]					       =		[]
      if self.test_slow_tokenizer:
       tokenizer_list.append((self.tokenizer_class, self.get_tokenizer())      )

      if self.test_rust_tokenizer:
       tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer())      )

      for tokenizer_class, tokenizer_utils in tokenizer_list:
       with tempfile.TemporaryDirectory() as tmp_dir:
        tokenizer_utils.save_pretrained(_SCREAMING_SNAKE_CASE      )

        with open(os.path.join(_SCREAMING_SNAKE_CASE   ,	"""special_tokens_map.json"""      )   ,	encoding="""utf-8"""      ) as json_file:
         A__							:   Union[str, Any]					       =		json.load(_SCREAMING_SNAKE_CASE      )

        with open(os.path.join(_SCREAMING_SNAKE_CASE   ,	"""tokenizer_config.json"""      )   ,	encoding="""utf-8"""      ) as json_file:
         A__							:   Dict					       =		json.load(_SCREAMING_SNAKE_CASE      )

        A__							:   Tuple					       =		[F"""<extra_id_{i}>""" for i in range(125      )]

        A__							:   Optional[Any]					       =		added_tokens_extra_ids + [
            "an_additional_special_token"
        ]
        A__							:   Dict					       =		added_tokens_extra_ids + [
            "an_additional_special_token"
        ]

        with open(os.path.join(_SCREAMING_SNAKE_CASE   ,	"""special_tokens_map.json"""      )   ,	"""w"""   ,	encoding="""utf-8"""      ) as outfile:
         json.dump(_SCREAMING_SNAKE_CASE   ,	_SCREAMING_SNAKE_CASE      )
        with open(os.path.join(_SCREAMING_SNAKE_CASE   ,	"""tokenizer_config.json"""      )   ,	"""w"""   ,	encoding="""utf-8"""      ) as outfile:
         json.dump(_SCREAMING_SNAKE_CASE   ,	_SCREAMING_SNAKE_CASE      )

        # the following checks allow us to verify that our test works as expected, i.e. that the tokenizer takes
        # into account the new value of additional_special_tokens given in the "tokenizer_config.json" and
        # "special_tokens_map.json" files
        A__							:   Union[str, Any]					       =		tokenizer_class.from_pretrained(
            _SCREAMING_SNAKE_CASE   ,	)
        self.assertIn(
            """an_additional_special_token"""   ,	tokenizer_without_change_in_init.additional_special_tokens      )
        # self.assertIn("an_additional_special_token",tokenizer_without_change_in_init.get_vocab()) # ByT5Tokenization no vocab
        self.assertEqual(
            ["""an_additional_special_token"""]   ,	tokenizer_without_change_in_init.convert_ids_to_tokens(
                tokenizer_without_change_in_init.convert_tokens_to_ids(["""an_additional_special_token"""]      )      )   ,	)

        # Now we test that we can change the value of additional_special_tokens in the from_pretrained
        A__							:   List[str]					       =		added_tokens_extra_ids + [AddedToken("""a_new_additional_special_token"""   ,	lstrip=_SCREAMING_SNAKE_CASE      )]
        A__							:   Union[str, Any]					       =		tokenizer_class.from_pretrained(
            _SCREAMING_SNAKE_CASE   ,	additional_special_tokens=_SCREAMING_SNAKE_CASE   ,	)

        self.assertIn("""a_new_additional_special_token"""   ,	tokenizer.additional_special_tokens      )
        self.assertEqual(
            ["""a_new_additional_special_token"""]   ,	tokenizer.convert_ids_to_tokens(
                tokenizer.convert_tokens_to_ids(["""a_new_additional_special_token"""]      )      )   ,	)






     def   __A      (			self      ):
      A__							:   Optional[Any]					       =		[]
      if self.test_slow_tokenizer:
       tokenizer_list.append((self.tokenizer_class, self.get_tokenizer())      )

      if self.test_rust_tokenizer:
       tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer())      )

      for tokenizer_class, tokenizer_utils in tokenizer_list:
       with tempfile.TemporaryDirectory() as tmp_dir:
        tokenizer_utils.save_pretrained(_SCREAMING_SNAKE_CASE      )

        A__							:   Tuple					       =		tokenizer_class.from_pretrained(_SCREAMING_SNAKE_CASE      )

        self.assertTrue(tokenizer.decode([255]      ) == """"""      )






     def   __A      (			self      ):
      pass






     def   __A      (			self      ):
      pass






     def   __A      (			self      ):
      pass






     def   __A      (			self      ):
      pass






     def   __A      (			self      ):
      # The default common tokenizer tests uses invalid tokens for ByT5 that can only accept one-character strings
      # and special added tokens as tokens
      A__							:   Optional[Any]					       =		self.get_tokenizers(fast=_SCREAMING_SNAKE_CASE   ,	do_lower_case=_SCREAMING_SNAKE_CASE      )
      for tokenizer in tokenizers:
       with self.subTest(F"""{tokenizer.__class__.__name__}"""      ):
        A__							:   List[str]					       =		["t", "h", "i", "s", " ", "i", "s", " ", "a", " ", "t", "e", "x", "t", "</s>"]
        A__							:   List[str]					       =		tokenizer.convert_tokens_to_string(_SCREAMING_SNAKE_CASE      )

        self.assertIsInstance(_SCREAMING_SNAKE_CASE   ,	_SCREAMING_SNAKE_CASE      )






     def   __A      (			self      ):
      A__							:   Optional[Any]					       =		self.get_tokenizers()
      for tokenizer in tokenizers:
       with self.subTest(F"""{tokenizer.__class__.__name__}"""      ):
        A__							:   Tuple					       =		[
            "bos_token",
            "eos_token",
            "unk_token",
            "sep_token",
            "pad_token",
            "cls_token",
            "mask_token",
        ]

        A__							:   Union[str, Any]					       =		0
        A__							:   Dict					       =		tokenizer.convert_ids_to_tokens(
            _SCREAMING_SNAKE_CASE   ,	skip_special_tokens=_SCREAMING_SNAKE_CASE      )

        for attr in attributes_list:
         setattr(_SCREAMING_SNAKE_CASE   ,	attr + """_id"""   ,	_SCREAMING_SNAKE_CASE      )
         self.assertEqual(getattr(_SCREAMING_SNAKE_CASE   ,	_SCREAMING_SNAKE_CASE      )   ,	_SCREAMING_SNAKE_CASE      )
         self.assertEqual(getattr(_SCREAMING_SNAKE_CASE   ,	attr + """_id"""      )   ,	_SCREAMING_SNAKE_CASE      )

         setattr(_SCREAMING_SNAKE_CASE   ,	attr + """_id"""   ,	_SCREAMING_SNAKE_CASE      )
         self.assertEqual(getattr(_SCREAMING_SNAKE_CASE   ,	_SCREAMING_SNAKE_CASE      )   ,	_SCREAMING_SNAKE_CASE      )
         self.assertEqual(getattr(_SCREAMING_SNAKE_CASE   ,	attr + """_id"""      )   ,	_SCREAMING_SNAKE_CASE      )

        setattr(_SCREAMING_SNAKE_CASE   ,	"""additional_special_tokens_ids"""   ,	[]      )
        self.assertListEqual(getattr(_SCREAMING_SNAKE_CASE   ,	"""additional_special_tokens"""      )   ,	[]      )
        self.assertListEqual(getattr(_SCREAMING_SNAKE_CASE   ,	"""additional_special_tokens_ids"""      )   ,	[]      )

        setattr(_SCREAMING_SNAKE_CASE   ,	"""additional_special_tokens_ids"""   ,	[token_id_to_test_setters]      )
        self.assertListEqual(getattr(_SCREAMING_SNAKE_CASE   ,	"""additional_special_tokens"""      )   ,	[token_to_test_setters]      )
        self.assertListEqual(getattr(_SCREAMING_SNAKE_CASE   ,	"""additional_special_tokens_ids"""      )   ,	[token_id_to_test_setters]      )






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      )



