



import gc
import unittest

from transformers import CTRLConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
				import torch

				from transformers import (
				    CTRL_PRETRAINED_MODEL_ARCHIVE_LIST,
				    CTRLForSequenceClassification,
				    CTRLLMHeadModel,
				    CTRLModel,
				)
class 				__A					:





			def __init__(self							,    __magic_name__							,    __magic_name__=14							,    __magic_name__=7							,    __magic_name__=True							,    __magic_name__=True							,    __magic_name__=True							,    __magic_name__=True							,    __magic_name__=True							,    __magic_name__=99							,    __magic_name__=32							,    __magic_name__=5							,    __magic_name__=4							,    __magic_name__=37							,    __magic_name__="gelu"							,    __magic_name__=0.1							,    __magic_name__=0.1							,    __magic_name__=512							,    __magic_name__=16							,    __magic_name__=2							,    __magic_name__=0.02							,    __magic_name__=3							,    __magic_name__=4							,    __magic_name__=None							,    ):
						lowerCamelCase__ :      Union[str, Any]								=		parent
						lowerCamelCase__ :      Any								=		batch_size
						lowerCamelCase__ :      Optional[int]								=		seq_length
						lowerCamelCase__ :      Any								=		is_training
						lowerCamelCase__ :      Any								=		use_token_type_ids
						lowerCamelCase__ :      Optional[Any]								=		use_input_mask
						lowerCamelCase__ :      Tuple								=		use_labels
						lowerCamelCase__ :      Tuple								=		use_mc_token_ids
						lowerCamelCase__ :      str								=		vocab_size
						lowerCamelCase__ :      Optional[int]								=		hidden_size
						lowerCamelCase__ :      Any								=		num_hidden_layers
						lowerCamelCase__ :      Any								=		num_attention_heads
						lowerCamelCase__ :      Optional[Any]								=		intermediate_size
						lowerCamelCase__ :      List[str]								=		hidden_act
						lowerCamelCase__ :      Any								=		hidden_dropout_prob
						lowerCamelCase__ :      int								=		attention_probs_dropout_prob
						lowerCamelCase__ :      int								=		max_position_embeddings
						lowerCamelCase__ :      int								=		type_vocab_size
						lowerCamelCase__ :      Optional[int]								=		type_sequence_label_size
						lowerCamelCase__ :      Union[str, Any]								=		initializer_range
						lowerCamelCase__ :      List[Any]								=		num_labels
						lowerCamelCase__ :      Optional[Any]								=		num_choices
						lowerCamelCase__ :      Dict								=		scope
						lowerCamelCase__ :      Optional[int]								=		self.vocab_size - 1





			def        _snake_case    (self				):
						lowerCamelCase__ :      int								=		ids_tensor([self.batch_size, self.seq_length]							,    self.vocab_size				)

						lowerCamelCase__ :      Any								=		None
						if self.use_input_mask:
									lowerCamelCase__ :      Union[str, Any]								=		random_attention_mask([self.batch_size, self.seq_length]				)

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

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

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

						lowerCamelCase__ :      Tuple								=		self.get_config()

						lowerCamelCase__ :      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        _snake_case    (self				):
						return 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							,    )





			def        _snake_case    (self							,    __magic_name__							,    __magic_name__							,    __magic_name__							,    __magic_name__							,    __magic_name__							,    *__magic_name__				):
						lowerCamelCase__ :      str								=		CTRLModel(config=__magic_name__				)
						model.to(__magic_name__				)
						model.eval()

						model(__magic_name__							,    token_type_ids=__magic_name__							,    head_mask=__magic_name__				)
						model(__magic_name__							,    token_type_ids=__magic_name__				)
						lowerCamelCase__ :      Any								=		model(__magic_name__				)
						self.parent.assertEqual(result.last_hidden_state.shape							,    (self.batch_size, self.seq_length, self.hidden_size)				)
						self.parent.assertEqual(len(result.past_key_values				)							,    config.n_layer				)





			def        _snake_case    (self							,    __magic_name__							,    __magic_name__							,    __magic_name__							,    __magic_name__							,    __magic_name__							,    *__magic_name__				):
						lowerCamelCase__ :      Optional[Any]								=		CTRLLMHeadModel(__magic_name__				)
						model.to(__magic_name__				)
						model.eval()

						lowerCamelCase__ :      List[Any]								=		model(__magic_name__							,    token_type_ids=__magic_name__							,    labels=__magic_name__				)
						self.parent.assertEqual(result.loss.shape							,    ()				)
						self.parent.assertEqual(result.logits.shape							,    (self.batch_size, self.seq_length, self.vocab_size)				)





			def        _snake_case    (self				):
						lowerCamelCase__ :      Union[str, Any]								=		self.prepare_config_and_inputs()

						(
						    (
						    lowerCamelCase__
						)							,(
						    lowerCamelCase__
						)							,(
						    lowerCamelCase__
						)							,(
						    lowerCamelCase__
						)							,(
						    lowerCamelCase__
						)							,(
						    lowerCamelCase__
						)							,(
						    lowerCamelCase__
						)							,(
						    lowerCamelCase__
						)							,(
						    lowerCamelCase__
						)							,
						) :      List[Any]								=		config_and_inputs

						lowerCamelCase__ :      Tuple								=		{"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """head_mask""": head_mask}

						return config, inputs_dict





			def        _snake_case    (self							,    __magic_name__							,    __magic_name__							,    __magic_name__							,    __magic_name__							,    *__magic_name__				):
						lowerCamelCase__ :      Any								=		self.num_labels
						lowerCamelCase__ :      str								=		CTRLForSequenceClassification(__magic_name__				)
						model.to(__magic_name__				)
						model.eval()
						lowerCamelCase__ :      int								=		ids_tensor([self.batch_size]							,    self.type_sequence_label_size				)
						lowerCamelCase__ :      Optional[int]								=		model(__magic_name__							,    token_type_ids=__magic_name__							,    labels=__magic_name__				)
						self.parent.assertEqual(result.logits.shape							,    (self.batch_size, self.num_labels)				)







@require_torch
class 				__A					( A_					, A_					, A_					, unittest.TestCase      ):
			UpperCamelCase					:str     =			(CTRLModel, CTRLLMHeadModel, CTRLForSequenceClassification) if is_torch_available() else ()
			UpperCamelCase					:str     =			(CTRLLMHeadModel,) if is_torch_available() else ()
			UpperCamelCase					:Tuple     =			(
			    {
			        '''feature-extraction''': CTRLModel,
			        '''text-classification''': CTRLForSequenceClassification,
			        '''text-generation''': CTRLLMHeadModel,
			        '''zero-shot''': CTRLForSequenceClassification,
			    }
			    if is_torch_available()
			    else {}
			)
			UpperCamelCase					:List[str]     =			True
			UpperCamelCase					:Dict     =			False
			UpperCamelCase					:Optional[int]     =			False





			def        _snake_case    (self							,    __magic_name__							,    __magic_name__							,    __magic_name__							,    __magic_name__							,    __magic_name__				):
						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        _snake_case    (self				):
						lowerCamelCase__ :      Tuple								=		CTRLModelTester(self				)
						lowerCamelCase__ :      Union[str, Any]								=		ConfigTester(self							,    config_class=__magic_name__							,    n_embd=37				)





			def        _snake_case    (self				):
						super().tearDown()
						# clean-up as much as possible GPU memory occupied by PyTorch
						gc.collect()
						torch.cuda.empty_cache()





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





			def        _snake_case    (self				):
						lowerCamelCase__ :      Union[str, Any]								=		self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_ctrl_model(*__magic_name__				)





			def        _snake_case    (self				):
						lowerCamelCase__ :      Optional[Any]								=		self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_lm_head_model(*__magic_name__				)





			@unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests."""				)
			def        _snake_case    (self				):
						pass





			@slow
			def        _snake_case    (self				):
						for model_name in CTRL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
									lowerCamelCase__ :      List[str]								=		CTRLModel.from_pretrained(__magic_name__				)
									self.assertIsNotNone(__magic_name__				)





			@unittest.skip("""The model doesn't support left padding"""				)  # and it's not used enough to be worth fixing :)
			def        _snake_case    (self				):
						pass







