




import sys
from collections.abc import Mapping

import numpy as np
import pyarrow as pa

from .. import config
from ..utils.py_utils import map_nested
from .formatting import TensorFormatter
class 				__snake_case     (TensorFormatter[Mapping, np.ndarray, Mapping]						):



				def __init__(					self					:						List[str]						,		_UpperCAmelCase					:						Optional[int]=None						,		**_UpperCAmelCase					:						Dict					)     ->			Optional[int]:





								'''simple docstring'''




								super().__init__(features=_UpperCAmelCase					)
								_lowerCAmelCase			:			Any        =					np_array_kwargs



				def 					SCREAMING_SNAKE_CASE				(					self					:						int						,		_UpperCAmelCase					:						Tuple					)     ->			Tuple:





								'''simple docstring'''




								if isinstance(_UpperCAmelCase						,		_UpperCAmelCase					):
												if column and all(
												    isinstance(_UpperCAmelCase						,		np.ndarray					) and x.shape == column[0].shape and x.dtype == column[0].dtype for x in column					):
																return np.stack(_UpperCAmelCase					)
												else:
																# don't use np.array(column, dtype=object)
																# since it fails in certain cases
																# see https://stackoverflow.com/q/51005699
																_lowerCAmelCase			:			List[Any]        =					np.empty(len(_UpperCAmelCase					)						,		dtype=_UpperCAmelCase					)
																_lowerCAmelCase			:			List[Any]        =					column
																return out
								return column



				def 					SCREAMING_SNAKE_CASE				(					self					:						Tuple						,		_UpperCAmelCase					:						Optional[int]					)     ->			Union[str, Any]:





								'''simple docstring'''




								if isinstance(_UpperCAmelCase						,		(str, bytes, type(_UpperCAmelCase					))					):
												return value
								elif isinstance(_UpperCAmelCase						,		(np.character, np.ndarray)					) and np.issubdtype(value.dtype						,		np.character					):
												return value
								elif isinstance(_UpperCAmelCase						,		np.number					):
												return value

								_lowerCAmelCase			:			List[str]        =					{}

								if isinstance(_UpperCAmelCase						,		np.ndarray					) and np.issubdtype(value.dtype						,		np.integer					):
												_lowerCAmelCase			:			Union[str, Any]        =					{"""dtype""": np.intaa}
								elif isinstance(_UpperCAmelCase						,		np.ndarray					) and np.issubdtype(value.dtype						,		np.floating					):
												_lowerCAmelCase			:			Tuple        =					{"""dtype""": np.floataa}
								elif config.PIL_AVAILABLE and "PIL" in sys.modules:
												import PIL.Image

												if isinstance(_UpperCAmelCase						,		PIL.Image.Image					):
																return np.asarray(_UpperCAmelCase						,		**self.np_array_kwargs					)

								return np.asarray(_UpperCAmelCase						,		**{**default_dtype, **self.np_array_kwargs}					)



				def 					SCREAMING_SNAKE_CASE				(					self					:						str						,		_UpperCAmelCase					:						Dict					)     ->			Optional[Any]:





								'''simple docstring'''




								if config.TORCH_AVAILABLE and "torch" in sys.modules:
												import torch

												if isinstance(_UpperCAmelCase						,		torch.Tensor					):
																return self._tensorize(data_struct.detach().cpu().numpy()[()]					)
								if hasattr(_UpperCAmelCase						,		"""__array__"""					) and not isinstance(_UpperCAmelCase						,		(np.ndarray, np.character, np.number)					):
												_lowerCAmelCase			:			str        =					data_struct.__array__()
								# support for nested types like struct of list of struct
								if isinstance(_UpperCAmelCase						,		np.ndarray					):
												if data_struct.dtype == object:
																return self._consolidate([self.recursive_tensorize(_UpperCAmelCase					) for substruct in data_struct]					)
								if isinstance(_UpperCAmelCase						,		(list, tuple)					):
												return self._consolidate([self.recursive_tensorize(_UpperCAmelCase					) for substruct in data_struct]					)
								return self._tensorize(_UpperCAmelCase					)



				def 					SCREAMING_SNAKE_CASE				(					self					:						List[str]						,		_UpperCAmelCase					:						dict					)     ->			List[str]:





								'''simple docstring'''




								return map_nested(self._recursive_tensorize						,		_UpperCAmelCase						,		map_list=_UpperCAmelCase					)



				def 					SCREAMING_SNAKE_CASE				(					self					:						Dict						,		_UpperCAmelCase					:						pa.Table					)     ->			Mapping:





								'''simple docstring'''




								_lowerCAmelCase			:			List[str]        =					self.numpy_arrow_extractor().extract_row(_UpperCAmelCase					)
								_lowerCAmelCase			:			Union[str, Any]        =					self.python_features_decoder.decode_row(_UpperCAmelCase					)
								return self.recursive_tensorize(_UpperCAmelCase					)



				def 					SCREAMING_SNAKE_CASE				(					self					:						Optional[Any]						,		_UpperCAmelCase					:						pa.Table					)     ->			np.ndarray:





								'''simple docstring'''




								_lowerCAmelCase			:			int        =					self.numpy_arrow_extractor().extract_column(_UpperCAmelCase					)
								_lowerCAmelCase			:			str        =					self.python_features_decoder.decode_column(_UpperCAmelCase						,		pa_table.column_names[0]					)
								_lowerCAmelCase			:			Union[str, Any]        =					self.recursive_tensorize(_UpperCAmelCase					)
								_lowerCAmelCase			:			str        =					self._consolidate(_UpperCAmelCase					)
								return column



				def 					SCREAMING_SNAKE_CASE				(					self					:						int						,		_UpperCAmelCase					:						pa.Table					)     ->			Mapping:





								'''simple docstring'''




								_lowerCAmelCase			:			str        =					self.numpy_arrow_extractor().extract_batch(_UpperCAmelCase					)
								_lowerCAmelCase			:			Optional[int]        =					self.python_features_decoder.decode_batch(_UpperCAmelCase					)
								_lowerCAmelCase			:			str        =					self.recursive_tensorize(_UpperCAmelCase					)
								for column_name in batch:
												_lowerCAmelCase			:			Any        =					self._consolidate(batch[column_name]					)
								return batch







