



from __future__ import annotations

import copy
import os
import tempfile
from importlib import import_module
from math import isnan

from transformers import is_tf_available
from transformers.models.auto import get_values
from transformers.testing_utils import _tf_gpu_memory_limit, require_tf, slow

from ..test_modeling_tf_common import ids_tensor


if is_tf_available():
     import numpy as np
     import tensorflow as tf

     from transformers import (
         TF_MODEL_FOR_CAUSAL_LM_MAPPING,
         TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING,
         TF_MODEL_FOR_MASKED_LM_MAPPING,
         TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING,
         TF_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING,
         TF_MODEL_FOR_PRETRAINING_MAPPING,
         TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING,
         TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
         TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
         TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING,
         TFSharedEmbeddings,
     )

     if _tf_gpu_memory_limit is not None:
          A_		:  List[Any]										=  tf.config.list_physical_devices('''GPU''')
          for gpu in gpus:
               # Restrict TensorFlow to only allocate x GB of memory on the GPUs
               try:
                    tf.config.set_logical_device_configuration(
                        gpu, [tf.config.LogicalDeviceConfiguration(memory_limit=_tf_gpu_memory_limit)]
                    )
                    A_		:  List[Any]										=  tf.config.list_logical_devices('''GPU''')
                    print('''Logical GPUs''', logical_gpus)
               except RuntimeError as e:
                    # Virtual devices must be set before GPUs have been initialized
                    print(e)



