




from __future__ import annotations

import random
import unittest

from transformers import TransfoXLConfig, is_tf_available
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
 import tensorflow as tf

 from transformers import (
     TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST,
     TFTransfoXLForSequenceClassification,
     TFTransfoXLLMHeadModel,
     TFTransfoXLModel,
 )
class 						_A :






  def __init__(  self		:     Union[str, Any]				,						_A		:     List[str]				,						)		->   Union[str, Any]:






       """simple docstring"""







       lowercase :       List[Any]       =			parent
       lowercase :       Any       =			13
       lowercase :       Any       =			7
       lowercase :       List[Any]       =			30
       lowercase :       Union[str, Any]       =			self.seq_length + self.mem_len
       lowercase :       Optional[Any]       =			15
       lowercase :       int       =			True
       lowercase :       Any       =			True
       lowercase :       List[Any]       =			99
       lowercase :       Optional[int]       =			[10, 50, 80]
       lowercase :       List[Any]       =			32
       lowercase :       List[str]       =			32
       lowercase :       Optional[int]       =			4
       lowercase :       Any       =			8
       lowercase :       Optional[int]       =			128
       lowercase :       List[str]       =			2
       lowercase :       List[Any]       =			2
       lowercase :       int       =			None
       lowercase :       Optional[int]       =			1
       lowercase :       str       =			0
       lowercase :       Optional[int]       =			3
       lowercase :       Any       =			self.vocab_size - 1
       lowercase :       Tuple       =			0.01






  def  __a      (  self		:     List[str]				)		->   Dict:






       """simple docstring"""







       lowercase :       int       =			ids_tensor([self.batch_size, self.seq_length]				,						self.vocab_size				)
       lowercase :       List[Any]       =			ids_tensor([self.batch_size, self.seq_length]				,						self.vocab_size				)

       lowercase :       Dict       =			None
       if self.use_labels:
            lowercase :       int       =			ids_tensor([self.batch_size, self.seq_length]				,						self.vocab_size				)

       lowercase :       Tuple       =			TransfoXLConfig(
           vocab_size=self.vocab_size				,						mem_len=self.mem_len				,						clamp_len=self.clamp_len				,						cutoffs=self.cutoffs				,						d_model=self.hidden_size				,						d_embed=self.d_embed				,						n_head=self.num_attention_heads				,						d_head=self.d_head				,						d_inner=self.d_inner				,						div_val=self.div_val				,						n_layer=self.num_hidden_layers				,						eos_token_id=self.eos_token_id				,						pad_token_id=self.vocab_size - 1				,						init_range=self.init_range				,						num_labels=self.num_labels				,						)

       return (config, input_ids_a, input_ids_a, lm_labels)






  def  __a      (  self		:     Optional[int]				)		->   List[str]:






       """simple docstring"""







       random.seed(self.seed				)
       tf.random.set_seed(self.seed				)






  def  __a      (  self		:     List[Any]				,						_A		:     Dict				,						_A		:     List[str]				,						_A		:     List[str]				,						_A		:     str				)		->   str:






       """simple docstring"""







       lowercase :       Optional[int]       =			TFTransfoXLModel(_A				)

       lowercase :       Optional[Any]       =			model(_A				).to_tuple()

       lowercase :       str       =			{'input_ids': input_ids_a, 'mems': mems_a}

       lowercase :       Union[str, Any]       =			model(_A				).to_tuple()

       self.parent.assertEqual(hidden_states_a.shape				,						(self.batch_size, self.seq_length, self.hidden_size)				)
       self.parent.assertEqual(hidden_states_a.shape				,						(self.batch_size, self.seq_length, self.hidden_size)				)
       self.parent.assertListEqual(
           [mem.shape for mem in mems_a]				,						[(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers				,						)
       self.parent.assertListEqual(
           [mem.shape for mem in mems_a]				,						[(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers				,						)






  def  __a      (  self		:     Optional[Any]				,						_A		:     Dict				,						_A		:     List[Any]				,						_A		:     Union[str, Any]				,						_A		:     Tuple				)		->   int:






       """simple docstring"""







       lowercase :       Union[str, Any]       =			TFTransfoXLLMHeadModel(_A				)

       lowercase :       Tuple       =			model(_A				).to_tuple()

       lowercase :       Tuple       =			{'input_ids': input_ids_a, 'labels': lm_labels}
       lowercase :       Optional[Any]       =			model(_A				).to_tuple()

       lowercase :       Union[str, Any]       =			model([input_ids_a, mems_a]				).to_tuple()

       lowercase :       str       =			{'input_ids': input_ids_a, 'mems': mems_a, 'labels': lm_labels}

       lowercase :       Optional[int]       =			model(_A				).to_tuple()

       self.parent.assertEqual(lm_logits_a.shape				,						(self.batch_size, self.seq_length, self.vocab_size)				)
       self.parent.assertListEqual(
           [mem.shape for mem in mems_a]				,						[(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers				,						)

       self.parent.assertEqual(lm_logits_a.shape				,						(self.batch_size, self.seq_length, self.vocab_size)				)
       self.parent.assertListEqual(
           [mem.shape for mem in mems_a]				,						[(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers				,						)






  def  __a      (  self		:     Tuple				,						_A		:     Union[str, Any]				,						_A		:     Dict				,						_A		:     Optional[Any]				,						_A		:     Optional[int]				)		->   Union[str, Any]:






       """simple docstring"""







       lowercase :       Optional[int]       =			TFTransfoXLForSequenceClassification(_A				)
       lowercase :       Tuple       =			model(_A				)
       self.parent.assertEqual(result.logits.shape				,						(self.batch_size, self.num_labels)				)






  def  __a      (  self		:     int				)		->   Optional[Any]:






       """simple docstring"""







       lowercase :       List[str]       =			self.prepare_config_and_inputs()
       (lowercase) :       int       =			config_and_inputs
       lowercase :       Dict       =			{'input_ids': input_ids_a}
       return config, inputs_dict


@require_tf
class 						_A (  _lowerCamelCase      ,       _lowerCamelCase      ,       unittest.TestCase				):
  _UpperCamelCase       :      Dict			=      (
      (TFTransfoXLModel, TFTransfoXLLMHeadModel, TFTransfoXLForSequenceClassification) if is_tf_available() else ()
  )
  _UpperCamelCase       :      Union[str, Any]			=      () if is_tf_available() else ()
  _UpperCamelCase       :      Tuple			=      (
      {
          """feature-extraction""": TFTransfoXLModel,
          """text-classification""": TFTransfoXLForSequenceClassification,
          """text-generation""": TFTransfoXLLMHeadModel,
          """zero-shot""": TFTransfoXLForSequenceClassification,
      }
      if is_tf_available()
      else {}
  )
  # TODO: add this test when TFTransfoXLLMHead has a linear output layer implemented
  _UpperCamelCase       :      Optional[int]			=      False
  _UpperCamelCase       :      Optional[Any]			=      False
  _UpperCamelCase       :      Tuple			=      False
  _UpperCamelCase       :      Optional[int]			=      False






  def  __a      (  self		:     str				,						_A		:     Union[str, Any]				,						_A		:     List[str]				,						_A		:     Optional[int]				,						_A		:     str				,						_A		:     Union[str, Any]				)		->   Tuple:






       """simple docstring"""







       if pipeline_test_casse_name == "TextGenerationPipelineTests":
            # Get `ValueError: AttributeError: 'NoneType' object has no attribute 'new_ones'` or `AssertionError`.
            # `TransfoXLConfig` was never used in pipeline tests: cannot create a simple
            # tokenizer.
            return True

       return False






  def  __a      (  self		:     Optional[int]				)		->   int:






       """simple docstring"""







       lowercase :       Optional[int]       =			TFTransfoXLModelTester(self				)
       lowercase :       Union[str, Any]       =			ConfigTester(self				,						config_class=_A				,						d_embed=37				)






  def  __a      (  self		:     Union[str, Any]				)		->   Optional[Any]:






       """simple docstring"""







       self.config_tester.run_common_tests()






  def  __a      (  self		:     str				)		->   Dict:






       """simple docstring"""







       self.model_tester.set_seed()
       lowercase :       int       =			self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_transfo_xl_model(*_A				)






  def  __a      (  self		:     Any				)		->   Union[str, Any]:






       """simple docstring"""







       self.model_tester.set_seed()
       lowercase :       int       =			self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_transfo_xl_lm_head(*_A				)






  def  __a      (  self		:     Any				)		->   Optional[int]:






       """simple docstring"""







       lowercase :       List[str]       =			self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_transfo_xl_for_sequence_classification(*_A				)






  def  __a      (  self		:     List[str]				)		->   List[Any]:






       """simple docstring"""







       lowercase :       Any       =			self.model_tester.prepare_config_and_inputs_for_common()
       lowercase :       int       =			[TFTransfoXLForSequenceClassification]

       for model_class in self.all_model_classes:
            lowercase :       Optional[int]       =			model_class(_A				)
            assert isinstance(model.get_input_embeddings()				,						tf.keras.layers.Layer				)
            if model_class in list_other_models_with_output_ebd:
                 lowercase :       Tuple       =			model.get_output_embeddings()
                 assert isinstance(_A				,						tf.keras.layers.Layer				)
                 lowercase :       Union[str, Any]       =			model.get_bias()
                 assert name is None
            else:
                 lowercase :       Optional[int]       =			model.get_output_embeddings()
                 assert x is None
                 lowercase :       Union[str, Any]       =			model.get_bias()
                 assert name is None






  def  __a      (  self		:     Any				)		->   Dict:






       """simple docstring"""







       pass






  @slow
  def  __a      (  self		:     int				)		->   Optional[int]:






       """simple docstring"""







       for model_name in TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
            lowercase :       Any       =			TFTransfoXLModel.from_pretrained(_A				)
            self.assertIsNotNone(_A				)






  @unittest.skip(reason='''This model doesn\'t play well with fit() due to not returning a single loss.'''				)
  def  __a      (  self		:     List[Any]				)		->   List[Any]:






       """simple docstring"""







       pass


@require_tf
class 						_A (  unittest.TestCase				):






  @unittest.skip('''Skip test until #12651 is resolved.'''				)
  @slow
  def  __a      (  self		:     int				)		->   Optional[int]:






       """simple docstring"""







       lowercase :       Dict       =			TFTransfoXLLMHeadModel.from_pretrained('''transfo-xl-wt103'''				)
       # fmt: off
       lowercase :       Union[str, Any]       =			tf.convert_to_tensor([[33,1_297,2,1,1_009,4,1_109,11_739,4_762,358,5,25,245,22,1_706,17,20_098,5,3_215,21,37,1_110,3,13,1_041,4,24,603,490,2,71_477,20_098,104_447,2,20_961,1,2_604,4,1,329,3,6_224,831,16_002,2,8,603,78_967,29_546,23,803,20,25,416,5,8,232,4,277,6,1_855,4_601,3,29_546,54,8,3_609,5,57_211,49,4,1,277,18,8,1_755,15_691,3,341,25,416,693,42_573,71,17,401,94,31,17_919,2,29_546,7_873,18,1,435,23,11_011,755,5,5_167,3,7_983,98,84,2,29_546,3_267,8,3_609,4,1,4_865,1_075,2,6_087,71,6,346,8,5_854,3,29_546,824,1_400,1_868,2,19,160,2,311,8,5_496,2,20_920,17,25,15_097,3,24,24,0]]				,						dtype=tf.intaa				)  # noqa: E231
       # fmt: on
       #  In 1991 , the remains of Russian Tsar Nicholas II and his family
       #  ( except for Alexei and Maria ) are discovered .
       #  The voice of Nicholas's young son , Tsarevich Alexei Nikolaevich , narrates the
       #  remainder of the story . 1883 Western Siberia ,
       #  a young Grigori Rasputin is asked by his father and a group of men to perform magic .
       #  Rasputin has a vision and denounces one of the men as a horse thief . Although his
       #  father initially slaps him for making such an accusation , Rasputin watches as the
       #  man is chased outside and beaten . Twenty years later , Rasputin sees a vision of
       #  the Virgin Mary , prompting him to become a priest . Rasputin quickly becomes famous ,
       #  with people , even a bishop , begging for his blessing . <eod> </s> <eos>

       # fmt: off
       lowercase :       List[str]       =			[33,1_297,2,1,1_009,4,1_109,11_739,4_762,358,5,25,245,22,1_706,17,20_098,5,3_215,21,37,1_110,3,13,1_041,4,24,603,490,2,71_477,20_098,104_447,2,20_961,1,2_604,4,1,329,3,6_224,831,16_002,2,8,603,78_967,29_546,23,803,20,25,416,5,8,232,4,277,6,1_855,4_601,3,29_546,54,8,3_609,5,57_211,49,4,1,277,18,8,1_755,15_691,3,341,25,416,693,42_573,71,17,401,94,31,17_919,2,29_546,7_873,18,1,435,23,11_011,755,5,5_167,3,7_983,98,84,2,29_546,3_267,8,3_609,4,1,4_865,1_075,2,6_087,71,6,346,8,5_854,3,29_546,824,1_400,1_868,2,19,160,2,311,8,5_496,2,20_920,17,25,15_097,3,24,24,0,33,1,1_857,2,1,1_009,4,1_109,11_739,4_762,358,5,25,245,28,1_110,3,13,1_041,4,24,603,490,2,71_477,20_098,104_447,2,20_961,1,2_604,4,1,329,3,0]  # noqa: E231
       # fmt: on
       #  In 1991, the remains of Russian Tsar Nicholas II and his family (
       #  except for Alexei and Maria ) are discovered. The voice of young son,
       #  Tsarevich Alexei Nikolaevich, narrates the remainder of the story.
       #  1883 Western Siberia, a young Grigori Rasputin is asked by his father
       #  and a group of men to perform magic. Rasputin has a vision and
       #  denounces one of the men as a horse thief. Although his father initially
       #  slaps him for making such an accusation, Rasputin watches as the man
       #  is chased outside and beaten. Twenty years later, Rasputin sees a vision
       #  of the Virgin Mary, prompting him to become a priest.
       #  Rasputin quickly becomes famous, with people, even a bishop, begging for
       #  his blessing. <unk> <unk> <eos> In the 1990s, the remains of Russian Tsar
       # Nicholas II and his family were discovered. The voice of <unk> young son,
       # Tsarevich Alexei Nikolaevich, narrates the remainder of the story.<eos>

       lowercase :       Dict       =			model.generate(_A				,						max_length=200				,						do_sample=_A				)
       self.assertListEqual(output_ids[0].numpy().tolist()				,						_A				)





lowerCAmelCase_						=			range(2, 20 + 1)
lowerCAmelCase_						=			[10**k for k in range(ks[-1] + 1)]
lowerCAmelCase_						=			{}






def  snake_case(    __magic_name__			,		__magic_name__			,		__magic_name__			,		__magic_name__   )			->							Any:





     '''simple docstring'''


     lowercase :       str       =			sum(a_i[j] for j in range(__magic_name__			,		len(__magic_name__   )   )   )
     lowercase :       Any       =			sum(a_i[j] * base[j] for j in range(min(len(__magic_name__   )			,		__magic_name__   )   )   )

     lowercase      ,	lowercase :       Optional[int]       =			0, 0
     lowercase :       str       =			n - i

     lowercase :       Optional[int]       =			memo.get(__magic_name__   )

     if sub_memo is not None:
          lowercase :       List[str]       =			sub_memo.get(__magic_name__   )

          if jumps is not None and len(__magic_name__   ) > 0:
               # find and make the largest jump without going over
               lowercase :       Dict       =			-1
               for _k in range(len(__magic_name__   ) - 1			,		-1			,		-1   ):
                    if jumps[_k][2] <= k and jumps[_k][1] <= max_dn:
                         lowercase :       Any       =			_k
                         break

               if max_jump >= 0:
                    lowercase      ,	lowercase      ,	lowercase :       List[str]       =			jumps[max_jump]
                    # since the difference between jumps is cached, add c
                    lowercase :       str       =			diff + c
                    for j in range(min(__magic_name__			,		len(__magic_name__   )   )   ):
                         lowercase      ,	lowercase :       Optional[Any]       =			divmod(__magic_name__			,		10   )
                    if new_c > 0:
                         add(__magic_name__			,		__magic_name__			,		__magic_name__   )

          else:
               lowercase :       Dict       =			[]
     else:
          lowercase :       Union[str, Any]       =			{c: []}
          lowercase :       Optional[Any]       =			sub_memo

     if dn >= max_dn or c + diff >= base[k]:
          return diff, dn

     if k > ks[0]:
          while True:
               # keep doing smaller jumps
               lowercase      ,	lowercase :       str       =			next_term(__magic_name__			,		k - 1			,		i + dn			,		__magic_name__   )
               diff += _diff
               dn += terms_jumped

               if dn >= max_dn or c + diff >= base[k]:
                    break
     else:
          # would be too small a jump, just compute sequential terms instead
          lowercase      ,	lowercase :       Optional[Any]       =			compute(__magic_name__			,		__magic_name__			,		i + dn			,		__magic_name__   )
          diff += _diff
          dn += terms_jumped

     lowercase :       Optional[Any]       =			sub_memo[c]

     # keep jumps sorted by # of terms skipped
     lowercase :       List[Any]       =			0
     while j < len(__magic_name__   ):
          if jumps[j][1] > dn:
               break
          j += 1

     # cache the jump for this value digitsum(b) and c
     sub_memo[c].insert(__magic_name__			,		(diff, dn, k)   )
     return (diff, dn)






def  snake_case(    __magic_name__			,		__magic_name__			,		__magic_name__			,		__magic_name__   )			->							Optional[int]:





     '''simple docstring'''


     if i >= n:
          return 0, i
     if k > len(__magic_name__   ):
          a_i.extend([0 for _ in range(k - len(__magic_name__   )   )]   )

     # note: a_i -> b * 10^k + c
     # ds_b -> digitsum(b)
     # ds_c -> digitsum(c)
     lowercase :       Optional[Any]       =			i
     lowercase      ,	lowercase      ,	lowercase :       List[str]       =			0, 0, 0
     for j in range(len(__magic_name__   )   ):
          if j >= k:
               ds_b += a_i[j]
          else:
               ds_c += a_i[j]

     while i < n:
          i += 1
          lowercase :       List[str]       =			ds_c + ds_b
          diff += addend
          lowercase :       Tuple       =			0
          for j in range(__magic_name__   ):
               lowercase :       int       =			a_i[j] + addend
               lowercase      ,	lowercase :       Any       =			divmod(__magic_name__			,		10   )

               ds_c += a_i[j]

          if addend > 0:
               break

     if addend > 0:
          add(__magic_name__			,		__magic_name__			,		__magic_name__   )
     return diff, i - start_i






def  snake_case(    __magic_name__			,		__magic_name__			,		__magic_name__   )			->							Tuple:





     '''simple docstring'''


     for j in range(__magic_name__			,		len(__magic_name__   )   ):
          lowercase :       Any       =			digits[j] + addend
          if s >= 10:
               lowercase      ,	lowercase :       List[str]       =			divmod(__magic_name__			,		10   )
               lowercase :       List[str]       =			addend // 10 + quotient
          else:
               lowercase :       Optional[Any]       =			s
               lowercase :       Tuple       =			addend // 10

          if addend == 0:
               break

     while addend > 0:
          lowercase      ,	lowercase :       str       =			divmod(__magic_name__			,		10   )
          digits.append(__magic_name__   )






def  snake_case(    __magic_name__ = 10**15   )			->							int:





     '''simple docstring'''


     lowercase :       List[Any]       =			[1]
     lowercase :       List[Any]       =			1
     lowercase :       str       =			0
     while True:
          lowercase      ,	lowercase :       str       =			next_term(__magic_name__			,		20			,		i + dn			,		__magic_name__   )
          dn += terms_jumped
          if dn == n - i:
               break

     lowercase :       str       =			0
     for j in range(len(__magic_name__   )   ):
          a_n += digits[j] * 10**j
     return a_n


if __name__ == "__main__":
 print(f'''{solution() = }''')