




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:






    """simple docstring"""





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





    def 							a__				(				self  )			->		Dict:
         UpperCAmelCase_      :							Optional[Any]       =      ids_tensor([self.batch_size, self.seq_length]       ,self.vocab_size  )
         UpperCAmelCase_      :							Dict       =      ids_tensor([self.batch_size, self.seq_length]       ,self.vocab_size  )

         UpperCAmelCase_      :							str       =      None
         if self.use_labels:
              UpperCAmelCase_      :							Union[str, Any]       =      ids_tensor([self.batch_size, self.seq_length]       ,self.vocab_size  )

         UpperCAmelCase_      :							List[str]       =      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[Any]:
         random.seed(self.seed  )
         tf.random.set_seed(self.seed  )





    def 							a__				(				self       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE  )			->		Optional[Any]:
         UpperCAmelCase_      :							Any       =      TFTransfoXLModel(SCREAMING_SNAKE_CASE_  )

         UpperCAmelCase_      :							Optional[Any]       =      model(SCREAMING_SNAKE_CASE_  ).to_tuple()

         UpperCAmelCase_      :							Optional[int]       =      {"""input_ids""": input_ids_a, """mems""": mems_a}

         UpperCAmelCase_      :							int       =      model(SCREAMING_SNAKE_CASE_  ).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       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE  )			->		Dict:
         UpperCAmelCase_      :							int       =      TFTransfoXLLMHeadModel(SCREAMING_SNAKE_CASE_  )

         UpperCAmelCase_      :							Optional[Any]       =      model(SCREAMING_SNAKE_CASE_  ).to_tuple()

         UpperCAmelCase_      :							Tuple       =      {"""input_ids""": input_ids_a, """labels""": lm_labels}
         UpperCAmelCase_      :							List[str]       =      model(SCREAMING_SNAKE_CASE_  ).to_tuple()

         UpperCAmelCase_      :							Any       =      model([input_ids_a, mems_a]  ).to_tuple()

         UpperCAmelCase_      :							Tuple       =      {"""input_ids""": input_ids_a, """mems""": mems_a, """labels""": lm_labels}

         UpperCAmelCase_      :							Optional[Any]       =      model(SCREAMING_SNAKE_CASE_  ).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       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE  )			->		Any:
         UpperCAmelCase_      :							Union[str, Any]       =      TFTransfoXLForSequenceClassification(SCREAMING_SNAKE_CASE_  )
         UpperCAmelCase_      :							Optional[Any]       =      model(SCREAMING_SNAKE_CASE_  )
         self.parent.assertEqual(result.logits.shape       ,(self.batch_size, self.num_labels)  )





    def 							a__				(				self  )			->		List[str]:
         UpperCAmelCase_      :							Any       =      self.prepare_config_and_inputs()
         (UpperCAmelCase_)      :							int       =      config_and_inputs
         UpperCAmelCase_      :							int       =      {"""input_ids""": input_ids_a}
         return config, inputs_dict