@require_tf
class 		_lowercase		:
   _UpperCAmelCase  						=      None
   _UpperCAmelCase  						=      ()
   _UpperCAmelCase  						=      ()
   _UpperCAmelCase  						=      True
   _UpperCAmelCase  						=      True
   _UpperCAmelCase  						=      True
   _UpperCAmelCase  						=      False

   def 		A				(   self      :							Dict				, __lowerCAmelCase      :							List[str]				, __lowerCAmelCase      :							List[Any]				, __lowerCAmelCase      :							Union[str, Any]=False				)							->					dict:


    """simple docstring"""






    a							=		copy.deepcopy(__lowerCAmelCase				)

    if model_class in get_values(__lowerCAmelCase				):
     a							=		{
         k: tf.tile(tf.expand_dims(__lowerCAmelCase				, 1				)				, (1, self.model_tester.num_choices) + (1,) * (v.ndim - 1)				)
         if isinstance(__lowerCAmelCase				, tf.Tensor				) and v.ndim > 0
         else v
         for k, v in inputs_dict.items()
     }

    if return_labels:
     if model_class in get_values(__lowerCAmelCase				):
      a							=		tf.ones(self.model_tester.batch_size				, dtype=tf.intaa				)
     elif model_class in get_values(__lowerCAmelCase				):
      a							=		tf.zeros(self.model_tester.batch_size				, dtype=tf.intaa				)
      a							=		tf.zeros(self.model_tester.batch_size				, dtype=tf.intaa				)
     elif model_class in [
         *get_values(__lowerCAmelCase				),
         *get_values(__lowerCAmelCase				),
     ]:
      a							=		tf.zeros(self.model_tester.batch_size				, dtype=tf.intaa				)
     elif model_class in get_values(__lowerCAmelCase				):
      a							=		tf.zeros(self.model_tester.batch_size				, dtype=tf.intaa				)
     elif model_class in [
         *get_values(__lowerCAmelCase				),
         *get_values(__lowerCAmelCase				),
         *get_values(__lowerCAmelCase				),
         *get_values(__lowerCAmelCase				),
         *get_values(__lowerCAmelCase				),
     ]:
      a							=		tf.zeros(
          (self.model_tester.batch_size, self.model_tester.seq_length)				, dtype=tf.intaa				)
    return inputs_dict

   @slow
   def 		A				(   self      :							List[str]				)							->					str:


    """simple docstring"""






    a		,	a							=		self.model_tester.prepare_config_and_inputs_for_common()
    for model_class in self.all_model_classes[:2]:
     a							=		self._prepare_for_class(__lowerCAmelCase				, __lowerCAmelCase				)
     a							=		model_class(__lowerCAmelCase				)

     @tf.function
     def run_in_graph_mode():
      return model(__lowerCAmelCase				)

     a							=		run_in_graph_mode()
     self.assertIsNotNone(__lowerCAmelCase				)

   @slow
   def 		A				(   self      :							Optional[int]				)							->					Union[str, Any]:


    """simple docstring"""






    a		,	a							=		self.model_tester.prepare_config_and_inputs_for_common()
    for model_class in self.all_model_classes[:2]:
     a							=		self._prepare_for_class(__lowerCAmelCase				, __lowerCAmelCase				)
     a							=		model_class(__lowerCAmelCase				)

     @tf.function(experimental_compile=__lowerCAmelCase				)
     def run_in_graph_mode():
      return model(__lowerCAmelCase				)

     a							=		run_in_graph_mode()
     self.assertIsNotNone(__lowerCAmelCase				)

   @slow
   def 		A				(   self      :							str				)							->					List[Any]:


    """simple docstring"""






    a		,	a							=		self.model_tester.prepare_config_and_inputs_for_common()
    for model_class in self.all_model_classes[:2]:
     a							=		model_class(__lowerCAmelCase				)
     if getattr(__lowerCAmelCase				, "hf_compute_loss"				, __lowerCAmelCase				):
      # Test that model correctly compute the loss with kwargs
      a							=		self._prepare_for_class(inputs_dict.copy()				, __lowerCAmelCase				, return_labels=__lowerCAmelCase				)
      # Is there a better way to remove these decoder inputs?
      a							=		{
          key: val
          for key, val in prepared_for_class.items()
          if key not in ("head_mask", "decoder_head_mask", "cross_attn_head_mask", "decoder_input_ids")
      }

      a							=		{
          "labels",
          "label",
          "label_ids",
          "start_positions",
          "start_position",
          "end_positions",
          "end_position",
          "next_sentence_label",
      }
      a							=		possible_label_cols.intersection(set(__lowerCAmelCase				)				)
      self.assertGreater(len(__lowerCAmelCase				)				, 0				, msg="No matching label names found!"				)
      a							=		{key: val for key, val in prepared_for_class.items() if key in label_names}
      a							=		{key: val for key, val in prepared_for_class.items() if key not in label_names}
      self.assertGreater(len(__lowerCAmelCase				)				, 0				)

      # Make sure it works with XLA!
      model.compile(optimizer=tf.keras.optimizers.SGD(0.0				)				, jit_compile=__lowerCAmelCase				)
      # Make sure the model fits without crashing regardless of where we pass the labels
      a							=		model.fit(
          __lowerCAmelCase				, validation_data=__lowerCAmelCase				, steps_per_epoch=1				, validation_steps=1				, shuffle=__lowerCAmelCase				, verbose=0				, )
      a							=		history.history["loss"][0]
      self.assertTrue(not isnan(__lowerCAmelCase				)				)
      a							=		history.history["val_loss"][0]
      self.assertTrue(not isnan(__lowerCAmelCase				)				)

      # Now test it with separate labels, to make sure that path works in XLA too.
      a							=		model_class(__lowerCAmelCase				)
      model.compile(optimizer=tf.keras.optimizers.SGD(0.0				)				, jit_compile=__lowerCAmelCase				)
      a							=		model.fit(
          __lowerCAmelCase				, __lowerCAmelCase				, validation_data=(inputs_minus_labels, labels)				, steps_per_epoch=1				, validation_steps=1				, shuffle=__lowerCAmelCase				, verbose=0				, )

      a							=		history.history["loss"][0]
      self.assertTrue(not isnan(__lowerCAmelCase				)				)
      a							=		history.history["val_loss"][0]
      self.assertTrue(not isnan(__lowerCAmelCase				)				)

   @slow
   def 		A				(   self      :							int				)							->					List[str]:


    """simple docstring"""






    a		,	a							=		self.model_tester.prepare_config_and_inputs_for_common()
    a							=		True
    a							=		True

    if hasattr(__lowerCAmelCase				, "use_cache"				):
     a							=		True

    a							=		getattr(self.model_tester				, "encoder_seq_length"				, self.model_tester.seq_length				)
    a							=		getattr(self.model_tester				, "key_length"				, __lowerCAmelCase				)

    for model_class in self.all_model_classes[:2]:
     a							=		self._prepare_for_class(__lowerCAmelCase				, __lowerCAmelCase				)
     a							=		model_class(__lowerCAmelCase				)
     model.build()
     a							=		len(model(__lowerCAmelCase				)				)

     for key in list(class_inputs_dict.keys()				):
      # Remove keys not in the serving signature, as the SavedModel will not be compiled to deal with them
      if key not in model.input_signature:
       del class_inputs_dict[key]
      # Check it's a tensor, in case the inputs dict has some bools in it too
      elif isinstance(class_inputs_dict[key]				, tf.Tensor				) and class_inputs_dict[key].dtype.is_integer:
       a							=		tf.cast(class_inputs_dict[key]				, tf.intaa				)

     if set(class_inputs_dict.keys()				) != set(model.input_signature.keys()				):
      continue  # Some models have inputs that the preparation functions don't create, we skip those

     with tempfile.TemporaryDirectory() as tmpdirname:
      model.save_pretrained(__lowerCAmelCase				, saved_model=__lowerCAmelCase				)
      a							=		os.path.join(__lowerCAmelCase				, "saved_model"				, "1"				)
      a							=		tf.keras.models.load_model(__lowerCAmelCase				)
      a							=		model(__lowerCAmelCase				)

      if self.is_encoder_decoder:
       a							=		outputs["encoder_hidden_states"]
       a							=		outputs["encoder_attentions"]
      else:
       a							=		outputs["hidden_states"]
       a							=		outputs["attentions"]

      self.assertEqual(len(__lowerCAmelCase				)				, __lowerCAmelCase				)

      a							=		getattr(
          self.model_tester				, "expected_num_hidden_layers"				, self.model_tester.num_hidden_layers + 1				)

      self.assertEqual(len(__lowerCAmelCase				)				, __lowerCAmelCase				)
      self.assertListEqual(
          list(output_hidden_states[0].shape[-2:]				)				, [self.model_tester.seq_length, self.model_tester.hidden_size]				, )

      self.assertEqual(len(__lowerCAmelCase				)				, self.model_tester.num_hidden_layers				)
      self.assertListEqual(
          list(output_attentions[0].shape[-3:]				)				, [self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length]				, )

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


    """simple docstring"""






    tf.keras.mixed_precision.set_global_policy("mixed_float16"				)

    # try/finally block to ensure subsequent tests run in float32
    try:
     a		,	a							=		self.model_tester.prepare_config_and_inputs_for_common()
     for model_class in self.all_model_classes[:2]:
      a							=		self._prepare_for_class(__lowerCAmelCase				, __lowerCAmelCase				)
      a							=		model_class(__lowerCAmelCase				)
      a							=		model(__lowerCAmelCase				)

      self.assertIsNotNone(__lowerCAmelCase				)
    finally:
     tf.keras.mixed_precision.set_global_policy("float32"				)

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


    """simple docstring"""






    a		,	a							=		self.model_tester.prepare_config_and_inputs_for_common()
    # head_mask and decoder_head_mask has different shapes than other input args
    if "head_mask" in inputs_dict:
     del inputs_dict["head_mask"]
    if "decoder_head_mask" in inputs_dict:
     del inputs_dict["decoder_head_mask"]
    if "cross_attn_head_mask" in inputs_dict:
     del inputs_dict["cross_attn_head_mask"]
    a							=		{
        module_member
        for model_class in self.all_model_classes
        for module in (import_module(model_class.__module__				),)
        for module_member_name in dir(__lowerCAmelCase				)
        if module_member_name.endswith("MainLayer"				)
        for module_member in (getattr(__lowerCAmelCase				, __lowerCAmelCase				),)
        if isinstance(__lowerCAmelCase				, __lowerCAmelCase				)
        and tf.keras.layers.Layer in module_member.__bases__
        and getattr(__lowerCAmelCase				, "_keras_serializable"				, __lowerCAmelCase				)
    }

    for main_layer_class in tf_main_layer_classes:
     # T5MainLayer needs an embed_tokens parameter when called without the inputs_embeds parameter
     if "T5" in main_layer_class.__name__:
      # Take the same values than in TFT5ModelTester for this shared layer
      a							=		TFSharedEmbeddings(self.model_tester.vocab_size				, self.model_tester.hidden_size				, name="shared"				)
      a							=		False
      a							=		main_layer_class(__lowerCAmelCase				, embed_tokens=__lowerCAmelCase				)
     else:
      a							=		main_layer_class(__lowerCAmelCase				)

     a							=		{
         name: tf.keras.Input(tensor.shape[1:]				, dtype=tensor.dtype				) for name, tensor in inputs_dict.items()
     }

     if hasattr(self.model_tester				, "num_labels"				):
      a							=		self.model_tester.num_labels
     else:
      a							=		2

     a							=		tf.data.Dataset.from_tensor_slices(
         (inputs_dict, np.ones((self.model_tester.batch_size, self.model_tester.seq_length, num_labels, 1)				))				).batch(1				)

     a							=		main_layer(__lowerCAmelCase				)[0]
     a							=		tf.keras.layers.Dense(__lowerCAmelCase				, activation="softmax"				, name="outputs"				)(__lowerCAmelCase				)
     a							=		tf.keras.models.Model(inputs=__lowerCAmelCase				, outputs=[outputs]				)

     model.compile(loss="binary_crossentropy"				, optimizer="adam"				, metrics=["binary_accuracy"]				)
     model.fit(__lowerCAmelCase				, epochs=1				)

     with tempfile.TemporaryDirectory() as tmpdirname:
      a							=		os.path.join(__lowerCAmelCase				, "keras_model.h5"				)
      model.save(__lowerCAmelCase				)
      if "T5" in main_layer_class.__name__:
       a							=		tf.keras.models.load_model(
           __lowerCAmelCase				, custom_objects={
               main_layer_class.__name__: main_layer_class,
               "TFSharedEmbeddings": TFSharedEmbeddings,
           }				, )
      else:
       a							=		tf.keras.models.load_model(
           __lowerCAmelCase				, custom_objects={main_layer_class.__name__: main_layer_class}				)
      assert isinstance(__lowerCAmelCase				, tf.keras.Model				)
      model(__lowerCAmelCase				)

   @slow
   def 		A				(   self      :							Any				)							->					Union[str, Any]:


    """simple docstring"""






    a		,	a							=		self.model_tester.prepare_config_and_inputs_for_common()

    for model_class in self.all_model_classes[:2]:
     a							=		model_class(__lowerCAmelCase				)

     a							=		copy.deepcopy(__lowerCAmelCase				)

     if not self.is_encoder_decoder:
      a							=		inputs["input_ids"]
      del inputs["input_ids"]
     else:
      a							=		inputs["input_ids"]
      a							=		inputs.get("decoder_input_ids"				, __lowerCAmelCase				)
      del inputs["input_ids"]
      inputs.pop("decoder_input_ids"				, __lowerCAmelCase				)

     if not self.is_encoder_decoder:
      a							=		model.get_input_embeddings()(__lowerCAmelCase				)
     else:
      a							=		model.get_input_embeddings()(__lowerCAmelCase				)
      a							=		model.get_input_embeddings()(__lowerCAmelCase				)

     a							=		self._prepare_for_class(__lowerCAmelCase				, __lowerCAmelCase				)

     @tf.function
     def run_in_graph_mode():
      return model(__lowerCAmelCase				)

     a							=		run_in_graph_mode()
     self.assertIsNotNone(__lowerCAmelCase				)

   def 		A				(   self      :							Union[str, Any]				, __lowerCAmelCase      :							Dict				, __lowerCAmelCase      :							List[str]				)							->					List[str]:


    """simple docstring"""






    a							=		[]
    if model.config.bos_token_id is not None:
     special_tokens.append(model.config.bos_token_id				)
    if model.config.pad_token_id is not None:
     special_tokens.append(model.config.pad_token_id				)
    if model.config.eos_token_id is not None:
     special_tokens.append(model.config.eos_token_id				)

    # create random bad tokens that are not special tokens
    a							=		[]
    while len(__lowerCAmelCase				) < num_bad_tokens:
     a							=		tf.squeeze(ids_tensor((1, 1)				, self.model_tester.vocab_size				)				, 0				).numpy()[0]
     if token not in special_tokens:
      bad_tokens.append(__lowerCAmelCase				)
    return bad_tokens

   def 		A				(   self      :							int				, __lowerCAmelCase      :							int				)							->					int:


    """simple docstring"""






    for token_id in output_ids[0].numpy().tolist():
     self.assertGreaterEqual(__lowerCAmelCase				, 0				)
     self.assertLess(__lowerCAmelCase				, self.model_tester.vocab_size				)




   def 		A				(   self      :							Optional[Any]				, __lowerCAmelCase      :							List[str]				, __lowerCAmelCase      :							Any				)							->					int:


    """simple docstring"""






    for bad_word_ids in bad_words_ids:
     # for all slices in batch
     for generated_ids_slice in generated_ids:
      # for all word idx
      for i in range(len(__lowerCAmelCase				)				, len(__lowerCAmelCase				)				):
       # if tokens match
       if generated_ids_slice[i - len(__lowerCAmelCase				) : i] == bad_word_ids:
        return True
    return False


