






import argparse
import logging
import os
from pathlib import Path
from typing import Any, Dict

import pytorch_lightning as pl
from pytorch_lightning.utilities import rank_zero_info

from transformers import (
    AdamW,
    AutoConfig,
    AutoModel,
    AutoModelForPreTraining,
    AutoModelForQuestionAnswering,
    AutoModelForSeqaSeqLM,
    AutoModelForSequenceClassification,
    AutoModelForTokenClassification,
    AutoModelWithLMHead,
    AutoTokenizer,
    PretrainedConfig,
    PreTrainedTokenizer,
)
from transformers.optimization import (
    Adafactor,
    get_cosine_schedule_with_warmup,
    get_cosine_with_hard_restarts_schedule_with_warmup,
    get_linear_schedule_with_warmup,
    get_polynomial_decay_schedule_with_warmup,
)
from transformers.utils.versions import require_version


A_	:	Optional[Any]				=				logging.getLogger(__name__)

require_version('pytorch_lightning>=1.0.4')

A_	:	Tuple				=				{
    'base': AutoModel,
    'sequence-classification': AutoModelForSequenceClassification,
    'question-answering': AutoModelForQuestionAnswering,
    'pretraining': AutoModelForPreTraining,
    'token-classification': AutoModelForTokenClassification,
    'language-modeling': AutoModelWithLMHead,
    'summarization': AutoModelForSeqaSeqLM,
    'translation': AutoModelForSeqaSeqLM,
}


# update this and the import above to support new schedulers from transformers.optimization
A_	:	int				=				{
    'linear': get_linear_schedule_with_warmup,
    'cosine': get_cosine_schedule_with_warmup,
    'cosine_w_restarts': get_cosine_with_hard_restarts_schedule_with_warmup,
    'polynomial': get_polynomial_decay_schedule_with_warmup,
    # '': get_constant_schedule,             # not supported for now
    # '': get_constant_schedule_with_warmup, # not supported for now
}
A_	:	Any				=				sorted(arg_to_scheduler.keys())
A_	:	Tuple				=				'{' + ', '.join(arg_to_scheduler_choices) + '}'




