





'''simple docstring'''


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    UpperCamelCase__	:







	def __init__(					self      : List[Any]			,			lowerCamelCase      : Dict			,			lowerCamelCase      : Tuple=1_4			,			lowerCamelCase      : str=7			,			lowerCamelCase      : Optional[int]=True			,			lowerCamelCase      : Tuple=True			,			lowerCamelCase      : List[str]=True			,			lowerCamelCase      : Optional[int]=True			,			lowerCamelCase      : Union[str, Any]=True			,			lowerCamelCase      : Optional[int]=9_9			,			lowerCamelCase      : Union[str, Any]=3_2			,			lowerCamelCase      : Optional[int]=5			,			lowerCamelCase      : Tuple=4			,			lowerCamelCase      : Union[str, Any]=3_7			,			lowerCamelCase      : Tuple="gelu"			,			lowerCamelCase      : Any=0.1			,			lowerCamelCase      : Dict=0.1			,			lowerCamelCase      : Optional[int]=5_1_2			,			lowerCamelCase      : Dict=1_6			,			lowerCamelCase      : str=2			,			lowerCamelCase      : Tuple=0.02			,			lowerCamelCase      : List[Any]=3			,			lowerCamelCase      : List[str]=4			,			lowerCamelCase      : int=None			,			):




				'''simple docstring'''
				a__	 =			parent
				a__	 =			batch_size
				a__	 =			seq_length
				a__	 =			is_training
				a__	 =			use_token_type_ids
				a__	 =			use_input_mask
				a__	 =			use_labels
				a__	 =			use_mc_token_ids
				a__	 =			vocab_size
				a__	 =			hidden_size
				a__	 =			num_hidden_layers
				a__	 =			num_attention_heads
				a__	 =			intermediate_size
				a__	 =			hidden_act
				a__	 =			hidden_dropout_prob
				a__	 =			attention_probs_dropout_prob
				a__	 =			max_position_embeddings
				a__	 =			type_vocab_size
				a__	 =			type_sequence_label_size
				a__	 =			initializer_range
				a__	 =			num_labels
				a__	 =			num_choices
				a__	 =			scope
				a__	 =			self.vocab_size - 1







	def     __a (					self      : List[Any]		):




				'''simple docstring'''
				a__	 =			ids_tensor([self.batch_size, self.seq_length]			,			self.vocab_size		)

				a__	 =			None
				if self.use_input_mask:
							a__	 =			random_attention_mask([self.batch_size, self.seq_length]		)

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

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

				a__	 =			None
				a__	 =			None
				a__	 =			None
				if self.use_labels:
							a__	 =			ids_tensor([self.batch_size]			,			self.type_sequence_label_size		)
							a__	 =			ids_tensor([self.batch_size, self.seq_length]			,			self.num_labels		)
							a__	 =			ids_tensor([self.batch_size]			,			self.num_choices		)

				a__	 =			self.get_config()

				a__	 =			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      : int		):




				'''simple docstring'''
				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      : int			,			lowerCamelCase      : Dict			,			lowerCamelCase      : Tuple			,			lowerCamelCase      : Optional[int]			,			lowerCamelCase      : Optional[int]			,			lowerCamelCase      : str			,			*lowerCamelCase      : List[str]		):




				'''simple docstring'''
				a__	 =			CTRLModel(config=lowerCamelCase__		)
				model.to(lowerCamelCase__		)
				model.eval()

				model(lowerCamelCase__			,			token_type_ids=lowerCamelCase__			,			head_mask=lowerCamelCase__		)
				model(lowerCamelCase__			,			token_type_ids=lowerCamelCase__		)
				a__	 =			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      : List[Any]			,			lowerCamelCase      : str			,			lowerCamelCase      : Optional[Any]			,			lowerCamelCase      : Tuple			,			lowerCamelCase      : Tuple			,			lowerCamelCase      : str			,			*lowerCamelCase      : Any		):




				'''simple docstring'''
				a__	 =			CTRLLMHeadModel(lowerCamelCase__		)
				model.to(lowerCamelCase__		)
				model.eval()

				a__	 =			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      : Union[str, Any]		):




				'''simple docstring'''
				a__	 =			self.prepare_config_and_inputs()

				(
				    a__						
				)	 =			config_and_inputs

				a__	 =			{"input_ids": input_ids, "token_type_ids": token_type_ids, "head_mask": head_mask}

				return config, inputs_dict







	def     __a (					self      : List[str]			,			lowerCamelCase      : int			,			lowerCamelCase      : int			,			lowerCamelCase      : List[str]			,			lowerCamelCase      : Optional[Any]			,			*lowerCamelCase      : Tuple		):




				'''simple docstring'''
				a__	 =			self.num_labels
				a__	 =			CTRLForSequenceClassification(lowerCamelCase__		)
				model.to(lowerCamelCase__		)
				model.eval()
				a__	 =			ids_tensor([self.batch_size]			,			self.type_sequence_label_size		)
				a__	 =			model(lowerCamelCase__			,			token_type_ids=lowerCamelCase__			,			labels=lowerCamelCase__		)
				self.parent.assertEqual(result.logits.shape			,			(self.batch_size, self.num_labels)		)