'''simple docstring'''
import tempfile
import unittest

import numpy as np

import transformers
from transformers import GPTaConfig, GPTaTokenizer, is_flax_available, is_torch_available
from transformers.testing_utils import is_pt_flax_cross_test, require_flax, slow

from ...generation.test_flax_utils import FlaxGenerationTesterMixin
from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask


if is_flax_available():
  import jax
  import jax.numpy as jnp

  from transformers.modeling_flax_pytorch_utils import (
      convert_pytorch_state_dict_to_flax,
      load_flax_weights_in_pytorch_model,
  )
  from transformers.models.gpta.modeling_flax_gpta import FlaxGPTaLMHeadModel, FlaxGPTaModel

if is_torch_available():
  import torch






class       __lowercase		:







     """simple docstring"""






     def __init__(		self  ,      _lowerCamelCase  ,      _lowerCamelCase=1_4  ,      _lowerCamelCase=7  ,      _lowerCamelCase=True  ,      _lowerCamelCase=True  ,      _lowerCamelCase=False  ,      _lowerCamelCase=True  ,      _lowerCamelCase=9_9  ,      _lowerCamelCase=3_2  ,      _lowerCamelCase=5  ,      _lowerCamelCase=4  ,      _lowerCamelCase=3_7  ,      _lowerCamelCase="gelu"  ,      _lowerCamelCase=0.1  ,      _lowerCamelCase=0.1  ,      _lowerCamelCase=5_1_2  ,      _lowerCamelCase=0.0_2  ,      ):
         __UpperCamelCase						:						int		     =	parent
         __UpperCamelCase						:						Union[str, Any]		     =	batch_size
         __UpperCamelCase						:						Tuple		     =	seq_length
         __UpperCamelCase						:						Tuple		     =	is_training
         __UpperCamelCase						:						str		     =	use_input_mask
         __UpperCamelCase						:						int		     =	use_token_type_ids
         __UpperCamelCase						:						List[Any]		     =	use_labels
         __UpperCamelCase						:						Tuple		     =	vocab_size
         __UpperCamelCase						:						Any		     =	hidden_size
         __UpperCamelCase						:						int		     =	num_hidden_layers
         __UpperCamelCase						:						List[Any]		     =	num_attention_heads
         __UpperCamelCase						:						str		     =	intermediate_size
         __UpperCamelCase						:						Any		     =	hidden_act
         __UpperCamelCase						:						Tuple		     =	hidden_dropout_prob
         __UpperCamelCase						:						Any		     =	attention_probs_dropout_prob
         __UpperCamelCase						:						Union[str, Any]		     =	max_position_embeddings
         __UpperCamelCase						:						Optional[int]		     =	initializer_range
         __UpperCamelCase						:						str		     =	None
         __UpperCamelCase						:						Dict		     =	vocab_size - 1
         __UpperCamelCase						:						Tuple		     =	vocab_size - 1
         __UpperCamelCase						:						int		     =	vocab_size - 1







     def lowerCAmelCase  (		self     ):
         __UpperCamelCase						:						Optional[Any]		     =	ids_tensor([self.batch_size, self.seq_length]  ,      self.vocab_size     )

         __UpperCamelCase						:						str		     =	None
         if self.use_input_mask:
             __UpperCamelCase						:						List[Any]		     =	random_attention_mask([self.batch_size, self.seq_length]     )

         __UpperCamelCase						:						Optional[Any]		     =	GPTaConfig(
             vocab_size=self.vocab_size  ,      n_embd=self.hidden_size  ,      n_layer=self.num_hidden_layers  ,      n_head=self.num_attention_heads  ,      n_positions=self.max_position_embeddings  ,      use_cache=_lowerCamelCase  ,      bos_token_id=self.bos_token_id  ,      eos_token_id=self.eos_token_id  ,      pad_token_id=self.pad_token_id  ,      )

         return (config, input_ids, input_mask)







     def lowerCAmelCase  (		self     ):
         __UpperCamelCase						:						Union[str, Any]		     =	self.prepare_config_and_inputs()
         __UpperCamelCase     ,       __UpperCamelCase     ,       __UpperCamelCase						:						Optional[Any]		     =	config_and_inputs
         __UpperCamelCase						:						Optional[Any]		     =	{'input_ids': input_ids, 'attention_mask': attention_mask}
         return config, inputs_dict







     def lowerCAmelCase  (		self     ):
         __UpperCamelCase     ,       __UpperCamelCase     ,       __UpperCamelCase						:						Optional[int]		     =	self.prepare_config_and_inputs()

         __UpperCamelCase						:						Optional[Any]		     =	floats_tensor([self.batch_size, self.seq_length, self.hidden_size]     )
         __UpperCamelCase						:						List[Any]		     =	ids_tensor([self.batch_size, self.seq_length]  ,      vocab_size=2     )

         return (
             config,
             input_ids,
             attention_mask,
             encoder_hidden_states,
             encoder_attention_mask,
         )







     def lowerCAmelCase  (		self  ,      _lowerCamelCase  ,      _lowerCamelCase  ,      _lowerCamelCase  ,      _lowerCamelCase     ):
         __UpperCamelCase						:						str		     =	2_0
         __UpperCamelCase						:						List[Any]		     =	model_class_name(_lowerCamelCase     )

         __UpperCamelCase						:						Optional[int]		     =	model.init_cache(input_ids.shape[0]  ,      _lowerCamelCase     )
         __UpperCamelCase						:						Union[str, Any]		     =	jnp.ones((input_ids.shape[0], max_decoder_length)  ,      dtype='i4'     )

         __UpperCamelCase						:						List[str]		     =	jnp.broadcast_to(
             jnp.arange(input_ids.shape[-1] - 1     )[None, :]  ,      (input_ids.shape[0], input_ids.shape[-1] - 1)     )
         __UpperCamelCase						:						List[Any]		     =	model(
             input_ids[:, :-1]  ,      attention_mask=_lowerCamelCase  ,      past_key_values=_lowerCamelCase  ,      position_ids=_lowerCamelCase  ,      )

         __UpperCamelCase						:						int		     =	jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]]  ,      dtype='i4'     )
         __UpperCamelCase						:						Tuple		     =	model(
             input_ids[:, -1:]  ,      attention_mask=_lowerCamelCase  ,      past_key_values=outputs_cache.past_key_values  ,      position_ids=_lowerCamelCase  ,      )

         __UpperCamelCase						:						List[str]		     =	model(_lowerCamelCase     )

         __UpperCamelCase						:						Optional[int]		     =	np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])     )     )
         self.parent.assertTrue(diff < 1E-3  ,      msg=f"""Max diff is {diff}"""     )







     def lowerCAmelCase  (		self  ,      _lowerCamelCase  ,      _lowerCamelCase  ,      _lowerCamelCase  ,      _lowerCamelCase     ):
         __UpperCamelCase						:						Optional[Any]		     =	2_0
         __UpperCamelCase						:						Any		     =	model_class_name(_lowerCamelCase     )

         __UpperCamelCase						:						Union[str, Any]		     =	jnp.concatenate(
             [attention_mask, jnp.zeros((attention_mask.shape[0], max_decoder_length - attention_mask.shape[1])     )]  ,      axis=-1  ,      )

         __UpperCamelCase						:						Any		     =	model.init_cache(input_ids.shape[0]  ,      _lowerCamelCase     )
         __UpperCamelCase						:						Optional[Any]		     =	jnp.broadcast_to(
             jnp.arange(input_ids.shape[-1] - 1     )[None, :]  ,      (input_ids.shape[0], input_ids.shape[-1] - 1)     )

         __UpperCamelCase						:						List[Any]		     =	model(
             input_ids[:, :-1]  ,      attention_mask=_lowerCamelCase  ,      past_key_values=_lowerCamelCase  ,      position_ids=_lowerCamelCase  ,      )
         __UpperCamelCase						:						Any		     =	jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]]  ,      dtype='i4'     )
         __UpperCamelCase						:						Dict		     =	model(
             input_ids[:, -1:]  ,      past_key_values=outputs_cache.past_key_values  ,      attention_mask=_lowerCamelCase  ,      position_ids=_lowerCamelCase  ,      )

         __UpperCamelCase						:						Optional[Any]		     =	model(_lowerCamelCase  ,      attention_mask=_lowerCamelCase     )

         __UpperCamelCase						:						Any		     =	np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])     )     )
         self.parent.assertTrue(diff < 1E-3  ,      msg=f"""Max diff is {diff}"""     )