class        _lowerCAmelCase( pl.LightningModule      ):





       """simple docstring"""







       def __init__(      self						,    _lowerCamelCase						,    _lowerCamelCase=None						,    _lowerCamelCase="base"						,    _lowerCamelCase=None						,    _lowerCamelCase=None						,    _lowerCamelCase=None						,    **_lowerCamelCase						,    ):
         super().__init__()
         # TODO: move to self.save_hyperparameters()
         # self.save_hyperparameters()
         # can also expand arguments into trainer signature for easier reading

         self.save_hyperparameters(lowerCamelCase__							)
         UpperCamelCase_:      Tuple					   =       0
         UpperCamelCase_:      int					   =       Path(self.hparams.output_dir							)
         UpperCamelCase_:      int					   =       self.hparams.cache_dir if self.hparams.cache_dir else None
         if config is None:
           UpperCamelCase_:      Optional[int]					   =       AutoConfig.from_pretrained(
               self.hparams.config_name if self.hparams.config_name else self.hparams.model_name_or_path						,    **({'num_labels': num_labels} if num_labels is not None else {})						,    cache_dir=lowerCamelCase__						,    **lowerCamelCase__						,    )
         else:
           UpperCamelCase_:      int					   =       config

         UpperCamelCase_:      Union[str, Any]					   =       ('encoder_layerdrop', 'decoder_layerdrop', 'dropout', 'attention_dropout')
         for p in extra_model_params:
           if getattr(self.hparams						,    lowerCamelCase__						,    lowerCamelCase__							):
             assert hasattr(self.config						,    lowerCamelCase__							), f'''model config doesn\'t have a `{p}` attribute'''
             setattr(self.config						,    lowerCamelCase__						,    getattr(self.hparams						,    lowerCamelCase__							)							)

         if tokenizer is None:
           UpperCamelCase_:      str					   =       AutoTokenizer.from_pretrained(
               self.hparams.tokenizer_name if self.hparams.tokenizer_name else self.hparams.model_name_or_path						,    cache_dir=lowerCamelCase__						,    )
         else:
           UpperCamelCase_:      List[str]					   =       tokenizer
         UpperCamelCase_:      Dict					   =       MODEL_MODES[mode]
         if model is None:
           UpperCamelCase_:      Union[str, Any]					   =       self.model_type.from_pretrained(
               self.hparams.model_name_or_path						,    from_tf=bool('.ckpt' in self.hparams.model_name_or_path							)						,    config=self.config						,    cache_dir=lowerCamelCase__						,    )
         else:
           UpperCamelCase_:      Dict					   =       model





       def     _a					(      self						,    *_lowerCamelCase						,    **_lowerCamelCase							):
         UpperCamelCase_:      Optional[int]					   =       self.model_type.from_pretrained(*lowerCamelCase__						,    **lowerCamelCase__							)





       def     _a					(      self							):
         UpperCamelCase_:      List[str]					   =       arg_to_scheduler[self.hparams.lr_scheduler]
         UpperCamelCase_:      str					   =       get_schedule_func(
             self.opt						,    num_warmup_steps=self.hparams.warmup_steps						,    num_training_steps=self.total_steps()							)
         UpperCamelCase_:      Optional[int]					   =       {'scheduler': scheduler, 'interval': 'step', 'frequency': 1}
         return scheduler





       def     _a					(      self							):
         UpperCamelCase_:      Tuple					   =       self.model
         UpperCamelCase_:      Dict					   =       ['bias', 'LayerNorm.weight']
         UpperCamelCase_:      List[str]					   =       [
             {
                 'params': [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay							)],
                 'weight_decay': self.hparams.weight_decay,
             },
             {
                 'params': [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay							)],
                 'weight_decay': 0.0,
             },
         ]
         if self.hparams.adafactor:
           UpperCamelCase_:      Optional[Any]					   =       Adafactor(
               lowerCamelCase__						,    lr=self.hparams.learning_rate						,    scale_parameter=lowerCamelCase__						,    relative_step=lowerCamelCase__							)

         else:
           UpperCamelCase_:      Optional[int]					   =       AdamW(
               lowerCamelCase__						,    lr=self.hparams.learning_rate						,    eps=self.hparams.adam_epsilon							)
         UpperCamelCase_:      List[Any]					   =       optimizer

         UpperCamelCase_:      List[Any]					   =       self.get_lr_scheduler()

         return [optimizer], [scheduler]





       def     _a					(      self						,    _lowerCamelCase						,    _lowerCamelCase							):
         return self.validation_step(lowerCamelCase__						,    lowerCamelCase__							)





       def     _a					(      self						,    _lowerCamelCase							):
         return self.validation_end(lowerCamelCase__							)





       def     _a					(      self							):
         UpperCamelCase_:      List[str]					   =       max(1						,    self.hparams.gpus							)  # TODO: consider num_tpu_cores
         UpperCamelCase_:      Optional[int]					   =       self.hparams.train_batch_size * self.hparams.accumulate_grad_batches * num_devices
         return (self.dataset_size / effective_batch_size) * self.hparams.max_epochs





       def     _a					(      self						,    _lowerCamelCase							):



         if stage == "test":
           UpperCamelCase_:      int					   =       len(self.test_dataloader().dataset							)
         else:
           UpperCamelCase_:      Any					   =       self.get_dataloader('train'						,    self.hparams.train_batch_size						,    shuffle=lowerCamelCase__							)
           UpperCamelCase_:      int					   =       len(self.train_dataloader().dataset							)





       def     _a					(      self						,    _lowerCamelCase						,    _lowerCamelCase						,    _lowerCamelCase = False							):
         raise NotImplementedError('You must implement this for your task'							)





       def     _a					(      self							):
         return self.train_loader





       def     _a					(      self							):
         return self.get_dataloader('dev'						,    self.hparams.eval_batch_size						,    shuffle=lowerCamelCase__							)





       def     _a					(      self							):
         return self.get_dataloader('test'						,    self.hparams.eval_batch_size						,    shuffle=lowerCamelCase__							)





       def     _a					(      self						,    _lowerCamelCase							):
         return os.path.join(
             self.hparams.data_dir						,    'cached_{}_{}_{}'.format(
                 lowerCamelCase__						,    list(filter(lowerCamelCase__						,    self.hparams.model_name_or_path.split('/'							)							)							).pop()						,    str(self.hparams.max_seq_length							)						,    )						,    )





       @pl.utilities.rank_zero_only
       def     _a					(      self						,    _lowerCamelCase							):
         UpperCamelCase_:      List[str]					   =       self.output_dir.joinpath('best_tfmr'							)
         UpperCamelCase_:      int					   =       self.step_count
         self.model.save_pretrained(lowerCamelCase__							)
         self.tokenizer.save_pretrained(lowerCamelCase__							)





       @staticmethod
       def     _a					(      _lowerCamelCase						,    _lowerCamelCase							):
         parser.add_argument(
             '--model_name_or_path'						,    default=lowerCamelCase__						,    type=lowerCamelCase__						,    required=lowerCamelCase__						,    help='Path to pretrained model or model identifier from huggingface.co/models'						,    )
         parser.add_argument(
             '--config_name'						,    default=''						,    type=lowerCamelCase__						,    help='Pretrained config name or path if not the same as model_name'							)
         parser.add_argument(
             '--tokenizer_name'						,    default=lowerCamelCase__						,    type=lowerCamelCase__						,    help='Pretrained tokenizer name or path if not the same as model_name'						,    )
         parser.add_argument(
             '--cache_dir'						,    default=''						,    type=lowerCamelCase__						,    help='Where do you want to store the pre-trained models downloaded from huggingface.co'						,    )
         parser.add_argument(
             '--encoder_layerdrop'						,    type=lowerCamelCase__						,    help='Encoder layer dropout probability (Optional). Goes into model.config'						,    )
         parser.add_argument(
             '--decoder_layerdrop'						,    type=lowerCamelCase__						,    help='Decoder layer dropout probability (Optional). Goes into model.config'						,    )
         parser.add_argument(
             '--dropout'						,    type=lowerCamelCase__						,    help='Dropout probability (Optional). Goes into model.config'						,    )
         parser.add_argument(
             '--attention_dropout'						,    type=lowerCamelCase__						,    help='Attention dropout probability (Optional). Goes into model.config'						,    )
         parser.add_argument('--learning_rate'						,    default=5e-5						,    type=lowerCamelCase__						,    help='The initial learning rate for Adam.'							)
         parser.add_argument(
             '--lr_scheduler'						,    default='linear'						,    choices=lowerCamelCase__						,    metavar=lowerCamelCase__						,    type=lowerCamelCase__						,    help='Learning rate scheduler'						,    )
         parser.add_argument('--weight_decay'						,    default=0.0						,    type=lowerCamelCase__						,    help='Weight decay if we apply some.'							)
         parser.add_argument('--adam_epsilon'						,    default=1e-8						,    type=lowerCamelCase__						,    help='Epsilon for Adam optimizer.'							)
         parser.add_argument('--warmup_steps'						,    default=0						,    type=lowerCamelCase__						,    help='Linear warmup over warmup_steps.'							)
         parser.add_argument('--num_workers'						,    default=4						,    type=lowerCamelCase__						,    help='kwarg passed to DataLoader'							)
         parser.add_argument('--num_train_epochs'						,    dest='max_epochs'						,    default=3						,    type=lowerCamelCase__							)
         parser.add_argument('--train_batch_size'						,    default=3_2						,    type=lowerCamelCase__							)
         parser.add_argument('--eval_batch_size'						,    default=3_2						,    type=lowerCamelCase__							)
         parser.add_argument('--adafactor'						,    action='store_true'							)







