


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






    '''simple docstring'''





    def __init__(	self				:   Union[str, Any]       ,   __snake_case				:   Dict       ,   ):





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





    def 					_lowerCamelCase (	self				:   str	):





       '''simple docstring'''
       UpperCAmelCase_							:      List[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_							:      List[Any]						=   None
       if self.use_labels:
          UpperCAmelCase_							:      Tuple						=   ids_tensor([self.batch_size, self.seq_length]       ,   self.vocab_size	)

       UpperCAmelCase_							:      Optional[Any]						=   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 					_lowerCamelCase (	self				:   List[str]	):





       '''simple docstring'''
       random.seed(self.seed	)
       tf.random.set_seed(self.seed	)





    def 					_lowerCamelCase (	self				:   Optional[Any]       ,   __snake_case				:   str       ,   __snake_case				:   List[str]       ,   __snake_case				:   int       ,   __snake_case				:   Any	):





       '''simple docstring'''
       UpperCAmelCase_							:      List[Any]						=   TFTransfoXLModel(__snake_case	)

       UpperCAmelCase_		,      UpperCAmelCase_							:      Any						=   model(__snake_case	).to_tuple()

       UpperCAmelCase_							:      Dict						=   {'''input_ids''': input_ids_a, '''mems''': mems_a}

       UpperCAmelCase_		,      UpperCAmelCase_							:      Tuple						=   model(__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 					_lowerCamelCase (	self				:   List[str]       ,   __snake_case				:   Tuple       ,   __snake_case				:   Optional[Any]       ,   __snake_case				:   Optional[int]       ,   __snake_case				:   str	):





       '''simple docstring'''
       UpperCAmelCase_							:      Any						=   TFTransfoXLLMHeadModel(__snake_case	)

       UpperCAmelCase_		,      UpperCAmelCase_							:      Optional[int]						=   model(__snake_case	).to_tuple()

       UpperCAmelCase_							:      Optional[Any]						=   {'''input_ids''': input_ids_a, '''labels''': lm_labels}
       UpperCAmelCase_		,      UpperCAmelCase_							:      List[str]						=   model(__snake_case	).to_tuple()

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

       UpperCAmelCase_							:      List[Any]						=   {'''input_ids''': input_ids_a, '''mems''': mems_a, '''labels''': lm_labels}

       UpperCAmelCase_		,      UpperCAmelCase_							:      Union[str, Any]						=   model(__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 					_lowerCamelCase (	self				:   Dict       ,   __snake_case				:   Optional[int]       ,   __snake_case				:   str       ,   __snake_case				:   List[Any]       ,   __snake_case				:   int	):





       '''simple docstring'''
       UpperCAmelCase_							:      int						=   TFTransfoXLForSequenceClassification(__snake_case	)
       UpperCAmelCase_							:      List[Any]						=   model(__snake_case	)
       self.parent.assertEqual(result.logits.shape       ,   (self.batch_size, self.num_labels)	)





    def 					_lowerCamelCase (	self				:   Dict	):





       '''simple docstring'''
       UpperCAmelCase_							:      Dict						=   self.prepare_config_and_inputs()
       ((UpperCAmelCase_)		,      (UpperCAmelCase_)		,      (UpperCAmelCase_)		,      (UpperCAmelCase_))							:      str						=   config_and_inputs
       UpperCAmelCase_							:      Any						=   {'''input_ids''': input_ids_a}
       return config, inputs_dict





@require_tf
class  lowerCAmelCase__(    snake_case__    ,    snake_case__    ,    unittest.TestCase						):






    '''simple docstring'''





    A_  :     Union[str, Any]			= (
        (TFTransfoXLModel, TFTransfoXLLMHeadModel, TFTransfoXLForSequenceClassification) if is_tf_available() else ()
    )
    A_  :     Union[str, Any]			= () if is_tf_available() else ()
    A_  :     Optional[int]			= (
        {
            '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
    A_  :     Dict			= False
    A_  :     int			= False
    A_  :     Any			= False
    A_  :     str			= False





    def 					_lowerCamelCase (	self				:   Dict       ,   __snake_case				:   str       ,   __snake_case				:   Dict       ,   __snake_case				:   int       ,   __snake_case				:   str       ,   __snake_case				:   int	):





       '''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 					_lowerCamelCase (	self				:   Optional[Any]	):





       '''simple docstring'''
       UpperCAmelCase_							:      Dict						=   TFTransfoXLModelTester(self	)
       UpperCAmelCase_							:      Tuple						=   ConfigTester(self       ,   config_class=__snake_case       ,   d_embed=37	)





    def 					_lowerCamelCase (	self				:   List[Any]	):





       '''simple docstring'''
       self.config_tester.run_common_tests()





    def 					_lowerCamelCase (	self				:   Optional[Any]	):





       '''simple docstring'''
       self.model_tester.set_seed()
       UpperCAmelCase_							:      int						=   self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_transfo_xl_model(*__snake_case	)





    def 					_lowerCamelCase (	self				:   int	):





       '''simple docstring'''
       self.model_tester.set_seed()
       UpperCAmelCase_							:      Optional[Any]						=   self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_transfo_xl_lm_head(*__snake_case	)





    def 					_lowerCamelCase (	self				:   int	):





       '''simple docstring'''
       UpperCAmelCase_							:      List[str]						=   self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_transfo_xl_for_sequence_classification(*__snake_case	)





    def 					_lowerCamelCase (	self				:   Optional[int]	):





       '''simple docstring'''
       UpperCAmelCase_		,      UpperCAmelCase_							:      List[str]						=   self.model_tester.prepare_config_and_inputs_for_common()
       UpperCAmelCase_							:      Any						=   [TFTransfoXLForSequenceClassification]

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





    def 					_lowerCamelCase (	self				:   Tuple	):





       '''simple docstring'''
       # TODO JP: Make TransfoXL XLA compliant
       pass





    @slow
    def 					_lowerCamelCase (	self				:   List[Any]	):





       '''simple docstring'''
       for model_name in TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
          UpperCAmelCase_							:      Dict						=   TFTransfoXLModel.from_pretrained(__snake_case	)
          self.assertIsNotNone(__snake_case	)





    @unittest.skip(reason='''This model doesn\'t play well with fit() due to not returning a single loss.'''	)
    def 					_lowerCamelCase (	self				:   Tuple	):





       '''simple docstring'''
       pass





@require_tf
class  lowerCAmelCase__(    unittest.TestCase						):






    '''simple docstring'''





    @unittest.skip('''Skip test until #12651 is resolved.'''	)
    @slow
    def 					_lowerCamelCase (	self				:   Any	):





       '''simple docstring'''
       UpperCAmelCase_							:      List[Any]						=   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_							:      Union[str, 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_							:      Union[str, Any]						=   model.generate(__snake_case       ,   max_length=200       ,   do_sample=__snake_case	)
       self.assertListEqual(output_ids[0].numpy().tolist()       ,   __snake_case	)



# This code is adapted from OpenAI's release
# https://github.com/openai/human-eval/blob/master/human_eval/execution.py

import contextlib
import faulthandler
import io
import multiprocessing
import os
import platform
import signal
import tempfile
def      snake_case_						( __lowercase			,       __lowercase			,       __lowercase			,       __lowercase       ):
   UpperCAmelCase_							:      int						=   multiprocessing.Manager()
   UpperCAmelCase_							:      Union[str, Any]						=   manager.list()

   UpperCAmelCase_							:      int						=   multiprocessing.Process(target=__lowercase			,       args=(check_program, result, timeout)       )
   p.start()
   p.join(timeout=timeout + 1       )
   if p.is_alive():
      p.kill()

   if not result:
      result.append('''timed out'''       )

   return {
       "task_id": task_id,
       "passed": result[0] == "passed",
       "result": result[0],
       "completion_id": completion_id,
   }
def      snake_case_						( __lowercase			,       __lowercase			,       __lowercase       ):
   with create_tempdir():
      # These system calls are needed when cleaning up tempdir.
      import os
      import shutil

      UpperCAmelCase_							:      str						=   shutil.rmtree
      UpperCAmelCase_							:      Tuple						=   os.rmdir
      UpperCAmelCase_							:      Dict						=   os.chdir

      # Disable functionalities that can make destructive changes to the test.
      reliability_guard()

      # Run program.
      try:
         UpperCAmelCase_							:      Optional[int]						=   {}
         with swallow_io():
            with time_limit(__lowercase       ):
               exec(__lowercase			,       __lowercase       )
         result.append('''passed'''       )
      except TimeoutException:
         result.append('''timed out'''       )
      except BaseException as e:
         result.append(F'''failed: {e}'''       )

      # Needed for cleaning up.
      UpperCAmelCase_							:      Optional[int]						=   rmtree
      UpperCAmelCase_							:      Optional[Any]						=   rmdir
      UpperCAmelCase_							:      Optional[Any]						=   chdir
@contextlib.contextmanager
def      snake_case_						( __lowercase       ):
   def signal_handler(__lowercase			,       __lowercase       ):
      raise TimeoutException('''Timed out!'''       )

   signal.setitimer(signal.ITIMER_REAL			,       __lowercase       )
   signal.signal(signal.SIGALRM			,       __lowercase       )
   try:
      yield
   finally:
      signal.setitimer(signal.ITIMER_REAL			,       0       )
@contextlib.contextmanager
def      snake_case_						( ):
   UpperCAmelCase_							:      Optional[Any]						=   WriteOnlyStringIO()
   with contextlib.redirect_stdout(__lowercase       ):
      with contextlib.redirect_stderr(__lowercase       ):
         with redirect_stdin(__lowercase       ):
            yield
@contextlib.contextmanager
def      snake_case_						( ):
   with tempfile.TemporaryDirectory() as dirname:
      with chdir(__lowercase       ):
         yield dirname





class  lowerCAmelCase__(    snake_case__						):






    '''simple docstring'''





    pass





class  lowerCAmelCase__(    io.StringIO						):






    '''simple docstring'''





    def 					_lowerCamelCase (	self				:   Dict       ,   *__snake_case				:   List[Any]       ,   **__snake_case				:   int	):





       '''simple docstring'''
       raise OSError





    def 					_lowerCamelCase (	self				:   Dict       ,   *__snake_case				:   int       ,   **__snake_case				:   Any	):





       '''simple docstring'''
       raise OSError





    def 					_lowerCamelCase (	self				:   int       ,   *__snake_case				:   List[str]       ,   **__snake_case				:   Optional[Any]	):





       '''simple docstring'''
       raise OSError





    def 					_lowerCamelCase (	self				:   Union[str, Any]       ,   *__snake_case				:   Optional[Any]       ,   **__snake_case				:   List[Any]	):





       '''simple docstring'''
       return False





class  lowerCAmelCase__(    contextlib._RedirectStream						):  # type: ignore






    '''simple docstring'''





    A_  :     Optional[Any]			= 'stdin'





@contextlib.contextmanager
def      snake_case_						( __lowercase       ):
   if root == ".":
      yield
      return
   UpperCAmelCase_							:      Tuple						=   os.getcwd()
   os.chdir(__lowercase       )
   try:
      yield
   except BaseException as exc:
      raise exc
   finally:
      os.chdir(__lowercase       )


def      snake_case_						( __lowercase=None       ):

   if maximum_memory_bytes is not None:
      import resource

      resource.setrlimit(resource.RLIMIT_AS			,       (maximum_memory_bytes, maximum_memory_bytes)       )
      resource.setrlimit(resource.RLIMIT_DATA			,       (maximum_memory_bytes, maximum_memory_bytes)       )
      if not platform.uname().system == "Darwin":
         resource.setrlimit(resource.RLIMIT_STACK			,       (maximum_memory_bytes, maximum_memory_bytes)       )

   faulthandler.disable()

   import builtins

   UpperCAmelCase_							:      Any						=   None
   UpperCAmelCase_							:      Any						=   None

   import os

   UpperCAmelCase_							:      Union[str, Any]						=   '''1'''

   UpperCAmelCase_							:      List[str]						=   None
   UpperCAmelCase_							:      Dict						=   None
   UpperCAmelCase_							:      Any						=   None
   UpperCAmelCase_							:      Optional[int]						=   None
   UpperCAmelCase_							:      List[str]						=   None
   UpperCAmelCase_							:      List[Any]						=   None
   UpperCAmelCase_							:      Union[str, Any]						=   None
   UpperCAmelCase_							:      str						=   None
   UpperCAmelCase_							:      Dict						=   None
   UpperCAmelCase_							:      int						=   None
   UpperCAmelCase_							:      Dict						=   None
   UpperCAmelCase_							:      List[Any]						=   None
   UpperCAmelCase_							:      List[Any]						=   None
   UpperCAmelCase_							:      Optional[Any]						=   None
   UpperCAmelCase_							:      Optional[Any]						=   None
   UpperCAmelCase_							:      Dict						=   None
   UpperCAmelCase_							:      Optional[Any]						=   None
   UpperCAmelCase_							:      Optional[Any]						=   None
   UpperCAmelCase_							:      Optional[Any]						=   None
   UpperCAmelCase_							:      List[Any]						=   None
   UpperCAmelCase_							:      int						=   None
   UpperCAmelCase_							:      Union[str, Any]						=   None
   UpperCAmelCase_							:      List[Any]						=   None
   UpperCAmelCase_							:      Dict						=   None
   UpperCAmelCase_							:      Union[str, Any]						=   None
   UpperCAmelCase_							:      Dict						=   None
   UpperCAmelCase_							:      Any						=   None

   import shutil

   UpperCAmelCase_							:      Union[str, Any]						=   None
   UpperCAmelCase_							:      Dict						=   None
   UpperCAmelCase_							:      Tuple						=   None

   import subprocess

   UpperCAmelCase_							:      Dict						=   None  # type: ignore

   UpperCAmelCase_							:      Union[str, Any]						=   None

   import sys

   UpperCAmelCase_							:      Optional[Any]						=   None
   UpperCAmelCase_							:      List[Any]						=   None
   UpperCAmelCase_							:      List[Any]						=   None
   UpperCAmelCase_							:      List[str]						=   None
   UpperCAmelCase_							:      Dict						=   None