@require_tf
class   __a(					_UpperCAmelCase    ,						_UpperCAmelCase    ,						unittest.TestCase       ):






    """simple docstring"""





    lowerCAmelCase        =				(
        (TFTransfoXLModel, TFTransfoXLLMHeadModel, TFTransfoXLForSequenceClassification) if is_tf_available() else ()
    )
    lowerCAmelCase        =				() if is_tf_available() else ()
    lowerCAmelCase        =				(
        {
            '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
    lowerCAmelCase        =				False
    lowerCAmelCase        =				False
    lowerCAmelCase        =				False
    lowerCAmelCase        =				False





    def 							a__				(				self       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE  )			->		List[str]:
         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  )			->		List[str]:
         UpperCAmelCase_      :							Optional[int]       =      TFTransfoXLModelTester(self  )
         UpperCAmelCase_      :							Optional[Any]       =      ConfigTester(self       ,config_class=SCREAMING_SNAKE_CASE_       ,d_embed=37  )





    def 							a__				(				self  )			->		List[str]:
         self.config_tester.run_common_tests()





    def 							a__				(				self  )			->		str:
         self.model_tester.set_seed()
         UpperCAmelCase_      :							Tuple       =      self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_transfo_xl_model(*SCREAMING_SNAKE_CASE_  )





    def 							a__				(				self  )			->		List[Any]:
         self.model_tester.set_seed()
         UpperCAmelCase_      :							Optional[int]       =      self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_transfo_xl_lm_head(*SCREAMING_SNAKE_CASE_  )





    def 							a__				(				self  )			->		str:
         UpperCAmelCase_      :							Any       =      self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_transfo_xl_for_sequence_classification(*SCREAMING_SNAKE_CASE_  )





    def 							a__				(				self  )			->		Optional[Any]:
         UpperCAmelCase_      :							Union[str, Any]       =      self.model_tester.prepare_config_and_inputs_for_common()
         UpperCAmelCase_      :							List[str]       =      [TFTransfoXLForSequenceClassification]

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





    def 							a__				(				self  )			->		List[str]:
         # TODO JP: Make TransfoXL XLA compliant
         pass





    @slow
    def 							a__				(				self  )			->		Any:
         for model_name in TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              UpperCAmelCase_      :							Optional[Any]       =      TFTransfoXLModel.from_pretrained(SCREAMING_SNAKE_CASE_  )
              self.assertIsNotNone(SCREAMING_SNAKE_CASE_  )





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


@require_tf
class   __a(					unittest.TestCase       ):






    """simple docstring"""





    @unittest.skip('''Skip test until #12651 is resolved.'''  )
    @slow
    def 							a__				(				self  )			->		Tuple:
         UpperCAmelCase_      :							int       =      TFTransfoXLLMHeadModel.from_pretrained('''transfo-xl-wt103'''  )
         # fmt: off
         UpperCAmelCase_      :							Optional[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
         UpperCAmelCase_      :							List[Any]       =      [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>

         UpperCAmelCase_      :							List[Any]       =      model.generate(SCREAMING_SNAKE_CASE_       ,max_length=200       ,do_sample=SCREAMING_SNAKE_CASE_  )
         self.assertListEqual(output_ids[0].numpy().tolist()       ,SCREAMING_SNAKE_CASE_  )





import re

import jax.numpy as jnp
from flax.traverse_util import flatten_dict, unflatten_dict
from jax.random import PRNGKey

from ..utils import logging


__a          =			logging.get_logger(__name__)







def lowerCamelCase__       (      _lowercase				):

     '''simple docstring'''


     UpperCAmelCase_      :							str       =      r'''\w+[.]\d+'''
     UpperCAmelCase_      :							int       =      re.findall(_lowercase			,						_lowercase				)
     for pat in pats:
          UpperCAmelCase_      :							List[Any]       =      key.replace(_lowercase			,						'''_'''.join(pat.split('''.'''				)				)				)
     return key







def lowerCamelCase__       (      _lowercase			,						_lowercase			,						_lowercase				):

     '''simple docstring'''


     UpperCAmelCase_      :							Dict       =      pt_tuple_key[:-1] + ('''scale''',)
     if (
         any('''norm''' in str_ for str_ in pt_tuple_key				)
         and (pt_tuple_key[-1] == "bias")
         and (pt_tuple_key[:-1] + ("bias",) not in random_flax_state_dict)
         and (pt_tuple_key[:-1] + ("scale",) in random_flax_state_dict)
     ):
          UpperCAmelCase_      :							List[Any]       =      pt_tuple_key[:-1] + ('''scale''',)
          return renamed_pt_tuple_key, pt_tensor
     elif pt_tuple_key[-1] in ["weight", "gamma"] and pt_tuple_key[:-1] + ("scale",) in random_flax_state_dict:
          UpperCAmelCase_      :							Any       =      pt_tuple_key[:-1] + ('''scale''',)
          return renamed_pt_tuple_key, pt_tensor

     # embedding
     if pt_tuple_key[-1] == "weight" and pt_tuple_key[:-1] + ("embedding",) in random_flax_state_dict:
          UpperCAmelCase_      :							Tuple       =      pt_tuple_key[:-1] + ('''embedding''',)
          return renamed_pt_tuple_key, pt_tensor

     # conv layer
     UpperCAmelCase_      :							List[Any]       =      pt_tuple_key[:-1] + ('''kernel''',)
     if pt_tuple_key[-1] == "weight" and pt_tensor.ndim == 4:
          UpperCAmelCase_      :							List[Any]       =      pt_tensor.transpose(2			,						3			,						1			,						0				)
          return renamed_pt_tuple_key, pt_tensor

     # linear layer
     UpperCAmelCase_      :							Dict       =      pt_tuple_key[:-1] + ('''kernel''',)
     if pt_tuple_key[-1] == "weight":
          UpperCAmelCase_      :							Tuple       =      pt_tensor.T
          return renamed_pt_tuple_key, pt_tensor

     # old PyTorch layer norm weight
     UpperCAmelCase_      :							Any       =      pt_tuple_key[:-1] + ('''weight''',)
     if pt_tuple_key[-1] == "gamma":
          return renamed_pt_tuple_key, pt_tensor

     # old PyTorch layer norm bias
     UpperCAmelCase_      :							Tuple       =      pt_tuple_key[:-1] + ('''bias''',)
     if pt_tuple_key[-1] == "beta":
          return renamed_pt_tuple_key, pt_tensor

     return pt_tuple_key, pt_tensor







def lowerCamelCase__       (      _lowercase			,						_lowercase			,						_lowercase=42				):

     '''simple docstring'''


     UpperCAmelCase_      :							Union[str, Any]       =      {k: v.numpy() for k, v in pt_state_dict.items()}

     # Step 2: Since the model is stateless, get random Flax params
     UpperCAmelCase_      :							str       =      flax_model.init_weights(PRNGKey(_lowercase				)				)

     UpperCAmelCase_      :							List[Any]       =      flatten_dict(_lowercase				)
     UpperCAmelCase_      :							int       =      {}

     # Need to change some parameters name to match Flax names
     for pt_key, pt_tensor in pt_state_dict.items():
          UpperCAmelCase_      :							Optional[int]       =      rename_key(_lowercase				)
          UpperCAmelCase_      :							List[str]       =      tuple(renamed_pt_key.split('''.'''				)				)

          # Correctly rename weight parameters
          UpperCAmelCase_,   UpperCAmelCase_      :							Any       =      rename_key_and_reshape_tensor(_lowercase			,						_lowercase			,						_lowercase				)

          if flax_key in random_flax_state_dict:
               if flax_tensor.shape != random_flax_state_dict[flax_key].shape:
                    raise ValueError(
                        f'''PyTorch checkpoint seems to be incorrect. Weight {pt_key} was expected to be of shape '''
                        f'''{random_flax_state_dict[flax_key].shape}, but is {flax_tensor.shape}.'''				)

        # also add unexpected weight so that warning is thrown
          UpperCAmelCase_      :							int       =      jnp.asarray(_lowercase				)

     return unflatten_dict(_lowercase				)