class        _lowerCAmelCase( pl.Callback      ):





       """simple docstring"""







       def     _a					(      self						,    _lowerCamelCase						,    _lowerCamelCase							):



         if (
             trainer.is_global_zero and trainer.global_rank == 0
         ):  # we initialize the retriever only on master worker with RAY. In new pytorch-lightning accelorators are removed.
           pl_module.model.rag.retriever.init_retrieval()  # better to use hook functions.







class        _lowerCAmelCase( pl.Callback      ):





       """simple docstring"""







       def     _a					(      self						,    _lowerCamelCase						,    _lowerCamelCase							):
         UpperCamelCase_:      int					   =       trainer.lr_schedulers[0]['scheduler']
         UpperCamelCase_:      Dict					   =       {f'''lr_group_{i}''': lr for i, lr in enumerate(lr_scheduler.get_lr()							)}
         pl_module.logger.log_metrics(lowerCamelCase__							)





       def     _a					(      self						,    _lowerCamelCase						,    _lowerCamelCase							):
         rank_zero_info('***** Validation results *****'							)
         UpperCamelCase_:      Optional[Any]					   =       trainer.callback_metrics
         # Log results
         for key in sorted(lowerCamelCase__							):
           if key not in ["log", "progress_bar"]:
             rank_zero_info('{} = {}\n'.format(lowerCamelCase__						,    str(metrics[key]							)							)							)





       def     _a					(      self						,    _lowerCamelCase						,    _lowerCamelCase							):
         rank_zero_info('***** Test results *****'							)
         UpperCamelCase_:      Dict					   =       trainer.callback_metrics
         # Log and save results to file
         UpperCamelCase_:      Optional[int]					   =       os.path.join(pl_module.hparams.output_dir						,    'test_results.txt'							)
         with open(lowerCamelCase__						,    'w'							) as writer:
           for key in sorted(lowerCamelCase__							):
             if key not in ["log", "progress_bar"]:
               rank_zero_info('{} = {}\n'.format(lowerCamelCase__						,    str(metrics[key]							)							)							)
               writer.write('{} = {}\n'.format(lowerCamelCase__						,    str(metrics[key]							)							)							)







