

from __future__ import annotations

import unittest

from transformers import AutoTokenizer, GPTJConfig, is_tf_available
from transformers.testing_utils import require_tf, slow, tooslow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin
from ...utils.test_modeling_tf_core import TFCoreModelTesterMixin


if is_tf_available():
  import tensorflow as tf

  from transformers.models.gptj.modeling_tf_gptj import (
      TFGPTJForCausalLM,
      TFGPTJForQuestionAnswering,
      TFGPTJForSequenceClassification,
      TFGPTJModel,
      shape_list,
  )







class     a__    :







  """simple docstring"""




  def __init__(     self      :	Union[str, Any]			,			UpperCAmelCase__      :	int						)   ->int:
        """simple docstring"""







        SCREAMING_SNAKE_CASE	: int					       =				parent
        SCREAMING_SNAKE_CASE	: Dict					       =				1_3
        SCREAMING_SNAKE_CASE	: int					       =				7
        SCREAMING_SNAKE_CASE	: Union[str, Any]					       =				True
        SCREAMING_SNAKE_CASE	: Tuple					       =				True
        SCREAMING_SNAKE_CASE	: List[Any]					       =				True
        SCREAMING_SNAKE_CASE	: Union[str, Any]					       =				True
        SCREAMING_SNAKE_CASE	: List[Any]					       =				True
        SCREAMING_SNAKE_CASE	: Dict					       =				9_9
        SCREAMING_SNAKE_CASE	: Dict					       =				3_2
        SCREAMING_SNAKE_CASE	: Optional[int]					       =				4
        SCREAMING_SNAKE_CASE	: str					       =				2
        SCREAMING_SNAKE_CASE	: int					       =				4
        SCREAMING_SNAKE_CASE	: Optional[int]					       =				3_7
        SCREAMING_SNAKE_CASE	: Dict					       =				"""gelu"""
        SCREAMING_SNAKE_CASE	: Any					       =				0.1
        SCREAMING_SNAKE_CASE	: str					       =				0.1
        SCREAMING_SNAKE_CASE	: Dict					       =				5_1_2
        SCREAMING_SNAKE_CASE	: List[str]					       =				1_6
        SCREAMING_SNAKE_CASE	: List[str]					       =				2
        SCREAMING_SNAKE_CASE	: Union[str, Any]					       =				0.02
        SCREAMING_SNAKE_CASE	: Dict					       =				3
        SCREAMING_SNAKE_CASE	: Any					       =				4
        SCREAMING_SNAKE_CASE	: str					       =				None
        SCREAMING_SNAKE_CASE	: int					       =				self.vocab_size - 1
        SCREAMING_SNAKE_CASE	: Dict					       =				self.vocab_size - 1
        SCREAMING_SNAKE_CASE	: int					       =				self.vocab_size - 1


  def 	_lowercase (     self      :	str						)   ->List[Any]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE	: Optional[int]					       =				ids_tensor([self.batch_size, self.seq_length]			,			self.vocab_size						)

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

        SCREAMING_SNAKE_CASE	: str					       =				None
        if self.use_token_type_ids:
              SCREAMING_SNAKE_CASE	: Tuple					       =				ids_tensor([self.batch_size, self.seq_length]			,			self.type_vocab_size						)

        SCREAMING_SNAKE_CASE	: Optional[int]					       =				None
        if self.use_mc_token_ids:
              SCREAMING_SNAKE_CASE	: Optional[Any]					       =				ids_tensor([self.batch_size, self.num_choices]			,			self.seq_length						)

        SCREAMING_SNAKE_CASE	: List[str]					       =				None
        SCREAMING_SNAKE_CASE	: List[str]					       =				None
        SCREAMING_SNAKE_CASE	: Optional[int]					       =				None
        if self.use_labels:
              SCREAMING_SNAKE_CASE	: List[str]					       =				ids_tensor([self.batch_size]			,			self.type_sequence_label_size						)
              SCREAMING_SNAKE_CASE	: Optional[int]					       =				ids_tensor([self.batch_size, self.seq_length]			,			self.num_labels						)
              SCREAMING_SNAKE_CASE	: Dict					       =				ids_tensor([self.batch_size]			,			self.num_choices						)

        SCREAMING_SNAKE_CASE	: List[Any]					       =				GPTJConfig(
            vocab_size=self.vocab_size			,			n_embd=self.hidden_size			,			n_layer=self.num_hidden_layers			,			n_head=self.num_attention_heads			,			intermediate_size=self.intermediate_size			,			hidden_act=self.hidden_act			,			hidden_dropout_prob=self.hidden_dropout_prob			,			attention_probs_dropout_prob=self.attention_probs_dropout_prob			,			n_positions=self.max_position_embeddings			,			type_vocab_size=self.type_vocab_size			,			initializer_range=self.initializer_range			,			bos_token_id=self.bos_token_id			,			eos_token_id=self.eos_token_id			,			pad_token_id=self.pad_token_id			,			rotary_dim=self.rotary_dim			,			return_dict=UpperCAmelCase__			,			)

        SCREAMING_SNAKE_CASE	: Tuple					       =				ids_tensor([self.num_hidden_layers, self.num_attention_heads]			,			2						)

        return (
            config,
            input_ids,
            input_mask,
            head_mask,
            token_type_ids,
            mc_token_ids,
            sequence_labels,
            token_labels,
            choice_labels,
        )


  def 	_lowercase (     self      :	Tuple			,			UpperCAmelCase__      :	Optional[Any]			,			UpperCAmelCase__      :	str			,			UpperCAmelCase__      :	Any			,			UpperCAmelCase__      :	Optional[int]			,			UpperCAmelCase__      :	Any			,			*UpperCAmelCase__      :	List[str]						)   ->str:
        """simple docstring"""







        SCREAMING_SNAKE_CASE	: Any					       =				TFGPTJModel(config=UpperCAmelCase__						)
        SCREAMING_SNAKE_CASE	: Optional[Any]					       =				{
            """input_ids""": input_ids,
            """attention_mask""": input_mask,
            """token_type_ids""": token_type_ids,
        }
        SCREAMING_SNAKE_CASE	: List[str]					       =				model(UpperCAmelCase__						)

        SCREAMING_SNAKE_CASE	: Optional[Any]					       =				[input_ids, None, input_mask]  # None is the input for 'past'
        SCREAMING_SNAKE_CASE	: str					       =				model(UpperCAmelCase__						)

        SCREAMING_SNAKE_CASE	: List[str]					       =				model(UpperCAmelCase__						)

        self.parent.assertEqual(result.last_hidden_state.shape			,			(self.batch_size, self.seq_length, self.hidden_size)						)


  def 	_lowercase (     self      :	int			,			UpperCAmelCase__      :	Any			,			UpperCAmelCase__      :	int			,			UpperCAmelCase__      :	Union[str, Any]			,			UpperCAmelCase__      :	List[str]			,			UpperCAmelCase__      :	List[str]			,			*UpperCAmelCase__      :	List[str]						)   ->List[str]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE	: int					       =				TFGPTJModel(config=UpperCAmelCase__						)

        # first forward pass
        SCREAMING_SNAKE_CASE	: Optional[int]					       =				model(UpperCAmelCase__			,			token_type_ids=UpperCAmelCase__			,			use_cache=UpperCAmelCase__						)
        SCREAMING_SNAKE_CASE	: List[Any]					       =				model(UpperCAmelCase__			,			token_type_ids=UpperCAmelCase__						)
        SCREAMING_SNAKE_CASE	: Tuple					       =				model(UpperCAmelCase__			,			token_type_ids=UpperCAmelCase__			,			use_cache=UpperCAmelCase__						)

        self.parent.assertTrue(len(UpperCAmelCase__						) == len(UpperCAmelCase__						)						)
        self.parent.assertTrue(len(UpperCAmelCase__						) == len(UpperCAmelCase__						) + 1						)

        SCREAMING_SNAKE_CASE       ,		SCREAMING_SNAKE_CASE	: List[str]					       =				outputs.to_tuple()

        # create hypothetical next token and extent to next_input_ids
        SCREAMING_SNAKE_CASE	: List[Any]					       =				ids_tensor((self.batch_size, 1)			,			config.vocab_size						)
        SCREAMING_SNAKE_CASE	: Optional[int]					       =				ids_tensor([self.batch_size, 1]			,			self.type_vocab_size						)

        # append to next input_ids and token_type_ids
        SCREAMING_SNAKE_CASE	: List[str]					       =				tf.concat([input_ids, next_tokens]			,			axis=-1						)
        SCREAMING_SNAKE_CASE	: Optional[Any]					       =				tf.concat([token_type_ids, next_token_types]			,			axis=-1						)

        SCREAMING_SNAKE_CASE	: Any					       =				model(UpperCAmelCase__			,			token_type_ids=UpperCAmelCase__						)["""last_hidden_state"""]
        SCREAMING_SNAKE_CASE	: Tuple					       =				model(UpperCAmelCase__			,			token_type_ids=UpperCAmelCase__			,			past_key_values=UpperCAmelCase__						)[
            """last_hidden_state"""
        ]

        # select random slice
        SCREAMING_SNAKE_CASE	: Tuple					       =				int(ids_tensor((1,)			,			shape_list(UpperCAmelCase__						)[-1]						)						)
        SCREAMING_SNAKE_CASE	: Union[str, Any]					       =				output_from_no_past[:, -1, random_slice_idx]
        SCREAMING_SNAKE_CASE	: List[Any]					       =				output_from_past[:, 0, random_slice_idx]

        # test that outputs are equal for slice
        tf.debugging.assert_near(UpperCAmelCase__			,			UpperCAmelCase__			,			rtol=1e-6						)


  def 	_lowercase (     self      :	Any			,			UpperCAmelCase__      :	str			,			UpperCAmelCase__      :	str			,			UpperCAmelCase__      :	Optional[int]			,			UpperCAmelCase__      :	Dict			,			UpperCAmelCase__      :	int			,			*UpperCAmelCase__      :	Tuple						)   ->List[str]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE	: Optional[int]					       =				TFGPTJModel(config=UpperCAmelCase__						)

        # create attention mask
        SCREAMING_SNAKE_CASE	: Optional[Any]					       =				self.seq_length // 2
        SCREAMING_SNAKE_CASE	: int					       =				tf.ones((self.batch_size, half_seq_length)			,			dtype=tf.intaa						)
        SCREAMING_SNAKE_CASE	: Tuple					       =				tf.zeros((self.batch_size, self.seq_length - half_seq_length)			,			dtype=tf.intaa						)
        SCREAMING_SNAKE_CASE	: Union[str, Any]					       =				tf.concat([attn_mask_begin, attn_mask_end]			,			axis=1						)

        # first forward pass
        SCREAMING_SNAKE_CASE       ,		SCREAMING_SNAKE_CASE	: Tuple					       =				model(UpperCAmelCase__			,			attention_mask=UpperCAmelCase__						).to_tuple()

        # create hypothetical next token and extent to next_input_ids
        SCREAMING_SNAKE_CASE	: Union[str, Any]					       =				ids_tensor((self.batch_size, 1)			,			config.vocab_size						)

        # change a random masked slice from input_ids
        SCREAMING_SNAKE_CASE	: List[str]					       =				ids_tensor((1,)			,			UpperCAmelCase__						).numpy() + 1
        SCREAMING_SNAKE_CASE	: Any					       =				ids_tensor((self.batch_size, self.seq_length)			,			config.vocab_size						)
        SCREAMING_SNAKE_CASE	: Union[str, Any]					       =				tf.range(self.seq_length						) == (self.seq_length - random_seq_idx_to_change)
        SCREAMING_SNAKE_CASE	: Tuple					       =				tf.transpose(
            tf.broadcast_to(tf.expand_dims(UpperCAmelCase__			,			-1						)			,			(self.seq_length, self.batch_size)						)						)
        SCREAMING_SNAKE_CASE	: Dict					       =				tf.where(UpperCAmelCase__			,			UpperCAmelCase__			,			UpperCAmelCase__						)

        # append to next input_ids and attn_mask
        SCREAMING_SNAKE_CASE	: Tuple					       =				tf.concat([input_ids, next_tokens]			,			axis=-1						)
        SCREAMING_SNAKE_CASE	: Union[str, Any]					       =				tf.concat([attn_mask, tf.ones((shape_list(UpperCAmelCase__						)[0], 1)			,			dtype=tf.intaa						)]			,			axis=1						)

        # get two different outputs
        SCREAMING_SNAKE_CASE	: Any					       =				model(UpperCAmelCase__			,			attention_mask=UpperCAmelCase__						)["""last_hidden_state"""]
        SCREAMING_SNAKE_CASE	: Any					       =				model(UpperCAmelCase__			,			past_key_values=UpperCAmelCase__			,			attention_mask=UpperCAmelCase__						)[
            """last_hidden_state"""
        ]

        # select random slice
        SCREAMING_SNAKE_CASE	: Optional[Any]					       =				int(ids_tensor((1,)			,			shape_list(UpperCAmelCase__						)[-1]						)						)
        SCREAMING_SNAKE_CASE	: str					       =				output_from_no_past[:, -1, random_slice_idx]
        SCREAMING_SNAKE_CASE	: Dict					       =				output_from_past[:, 0, random_slice_idx]

        # test that outputs are equal for slice
        tf.debugging.assert_near(UpperCAmelCase__			,			UpperCAmelCase__			,			rtol=1e-12						)


  def 	_lowercase (     self      :	Any			,			UpperCAmelCase__      :	Optional[Any]			,			UpperCAmelCase__      :	Dict			,			UpperCAmelCase__      :	List[str]			,			UpperCAmelCase__      :	Optional[Any]			,			UpperCAmelCase__      :	Optional[int]			,			*UpperCAmelCase__      :	Any						)   ->int:
        """simple docstring"""







        SCREAMING_SNAKE_CASE	: Union[str, Any]					       =				TFGPTJModel(config=UpperCAmelCase__						)

        SCREAMING_SNAKE_CASE	: int					       =				input_ids[:1, :]
        SCREAMING_SNAKE_CASE	: Optional[Any]					       =				input_mask[:1, :]
        SCREAMING_SNAKE_CASE	: Union[str, Any]					       =				token_type_ids[:1, :]
        SCREAMING_SNAKE_CASE	: List[Any]					       =				1

        # first forward pass
        SCREAMING_SNAKE_CASE	: List[str]					       =				model(UpperCAmelCase__			,			attention_mask=UpperCAmelCase__			,			token_type_ids=UpperCAmelCase__			,			use_cache=UpperCAmelCase__						)

        SCREAMING_SNAKE_CASE       ,		SCREAMING_SNAKE_CASE	: List[str]					       =				outputs.to_tuple()

        # create hypothetical next token and extent to next_input_ids
        SCREAMING_SNAKE_CASE	: List[Any]					       =				ids_tensor((self.batch_size, 3)			,			config.vocab_size						)
        SCREAMING_SNAKE_CASE	: Tuple					       =				ids_tensor((self.batch_size, 3)			,			2						)
        SCREAMING_SNAKE_CASE	: str					       =				ids_tensor((self.batch_size, 3)			,			self.type_vocab_size						)

        # append to next input_ids and token_type_ids
        SCREAMING_SNAKE_CASE	: List[Any]					       =				tf.concat([input_ids, next_tokens]			,			axis=-1						)
        SCREAMING_SNAKE_CASE	: Union[str, Any]					       =				tf.concat([input_mask, next_attn_mask]			,			axis=-1						)
        SCREAMING_SNAKE_CASE	: List[Any]					       =				tf.concat([token_type_ids, next_token_types]			,			axis=-1						)

        SCREAMING_SNAKE_CASE	: List[Any]					       =				model(
            UpperCAmelCase__			,			token_type_ids=UpperCAmelCase__			,			attention_mask=UpperCAmelCase__						)["""last_hidden_state"""]
        SCREAMING_SNAKE_CASE	: Any					       =				model(
            UpperCAmelCase__			,			token_type_ids=UpperCAmelCase__			,			attention_mask=UpperCAmelCase__			,			past_key_values=UpperCAmelCase__			,			)["""last_hidden_state"""]
        self.parent.assertTrue(output_from_past.shape[1] == next_tokens.shape[1]						)

        # select random slice
        SCREAMING_SNAKE_CASE	: Dict					       =				int(ids_tensor((1,)			,			shape_list(UpperCAmelCase__						)[-1]						)						)
        SCREAMING_SNAKE_CASE	: Optional[Any]					       =				output_from_no_past[:, -3:, random_slice_idx]
        SCREAMING_SNAKE_CASE	: Any					       =				output_from_past[:, :, random_slice_idx]

        # test that outputs are equal for slice
        tf.debugging.assert_near(UpperCAmelCase__			,			UpperCAmelCase__			,			rtol=1e-3						)


  def 	_lowercase (     self      :	Dict			,			UpperCAmelCase__      :	Optional[Any]			,			UpperCAmelCase__      :	str			,			UpperCAmelCase__      :	List[str]			,			UpperCAmelCase__      :	Optional[Any]			,			UpperCAmelCase__      :	Any			,			*UpperCAmelCase__      :	List[Any]						)   ->Tuple:
        """simple docstring"""







        SCREAMING_SNAKE_CASE	: Union[str, Any]					       =				TFGPTJForCausalLM(config=UpperCAmelCase__						)
        SCREAMING_SNAKE_CASE	: List[Any]					       =				{
            """input_ids""": input_ids,
            """attention_mask""": input_mask,
            """token_type_ids""": token_type_ids,
        }
        SCREAMING_SNAKE_CASE	: Dict					       =				model(UpperCAmelCase__						)
        self.parent.assertEqual(result.logits.shape			,			(self.batch_size, self.seq_length, self.vocab_size)						)




  def 	_lowercase (     self      :	List[Any]						)   ->int:
        """simple docstring"""







        SCREAMING_SNAKE_CASE	: int					       =				self.prepare_config_and_inputs()

        (
            (
            SCREAMING_SNAKE_CASE
        )       ,		(
            SCREAMING_SNAKE_CASE
        )       ,		(
            SCREAMING_SNAKE_CASE
        )       ,		(
            SCREAMING_SNAKE_CASE
        )       ,		(
            SCREAMING_SNAKE_CASE
        )       ,		(
            SCREAMING_SNAKE_CASE
        )       ,		(
            SCREAMING_SNAKE_CASE
        )       ,		(
            SCREAMING_SNAKE_CASE
        )       ,		(
            SCREAMING_SNAKE_CASE
        )       ,		
        )	: Tuple					       =				config_and_inputs

        SCREAMING_SNAKE_CASE	: Optional[int]					       =				{
            """input_ids""": input_ids,
            """token_type_ids""": token_type_ids,
            """attention_mask""": input_mask,
        }
        return config, inputs_dict