from __future__ import annotations

import unittest

from transformers import CTRLConfig, 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, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
   import tensorflow as tf

   from transformers.models.ctrl.modeling_tf_ctrl import (
       TF_CTRL_PRETRAINED_MODEL_ARCHIVE_LIST,
       TFCTRLForSequenceClassification,
       TFCTRLLMHeadModel,
       TFCTRLModel,
   )




class 			a__       (					UpperCamelCase__      ):







     def __init__(	self  ,		A  ,		)  ->    List[Any]:



          '''simple docstring'''



          a      =      parent
          a      =      13
          a      =      7
          a      =      True
          a      =      True
          a      =      True
          a      =      True
          a      =      True
          a      =      99
          a      =      32
          a      =      2
          a      =      4
          a      =      37
          a      =      "gelu"
          a      =      0.1
          a      =      0.1
          a      =      512
          a      =      16
          a      =      2
          a      =      0.0_2
          a      =      3
          a      =      4
          a      =      None
          a      =      self.vocab_size - 1







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



          '''simple docstring'''



          a      =      ids_tensor([self.batch_size, self.seq_length]  ,		self.vocab_size )

          a      =      None
          if self.use_input_mask:
               a      =      random_attention_mask([self.batch_size, self.seq_length] )

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

          a      =      None
          if self.use_mc_token_ids:
               a      =      ids_tensor([self.batch_size, self.num_choices]  ,		self.seq_length )

          a      =      None
          a      =      None
          a      =      None
          if self.use_labels:
               a      =      ids_tensor([self.batch_size]  ,		self.type_sequence_label_size )
               a      =      ids_tensor([self.batch_size, self.seq_length]  ,		self.num_labels )
               a      =      ids_tensor([self.batch_size]  ,		self.num_choices )

          a      =      CTRLConfig(
              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  ,		pad_token_id=self.pad_token_id  ,		)

          a      =      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 			lowerCAmelCase_				(	self  ,		A  ,		A  ,		A  ,		A  ,		A  ,		*A )  ->    Optional[int]:



          '''simple docstring'''



          a      =      TFCTRLModel(config=A )
          a      =      {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}
          a      =      model(A )

          a      =      [input_ids, None, input_mask]  # None is the input for 'past'
          a      =      model(A )

          a      =      model(A )

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







     def 			lowerCAmelCase_				(	self  ,		A  ,		A  ,		A  ,		A  ,		A  ,		*A )  ->    Tuple:



          '''simple docstring'''



          a      =      TFCTRLLMHeadModel(config=A )
          a      =      {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}
          a      =      model(A )
          self.parent.assertEqual(result.logits.shape  ,		(self.batch_size, self.seq_length, self.vocab_size) )







     def 			lowerCAmelCase_				(	self  ,		A  ,		A  ,		A  ,		A  ,		A  ,		*A )  ->    List[Any]:



          '''simple docstring'''



          a      =      self.num_labels
          a      =      ids_tensor([self.batch_size]  ,		self.type_sequence_label_size )
          a      =      {
              "input_ids": input_ids,
              "token_type_ids": token_type_ids,
              "labels": sequence_labels,
          }
          a      =      TFCTRLForSequenceClassification(A )
          a      =      model(A )
          self.parent.assertEqual(result.logits.shape  ,		(self.batch_size, self.num_labels) )







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



          '''simple docstring'''



          a      =      self.prepare_config_and_inputs()

          (
              (
              a
          )  ,      (
              a
          )  ,      (
              a
          )  ,      (
              a
          )  ,      (
              a
          )  ,      (
              a
          )  ,      (
              a
          )  ,      (
              a
          )  ,      (
              a
          )  ,      
          )      =      config_and_inputs

          a      =      {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask}
          return config, inputs_dict







