

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		:


					'''simple docstring'''






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






					def 						__A    (				self    ):
						A__							:					Optional[int]       =	ids_tensor([self.batch_size, self.seq_length]					, self.vocab_size    )

						A__							:					int       =	None
						if self.use_input_mask:
							A__							:					List[Any]       =	random_attention_mask([self.batch_size, self.seq_length]    )

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

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

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

						A__							:					Any       =	self.get_config()

						A__							:					Any       =	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    ):
						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 						__A    (				self					, A__					, A__					, A__					, A__					, A__					, *A__    ):
						A__							:					Optional[int]       =	CTRLModel(config=lowerCAmelCase_    )
						model.to(lowerCAmelCase_    )
						model.eval()

						model(lowerCAmelCase_					, token_type_ids=lowerCAmelCase_					, head_mask=lowerCAmelCase_    )
						model(lowerCAmelCase_					, token_type_ids=lowerCAmelCase_    )
						A__							:					Union[str, Any]       =	model(lowerCAmelCase_    )
						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 						__A    (				self					, A__					, A__					, A__					, A__					, A__					, *A__    ):
						A__							:					str       =	CTRLLMHeadModel(lowerCAmelCase_    )
						model.to(lowerCAmelCase_    )
						model.eval()

						A__							:					str       =	model(lowerCAmelCase_					, token_type_ids=lowerCAmelCase_					, labels=lowerCAmelCase_    )
						self.parent.assertEqual(result.loss.shape					, ()    )
						self.parent.assertEqual(result.logits.shape					, (self.batch_size, self.seq_length, self.vocab_size)    )






					def 						__A    (				self    ):
						A__							:					int       =	self.prepare_config_and_inputs()

						(
						    (
						    A__    
						)     ,     (
						    A__    
						)     ,     (
						    A__    
						)     ,     (
						    A__    
						)     ,     (
						    A__    
						)     ,     (
						    A__    
						)     ,     (
						    A__    
						)     ,     (
						    A__    
						)     ,     (
						    A__    
						)     ,         
						)							:					List[str]       =	config_and_inputs

						A__							:					Any       =	{"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """head_mask""": head_mask}

						return config, inputs_dict






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



@require_torch
class 					_a		(__UpperCAmelCase	,     __UpperCAmelCase	,     __UpperCAmelCase	,     unittest.TestCase       ):


					'''simple docstring'''






					UpperCAmelCase__:     Dict													= (CTRLModel, CTRLLMHeadModel, CTRLForSequenceClassification) if is_torch_available() else ()
					UpperCAmelCase__:     Optional[int]													= (CTRLLMHeadModel,) if is_torch_available() else ()
					UpperCAmelCase__:     Union[str, Any]													= (
					    {
					        '''feature-extraction''': CTRLModel,
					        '''text-classification''': CTRLForSequenceClassification,
					        '''text-generation''': CTRLLMHeadModel,
					        '''zero-shot''': CTRLForSequenceClassification,
					    }
					    if is_torch_available()
					    else {}
					)
					UpperCAmelCase__:     Tuple													= True
					UpperCAmelCase__:     Optional[int]													= False
					UpperCAmelCase__:     Optional[int]													= False






					def 						__A    (				self					, A__					, A__					, A__					, A__					, A__    ):







						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    ):
						A__							:					int       =	CTRLModelTester(self    )
						A__							:					Union[str, Any]       =	ConfigTester(self					, config_class=lowerCAmelCase_					, n_embd=37    )






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






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






					def 						__A    (				self    ):
						A__							:					Optional[Any]       =	self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_ctrl_model(*lowerCAmelCase_    )






					def 						__A    (				self    ):
						A__							:					Optional[int]       =	self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_lm_head_model(*lowerCAmelCase_    )






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






					@slow
					def 						__A    (				self    ):







						for model_name in CTRL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
							A__							:					Any       =	CTRLModel.from_pretrained(lowerCAmelCase_    )
							self.assertIsNotNone(lowerCAmelCase_    )






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



@require_torch
class 					_a		(unittest.TestCase       ):


					'''simple docstring'''






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






					@slow
					def 						__A    (				self    ):
						A__							:					str       =	CTRLLMHeadModel.from_pretrained("""ctrl"""    )
						model.to(lowerCAmelCase_    )
						A__							:					str       =	torch.tensor(
						    [[1_1859, 0, 1611, 8]]					, dtype=torch.long					, device=lowerCAmelCase_    )  # Legal the president is
						A__							:					int       =	[
						    1_1859,
						    0,
						    1611,
						    8,
						    5,
						    150,
						    2_6449,
						    2,
						    19,
						    348,
						    469,
						    3,
						    2595,
						    48,
						    2_0740,
						    24_6533,
						    24_6533,
						    19,
						    30,
						    5,
						]  # Legal the president is a good guy and I don't want to lose my job. \n \n I have a

						A__							:					Any       =	model.generate(lowerCAmelCase_					, do_sample=lowerCAmelCase_    )
						self.assertListEqual(output_ids[0].tolist()					, lowerCAmelCase_    )


class 					_a		:


					'''simple docstring'''






					def __init__(				self    ):
						A__							:					str       =	""""""
						A__							:					Any       =	""""""
						A__							:					List[Any]       =	[]






					def 						__A    (				self					, A__					, A__    ):
						if m == -1:
							return n + 1
						elif n == -1:
							return m + 1
						elif self.dp[m][n] > -1:
							return self.dp[m][n]
						else:
							if self.worda[m] == self.worda[n]:
								A__							:					Optional[Any]       =	self.__min_dist_top_down_dp(m - 1					, n - 1    )
							else:
								A__							:					Union[str, Any]       =	self.__min_dist_top_down_dp(A__					, n - 1    )
								A__							:					Union[str, Any]       =	self.__min_dist_top_down_dp(m - 1					, A__    )
								A__							:					Union[str, Any]       =	self.__min_dist_top_down_dp(m - 1					, n - 1    )
								A__							:					List[Any]       =	1 + min(A__					, A__					, A__    )

							return self.dp[m][n]






					def 						__A    (				self					, A__					, A__    ):
						A__							:					Tuple       =	worda
						A__							:					Dict       =	worda
						A__							:					Optional[Any]       =	[[-1 for _ in range(len(A__    )    )] for _ in range(len(A__    )    )]

						return self.__min_dist_top_down_dp(len(A__    ) - 1					, len(A__    ) - 1    )






					def 						__A    (				self					, A__					, A__    ):
						A__							:					Optional[Any]       =	worda
						A__							:					Dict       =	worda
						A__							:					Union[str, Any]       =	len(A__    )
						A__							:					List[str]       =	len(A__    )
						A__							:					int       =	[[0 for _ in range(n + 1    )] for _ in range(m + 1    )]

						for i in range(m + 1    ):
							for j in range(n + 1    ):
								if i == 0:  # first string is empty
									A__							:					Tuple       =	j
								elif j == 0:  # second string is empty
									A__							:					Dict       =	i
								elif worda[i - 1] == worda[j - 1]:  # last characters are equal
									A__							:					str       =	self.dp[i - 1][j - 1]
								else:
									A__							:					Union[str, Any]       =	self.dp[i][j - 1]
									A__							:					str       =	self.dp[i - 1][j]
									A__							:					Union[str, Any]       =	self.dp[i - 1][j - 1]
									A__							:					Tuple       =	1 + min(A__					, A__					, A__    )
						return self.dp[m][n]


if __name__ == "__main__":
	A_ :				Union[str, Any]						 =    EditDistance()

	print('****************** Testing Edit Distance DP Algorithm ******************')
	print()

	A_ :				int						 =    input('Enter the first string: ').strip()
	A_ :				List[str]						 =    input('Enter the second string: ').strip()

	print()
	print(f'''The minimum edit distance is: {solver.min_dist_top_down(Sa, Sa)}''')
	print(f'''The minimum edit distance is: {solver.min_dist_bottom_up(Sa, Sa)}''')
	print()
	print('*************** End of Testing Edit Distance DP Algorithm ***************')