@require_tf
class     a__    (				UpperCAmelCase		,     UpperCAmelCase		,     UpperCAmelCase		,     unittest.TestCase    ):







  """simple docstring"""




  UpperCAmelCase__ :	Optional[Any]         =(
      (TFGPTJForCausalLM, TFGPTJForSequenceClassification, TFGPTJForQuestionAnswering, TFGPTJModel)
      if is_tf_available()
      else ()
  )

  UpperCAmelCase__ :	Optional[int]         =(TFGPTJForCausalLM,) if is_tf_available() else ()
  UpperCAmelCase__ :	Tuple         =(
      {
          """feature-extraction""": TFGPTJModel,
          """question-answering""": TFGPTJForQuestionAnswering,
          """text-classification""": TFGPTJForSequenceClassification,
          """text-generation""": TFGPTJForCausalLM,
          """zero-shot""": TFGPTJForSequenceClassification,
      }
      if is_tf_available()
      else {}
  )
  UpperCAmelCase__ :	Dict         =False
  UpperCAmelCase__ :	Optional[int]         =False
  UpperCAmelCase__ :	Tuple         =False
  UpperCAmelCase__ :	Union[str, Any]         =False


  def 	_lowercase (     self      :	Union[str, Any]			,			UpperCAmelCase__      :	List[str]			,			UpperCAmelCase__      :	Optional[Any]			,			UpperCAmelCase__      :	List[Any]			,			UpperCAmelCase__      :	str			,			UpperCAmelCase__      :	Union[str, Any]						)   ->str:
        """simple docstring"""







        if (
            pipeline_test_casse_name == "QAPipelineTests"
            and tokenizer_name is not None
            and not tokenizer_name.endswith("""Fast"""						)
        ):
              # `QAPipelineTests` fails for a few models when the slower tokenizer are used.
              # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework)
              # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer
              return True

        return False


  def 	_lowercase (     self      :	Dict						)   ->List[str]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE	: str					       =				TFGPTJModelTester(self						)
        SCREAMING_SNAKE_CASE	: List[Any]					       =				ConfigTester(self			,			config_class=UpperCAmelCase__			,			n_embd=3_7						)


  def 	_lowercase (     self      :	int						)   ->List[Any]:
        """simple docstring"""







        self.config_tester.run_common_tests()


  def 	_lowercase (     self      :	Tuple						)   ->Tuple:
        """simple docstring"""







        SCREAMING_SNAKE_CASE	: Any					       =				self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_gptj_model(*UpperCAmelCase__						)


  def 	_lowercase (     self      :	List[Any]						)   ->Optional[Any]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE	: Dict					       =				self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_gptj_model_past(*UpperCAmelCase__						)


  def 	_lowercase (     self      :	Union[str, Any]						)   ->str:
        """simple docstring"""







        SCREAMING_SNAKE_CASE	: str					       =				self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_gptj_model_attention_mask_past(*UpperCAmelCase__						)


  def 	_lowercase (     self      :	Tuple						)   ->List[str]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE	: int					       =				self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_gptj_model_past_large_inputs(*UpperCAmelCase__						)


  def 	_lowercase (     self      :	List[Any]						)   ->List[str]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE	: Union[str, Any]					       =				self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_gptj_lm_head_model(*UpperCAmelCase__						)


  @slow
  @unittest.skipIf(
      not is_tf_available() or len(tf.config.list_physical_devices("""GPU"""						)						) > 0			,			"""skip testing on GPU for now to avoid GPU OOM."""			,			)
  def 	_lowercase (     self      :	Any						)   ->Optional[Any]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE	: Union[str, Any]					       =				TFGPTJModel.from_pretrained("""EleutherAI/gpt-j-6B"""			,			from_pt=UpperCAmelCase__						)
        self.assertIsNotNone(UpperCAmelCase__						)




  @unittest.skip(reason="""Currently, model embeddings are going to undergo a major refactor."""						)
  def 	_lowercase (     self      :	int						)   ->int:
        """simple docstring"""







        super().test_resize_token_embeddings()







