
'''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_					:






						'''simple docstring'''






						def __init__( self   ,       _lowercase   ,       _lowercase=14   ,       _lowercase=7   ,       _lowercase=True   ,       _lowercase=True   ,       _lowercase=True   ,       _lowercase=True   ,       _lowercase=True   ,       _lowercase=99   ,       _lowercase=32   ,       _lowercase=5   ,       _lowercase=4   ,       _lowercase=37   ,       _lowercase="gelu"   ,       _lowercase=0.1   ,       _lowercase=0.1   ,       _lowercase=512   ,       _lowercase=16   ,       _lowercase=2   ,       _lowercase=0.02   ,       _lowercase=3   ,       _lowercase=4   ,       _lowercase=None   ,       ):

												"""simple docstring"""



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




						def  _lowercase     ( self				):

												"""simple docstring"""



												_lowerCAmelCase  						=			ids_tensor([self.batch_size, self.seq_length]   ,       self.vocab_size				)

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

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

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

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

												_lowerCAmelCase  						=			self.get_config()

												_lowerCAmelCase  						=			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  _lowercase     ( self				):

												"""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  _lowercase     ( self   ,       _lowercase   ,       _lowercase   ,       _lowercase   ,       _lowercase   ,       _lowercase   ,       *_lowercase				):

												"""simple docstring"""



												_lowerCAmelCase  						=			CTRLModel(config=_lowercase				)
												model.to(_lowercase				)
												model.eval()

												model(_lowercase   ,       token_type_ids=_lowercase   ,       head_mask=_lowercase				)
												model(_lowercase   ,       token_type_ids=_lowercase				)
												_lowerCAmelCase  						=			model(_lowercase				)
												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  _lowercase     ( self   ,       _lowercase   ,       _lowercase   ,       _lowercase   ,       _lowercase   ,       _lowercase   ,       *_lowercase				):

												"""simple docstring"""



												_lowerCAmelCase  						=			CTRLLMHeadModel(_lowercase				)
												model.to(_lowercase				)
												model.eval()

												_lowerCAmelCase  						=			model(_lowercase   ,       token_type_ids=_lowercase   ,       labels=_lowercase				)
												self.parent.assertEqual(result.loss.shape   ,       ()				)
												self.parent.assertEqual(result.logits.shape   ,       (self.batch_size, self.seq_length, self.vocab_size)				)




						def  _lowercase     ( self				):

												"""simple docstring"""



												_lowerCAmelCase  						=			self.prepare_config_and_inputs()

												(
												    (
												    _lowerCAmelCase   
												)						,   (
												    _lowerCAmelCase   
												)						,   (
												    _lowerCAmelCase   
												)						,   (
												    _lowerCAmelCase   
												)						,   (
												    _lowerCAmelCase   
												)						,   (
												    _lowerCAmelCase   
												)						,   (
												    _lowerCAmelCase   
												)						,   (
												    _lowerCAmelCase   
												)						,   (
												    _lowerCAmelCase   
												)						,      
												)  						=			config_and_inputs

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

												return config, inputs_dict




						def  _lowercase     ( self   ,       _lowercase   ,       _lowercase   ,       _lowercase   ,       _lowercase   ,       *_lowercase				):

												"""simple docstring"""



												_lowerCAmelCase  						=			self.num_labels
												_lowerCAmelCase  						=			CTRLForSequenceClassification(_lowercase				)
												model.to(_lowercase				)
												model.eval()
												_lowerCAmelCase  						=			ids_tensor([self.batch_size]   ,       self.type_sequence_label_size				)
												_lowerCAmelCase  						=			model(_lowercase   ,       token_type_ids=_lowercase   ,       labels=_lowercase				)
												self.parent.assertEqual(result.logits.shape   ,       (self.batch_size, self.num_labels)				)






@require_torch
class   UpperCAmelCase_					(		_SCREAMING_SNAKE_CASE	,							_SCREAMING_SNAKE_CASE	,							_SCREAMING_SNAKE_CASE	,							unittest.TestCase			):






						'''simple docstring'''






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




						def  _lowercase     ( self   ,       _lowercase   ,       _lowercase   ,       _lowercase   ,       _lowercase   ,       _lowercase				):

												"""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  _lowercase     ( self				):

												"""simple docstring"""



												_lowerCAmelCase  						=			CTRLModelTester(self				)
												_lowerCAmelCase  						=			ConfigTester(self   ,       config_class=_lowercase   ,       n_embd=37				)




						def  _lowercase     ( self				):

												"""simple docstring"""



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




						def  _lowercase     ( self				):

												"""simple docstring"""



												self.config_tester.run_common_tests()




						def  _lowercase     ( self				):

												"""simple docstring"""



												_lowerCAmelCase  						=			self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_ctrl_model(*_lowercase				)




						def  _lowercase     ( self				):

												"""simple docstring"""



												_lowerCAmelCase  						=			self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_lm_head_model(*_lowercase				)




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

												"""simple docstring"""



												pass




						@slow
						def  _lowercase     ( self				):

												"""simple docstring"""



												for model_name in CTRL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																		_lowerCAmelCase  						=			CTRLModel.from_pretrained(_lowercase				)
																		self.assertIsNotNone(_lowercase				)




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

												"""simple docstring"""



												pass






@require_torch
class   UpperCAmelCase_					(		unittest.TestCase			):






						'''simple docstring'''






						def  _lowercase     ( self				):

												"""simple docstring"""



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




						@slow
						def  _lowercase     ( self				):

												"""simple docstring"""



												_lowerCAmelCase  						=			CTRLLMHeadModel.from_pretrained("""ctrl"""				)
												model.to(_lowercase				)
												_lowerCAmelCase  						=			torch.tensor(
												    [[11_859, 0, 1_611, 8]]   ,       dtype=torch.long   ,       device=_lowercase				)  # Legal the president is
												_lowerCAmelCase  						=			[
												    11_859,
												    0,
												    1_611,
												    8,
												    5,
												    150,
												    26_449,
												    2,
												    19,
												    348,
												    469,
												    3,
												    2_595,
												    48,
												    20_740,
												    246_533,
												    246_533,
												    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  						=			model.generate(_lowercase   ,       do_sample=_lowercase				)
												self.assertListEqual(output_ids[0].tolist()   ,       _lowercase				)


'''simple docstring'''



from __future__ import annotations

from typing import Any




class   UpperCAmelCase_					(		_SCREAMING_SNAKE_CASE			):






						'''simple docstring'''






						pass






class   UpperCAmelCase_					:






						'''simple docstring'''






						def __init__( self   ,       _lowercase				):

												"""simple docstring"""



												_lowerCAmelCase  						=			data
												_lowerCAmelCase  						=			None




						def __iter__( self				):

												"""simple docstring"""



												_lowerCAmelCase  						=			self
												_lowerCAmelCase  						=			[]
												while node:
																		if node in visited:
																								raise ContainsLoopError
																		visited.append(_lowercase				)
																		yield node.data
																		_lowerCAmelCase  						=			node.next_node




						@property
						def  _lowercase     ( self				):

												"""simple docstring"""



												try:
																		list(self				)
																		return False
												except ContainsLoopError:
																		return True


if __name__ == "__main__":
						_lowercase    =		Node(1)
						_lowercase    =		Node(2)
						_lowercase    =		Node(3)
						_lowercase    =		Node(4)
						print(root_node.has_loop)  # False
						_lowercase    =		root_node.next_node
						print(root_node.has_loop)  # True

						_lowercase    =		Node(5)
						_lowercase    =		Node(6)
						_lowercase    =		Node(5)
						_lowercase    =		Node(6)
						print(root_node.has_loop)  # False

						_lowercase    =		Node(1)
						print(root_node.has_loop)  # False