@require_torch
class 				__A					( unittest.TestCase      ):





			def        _snake_case    (self				):
						super().tearDown()
						# clean-up as much as possible GPU memory occupied by PyTorch
						gc.collect()
						torch.cuda.empty_cache()





			@slow
			def        _snake_case    (self				):
						lowerCamelCase__ :      Dict								=		CTRLLMHeadModel.from_pretrained("""ctrl"""				)
						model.to(__magic_name__				)
						lowerCamelCase__ :      Optional[int]								=		torch.tensor(
						    [[11859, 0, 1611, 8]]							,    dtype=torch.long							,    device=__magic_name__				)  # Legal the president is
						lowerCamelCase__ :      Optional[Any]								=		[
						    11859,
						    0,
						    1611,
						    8,
						    5,
						    150,
						    26449,
						    2,
						    19,
						    348,
						    469,
						    3,
						    2595,
						    48,
						    20740,
						    246533,
						    246533,
						    19,
						    30,
						    5,
						]  # Legal the president is a good guy and I don't want to lose my job. \n \n I have a

						lowerCamelCase__ :      Union[str, Any]								=		model.generate(__magic_name__							,    do_sample=__magic_name__				)
						self.assertListEqual(output_ids[0].tolist()							,    __magic_name__				)








import itertools
import string
from collections.abc import Generator, Iterable