@require_tf
@tooslow
# Marked as @tooslow due to GPU OOM -- but still useful to run locally. Requires ~39GB of RAM.
class     a__    (				unittest.TestCase    ):







  """simple docstring"""




  def 	_lowercase (     self      :	List[Any]						)   ->int:
        """simple docstring"""







        SCREAMING_SNAKE_CASE	: str					       =				TFGPTJForCausalLM.from_pretrained("""EleutherAI/gpt-j-6B"""			,			from_pt=UpperCAmelCase__						)
        SCREAMING_SNAKE_CASE	: str					       =				tf.convert_to_tensor([[4_6_4, 3_2_9_0]]			,			dtype=tf.intaa						)  # The dog
        # fmt: off
        # The dog is a man's best friend. It is a loyal companion, and it is a friend
        SCREAMING_SNAKE_CASE	: Union[str, Any]					       =				[4_6_4, 3_2_9_0, 3_1_8, 2_5_7, 5_8_2, 3_3_8, 1_2_6_6, 1_5_4_5, 1_3, 6_3_2, 3_1_8, 2_5_7, 9_1_1_2, 1_5_1_8_5, 1_1, 2_9_0, 3_4_0, 3_1_8, 2_5_7, 1_5_4_5]
        # fmt: on
        SCREAMING_SNAKE_CASE	: Tuple					       =				model.generate(UpperCAmelCase__			,			do_sample=UpperCAmelCase__						)
        self.assertListEqual(output_ids[0].numpy().tolist()			,			UpperCAmelCase__						)


  def 	_lowercase (     self      :	Any						)   ->Dict:
        """simple docstring"""







        SCREAMING_SNAKE_CASE	: List[str]					       =				AutoTokenizer.from_pretrained("""EleutherAI/gpt-j-6B"""			,			revision="""float16"""						)
        SCREAMING_SNAKE_CASE	: Optional[Any]					       =				TFGPTJForCausalLM.from_pretrained("""EleutherAI/gpt-j-6B"""			,			revision="""float16"""			,			from_pt=UpperCAmelCase__						)

        SCREAMING_SNAKE_CASE	: int					       =				tokenizer("""Today is a nice day and"""			,			return_tensors="""tf"""						)
        # forces the generation to happen on CPU, to avoid GPU-related quirks
        with tf.device(""":/CPU:0"""						):
              SCREAMING_SNAKE_CASE	: Tuple					       =				model.generate(**UpperCAmelCase__			,			do_sample=UpperCAmelCase__			,			seed=[4_2, 0]						)
        SCREAMING_SNAKE_CASE	: Union[str, Any]					       =				tokenizer.decode(output_ids[0]			,			skip_special_tokens=UpperCAmelCase__						)

        SCREAMING_SNAKE_CASE	: Optional[int]					       =				"""Today is a nice day and I’m going to go for a walk. I’"""
        self.assertEqual(UpperCAmelCase__			,			UpperCAmelCase__						)


  def 	_lowercase (     self      :	Dict						)   ->List[str]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE	: Optional[Any]					       =				TFGPTJForCausalLM.from_pretrained("""EleutherAI/gpt-j-6B"""			,			revision="""float16"""			,			from_pt=UpperCAmelCase__						)
        SCREAMING_SNAKE_CASE	: Dict					       =				AutoTokenizer.from_pretrained("""EleutherAI/gpt-j-6B"""			,			revision="""float16"""						)

        SCREAMING_SNAKE_CASE	: Tuple					       =				"""left"""

        # Define PAD Token = EOS Token = 50256
        SCREAMING_SNAKE_CASE	: Tuple					       =				tokenizer.eos_token
        SCREAMING_SNAKE_CASE	: Union[str, Any]					       =				model.config.eos_token_id

        # use different length sentences to test batching
        SCREAMING_SNAKE_CASE	: List[str]					       =				[
            """Hello, my dog is a little""",
            """Today, I""",
        ]
        SCREAMING_SNAKE_CASE	: Any					       =				[
            """Hello, my dog is a little over a year old and has been diagnosed with hip dysplasia""",
            """Today, I’m going to be talking about a topic that’""",
        ]
        return model, tokenizer, sentences, expected_output_sentences


  def 	_lowercase (     self      :	List[str]						)   ->List[str]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE       ,		SCREAMING_SNAKE_CASE       ,		SCREAMING_SNAKE_CASE       ,		SCREAMING_SNAKE_CASE	: Any					       =				self._get_beam_search_test_objects()

        SCREAMING_SNAKE_CASE	: Optional[Any]					       =				tokenizer(UpperCAmelCase__			,			return_tensors="""tf"""			,			padding=UpperCAmelCase__						)
        SCREAMING_SNAKE_CASE	: Union[str, Any]					       =				model.generate(**UpperCAmelCase__			,			do_sample=UpperCAmelCase__			,			num_beams=2						)
        SCREAMING_SNAKE_CASE	: Optional[Any]					       =				tokenizer.batch_decode(UpperCAmelCase__			,			skip_special_tokens=UpperCAmelCase__						)
        self.assertListEqual(UpperCAmelCase__			,			UpperCAmelCase__						)


  def 	_lowercase (     self      :	Union[str, Any]						)   ->List[str]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE       ,		SCREAMING_SNAKE_CASE       ,		SCREAMING_SNAKE_CASE       ,		SCREAMING_SNAKE_CASE	: Union[str, Any]					       =				self._get_beam_search_test_objects()

        SCREAMING_SNAKE_CASE	: Optional[int]					       =				tokenizer(UpperCAmelCase__			,			return_tensors="""tf"""			,			padding=UpperCAmelCase__						)
        SCREAMING_SNAKE_CASE	: Optional[Any]					       =				tokenizer(sentences[0]			,			return_tensors="""tf"""						)
        SCREAMING_SNAKE_CASE	: Optional[int]					       =				model.generate(**UpperCAmelCase__			,			do_sample=UpperCAmelCase__			,			num_beams=2						)
        SCREAMING_SNAKE_CASE	: Union[str, Any]					       =				(
            shape_list(inputs_non_padded["""input_ids"""]						)[-1]
            - tf.reduce_sum(tf.cast(inputs["""attention_mask"""][-1]			,			tf.intaa						)						).numpy()
        )
        SCREAMING_SNAKE_CASE	: Tuple					       =				tokenizer(sentences[1]			,			return_tensors="""tf"""						)
        SCREAMING_SNAKE_CASE	: int					       =				model.generate(
            **UpperCAmelCase__			,			do_sample=UpperCAmelCase__			,			num_beams=2			,			max_length=model.config.max_length - num_paddings						)
        SCREAMING_SNAKE_CASE	: Optional[int]					       =				tokenizer.decode(output_non_padded[0]			,			skip_special_tokens=UpperCAmelCase__						)
        SCREAMING_SNAKE_CASE	: Union[str, Any]					       =				tokenizer.decode(output_padded[0]			,			skip_special_tokens=UpperCAmelCase__						)
        self.assertListEqual(UpperCAmelCase__			,			[non_padded_sentence, padded_sentence]						)




  def 	_lowercase (     self      :	Union[str, Any]						)   ->Optional[int]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE       ,		SCREAMING_SNAKE_CASE       ,		SCREAMING_SNAKE_CASE       ,		SCREAMING_SNAKE_CASE	: Union[str, Any]					       =				self._get_beam_search_test_objects()

        SCREAMING_SNAKE_CASE	: Dict					       =				tokenizer(UpperCAmelCase__			,			return_tensors="""tf"""			,			padding=UpperCAmelCase__						)
        SCREAMING_SNAKE_CASE	: List[str]					       =				tf.function(model.generate			,			jit_compile=UpperCAmelCase__						)
        SCREAMING_SNAKE_CASE	: Any					       =				xla_generate(**UpperCAmelCase__			,			do_sample=UpperCAmelCase__			,			num_beams=2						)
        SCREAMING_SNAKE_CASE	: str					       =				tokenizer.batch_decode(UpperCAmelCase__			,			skip_special_tokens=UpperCAmelCase__						)
        self.assertListEqual(UpperCAmelCase__			,			UpperCAmelCase__						)