def 						snake_case      (UpperCAmelCase__			,					UpperCAmelCase__						) ->       Union[str, Any]:
  #  To allow all pl args uncomment the following line
  #  parser = pl.Trainer.add_argparse_args(parser)
  parser.add_argument(
      '--output_dir'			,					default=lowercase__			,					type=lowercase__			,					required=lowercase__			,					help='The output directory where the model predictions and checkpoints will be written.'			,					)
  parser.add_argument(
      '--fp16'			,					action='store_true'			,					help='Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit'			,					)

  parser.add_argument(
      '--fp16_opt_level'			,					type=lowercase__			,					default='O2'			,					help=(
          'For fp16: Apex AMP optimization level selected in [\'O0\', \'O1\', \'O2\', and \'O3\'].'
          'See details at https://nvidia.github.io/apex/amp.html'
      )			,					)
  parser.add_argument('--n_tpu_cores'			,					dest='tpu_cores'			,					type=lowercase__						)
  parser.add_argument('--max_grad_norm'			,					dest='gradient_clip_val'			,					default=1.0			,					type=lowercase__			,					help='Max gradient norm'						)
  parser.add_argument('--do_train'			,					action='store_true'			,					help='Whether to run training.'						)
  parser.add_argument('--do_predict'			,					action='store_true'			,					help='Whether to run predictions on the test set.'						)
  parser.add_argument(
      '--gradient_accumulation_steps'			,					dest='accumulate_grad_batches'			,					type=lowercase__			,					default=1			,					help='Number of updates steps to accumulate before performing a backward/update pass.'			,					)
  parser.add_argument('--seed'			,					type=lowercase__			,					default=4_2			,					help='random seed for initialization'						)
  parser.add_argument(
      '--data_dir'			,					default=lowercase__			,					type=lowercase__			,					required=lowercase__			,					help='The input data dir. Should contain the training files for the CoNLL-2003 NER task.'			,					)

