'''simple docstring'''





import argparse
import os

import align
import numpy as np
import requests
import tensorflow as tf
import torch
from PIL import Image
from tokenizer import Tokenizer

from transformers import (
    AlignConfig,
    AlignModel,
    AlignProcessor,
    BertConfig,
    BertTokenizer,
    EfficientNetConfig,
    EfficientNetImageProcessor,
)
from transformers.utils import logging


logging.set_verbosity_info()
UpperCamelCase       :     Optional[int]			=    logging.get_logger(__name__)






def SCREAMING_SNAKE_CASE__  (				snake_case       :				Any  )   ->				Tuple:







     """simple docstring"""
     a					:							Any							= tf.image.resize(snake_case				,	(346, 346)  )
     a					:							Any							= tf.image.crop_to_bounding_box(snake_case				,	(346 - 289) // 2				,	(346 - 289) // 2				,	289				,	289  )
     return image






def SCREAMING_SNAKE_CASE__  (				)   ->				Any:







     """simple docstring"""
     a					:							Dict							= EfficientNetConfig.from_pretrained('google/efficientnet-b7'  )
     a					:							Optional[Any]							= 289
     a					:							str							= 640
     a					:							int							= {'0': 'LABEL_0', '1': 'LABEL_1'}
     a					:							Optional[int]							= {'LABEL_0': 0, 'LABEL_1': 1}
     a					:							List[str]							= []

     a					:							Optional[Any]							= BertConfig()
     a					:							Tuple							= AlignConfig.from_text_vision_configs(
         text_config=snake_case				,	vision_config=snake_case				,	projection_dim=640  )
     return config






def SCREAMING_SNAKE_CASE__  (				)   ->				Optional[Any]:







     """simple docstring"""
     a					:							Any							= 'http://images.cocodataset.org/val2017/000000039769.jpg'
     a					:							int							= Image.open(requests.get(snake_case				,	stream=snake_case  ).raw  )
     return im






def SCREAMING_SNAKE_CASE__  (				)   ->				Optional[int]:







     """simple docstring"""
     a					:							Union[str, Any]							= EfficientNetImageProcessor(
         do_center_crop=snake_case				,	rescale_factor=1 / 1_27.5				,	rescale_offset=snake_case				,	do_normalize=snake_case				,	include_top=snake_case				,	resample=Image.BILINEAR				,	)
     a					:							List[str]							= BertTokenizer.from_pretrained('bert-base-uncased'  )
     a					:							int							= 64
     a					:							str							= AlignProcessor(image_processor=snake_case				,	tokenizer=snake_case  )
     return processor






def SCREAMING_SNAKE_CASE__  (				snake_case       :				Optional[Any]  )   ->				str:







     """simple docstring"""
     # EfficientNet image encoder
     a					:							List[str]							= [v.split('_'  )[0].split('block'  )[1] for v in original_param_names if v.startswith('block'  )]
     a					:							Any							= list(set(snake_case  )  )
     a					:							Union[str, Any]							= sorted(snake_case  )
     a					:							Union[str, Any]							= len(snake_case  )
     a					:							Any							= {b: str(snake_case  ) for b, i in zip(snake_case				,	range(snake_case  )  )}

     a					:							Dict							= []
     rename_keys.append(('stem_conv/kernel:0', 'embeddings.convolution.weight')  )
     rename_keys.append(('stem_bn/gamma:0', 'embeddings.batchnorm.weight')  )
     rename_keys.append(('stem_bn/beta:0', 'embeddings.batchnorm.bias')  )
     rename_keys.append(('stem_bn/moving_mean:0', 'embeddings.batchnorm.running_mean')  )
     rename_keys.append(('stem_bn/moving_variance:0', 'embeddings.batchnorm.running_var')  )

     for b in block_names:
          a					:							List[str]							= block_name_mapping[b]
          rename_keys.append((F"""block{b}_expand_conv/kernel:0""", F"""encoder.blocks.{hf_b}.expansion.expand_conv.weight""")  )
          rename_keys.append((F"""block{b}_expand_bn/gamma:0""", F"""encoder.blocks.{hf_b}.expansion.expand_bn.weight""")  )
          rename_keys.append((F"""block{b}_expand_bn/beta:0""", F"""encoder.blocks.{hf_b}.expansion.expand_bn.bias""")  )
          rename_keys.append(
              (F"""block{b}_expand_bn/moving_mean:0""", F"""encoder.blocks.{hf_b}.expansion.expand_bn.running_mean""")  )
          rename_keys.append(
              (F"""block{b}_expand_bn/moving_variance:0""", F"""encoder.blocks.{hf_b}.expansion.expand_bn.running_var""")  )
          rename_keys.append(
              (F"""block{b}_dwconv/depthwise_kernel:0""", F"""encoder.blocks.{hf_b}.depthwise_conv.depthwise_conv.weight""")  )
          rename_keys.append((F"""block{b}_bn/gamma:0""", F"""encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.weight""")  )
          rename_keys.append((F"""block{b}_bn/beta:0""", F"""encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.bias""")  )
          rename_keys.append(
              (F"""block{b}_bn/moving_mean:0""", F"""encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.running_mean""")  )
          rename_keys.append(
              (F"""block{b}_bn/moving_variance:0""", F"""encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.running_var""")  )

          rename_keys.append((F"""block{b}_se_reduce/kernel:0""", F"""encoder.blocks.{hf_b}.squeeze_excite.reduce.weight""")  )
          rename_keys.append((F"""block{b}_se_reduce/bias:0""", F"""encoder.blocks.{hf_b}.squeeze_excite.reduce.bias""")  )
          rename_keys.append((F"""block{b}_se_expand/kernel:0""", F"""encoder.blocks.{hf_b}.squeeze_excite.expand.weight""")  )
          rename_keys.append((F"""block{b}_se_expand/bias:0""", F"""encoder.blocks.{hf_b}.squeeze_excite.expand.bias""")  )
          rename_keys.append(
              (F"""block{b}_project_conv/kernel:0""", F"""encoder.blocks.{hf_b}.projection.project_conv.weight""")  )
          rename_keys.append((F"""block{b}_project_bn/gamma:0""", F"""encoder.blocks.{hf_b}.projection.project_bn.weight""")  )
          rename_keys.append((F"""block{b}_project_bn/beta:0""", F"""encoder.blocks.{hf_b}.projection.project_bn.bias""")  )
          rename_keys.append(
              (F"""block{b}_project_bn/moving_mean:0""", F"""encoder.blocks.{hf_b}.projection.project_bn.running_mean""")  )
          rename_keys.append(
              (F"""block{b}_project_bn/moving_variance:0""", F"""encoder.blocks.{hf_b}.projection.project_bn.running_var""")  )

     a					:							int							= {}
     for item in rename_keys:
          if item[0] in original_param_names:
               a					:							Any							= 'vision_model.' + item[1]

    # BERT text encoder
     a					:							Any							= []
     a					:							Any							= 'tf_bert_model/bert'
     a					:							str							= 'text_model'
     for i in range(12  ):
          rename_keys.append(
              (
                  F"""{old}/encoder/layer_._{i}/attention/self/query/kernel:0""",
                  F"""{new}.encoder.layer.{i}.attention.self.query.weight""",
              )  )
          rename_keys.append(
              (
                  F"""{old}/encoder/layer_._{i}/attention/self/query/bias:0""",
                  F"""{new}.encoder.layer.{i}.attention.self.query.bias""",
              )  )
          rename_keys.append(
              (
                  F"""{old}/encoder/layer_._{i}/attention/self/key/kernel:0""",
                  F"""{new}.encoder.layer.{i}.attention.self.key.weight""",
              )  )
          rename_keys.append(
              (
                  F"""{old}/encoder/layer_._{i}/attention/self/key/bias:0""",
                  F"""{new}.encoder.layer.{i}.attention.self.key.bias""",
              )  )
          rename_keys.append(
              (
                  F"""{old}/encoder/layer_._{i}/attention/self/value/kernel:0""",
                  F"""{new}.encoder.layer.{i}.attention.self.value.weight""",
              )  )
          rename_keys.append(
              (
                  F"""{old}/encoder/layer_._{i}/attention/self/value/bias:0""",
                  F"""{new}.encoder.layer.{i}.attention.self.value.bias""",
              )  )
          rename_keys.append(
              (
                  F"""{old}/encoder/layer_._{i}/attention/output/dense/kernel:0""",
                  F"""{new}.encoder.layer.{i}.attention.output.dense.weight""",
              )  )
          rename_keys.append(
              (
                  F"""{old}/encoder/layer_._{i}/attention/output/dense/bias:0""",
                  F"""{new}.encoder.layer.{i}.attention.output.dense.bias""",
              )  )
          rename_keys.append(
              (
                  F"""{old}/encoder/layer_._{i}/attention/output/LayerNorm/gamma:0""",
                  F"""{new}.encoder.layer.{i}.attention.output.LayerNorm.weight""",
              )  )
          rename_keys.append(
              (
                  F"""{old}/encoder/layer_._{i}/attention/output/LayerNorm/beta:0""",
                  F"""{new}.encoder.layer.{i}.attention.output.LayerNorm.bias""",
              )  )
          rename_keys.append(
              (
                  F"""{old}/encoder/layer_._{i}/intermediate/dense/kernel:0""",
                  F"""{new}.encoder.layer.{i}.intermediate.dense.weight""",
              )  )
          rename_keys.append(
              (
                  F"""{old}/encoder/layer_._{i}/intermediate/dense/bias:0""",
                  F"""{new}.encoder.layer.{i}.intermediate.dense.bias""",
              )  )
          rename_keys.append(
              (F"""{old}/encoder/layer_._{i}/output/dense/kernel:0""", F"""{new}.encoder.layer.{i}.output.dense.weight""")  )
          rename_keys.append(
              (F"""{old}/encoder/layer_._{i}/output/dense/bias:0""", F"""{new}.encoder.layer.{i}.output.dense.bias""")  )
          rename_keys.append(
              (F"""{old}/encoder/layer_._{i}/output/LayerNorm/gamma:0""", F"""{new}.encoder.layer.{i}.output.LayerNorm.weight""")  )
          rename_keys.append(
              (F"""{old}/encoder/layer_._{i}/output/LayerNorm/beta:0""", F"""{new}.encoder.layer.{i}.output.LayerNorm.bias""")  )

     rename_keys.append((F"""{old}/embeddings/word_embeddings/weight:0""", F"""{new}.embeddings.word_embeddings.weight""")  )
     rename_keys.append(
         (F"""{old}/embeddings/position_embeddings/embeddings:0""", F"""{new}.embeddings.position_embeddings.weight""")  )
     rename_keys.append(
         (F"""{old}/embeddings/token_type_embeddings/embeddings:0""", F"""{new}.embeddings.token_type_embeddings.weight""")  )
     rename_keys.append((F"""{old}/embeddings/LayerNorm/gamma:0""", F"""{new}.embeddings.LayerNorm.weight""")  )
     rename_keys.append((F"""{old}/embeddings/LayerNorm/beta:0""", F"""{new}.embeddings.LayerNorm.bias""")  )

     rename_keys.append((F"""{old}/pooler/dense/kernel:0""", F"""{new}.pooler.dense.weight""")  )
     rename_keys.append((F"""{old}/pooler/dense/bias:0""", F"""{new}.pooler.dense.bias""")  )
     rename_keys.append(('dense/kernel:0', 'text_projection.weight')  )
     rename_keys.append(('dense/bias:0', 'text_projection.bias')  )
     rename_keys.append(('dense/bias:0', 'text_projection.bias')  )
     rename_keys.append(('temperature:0', 'temperature')  )

     for item in rename_keys:
          if item[0] in original_param_names:
               a					:							Any							= item[1]
     return key_mapping






def SCREAMING_SNAKE_CASE__  (				snake_case       :				Optional[int]				,	snake_case       :				Union[str, Any]				,	snake_case       :				Union[str, Any]  )   ->				Union[str, Any]:







     """simple docstring"""
     list(hf_params.keys()  )

     for key, value in tf_params.items():
          if key not in key_mapping:
               continue

          a					:							List[str]							= key_mapping[key]
          if "_conv" in key and "kernel" in key:
               a					:							List[str]							= torch.from_numpy(snake_case  ).permute(3				,	2				,	0				,	1  )
          elif "embeddings" in key:
               a					:							str							= torch.from_numpy(snake_case  )
          elif "depthwise_kernel" in key:
               a					:							int							= torch.from_numpy(snake_case  ).permute(2				,	3				,	0				,	1  )
          elif "kernel" in key:
               a					:							List[Any]							= torch.from_numpy(np.transpose(snake_case  )  )
          elif "temperature" in key:
               a					:							List[str]							= value
          elif "bn/gamma" or "bn/beta" in key:
               a					:							List[Any]							= torch.from_numpy(np.transpose(snake_case  )  ).squeeze()
          else:
               a					:							int							= torch.from_numpy(snake_case  )

          # Replace HF parameters with original TF model parameters
          hf_params[hf_key].copy_(snake_case  )






@torch.no_grad()
def SCREAMING_SNAKE_CASE__  (				snake_case       :				int				,	snake_case       :				Union[str, Any]				,	snake_case       :				str				,	snake_case       :				Any  )   ->				Any:







     """simple docstring"""
     a					:							int							= 64
     a					:							List[Any]							= Tokenizer(snake_case  )
     a					:							Tuple							= align.Align('efficientnet-b7'				,	'bert-base'				,	640				,	snake_case				,	tok.get_vocab_size()  )
     original_model.compile()
     original_model.load_weights(snake_case  )

     a					:							str							= original_model.trainable_variables
     a					:							Union[str, Any]							= original_model.non_trainable_variables
     a					:							List[Any]							= {param.name: param.numpy() for param in tf_params}
     for param in tf_non_train_params:
          a					:							Dict							= param.numpy()
     a					:							List[str]							= list(tf_params.keys()  )

     # Load HuggingFace model
     a					:							Dict							= get_align_config()
     a					:							List[str]							= AlignModel(snake_case  ).eval()
     a					:							Union[str, Any]							= hf_model.state_dict()

     # Create src-to-dst parameter name mapping dictionary
     print('Converting parameters...'  )
     a					:							List[Any]							= rename_keys(snake_case  )
     replace_params(snake_case				,	snake_case				,	snake_case  )

     # Initialize processor
     a					:							List[str]							= get_processor()
     a					:							Dict							= processor(
         images=prepare_img()				,	text='A picture of a cat'				,	padding='max_length'				,	max_length=64				,	return_tensors='pt'  )

     # HF model inference
     hf_model.eval()
     with torch.no_grad():
          a					:							Any							= hf_model(**snake_case  )

     a					:							List[str]							= outputs.image_embeds.detach().numpy()
     a					:							List[Any]							= outputs.text_embeds.detach().numpy()

     # Original model inference
     a					:							Union[str, Any]							= False
     a					:							List[str]							= EfficientNetImageProcessor(
         do_center_crop=snake_case				,	do_rescale=snake_case				,	do_normalize=snake_case				,	include_top=snake_case				,	resample=Image.BILINEAR				,	)
     a					:							Union[str, Any]							= tf_image_processor(images=prepare_img()				,	return_tensors='tf'				,	data_format='channels_last'  )['pixel_values']
     a					:							str							= tok(tf.constant(['A picture of a cat']  )  )

     a					:							Dict							= original_model.image_encoder(snake_case				,	training=snake_case  )
     a					:							str							= original_model.text_encoder(snake_case				,	training=snake_case  )

     a					:							Optional[int]							= tf.nn.la_normalize(snake_case				,	axis=-1  )
     a					:							Any							= tf.nn.la_normalize(snake_case				,	axis=-1  )

     # Check whether original and HF model outputs match  -> np.allclose
     if not np.allclose(snake_case				,	snake_case				,	atol=1E-3  ):
          raise ValueError('The predicted image features are not the same.'  )
     if not np.allclose(snake_case				,	snake_case				,	atol=1E-3  ):
          raise ValueError('The predicted text features are not the same.'  )
     print('Model outputs match!'  )

     if save_model:
          # Create folder to save model
          if not os.path.isdir(snake_case  ):
               os.mkdir(snake_case  )
          # Save converted model and image processor
          hf_model.save_pretrained(snake_case  )
          processor.save_pretrained(snake_case  )

     if push_to_hub:
          # Push model and image processor to hub
          print('Pushing converted ALIGN to the hub...'  )
          processor.push_to_hub('align-base'  )
          hf_model.push_to_hub('align-base'  )


if __name__ == "__main__":
      UpperCamelCase       :     List[Any]			=    argparse.ArgumentParser()
      # Required parameters
      parser.add_argument(
          """--checkpoint_path""",
          default="""./weights/model-weights""",
          type=str,
          help="""Path to the pretrained TF ALIGN checkpoint.""",
      )
      parser.add_argument(
          """--pytorch_dump_folder_path""",
          default="""hf_model""",
          type=str,
          help="""Path to the output PyTorch model directory.""",
      )
      parser.add_argument("""--save_model""", action="""store_true""", help="""Save model to local""")
      parser.add_argument("""--push_to_hub""", action="""store_true""", help="""Push model and image processor to the hub""")

      UpperCamelCase       :     Optional[Any]			=    parser.parse_args()
      convert_align_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.save_model, args.push_to_hub)