import os
from typing import List, Union

import tensorflow as tf
from tensorflow_text import BertTokenizer as BertTokenizerLayer
from tensorflow_text import FastBertTokenizer, ShrinkLongestTrimmer, case_fold_utfa, combine_segments, pad_model_inputs

from .tokenization_bert import BertTokenizer







class     a__    (				tf.keras.layers.Layer    ):







  """simple docstring"""




  def __init__(     self      :	str			,			UpperCAmelCase__      :	List			,			UpperCAmelCase__      :	bool			,			UpperCAmelCase__      :	int = None			,			UpperCAmelCase__      :	int = None			,			UpperCAmelCase__      :	int = None			,			UpperCAmelCase__      :	str = "longest"			,			UpperCAmelCase__      :	bool = True			,			UpperCAmelCase__      :	int = 5_1_2			,			UpperCAmelCase__      :	int = None			,			UpperCAmelCase__      :	bool = True			,			UpperCAmelCase__      :	bool = True			,			UpperCAmelCase__      :	bool = True			,			**UpperCAmelCase__      :	Optional[int]			,			)   ->Union[str, Any]:
        """simple docstring"""







        super().__init__()
        if use_fast_bert_tokenizer:
              SCREAMING_SNAKE_CASE	: Any					       =				FastBertTokenizer(
                  UpperCAmelCase__			,			token_out_type=tf.intaa			,			lower_case_nfd_strip_accents=UpperCAmelCase__			,			**UpperCAmelCase__						)
        else:
              SCREAMING_SNAKE_CASE	: Any					       =				tf.lookup.StaticVocabularyTable(
                  tf.lookup.KeyValueTensorInitializer(
                      keys=UpperCAmelCase__			,			key_dtype=tf.string			,			values=tf.range(tf.size(UpperCAmelCase__			,			out_type=tf.intaa						)			,			dtype=tf.intaa						)			,			value_dtype=tf.intaa			,			)			,			num_oov_buckets=1			,			)
              SCREAMING_SNAKE_CASE	: Dict					       =				BertTokenizerLayer(
                  UpperCAmelCase__			,			token_out_type=tf.intaa			,			lower_case=UpperCAmelCase__			,			**UpperCAmelCase__						)

        SCREAMING_SNAKE_CASE	: Any					       =				vocab_list
        SCREAMING_SNAKE_CASE	: int					       =				do_lower_case
        SCREAMING_SNAKE_CASE	: Optional[Any]					       =				cls_token_id or vocab_list.index("""[CLS]"""						)
        SCREAMING_SNAKE_CASE	: int					       =				sep_token_id or vocab_list.index("""[SEP]"""						)
        SCREAMING_SNAKE_CASE	: int					       =				pad_token_id or vocab_list.index("""[PAD]"""						)
        SCREAMING_SNAKE_CASE	: Optional[Any]					       =				ShrinkLongestTrimmer(max_length - 3			,			axis=1						)  # Allow room for special tokens
        SCREAMING_SNAKE_CASE	: Tuple					       =				max_length
        SCREAMING_SNAKE_CASE	: List[str]					       =				padding
        SCREAMING_SNAKE_CASE	: Optional[int]					       =				truncation
        SCREAMING_SNAKE_CASE	: Optional[int]					       =				pad_to_multiple_of
        SCREAMING_SNAKE_CASE	: Dict					       =				return_token_type_ids
        SCREAMING_SNAKE_CASE	: str					       =				return_attention_mask


  @classmethod
  def 	_lowercase (     cls      :	Optional[int]			,			UpperCAmelCase__      :	"PreTrainedTokenizerBase"			,			**UpperCAmelCase__      :	Tuple						)   ->str:  # noqa: F821
        """simple docstring"""







        SCREAMING_SNAKE_CASE	: Any					       =				kwargs.pop("""do_lower_case"""			,			UpperCAmelCase__						)
        SCREAMING_SNAKE_CASE	: List[Any]					       =				tokenizer.do_lower_case if do_lower_case is None else do_lower_case
        SCREAMING_SNAKE_CASE	: Any					       =				kwargs.pop("""cls_token_id"""			,			UpperCAmelCase__						)
        SCREAMING_SNAKE_CASE	: Any					       =				tokenizer.cls_token_id if cls_token_id is None else cls_token_id
        SCREAMING_SNAKE_CASE	: Optional[int]					       =				kwargs.pop("""sep_token_id"""			,			UpperCAmelCase__						)
        SCREAMING_SNAKE_CASE	: List[Any]					       =				tokenizer.sep_token_id if sep_token_id is None else sep_token_id
        SCREAMING_SNAKE_CASE	: int					       =				kwargs.pop("""pad_token_id"""			,			UpperCAmelCase__						)
        SCREAMING_SNAKE_CASE	: Any					       =				tokenizer.pad_token_id if pad_token_id is None else pad_token_id

        SCREAMING_SNAKE_CASE	: List[str]					       =				tokenizer.get_vocab()
        SCREAMING_SNAKE_CASE	: List[str]					       =				sorted([(wordpiece, idx) for wordpiece, idx in vocab.items()]			,			key=lambda UpperCAmelCase__						: x[1]						)
        SCREAMING_SNAKE_CASE	: Optional[Any]					       =				[entry[0] for entry in vocab]
        return cls(
            vocab_list=UpperCAmelCase__			,			do_lower_case=UpperCAmelCase__			,			cls_token_id=UpperCAmelCase__			,			sep_token_id=UpperCAmelCase__			,			pad_token_id=UpperCAmelCase__			,			**UpperCAmelCase__			,			)


  @classmethod
  def 	_lowercase (     cls      :	str			,			UpperCAmelCase__      :	Union[str, os.PathLike]			,			*UpperCAmelCase__      :	Dict			,			**UpperCAmelCase__      :	int						)   ->Any:
        """simple docstring"""







        try:
              SCREAMING_SNAKE_CASE	: List[str]					       =				BertTokenizer.from_pretrained(UpperCAmelCase__			,			*UpperCAmelCase__			,			**UpperCAmelCase__						)
        except:  # noqa: E722
              from .tokenization_bert_fast import BertTokenizerFast

              SCREAMING_SNAKE_CASE	: Union[str, Any]					       =				BertTokenizerFast.from_pretrained(UpperCAmelCase__			,			*UpperCAmelCase__			,			**UpperCAmelCase__						)
        return cls.from_tokenizer(UpperCAmelCase__			,			**UpperCAmelCase__						)


  def 	_lowercase (     self      :	Tuple			,			UpperCAmelCase__      :	List[str]						)   ->List[str]:
        """simple docstring"""







        if self.do_lower_case:
              SCREAMING_SNAKE_CASE	: Optional[Any]					       =				case_fold_utfa(UpperCAmelCase__						)
        SCREAMING_SNAKE_CASE	: int					       =				self.tf_tokenizer.tokenize(UpperCAmelCase__						)
        return tokens.merge_dims(1			,			-1						)


  def 	_lowercase (     self      :	Tuple			,			UpperCAmelCase__      :	Any			,			UpperCAmelCase__      :	Dict=None			,			UpperCAmelCase__      :	Optional[int]=None			,			UpperCAmelCase__      :	Optional[Any]=None			,			UpperCAmelCase__      :	Union[str, Any]=None			,			UpperCAmelCase__      :	Dict=None			,			UpperCAmelCase__      :	int=None			,			UpperCAmelCase__      :	Tuple=None			,			)   ->Any:
        """simple docstring"""







        if padding is None:
              SCREAMING_SNAKE_CASE	: int					       =				self.padding
        if padding not in ("longest", "max_length"):
              raise ValueError("""Padding must be either 'longest' or 'max_length'!"""						)
        if max_length is not None and text_pair is not None:
              # Because we have to instantiate a Trimmer to do it properly
              raise ValueError("""max_length cannot be overridden at call time when truncating paired texts!"""						)
        if max_length is None:
              SCREAMING_SNAKE_CASE	: Optional[int]					       =				self.max_length
        if truncation is None:
              SCREAMING_SNAKE_CASE	: str					       =				self.truncation
        if pad_to_multiple_of is None:
              SCREAMING_SNAKE_CASE	: Union[str, Any]					       =				self.pad_to_multiple_of
        if return_token_type_ids is None:
              SCREAMING_SNAKE_CASE	: Any					       =				self.return_token_type_ids
        if return_attention_mask is None:
              SCREAMING_SNAKE_CASE	: int					       =				self.return_attention_mask
        if not isinstance(UpperCAmelCase__			,			tf.Tensor						):
              SCREAMING_SNAKE_CASE	: str					       =				tf.convert_to_tensor(UpperCAmelCase__						)
        if text_pair is not None and not isinstance(UpperCAmelCase__			,			tf.Tensor						):
              SCREAMING_SNAKE_CASE	: int					       =				tf.convert_to_tensor(UpperCAmelCase__						)
        if text_pair is not None:
              if text.shape.rank > 1:
                    raise ValueError("""text argument should not be multidimensional when a text pair is supplied!"""						)
              if text_pair.shape.rank > 1:
                    raise ValueError("""text_pair should not be multidimensional!"""						)
        if text.shape.rank == 2:
              SCREAMING_SNAKE_CASE       ,		SCREAMING_SNAKE_CASE	: Dict					       =				text[:, 0], text[:, 1]
        SCREAMING_SNAKE_CASE	: Optional[int]					       =				self.unpaired_tokenize(UpperCAmelCase__						)
        if text_pair is None:  # Unpaired text
              if truncation:
                    SCREAMING_SNAKE_CASE	: int					       =				text[:, : max_length - 2]  # Allow room for special tokens
              SCREAMING_SNAKE_CASE       ,		SCREAMING_SNAKE_CASE	: List[str]					       =				combine_segments(
                  (text,)			,			start_of_sequence_id=self.cls_token_id			,			end_of_segment_id=self.sep_token_id						)
        else:  # Paired text
              SCREAMING_SNAKE_CASE	: Union[str, Any]					       =				self.unpaired_tokenize(UpperCAmelCase__						)
              if truncation:
                    SCREAMING_SNAKE_CASE       ,		SCREAMING_SNAKE_CASE	: Any					       =				self.paired_trimmer.trim([text, text_pair]						)
              SCREAMING_SNAKE_CASE       ,		SCREAMING_SNAKE_CASE	: str					       =				combine_segments(
                  (text, text_pair)			,			start_of_sequence_id=self.cls_token_id			,			end_of_segment_id=self.sep_token_id						)
        if padding == "longest":
              SCREAMING_SNAKE_CASE	: Optional[int]					       =				input_ids.bounding_shape(axis=1						)
              if pad_to_multiple_of is not None:
                    # No ceiling division in tensorflow, so we negate floordiv instead
                    SCREAMING_SNAKE_CASE	: Any					       =				pad_to_multiple_of * (-tf.math.floordiv(-pad_length			,			UpperCAmelCase__						))
        else:
              SCREAMING_SNAKE_CASE	: Optional[int]					       =				max_length

        SCREAMING_SNAKE_CASE       ,		SCREAMING_SNAKE_CASE	: Tuple					       =				pad_model_inputs(UpperCAmelCase__			,			max_seq_length=UpperCAmelCase__			,			pad_value=self.pad_token_id						)
        SCREAMING_SNAKE_CASE	: Any					       =				{"""input_ids""": input_ids}
        if return_attention_mask:
              SCREAMING_SNAKE_CASE	: Optional[int]					       =				attention_mask
        if return_token_type_ids:
              SCREAMING_SNAKE_CASE       ,		SCREAMING_SNAKE_CASE	: Optional[Any]					       =				pad_model_inputs(
                  UpperCAmelCase__			,			max_seq_length=UpperCAmelCase__			,			pad_value=self.pad_token_id						)
              SCREAMING_SNAKE_CASE	: List[str]					       =				token_type_ids
        return output




  def 	_lowercase (     self      :	Optional[int]						)   ->Tuple:
        """simple docstring"""







        return {
            "vocab_list": self.vocab_list,
            "do_lower_case": self.do_lower_case,
            "cls_token_id": self.cls_token_id,
            "sep_token_id": self.sep_token_id,
            "pad_token_id": self.pad_token_id,
        }