@require_tf
class 			a__       (					UpperCamelCase__   ,					UpperCamelCase__   ,					unittest.TestCase      ):
     a		:			Any							=	(TFCTRLModel, TFCTRLLMHeadModel, TFCTRLForSequenceClassification) if is_tf_available() else ()
     a		:			Optional[Any]							=	(TFCTRLLMHeadModel,) if is_tf_available() else ()
     a		:			List[Any]							=	(
         {
             """feature-extraction""": TFCTRLModel,
             """text-classification""": TFCTRLForSequenceClassification,
             """text-generation""": TFCTRLLMHeadModel,
             """zero-shot""": TFCTRLForSequenceClassification,
         }
         if is_tf_available()
         else {}
     )
     a		:			Union[str, Any]							=	False
     a		:			str							=	False







     def 			lowerCAmelCase_				(	self  ,		A  ,		A  ,		A  ,		A  ,		A )  ->    List[str]:



          '''simple docstring'''



          if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests":
               # Get `tokenizer does not have a padding token` error for both fast/slow tokenizers.
               # `CTRLConfig` was never used in pipeline tests, either because of a missing checkpoint or because a tiny
               # config could not be created.
               return True

          return False







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



          '''simple docstring'''



          a      =      TFCTRLModelTester(self )
          a      =      ConfigTester(self  ,		config_class=A  ,		n_embd=37 )







     def 			lowerCAmelCase_				(	self )  ->    Tuple:



          '''simple docstring'''



          self.config_tester.run_common_tests()







     def 			lowerCAmelCase_				(	self )  ->    Optional[Any]:



          '''simple docstring'''



          a      =      self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_ctrl_model(*A )







     def 			lowerCAmelCase_				(	self )  ->    List[str]:



          '''simple docstring'''



          a      =      self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_ctrl_lm_head(*A )







     def 			lowerCAmelCase_				(	self )  ->    Optional[Any]:



          '''simple docstring'''



          a      =      self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_ctrl_for_sequence_classification(*A )







     def 			lowerCAmelCase_				(	self )  ->    Tuple:



          '''simple docstring'''



          a  ,      a      =      self.model_tester.prepare_config_and_inputs_for_common()
          a      =      [TFCTRLLMHeadModel]
          a      =      [TFCTRLForSequenceClassification]

          for model_class in self.all_model_classes:
               a      =      model_class(A )
               model.build()  # may be needed for the get_bias() call below
               assert isinstance(model.get_input_embeddings()  ,		tf.keras.layers.Layer )

               if model_class in list_lm_models:
                    a      =      model.get_output_embeddings()
                    assert isinstance(A  ,		tf.keras.layers.Layer )
                    a      =      model.get_bias()
                    assert isinstance(A  ,		A )
                    for k, v in name.items():
                         assert isinstance(A  ,		tf.Variable )
               elif model_class in list_other_models_with_output_ebd:
                    a      =      model.get_output_embeddings()
                    assert isinstance(A  ,		tf.keras.layers.Layer )
                    a      =      model.get_bias()
                    assert name is None
               else:
                    a      =      model.get_output_embeddings()
                    assert x is None
                    a      =      model.get_bias()
                    assert name is None







     @slow
     def 			lowerCAmelCase_				(	self )  ->    Tuple:



          '''simple docstring'''



          for model_name in TF_CTRL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               a      =      TFCTRLModel.from_pretrained(A )
               self.assertIsNotNone(A )







@require_tf
class 			a__       (					unittest.TestCase      ):







     @slow
     def 			lowerCAmelCase_				(	self )  ->    Any:



          '''simple docstring'''



          a      =      TFCTRLLMHeadModel.from_pretrained("ctrl" )
          a      =      tf.convert_to_tensor([[11859, 0, 1611, 8]]  ,		dtype=tf.intaa )  # Legal the president is
          a      =      [
              11859,
              0,
              1611,
              8,
              5,
              150,
              26449,
              2,
              19,
              348,
              469,
              3,
              2595,
              48,
              20740,
              246533,
              246533,
              19,
              30,
              5,
          ]  # Legal the president is a good guy and I don't want to lose my job. \n \n I have a

          a      =      model.generate(A  ,		do_sample=A )
          self.assertListEqual(output_ids[0].numpy().tolist()  ,		A )