def 						snake_case      (UpperCAmelCase__			,					UpperCAmelCase__			,					UpperCAmelCase__=None			,					UpperCAmelCase__=True			,					UpperCAmelCase__=None			,					UpperCAmelCase__=[]			,					UpperCAmelCase__=None			,					UpperCAmelCase__=None			,					**UpperCAmelCase__			,					) ->       int:
  pl.seed_everything(args.seed						)

  # init model
  UpperCamelCase_:      str					   =       Path(model.hparams.output_dir						)
  odir.mkdir(exist_ok=lowercase__						)

  # add custom checkpoints
  if checkpoint_callback is None:
    UpperCamelCase_:      str					   =       pl.callbacks.ModelCheckpoint(
        filepath=args.output_dir			,					prefix='checkpoint'			,					monitor='val_loss'			,					mode='min'			,					save_top_k=1						)
  if early_stopping_callback:
    extra_callbacks.append(lowercase__						)
  if logging_callback is None:
    UpperCamelCase_:      int					   =       LoggingCallback()

  UpperCamelCase_:      Dict					   =       {}

  # TODO: remove with PyTorch 1.6 since pl uses native amp
  if args.fpaa:
    UpperCamelCase_:      Optional[Any]					   =       1_6
    # train_params["amp_level"] = args.fp16_opt_level

  if args.gpus > 1:
    UpperCamelCase_:      Optional[int]					   =       'auto'  # "ddp"
    UpperCamelCase_:      List[str]					   =       'ddp'

  UpperCamelCase_:      Optional[int]					   =       args.accumulate_grad_batches
  UpperCamelCase_:      Union[str, Any]					   =       None  # extra_train_kwargs.get("profiler", None) #get unwanted logs
  UpperCamelCase_:      Union[str, Any]					   =       'auto'

  UpperCamelCase_:      Union[str, Any]					   =       pl.Trainer.from_argparse_args(
      lowercase__			,					weights_summary=lowercase__			,					callbacks=[logging_callback] + extra_callbacks + [checkpoint_callback] + [InitCallback()]			,					logger=lowercase__			,					**lowercase__			,					)

  if args.do_train:
    trainer.fit(lowercase__						)

  return trainer







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        _lowerCAmelCase( UpperCAmelCase_      ):





       """simple docstring"""







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





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

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

         UpperCamelCase_:      Optional[Any]					   =       None
         if self.use_token_type_ids:
           UpperCamelCase_:      str					   =       ids_tensor([self.batch_size, self.seq_length]						,    self.type_vocab_size							)

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

         UpperCamelCase_:      Any					   =       None
         UpperCamelCase_:      Any					   =       None
         UpperCamelCase_:      Dict					   =       None
         if self.use_labels:
           UpperCamelCase_:      str					   =       ids_tensor([self.batch_size]						,    self.type_sequence_label_size							)
           UpperCamelCase_:      Dict					   =       ids_tensor([self.batch_size, self.seq_length]						,    self.num_labels							)
           UpperCamelCase_:      Union[str, Any]					   =       ids_tensor([self.batch_size]						,    self.num_choices							)

         UpperCamelCase_:      List[str]					   =       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						,    )

         UpperCamelCase_:      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     _a					(      self						,    _lowerCamelCase						,    _lowerCamelCase						,    _lowerCamelCase						,    _lowerCamelCase						,    _lowerCamelCase						,    *_lowerCamelCase							):
         UpperCamelCase_:      Dict					   =       TFCTRLModel(config=_lowerCamelCase							)
         UpperCamelCase_:      int					   =       {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids}
         UpperCamelCase_:      Optional[int]					   =       model(_lowerCamelCase							)

         UpperCamelCase_:      Optional[int]					   =       [input_ids, None, input_mask]  # None is the input for 'past'
         UpperCamelCase_:      Dict					   =       model(_lowerCamelCase							)

         UpperCamelCase_:      List[str]					   =       model(_lowerCamelCase							)

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





       def     _a					(      self						,    _lowerCamelCase						,    _lowerCamelCase						,    _lowerCamelCase						,    _lowerCamelCase						,    _lowerCamelCase						,    *_lowerCamelCase							):
         UpperCamelCase_:      int					   =       TFCTRLLMHeadModel(config=_lowerCamelCase							)
         UpperCamelCase_:      Optional[int]					   =       {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids}
         UpperCamelCase_:      List[Any]					   =       model(_lowerCamelCase							)
         self.parent.assertEqual(result.logits.shape						,    (self.batch_size, self.seq_length, self.vocab_size)							)





       def     _a					(      self						,    _lowerCamelCase						,    _lowerCamelCase						,    _lowerCamelCase						,    _lowerCamelCase						,    _lowerCamelCase						,    *_lowerCamelCase							):
         UpperCamelCase_:      List[str]					   =       self.num_labels
         UpperCamelCase_:      Dict					   =       ids_tensor([self.batch_size]						,    self.type_sequence_label_size							)
         UpperCamelCase_:      List[Any]					   =       {
             'input_ids': input_ids,
             'token_type_ids': token_type_ids,
             'labels': sequence_labels,
         }
         UpperCamelCase_:      List[str]					   =       TFCTRLForSequenceClassification(_lowerCamelCase							)
         UpperCamelCase_:      Tuple					   =       model(_lowerCamelCase							)
         self.parent.assertEqual(result.logits.shape						,    (self.batch_size, self.num_labels)							)





       def     _a					(      self							):
         UpperCamelCase_:      int					   =       self.prepare_config_and_inputs()

         (
             (
             UpperCamelCase_
         )   ,(
             UpperCamelCase_
         )   ,(
             UpperCamelCase_
         )   ,(
             UpperCamelCase_
         )   ,(
             UpperCamelCase_
         )   ,(
             UpperCamelCase_
         )   ,(
             UpperCamelCase_
         )   ,(
             UpperCamelCase_
         )   ,(
             UpperCamelCase_
         )   ,
         ):      str					   =       config_and_inputs

         UpperCamelCase_:      List[str]					   =       {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask}
         return config, inputs_dict