def      _A				(UpperCamelCase		:      Iterable[str]      ,			UpperCamelCase		:      int )  ->Generator[tuple[str, ...], None, None]:



			'''simple docstring'''







			lowerCamelCase__ :      Any								=		iter(UpperCamelCase )
			while True:
						lowerCamelCase__ :      Union[str, Any]								=		tuple(itertools.islice(UpperCamelCase      ,			UpperCamelCase ) )
						if not chunk:
									return
						yield chunk






def      _A				(UpperCamelCase		:      str )  ->str:



			'''simple docstring'''







			lowerCamelCase__ :      Tuple								=		"""""".join([c.upper() for c in dirty if c in string.ascii_letters] )
			lowerCamelCase__ :      Any								=		""""""

			if len(UpperCamelCase ) < 2:
						return dirty

			for i in range(len(UpperCamelCase ) - 1 ):
						clean += dirty[i]

						if dirty[i] == dirty[i + 1]:
									clean += "X"

			clean += dirty[-1]

			if len(UpperCamelCase ) & 1:
						clean += "X"

			return clean






def      _A				(UpperCamelCase		:      str )  ->list[str]:



			'''simple docstring'''







			lowerCamelCase__ :      Optional[Any]								=		"""ABCDEFGHIKLMNOPQRSTUVWXYZ"""
			# we're using a list instead of a '2d' array because it makes the math
			# for setting up the table and doing the actual encoding/decoding simpler
			lowerCamelCase__ :      List[Any]								=		[]

			# copy key chars into the table if they are in `alphabet` ignoring duplicates
			for char in key.upper():
						if char not in table and char in alphabet:
									table.append(UpperCamelCase )

    # fill the rest of the table in with the remaining alphabet chars
			for char in alphabet:
						if char not in table:
									table.append(UpperCamelCase )

			return table






def      _A				(UpperCamelCase		:      str      ,			UpperCamelCase		:      str )  ->str:



			'''simple docstring'''







			lowerCamelCase__ :      Tuple								=		generate_table(UpperCamelCase )
			lowerCamelCase__ :      int								=		prepare_input(UpperCamelCase )
			lowerCamelCase__ :      List[str]								=		""""""

			# https://en.wikipedia.org/wiki/Playfair_cipher#Description
			for chara, chara in chunker(UpperCamelCase      ,			2 ):
						lowerCamelCase__							,lowerCamelCase__ :      Optional[Any]								=		divmod(table.index(UpperCamelCase )      ,			5 )
						lowerCamelCase__							,lowerCamelCase__ :      Optional[Any]								=		divmod(table.index(UpperCamelCase )      ,			5 )

						if rowa == rowa:
									ciphertext += table[rowa * 5 + (cola + 1) % 5]
									ciphertext += table[rowa * 5 + (cola + 1) % 5]
						elif cola == cola:
									ciphertext += table[((rowa + 1) % 5) * 5 + cola]
									ciphertext += table[((rowa + 1) % 5) * 5 + cola]
						else:  # rectangle
									ciphertext += table[rowa * 5 + cola]
									ciphertext += table[rowa * 5 + cola]

			return ciphertext






def      _A				(UpperCamelCase		:      str      ,			UpperCamelCase		:      str )  ->str:



			'''simple docstring'''







			lowerCamelCase__ :      Any								=		generate_table(UpperCamelCase )
			lowerCamelCase__ :      Any								=		""""""

			# https://en.wikipedia.org/wiki/Playfair_cipher#Description
			for chara, chara in chunker(UpperCamelCase      ,			2 ):
						lowerCamelCase__							,lowerCamelCase__ :      int								=		divmod(table.index(UpperCamelCase )      ,			5 )
						lowerCamelCase__							,lowerCamelCase__ :      Any								=		divmod(table.index(UpperCamelCase )      ,			5 )

						if rowa == rowa:
									plaintext += table[rowa * 5 + (cola - 1) % 5]
									plaintext += table[rowa * 5 + (cola - 1) % 5]
						elif cola == cola:
									plaintext += table[((rowa - 1) % 5) * 5 + cola]
									plaintext += table[((rowa - 1) % 5) * 5 + cola]
						else:  # rectangle
									plaintext += table[rowa * 5 + cola]
									plaintext += table[rowa * 5 + cola]

			return plaintext