'''simple docstring'''





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   UpperCamelCase					(       a_       ):







    """simple docstring"""





    def __init__(					self     :						Dict							,							UpperCAmelCase_     :						List[str]							,							):


         """simple docstring"""







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





    def    SCREAMING_SNAKE_CASE_     (					self     :						int):


         """simple docstring"""







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

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

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

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

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

         a					:							Dict							= 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					:							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    SCREAMING_SNAKE_CASE_     (					self     :						Union[str, Any]							,							UpperCAmelCase_     :						Optional[Any]							,							UpperCAmelCase_     :						Optional[Any]							,							UpperCAmelCase_     :						Dict							,							UpperCAmelCase_     :						List[Any]							,							UpperCAmelCase_     :						str							,							*UpperCAmelCase_     :						List[str]):


         """simple docstring"""







         a					:							Union[str, Any]							= TFCTRLModel(config=UpperCAmelCase_)
         a					:							Dict							= {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids}
         a					:							Tuple							= model(UpperCAmelCase_)

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

         a					:							List[str]							= model(UpperCAmelCase_)

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





    def    SCREAMING_SNAKE_CASE_     (					self     :						List[str]							,							UpperCAmelCase_     :						Optional[Any]							,							UpperCAmelCase_     :						List[str]							,							UpperCAmelCase_     :						Dict							,							UpperCAmelCase_     :						Tuple							,							UpperCAmelCase_     :						Dict							,							*UpperCAmelCase_     :						str):


         """simple docstring"""







         a					:							Optional[int]							= TFCTRLLMHeadModel(config=UpperCAmelCase_)
         a					:							Tuple							= {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids}
         a					:							int							= model(UpperCAmelCase_)
         self.parent.assertEqual(result.logits.shape							,							(self.batch_size, self.seq_length, self.vocab_size))





    def    SCREAMING_SNAKE_CASE_     (					self     :						Tuple							,							UpperCAmelCase_     :						str							,							UpperCAmelCase_     :						Optional[Any]							,							UpperCAmelCase_     :						int							,							UpperCAmelCase_     :						Tuple							,							UpperCAmelCase_     :						Optional[Any]							,							*UpperCAmelCase_     :						List[str]):


         """simple docstring"""







         a					:							Tuple							= self.num_labels
         a					:							List[str]							= ids_tensor([self.batch_size]							,							self.type_sequence_label_size)
         a					:							int							= {
             'input_ids': input_ids,
             'token_type_ids': token_type_ids,
             'labels': sequence_labels,
         }
         a					:							str							= TFCTRLForSequenceClassification(UpperCAmelCase_)
         a					:							Union[str, Any]							= model(UpperCAmelCase_)
         self.parent.assertEqual(result.logits.shape							,							(self.batch_size, self.num_labels))







    def    SCREAMING_SNAKE_CASE_     (					self     :						int):


         """simple docstring"""







         a					:							Optional[int]							= self.prepare_config_and_inputs()

         (
             (
             a
         )							,			(
             a
         )							,			(
             a
         )							,			(
             a
         )							,			(
             a
         )							,			(
             a
         )							,			(
             a
         )							,			(
             a
         )							,			(
             a
         )							,			
         )					:							int							= config_and_inputs

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