@require_torch
class    UpperCamelCase__	(		_a						,_a						,_a						,unittest.TestCase  ):
	lowerCAmelCase__       :      Optional[Any]										=    (CTRLModel, CTRLLMHeadModel, CTRLForSequenceClassification) if is_torch_available() else ()
	lowerCAmelCase__       :      Any										=    (CTRLLMHeadModel,) if is_torch_available() else ()
	lowerCAmelCase__       :      Any										=    (
	    {
	        "feature-extraction": CTRLModel,
	        "text-classification": CTRLForSequenceClassification,
	        "text-generation": CTRLLMHeadModel,
	        "zero-shot": CTRLForSequenceClassification,
	    }
	    if is_torch_available()
	    else {}
	)
	lowerCAmelCase__       :      Optional[int]										=    True
	lowerCAmelCase__       :      List[str]										=    False
	lowerCAmelCase__       :      List[str]										=    False







	def     __a (					self      : List[str]			,			lowerCamelCase      : Optional[Any]			,			lowerCamelCase      : Any			,			lowerCamelCase      : Optional[Any]			,			lowerCamelCase      : List[str]			,			lowerCamelCase      : 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     __a (					self      : Optional[Any]		):




				'''simple docstring'''
				a__	 =			CTRLModelTester(self		)
				a__	 =			ConfigTester(self			,			config_class=lowerCamelCase__			,			n_embd=3_7		)







	def     __a (					self      : Tuple		):




				'''simple docstring'''
				super().tearDown()
				# clean-up as much as possible GPU memory occupied by PyTorch
				gc.collect()
				torch.cuda.empty_cache()







	def     __a (					self      : Any		):




				'''simple docstring'''
				self.config_tester.run_common_tests()







	def     __a (					self      : List[str]		):




				'''simple docstring'''
				a__	 =			self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_ctrl_model(*lowerCamelCase__		)







	def     __a (					self      : Dict		):




				'''simple docstring'''
				a__	 =			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      : List[Any]		):




				'''simple docstring'''
				pass







	@slow
	def     __a (					self      : Tuple		):




				'''simple docstring'''
				for model_name in CTRL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
							a__	 =			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      : List[Any]		):




				'''simple docstring'''
				pass