@require_flax
class       __lowercase		(    _lowerCamelCase      ,				_lowerCamelCase      ,				unittest.TestCase    ):







     """simple docstring"""






     SCREAMING_SNAKE_CASE__		 =    (FlaxGPTaModel, FlaxGPTaLMHeadModel) if is_flax_available() else ()
     SCREAMING_SNAKE_CASE__		 =    (FlaxGPTaLMHeadModel,) if is_flax_available() else ()







     def lowerCAmelCase  (		self     ):
         __UpperCamelCase						:						Optional[int]		     =	FlaxGPTaModelTester(self     )







     def lowerCAmelCase  (		self     ):
         for model_class_name in self.all_model_classes:
             __UpperCamelCase     ,       __UpperCamelCase     ,       __UpperCamelCase						:						Union[str, Any]		     =	self.model_tester.prepare_config_and_inputs()
             self.model_tester.check_use_cache_forward(_lowerCamelCase  ,      _lowerCamelCase  ,      _lowerCamelCase  ,      _lowerCamelCase     )







     def lowerCAmelCase  (		self     ):
         for model_class_name in self.all_model_classes:
             __UpperCamelCase     ,       __UpperCamelCase     ,       __UpperCamelCase						:						Optional[int]		     =	self.model_tester.prepare_config_and_inputs()
             self.model_tester.check_use_cache_forward_with_attn_mask(
                 _lowerCamelCase  ,      _lowerCamelCase  ,      _lowerCamelCase  ,      _lowerCamelCase     )







     @slow
     def lowerCAmelCase  (		self     ):
         __UpperCamelCase						:						Optional[int]		     =	GPTaTokenizer.from_pretrained('gpt2'  ,      pad_token='</s>'  ,      padding_side='left'     )
         __UpperCamelCase						:						str		     =	tokenizer(['Hello this is a long string', 'Hey']  ,      return_tensors='np'  ,      padding=_lowerCamelCase  ,      truncation=_lowerCamelCase     )

         __UpperCamelCase						:						int		     =	FlaxGPTaLMHeadModel.from_pretrained('gpt2'     )
         __UpperCamelCase						:						Union[str, Any]		     =	False
         __UpperCamelCase						:						Optional[Any]		     =	model.config.eos_token_id

         __UpperCamelCase						:						List[str]		     =	jax.jit(model.generate     )

         __UpperCamelCase						:						List[str]		     =	jit_generate(inputs['input_ids']  ,      attention_mask=inputs['attention_mask']     ).sequences

         __UpperCamelCase						:						Optional[int]		     =	tokenizer.batch_decode(_lowerCamelCase  ,      skip_special_tokens=_lowerCamelCase     )

         __UpperCamelCase						:						Dict		     =	[
             'Hello this is a long string of words. I\'m going to start with the first one.\n',
             'Hey, I\'m not sure if I\'m going to be able to do',
         ]

         self.assertListEqual(_lowerCamelCase  ,      _lowerCamelCase     )







     @is_pt_flax_cross_test
     def lowerCAmelCase  (		self     ):
         __UpperCamelCase     ,       __UpperCamelCase						:						Optional[int]		     =	self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
             with self.subTest(model_class.__name__     ):
                 # prepare inputs
                 __UpperCamelCase						:						Tuple		     =	self._prepare_for_class(_lowerCamelCase  ,      _lowerCamelCase     )
                 __UpperCamelCase						:						Dict		     =	{k: torch.tensor(v.tolist()     ) for k, v in prepared_inputs_dict.items()}

                 # load corresponding PyTorch class
                 __UpperCamelCase						:						Union[str, Any]		     =	model_class.__name__[4:]  # Skip the "Flax" at the beginning
                 __UpperCamelCase						:						List[str]		     =	getattr(_lowerCamelCase  ,      _lowerCamelCase     )

                 __UpperCamelCase     ,       __UpperCamelCase						:						Tuple		     =	pt_inputs['input_ids'].shape
                 __UpperCamelCase						:						int		     =	np.random.randint(0  ,      seq_length - 1  ,      size=(batch_size,)     )
                 for batch_idx, start_index in enumerate(_lowerCamelCase     ):
                     __UpperCamelCase						:						int		     =	0
                     __UpperCamelCase						:						Tuple		     =	1
                     __UpperCamelCase						:						Optional[int]		     =	0
                     __UpperCamelCase						:						List[Any]		     =	1
                 __UpperCamelCase						:						str		     =	pt_model_class(_lowerCamelCase     ).eval()
                 __UpperCamelCase						:						Union[str, Any]		     =	model_class(_lowerCamelCase  ,      dtype=jnp.floataa     )

                 __UpperCamelCase						:						Optional[int]		     =	convert_pytorch_state_dict_to_flax(pt_model.state_dict()  ,      _lowerCamelCase     )
                 __UpperCamelCase						:						List[str]		     =	fx_state

                 with torch.no_grad():
                     __UpperCamelCase						:						List[Any]		     =	pt_model(**_lowerCamelCase     ).to_tuple()

                 __UpperCamelCase						:						str		     =	fx_model(**_lowerCamelCase     ).to_tuple()
                 self.assertEqual(len(_lowerCamelCase     )  ,      len(_lowerCamelCase     )  ,      'Output lengths differ between Flax and PyTorch'     )
                 for fx_output, pt_output in zip(_lowerCamelCase  ,      _lowerCamelCase     ):
                     self.assert_almost_equals(fx_output[:, -1]  ,      pt_output[:, -1].numpy()  ,      4E-2     )

                 with tempfile.TemporaryDirectory() as tmpdirname:
                     pt_model.save_pretrained(_lowerCamelCase     )
                     __UpperCamelCase						:						Any		     =	model_class.from_pretrained(_lowerCamelCase  ,      from_pt=_lowerCamelCase     )

                 __UpperCamelCase						:						Union[str, Any]		     =	fx_model_loaded(**_lowerCamelCase     ).to_tuple()
                 self.assertEqual(
                     len(_lowerCamelCase     )  ,      len(_lowerCamelCase     )  ,      'Output lengths differ between Flax and PyTorch'     )
                 for fx_output_loaded, pt_output in zip(_lowerCamelCase  ,      _lowerCamelCase     ):
                     self.assert_almost_equals(fx_output_loaded[:, -1]  ,      pt_output[:, -1].numpy()  ,      4E-2     )







     @is_pt_flax_cross_test
     def lowerCAmelCase  (		self     ):
         __UpperCamelCase     ,       __UpperCamelCase						:						Optional[Any]		     =	self.model_tester.prepare_config_and_inputs_for_common()
         for model_class in self.all_model_classes:
             with self.subTest(model_class.__name__     ):
                 # prepare inputs
                 __UpperCamelCase						:						Tuple		     =	self._prepare_for_class(_lowerCamelCase  ,      _lowerCamelCase     )
                 __UpperCamelCase						:						int		     =	{k: torch.tensor(v.tolist()     ) for k, v in prepared_inputs_dict.items()}

                 # load corresponding PyTorch class
                 __UpperCamelCase						:						Optional[Any]		     =	model_class.__name__[4:]  # Skip the "Flax" at the beginning
                 __UpperCamelCase						:						int		     =	getattr(_lowerCamelCase  ,      _lowerCamelCase     )

                 __UpperCamelCase						:						Optional[Any]		     =	pt_model_class(_lowerCamelCase     ).eval()
                 __UpperCamelCase						:						List[Any]		     =	model_class(_lowerCamelCase  ,      dtype=jnp.floataa     )

                 __UpperCamelCase						:						str		     =	load_flax_weights_in_pytorch_model(_lowerCamelCase  ,      fx_model.params     )
                 __UpperCamelCase     ,       __UpperCamelCase						:						int		     =	pt_inputs['input_ids'].shape
                 __UpperCamelCase						:						Dict		     =	np.random.randint(0  ,      seq_length - 1  ,      size=(batch_size,)     )
                 for batch_idx, start_index in enumerate(_lowerCamelCase     ):
                     __UpperCamelCase						:						Union[str, Any]		     =	0
                     __UpperCamelCase						:						List[str]		     =	1
                     __UpperCamelCase						:						Optional[int]		     =	0
                     __UpperCamelCase						:						Optional[int]		     =	1

                 # make sure weights are tied in PyTorch
                 pt_model.tie_weights()

                 with torch.no_grad():
                     __UpperCamelCase						:						Any		     =	pt_model(**_lowerCamelCase     ).to_tuple()

                 __UpperCamelCase						:						Optional[Any]		     =	fx_model(**_lowerCamelCase     ).to_tuple()
                 self.assertEqual(len(_lowerCamelCase     )  ,      len(_lowerCamelCase     )  ,      'Output lengths differ between Flax and PyTorch'     )
                 for fx_output, pt_output in zip(_lowerCamelCase  ,      _lowerCamelCase     ):
                     self.assert_almost_equals(fx_output[:, -1]  ,      pt_output[:, -1].numpy()  ,      4E-2     )

                 with tempfile.TemporaryDirectory() as tmpdirname:
                     fx_model.save_pretrained(_lowerCamelCase     )
                     __UpperCamelCase						:						int		     =	pt_model_class.from_pretrained(_lowerCamelCase  ,      from_flax=_lowerCamelCase     )

                 with torch.no_grad():
                     __UpperCamelCase						:						Dict		     =	pt_model_loaded(**_lowerCamelCase     ).to_tuple()

                 self.assertEqual(
                     len(_lowerCamelCase     )  ,      len(_lowerCamelCase     )  ,      'Output lengths differ between Flax and PyTorch'     )
                 for fx_output, pt_output in zip(_lowerCamelCase  ,      _lowerCamelCase     ):
                     self.assert_almost_equals(fx_output[:, -1]  ,      pt_output[:, -1].numpy()  ,      4E-2     )







     @slow
     def lowerCAmelCase  (		self     ):
         for model_class_name in self.all_model_classes:
             __UpperCamelCase						:						Union[str, Any]		     =	model_class_name.from_pretrained('gpt2'  ,      from_pt=_lowerCamelCase     )
             __UpperCamelCase						:						List[str]		     =	model(np.ones((1, 1)     )     )
             self.assertIsNotNone(_lowerCamelCase     )