@require_tf
class   UpperCamelCase					(       a_    ,     a_    ,     unittest.TestCase       ):







    """simple docstring"""





    A     :    str				=			(TFCTRLModel, TFCTRLLMHeadModel, TFCTRLForSequenceClassification) if is_tf_available() else ()
    A     :    Optional[int]				=			(TFCTRLLMHeadModel,) if is_tf_available() else ()
    A     :    str				=			(
        {
            "feature-extraction": TFCTRLModel,
            "text-classification": TFCTRLForSequenceClassification,
            "text-generation": TFCTRLLMHeadModel,
            "zero-shot": TFCTRLForSequenceClassification,
        }
        if is_tf_available()
        else {}
    )
    A     :    int				=			False
    A     :    Optional[Any]				=			False





    def    SCREAMING_SNAKE_CASE_     (					self     :						Union[str, Any]							,							UpperCAmelCase_     :						Dict							,							UpperCAmelCase_     :						Any							,							UpperCAmelCase_     :						Optional[Any]							,							UpperCAmelCase_     :						Tuple							,							UpperCAmelCase_     :						Optional[Any]):


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


         """simple docstring"""







         a					:							Any							= TFCTRLModelTester(self)
         a					:							Dict							= ConfigTester(self							,							config_class=UpperCAmelCase_							,							n_embd=3_7)





    def    SCREAMING_SNAKE_CASE_     (					self     :						List[Any]):


         """simple docstring"""







         self.config_tester.run_common_tests()





    def    SCREAMING_SNAKE_CASE_     (					self     :						str):


         """simple docstring"""







         a					:							Optional[Any]							= self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_ctrl_model(*UpperCAmelCase_)





    def    SCREAMING_SNAKE_CASE_     (					self     :						Dict):


         """simple docstring"""







         a					:							List[Any]							= self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_ctrl_lm_head(*UpperCAmelCase_)





    def    SCREAMING_SNAKE_CASE_     (					self     :						List[str]):


         """simple docstring"""







         a					:							str							= self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_ctrl_for_sequence_classification(*UpperCAmelCase_)





    def    SCREAMING_SNAKE_CASE_     (					self     :						Optional[Any]):


         """simple docstring"""







         a							,			a					:							Optional[Any]							= self.model_tester.prepare_config_and_inputs_for_common()
         a					:							int							= [TFCTRLLMHeadModel]
         a					:							int							= [TFCTRLForSequenceClassification]

         for model_class in self.all_model_classes:
              a					:							int							= model_class(UpperCAmelCase_)
              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					:							Optional[Any]							= model.get_output_embeddings()
                   assert isinstance(UpperCAmelCase_							,							tf.keras.layers.Layer)
                   a					:							int							= model.get_bias()
                   assert isinstance(UpperCAmelCase_							,							UpperCAmelCase_)
                   for k, v in name.items():
                        assert isinstance(UpperCAmelCase_							,							tf.Variable)
              elif model_class in list_other_models_with_output_ebd:
                   a					:							List[str]							= model.get_output_embeddings()
                   assert isinstance(UpperCAmelCase_							,							tf.keras.layers.Layer)
                   a					:							List[Any]							= model.get_bias()
                   assert name is None
              else:
                   a					:							List[str]							= model.get_output_embeddings()
                   assert x is None
                   a					:							Optional[Any]							= model.get_bias()
                   assert name is None







    @slow
    def    SCREAMING_SNAKE_CASE_     (					self     :						Dict):


         """simple docstring"""







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






@require_tf
class   UpperCamelCase					(       unittest.TestCase       ):







    """simple docstring"""





    @slow
    def    SCREAMING_SNAKE_CASE_     (					self     :						Tuple):


         """simple docstring"""







         a					:							List[Any]							= TFCTRLLMHeadModel.from_pretrained('ctrl')
         a					:							Union[str, Any]							= tf.convert_to_tensor([[1_1_8_5_9, 0, 1_6_1_1, 8]]							,							dtype=tf.intaa)  # Legal the president is
         a					:							List[Any]							= [
             1_1_8_5_9,
             0,
             1_6_1_1,
             8,
             5,
             1_5_0,
             2_6_4_4_9,
             2,
             1_9,
             3_4_8,
             4_6_9,
             3,
             2_5_9_5,
             4_8,
             2_0_7_4_0,
             2_4_6_5_3_3,
             2_4_6_5_3_3,
             1_9,
             3_0,
             5,
         ]  # Legal the president is a good guy and I don't want to lose my job. \n \n I have a

         a					:							List[str]							= model.generate(UpperCAmelCase_							,							do_sample=UpperCAmelCase_)
         self.assertListEqual(output_ids[0].numpy().tolist()							,							UpperCAmelCase_)