@require_tf
class        _lowerCAmelCase( UpperCAmelCase_							,			UpperCAmelCase_							,			unittest.TestCase      ):





       """simple docstring"""







       a       :	Tuple								=(TFCTRLModel, TFCTRLLMHeadModel, TFCTRLForSequenceClassification) if is_tf_available() else ()
       a       :	str								=(TFCTRLLMHeadModel,) if is_tf_available() else ()
       a       :	int								=(
           {
               '''feature-extraction''': TFCTRLModel,
               '''text-classification''': TFCTRLForSequenceClassification,
               '''text-generation''': TFCTRLLMHeadModel,
               '''zero-shot''': TFCTRLForSequenceClassification,
           }
           if is_tf_available()
           else {}
       )
       a       :	Tuple								=False
       a       :	str								=False





       def     _a					(      self						,    _lowerCamelCase						,    _lowerCamelCase						,    _lowerCamelCase						,    _lowerCamelCase						,    _lowerCamelCase							):
         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     _a					(      self							):
         UpperCamelCase_:      List[str]					   =       TFCTRLModelTester(self							)
         UpperCamelCase_:      List[Any]					   =       ConfigTester(self						,    config_class=_lowerCamelCase						,    n_embd=3_7							)





       def     _a					(      self							):
         self.config_tester.run_common_tests()





       def     _a					(      self							):
         UpperCamelCase_:      Dict					   =       self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_ctrl_model(*_lowerCamelCase							)





       def     _a					(      self							):
         UpperCamelCase_:      Optional[int]					   =       self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_ctrl_lm_head(*_lowerCamelCase							)





       def     _a					(      self							):
         UpperCamelCase_:      Union[str, Any]					   =       self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_ctrl_for_sequence_classification(*_lowerCamelCase							)





       def     _a					(      self							):
         UpperCamelCase_   ,UpperCamelCase_:      Union[str, Any]					   =       self.model_tester.prepare_config_and_inputs_for_common()
         UpperCamelCase_:      Optional[Any]					   =       [TFCTRLLMHeadModel]
         UpperCamelCase_:      Optional[Any]					   =       [TFCTRLForSequenceClassification]

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





       @slow
       def     _a					(      self							):
         for model_name in TF_CTRL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           UpperCamelCase_:      Optional[Any]					   =       TFCTRLModel.from_pretrained(_lowerCamelCase							)
           self.assertIsNotNone(_lowerCamelCase							)







@require_tf
class        _lowerCAmelCase( unittest.TestCase      ):





       """simple docstring"""







       @slow
       def     _a					(      self							):
         UpperCamelCase_:      Optional[int]					   =       TFCTRLLMHeadModel.from_pretrained('ctrl'							)
         UpperCamelCase_:      Any					   =       tf.convert_to_tensor([[1_1_8_5_9, 0, 1_6_1_1, 8]]						,    dtype=tf.intaa							)  # Legal the president is
         UpperCamelCase_:      Dict					   =       [
             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

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