






import json
import os
from typing import TYPE_CHECKING, List, Optional, Tuple

import regex as re

from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import logging


if TYPE_CHECKING:
   from transformers.pipelines.conversational import Conversation

A_	:	Any				=				logging.get_logger(__name__)

A_	:	Tuple				=				{'vocab_file': 'vocab.json', 'merges_file': 'merges.txt'}

A_	:	List[str]				=				{
    'vocab_file': {
        'microsoft/deberta-base': 'https://huggingface.co/microsoft/deberta-base/resolve/main/vocab.json',
        'microsoft/deberta-large': 'https://huggingface.co/microsoft/deberta-large/resolve/main/vocab.json',
        'microsoft/deberta-xlarge': 'https://huggingface.co/microsoft/deberta-xlarge/resolve/main/vocab.json',
        'microsoft/deberta-base-mnli': 'https://huggingface.co/microsoft/deberta-base-mnli/resolve/main/vocab.json',
        'microsoft/deberta-large-mnli': 'https://huggingface.co/microsoft/deberta-large-mnli/resolve/main/vocab.json',
        'microsoft/deberta-xlarge-mnli': (
            'https://huggingface.co/microsoft/deberta-xlarge-mnli/resolve/main/vocab.json'
        ),
    },
    'merges_file': {
        'microsoft/deberta-base': 'https://huggingface.co/microsoft/deberta-base/resolve/main/merges.txt',
        'microsoft/deberta-large': 'https://huggingface.co/microsoft/deberta-large/resolve/main/merges.txt',
        'microsoft/deberta-xlarge': 'https://huggingface.co/microsoft/deberta-xlarge/resolve/main/merges.txt',
        'microsoft/deberta-base-mnli': 'https://huggingface.co/microsoft/deberta-base-mnli/resolve/main/merges.txt',
        'microsoft/deberta-large-mnli': 'https://huggingface.co/microsoft/deberta-large-mnli/resolve/main/merges.txt',
        'microsoft/deberta-xlarge-mnli': (
            'https://huggingface.co/microsoft/deberta-xlarge-mnli/resolve/main/merges.txt'
        ),
    },
}

A_	:	Dict				=				{
    'microsoft/deberta-base': 512,
    'microsoft/deberta-large': 512,
    'microsoft/deberta-xlarge': 512,
    'microsoft/deberta-base-mnli': 512,
    'microsoft/deberta-large-mnli': 512,
    'microsoft/deberta-xlarge-mnli': 512,
}

A_	:	List[str]				=				{
    'microsoft/deberta-base': {'do_lower_case': False},
    'microsoft/deberta-large': {'do_lower_case': False},
}

def 						snake_case      () ->       Optional[int]:
  UpperCamelCase_:      Dict					   =       (
      list(range(ord('!'						)			,					ord('~'						) + 1						)						) + list(range(ord('¡'						)			,					ord('¬'						) + 1						)						) + list(range(ord('®'						)			,					ord('ÿ'						) + 1						)						)
  )
  UpperCamelCase_:      Any					   =       bs[:]
  UpperCamelCase_:      int					   =       0
  for b in range(2**8						):
    if b not in bs:
      bs.append(UpperCAmelCase__						)
      cs.append(2**8 + n						)
      n += 1
  UpperCamelCase_:      Any					   =       [chr(UpperCAmelCase__						) for n in cs]
  return dict(zip(UpperCAmelCase__			,					UpperCAmelCase__						)						)

def 						snake_case      (UpperCAmelCase__						) ->       Union[str, Any]:
  UpperCamelCase_:      List[Any]					   =       set()
  UpperCamelCase_:      Optional[Any]					   =       word[0]
  for char in word[1:]:
    pairs.add((prev_char, char)						)
    UpperCamelCase_:      Dict					   =       char
  return pairs