@require_torch
class    UpperCamelCase__	(		unittest.TestCase  ):







	def     __a (					self      : Optional[Any]		):




				'''simple docstring'''
				super().tearDown()
				# clean-up as much as possible GPU memory occupied by PyTorch
				gc.collect()
				torch.cuda.empty_cache()







	@slow
	def     __a (					self      : Tuple		):




				'''simple docstring'''
				a__	 =			CTRLLMHeadModel.from_pretrained("ctrl"		)
				model.to(lowerCamelCase__		)
				a__	 =			torch.tensor(
				    [[1_1_8_5_9, 0, 1_6_1_1, 8]]			,			dtype=torch.long			,			device=lowerCamelCase__		)  # Legal the president is
				a__	 =			[
				    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__	 =			model.generate(lowerCamelCase__			,			do_sample=lowerCamelCase__		)
				self.assertListEqual(output_ids[0].tolist()			,			lowerCamelCase__		)






from __future__ import annotations

from typing import Any

class __UpperCamelCase     :






					'''simple docstring'''



					def __init__(				self				,      lowerCamelCase__						):
						UpperCAmelCase__:	Optional[int]									= num_of_nodes
						UpperCAmelCase__:	list[list[int]]									= []
						UpperCAmelCase__:	dict[int, int]									= {}





					def    _UpperCAmelCase    (				self				,      lowerCamelCase__				,      lowerCamelCase__				,      lowerCamelCase__						):
						self.m_edges.append([u_node, v_node, weight]						)





					def    _UpperCAmelCase    (				self				,      lowerCamelCase__						):

						if self.m_component[u_node] == u_node:
							return u_node
						return self.find_component(self.m_component[u_node]						)





					def    _UpperCAmelCase    (				self				,      lowerCamelCase__						):

						if self.m_component[u_node] != u_node:
							for k in self.m_component:
								UpperCAmelCase__:	Optional[Any]									= self.find_component(lowerCamelCase__						)





					def    _UpperCAmelCase    (				self				,      lowerCamelCase__				,      lowerCamelCase__				,      lowerCamelCase__						):

						if component_size[u_node] <= component_size[v_node]:
							UpperCAmelCase__:	Tuple									= v_node
							component_size[v_node] += component_size[u_node]
							self.set_component(lowerCamelCase__						)

						elif component_size[u_node] >= component_size[v_node]:
							UpperCAmelCase__:	Dict									= self.find_component(lowerCamelCase__						)
							component_size[u_node] += component_size[v_node]
							self.set_component(lowerCamelCase__						)





					def    _UpperCAmelCase    (				self						):
						UpperCAmelCase__:	Dict									= []
						UpperCAmelCase__:	int									= 0

						UpperCAmelCase__:	list[Any]									= [-1] * self.m_num_of_nodes

						# A list of components (initialized to all of the nodes)
						for node in range(self.m_num_of_nodes						):
							self.m_component.update({node: node}						)
							component_size.append(1						)

						UpperCAmelCase__:	Union[str, Any]									= self.m_num_of_nodes

						while num_of_components > 1:
							for edge in self.m_edges:
								UpperCAmelCase__							,						UpperCAmelCase__							,						UpperCAmelCase__:	str									= edge

								UpperCAmelCase__:	str									= self.m_component[u]
								UpperCAmelCase__:	Optional[Any]									= self.m_component[v]

								if u_component != v_component:

									for component in (u_component, v_component):
										if (
										    minimum_weight_edge[component] == -1
										    or minimum_weight_edge[component][2] > w
										):
											UpperCAmelCase__:	List[Any]									= [u, v, w]

							for edge in minimum_weight_edge:
								if isinstance(lowerCamelCase__				,      lowerCamelCase__						):
									UpperCAmelCase__							,						UpperCAmelCase__							,						UpperCAmelCase__:	str									= edge

									UpperCAmelCase__:	str									= self.m_component[u]
									UpperCAmelCase__:	int									= self.m_component[v]

									if u_component != v_component:
										mst_weight += w
										self.union(lowerCamelCase__				,      lowerCamelCase__				,      lowerCamelCase__						)
										print(F"Added edge [{u} - {v}]\nAdded weight: {w}\n"						)
										num_of_components -= 1

							UpperCAmelCase__:	Any									= [-1] * self.m_num_of_nodes
						print(F"The total weight of the minimal spanning tree is: {mst_weight}"						)



def 			_A	(      ):
	pass


if __name__ == "__main__":
					import doctest

					doctest.testmod()