class        _lowerCAmelCase( UpperCAmelCase_      ):





       """simple docstring"""







       a       :	int								=VOCAB_FILES_NAMES
       a       :	Optional[Any]								=PRETRAINED_VOCAB_FILES_MAP
       a       :	Optional[int]								=PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
       a       :	Any								=['''input_ids''', '''attention_mask''', '''token_type_ids''']





       def __init__(      self						,    _lowerCamelCase						,    _lowerCamelCase						,    _lowerCamelCase="replace"						,    _lowerCamelCase="[CLS]"						,    _lowerCamelCase="[SEP]"						,    _lowerCamelCase="[SEP]"						,    _lowerCamelCase="[CLS]"						,    _lowerCamelCase="[UNK]"						,    _lowerCamelCase="[PAD]"						,    _lowerCamelCase="[MASK]"						,    _lowerCamelCase=False						,    _lowerCamelCase=False						,    **_lowerCamelCase						,    ):
         UpperCamelCase_:      Union[str, Any]					   =       AddedToken(_lowerCamelCase						,    lstrip=_lowerCamelCase						,    rstrip=_lowerCamelCase							) if isinstance(_lowerCamelCase						,    _lowerCamelCase							) else bos_token
         UpperCamelCase_:      str					   =       AddedToken(_lowerCamelCase						,    lstrip=_lowerCamelCase						,    rstrip=_lowerCamelCase							) if isinstance(_lowerCamelCase						,    _lowerCamelCase							) else eos_token
         UpperCamelCase_:      Union[str, Any]					   =       AddedToken(_lowerCamelCase						,    lstrip=_lowerCamelCase						,    rstrip=_lowerCamelCase							) if isinstance(_lowerCamelCase						,    _lowerCamelCase							) else sep_token
         UpperCamelCase_:      Dict					   =       AddedToken(_lowerCamelCase						,    lstrip=_lowerCamelCase						,    rstrip=_lowerCamelCase							) if isinstance(_lowerCamelCase						,    _lowerCamelCase							) else cls_token
         UpperCamelCase_:      Optional[int]					   =       AddedToken(_lowerCamelCase						,    lstrip=_lowerCamelCase						,    rstrip=_lowerCamelCase							) if isinstance(_lowerCamelCase						,    _lowerCamelCase							) else unk_token
         UpperCamelCase_:      Any					   =       AddedToken(_lowerCamelCase						,    lstrip=_lowerCamelCase						,    rstrip=_lowerCamelCase							) if isinstance(_lowerCamelCase						,    _lowerCamelCase							) else pad_token

         # Mask token behave like a normal word, i.e. include the space before it
         UpperCamelCase_:      Tuple					   =       AddedToken(_lowerCamelCase						,    lstrip=_lowerCamelCase						,    rstrip=_lowerCamelCase							) if isinstance(_lowerCamelCase						,    _lowerCamelCase							) else mask_token

         super().__init__(
             errors=_lowerCamelCase						,    bos_token=_lowerCamelCase						,    eos_token=_lowerCamelCase						,    unk_token=_lowerCamelCase						,    sep_token=_lowerCamelCase						,    cls_token=_lowerCamelCase						,    pad_token=_lowerCamelCase						,    mask_token=_lowerCamelCase						,    add_prefix_space=_lowerCamelCase						,    add_bos_token=_lowerCamelCase						,    **_lowerCamelCase						,    )
         UpperCamelCase_:      List[str]					   =       add_bos_token

         with open(_lowerCamelCase						,    encoding='utf-8'							) as vocab_handle:
           UpperCamelCase_:      List[str]					   =       json.load(_lowerCamelCase							)
         UpperCamelCase_:      List[Any]					   =       {v: k for k, v in self.encoder.items()}
         UpperCamelCase_:      int					   =       errors  # how to handle errors in decoding
         UpperCamelCase_:      str					   =       bytes_to_unicode()
         UpperCamelCase_:      Tuple					   =       {v: k for k, v in self.byte_encoder.items()}
         with open(_lowerCamelCase						,    encoding='utf-8'							) as merges_handle:
           UpperCamelCase_:      List[Any]					   =       merges_handle.read().split('\n'							)[1:-1]
         UpperCamelCase_:      int					   =       [tuple(merge.split()							) for merge in bpe_merges]
         UpperCamelCase_:      Optional[int]					   =       dict(zip(_lowerCamelCase						,    range(len(_lowerCamelCase							)							)							)							)
         UpperCamelCase_:      Tuple					   =       {}
         UpperCamelCase_:      str					   =       add_prefix_space

         # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
         UpperCamelCase_:      List[Any]					   =       re.compile(r'\'s|\'t|\'re|\'ve|\'m|\'ll|\'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+'							)





       @property
       # Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer.vocab_size
       def     _a					(      self							):
         return len(self.encoder							)





       def     _a					(      self							):
         return dict(self.encoder						,    **self.added_tokens_encoder							)





       def     _a					(      self						,    _lowerCamelCase							):
         if token in self.cache:
           return self.cache[token]
         UpperCamelCase_:      List[str]					   =       tuple(_lowerCamelCase							)
         UpperCamelCase_:      Dict					   =       get_pairs(_lowerCamelCase							)

         if not pairs:
           return token

         while True:
           UpperCamelCase_:      List[Any]					   =       min(_lowerCamelCase						,    key=lambda _lowerCamelCase							: self.bpe_ranks.get(_lowerCamelCase						,    float('inf'							)							)							)
           if bigram not in self.bpe_ranks:
             break
           UpperCamelCase_   ,UpperCamelCase_:      Optional[Any]					   =       bigram
           UpperCamelCase_:      List[str]					   =       []
           UpperCamelCase_:      int					   =       0
           while i < len(_lowerCamelCase							):
             try:
               UpperCamelCase_:      List[str]					   =       word.index(_lowerCamelCase						,    _lowerCamelCase							)
             except ValueError:
               new_word.extend(word[i:]							)
               break
             else:
               new_word.extend(word[i:j]							)
               UpperCamelCase_:      Tuple					   =       j

             if word[i] == first and i < len(_lowerCamelCase							) - 1 and word[i + 1] == second:
               new_word.append(first + second							)
               i += 2
             else:
               new_word.append(word[i]							)
               i += 1
           UpperCamelCase_:      Tuple					   =       tuple(_lowerCamelCase							)
           UpperCamelCase_:      int					   =       new_word
           if len(_lowerCamelCase							) == 1:
             break
           else:
             UpperCamelCase_:      str					   =       get_pairs(_lowerCamelCase							)
         UpperCamelCase_:      Optional[int]					   =       ' '.join(_lowerCamelCase							)
         UpperCamelCase_:      Optional[int]					   =       word
         return word





       def     _a					(      self						,    _lowerCamelCase						,    _lowerCamelCase = None							):
         if token_ids_a is None:
           return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
         UpperCamelCase_:      Union[str, Any]					   =       [self.cls_token_id]
         UpperCamelCase_:      int					   =       [self.sep_token_id]
         return cls + token_ids_a + sep + token_ids_a + sep





       def     _a					(      self						,    _lowerCamelCase						,    _lowerCamelCase = None						,    _lowerCamelCase = False							):
         if already_has_special_tokens:
           return super().get_special_tokens_mask(
               token_ids_a=_lowerCamelCase						,    token_ids_a=_lowerCamelCase						,    already_has_special_tokens=_lowerCamelCase							)

         if token_ids_a is None:
           return [1] + ([0] * len(_lowerCamelCase							)) + [1]
         return [1] + ([0] * len(_lowerCamelCase							)) + [1] + ([0] * len(_lowerCamelCase							)) + [1]





       def     _a					(      self						,    _lowerCamelCase						,    _lowerCamelCase = None							):
         UpperCamelCase_:      Dict					   =       [self.sep_token_id]
         UpperCamelCase_:      Tuple					   =       [self.cls_token_id]

         if token_ids_a is None:
           return len(cls + token_ids_a + sep							) * [0]
         return len(cls + token_ids_a + sep							) * [0] + len(token_ids_a + sep							) * [1]





       def     _a					(      self						,    _lowerCamelCase							):
         UpperCamelCase_:      List[str]					   =       []
         for token in re.findall(self.pat						,    _lowerCamelCase							):
           UpperCamelCase_:      List[str]					   =       ''.join(
               self.byte_encoder[b] for b in token.encode('utf-8'							)							)  # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
           bpe_tokens.extend(bpe_token for bpe_token in self.bpe(_lowerCamelCase							).split(' '							)							)
         return bpe_tokens





       def     _a					(      self						,    _lowerCamelCase							):
         return self.encoder.get(_lowerCamelCase						,    self.encoder.get(self.unk_token							)							)





       def     _a					(      self						,    _lowerCamelCase							):
         return self.decoder.get(_lowerCamelCase							)





       def     _a					(      self						,    _lowerCamelCase							):
         UpperCamelCase_:      List[Any]					   =       ''.join(_lowerCamelCase							)
         UpperCamelCase_:      Dict					   =       bytearray([self.byte_decoder[c] for c in text]							).decode('utf-8'						,    errors=self.errors							)
         return text





       def     _a					(      self						,    _lowerCamelCase						,    _lowerCamelCase = None							):
         if not os.path.isdir(_lowerCamelCase							):
           logger.error(f'''Vocabulary path ({save_directory}) should be a directory'''							)
           return
         UpperCamelCase_:      List[Any]					   =       os.path.join(
             _lowerCamelCase						,    (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']							)
         UpperCamelCase_:      Dict					   =       os.path.join(
             _lowerCamelCase						,    (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['merges_file']							)

         with open(_lowerCamelCase						,    'w'						,    encoding='utf-8'							) as f:
           f.write(json.dumps(self.encoder						,    indent=2						,    sort_keys=_lowerCamelCase						,    ensure_ascii=_lowerCamelCase							) + '\n'							)

         UpperCamelCase_:      Optional[int]					   =       0
         with open(_lowerCamelCase						,    'w'						,    encoding='utf-8'							) as writer:
           writer.write('#version: 0.2\n'							)
           for bpe_tokens, token_index in sorted(self.bpe_ranks.items()						,    key=lambda _lowerCamelCase							: kv[1]							):
             if index != token_index:
               logger.warning(
                   f'''Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.'''
                   ' Please check that the tokenizer is not corrupted!'							)
               UpperCamelCase_:      Union[str, Any]					   =       token_index
             writer.write(' '.join(_lowerCamelCase							) + '\n'							)
             index += 1

         return vocab_file, merge_file





       def     _a					(      self						,    _lowerCamelCase						,    _lowerCamelCase=False						,    **_lowerCamelCase							):
         UpperCamelCase_:      str					   =       kwargs.pop('add_prefix_space'						,    self.add_prefix_space							)
         if (is_split_into_words or add_prefix_space) and (len(_lowerCamelCase							) > 0 and not text[0].isspace()):
           UpperCamelCase_:      Optional[int]					   =       ' ' + text
         return (text, kwargs)





       def     _a					(      self						,    _lowerCamelCase							):
         UpperCamelCase_:      str					   =       []
         for is_user, text in conversation.iter_texts():
           input_ids.extend(self.encode(_lowerCamelCase						,    add_special_tokens=_lowerCamelCase							) + [self.eos_token_id]							)
         if len(_lowerCamelCase							) > self.model_max_length:
           UpperCamelCase_:      List[Any]					   =       input_ids[-self.model_max_length :]
         return input_ids







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							)