






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

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

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

											lowerCAmelCase   :Optional[int]						=			None
											if self.use_mc_token_ids:
																	lowerCAmelCase   :Any						=			ids_tensor([self.batch_size, self.num_choices]     , self.seq_length   )

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

											lowerCAmelCase   :List[Any]						=			self.get_config()

											lowerCAmelCase   :str						=			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        UpperCAmelCase__ (							self							:	int   )	->       Any:
											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        UpperCAmelCase__ (							self							:	Dict     , UpperCAmelCase							:	str     , UpperCAmelCase							:	int     , UpperCAmelCase							:	str     , UpperCAmelCase							:	Optional[Any]     , UpperCAmelCase							:	int     , *UpperCAmelCase							:	str   )	->       int:
											lowerCAmelCase   :Union[str, Any]						=			CTRLModel(config=UpperCAmelCase   )
											model.to(UpperCAmelCase   )
											model.eval()

											model(UpperCAmelCase     , token_type_ids=UpperCAmelCase     , head_mask=UpperCAmelCase   )
											model(UpperCAmelCase     , token_type_ids=UpperCAmelCase   )
											lowerCAmelCase   :Optional[Any]						=			model(UpperCAmelCase   )
											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        UpperCAmelCase__ (							self							:	List[str]     , UpperCAmelCase							:	Optional[Any]     , UpperCAmelCase							:	Tuple     , UpperCAmelCase							:	Union[str, Any]     , UpperCAmelCase							:	Optional[Any]     , UpperCAmelCase							:	Optional[int]     , *UpperCAmelCase							:	Tuple   )	->       Tuple:
											lowerCAmelCase   :Dict						=			CTRLLMHeadModel(UpperCAmelCase   )
											model.to(UpperCAmelCase   )
											model.eval()

											lowerCAmelCase   :Dict						=			model(UpperCAmelCase     , token_type_ids=UpperCAmelCase     , labels=UpperCAmelCase   )
											self.parent.assertEqual(result.loss.shape     , ()   )
											self.parent.assertEqual(result.logits.shape     , (self.batch_size, self.seq_length, self.vocab_size)   )
					def        UpperCAmelCase__ (							self							:	List[str]   )	->       List[Any]:
											lowerCAmelCase   :Optional[int]						=			self.prepare_config_and_inputs()

											(
											    lowerCAmelCase    
											)   :List[Any]						=			config_and_inputs

											lowerCAmelCase   :int						=			{"input_ids": input_ids, "token_type_ids": token_type_ids, "head_mask": head_mask}

											return config, inputs_dict
					def        UpperCAmelCase__ (							self							:	Union[str, Any]     , UpperCAmelCase							:	Union[str, Any]     , UpperCAmelCase							:	Dict     , UpperCAmelCase							:	Optional[int]     , UpperCAmelCase							:	int     , *UpperCAmelCase							:	Union[str, Any]   )	->       int:
											lowerCAmelCase   :Union[str, Any]						=			self.num_labels
											lowerCAmelCase   :Union[str, Any]						=			CTRLForSequenceClassification(UpperCAmelCase   )
											model.to(UpperCAmelCase   )
											model.eval()
											lowerCAmelCase   :Tuple						=			ids_tensor([self.batch_size]     , self.type_sequence_label_size   )
											lowerCAmelCase   :Union[str, Any]						=			model(UpperCAmelCase     , token_type_ids=UpperCAmelCase     , labels=UpperCAmelCase   )
											self.parent.assertEqual(result.logits.shape     , (self.batch_size, self.num_labels)   )




@require_torch
class 						__UpperCamelCase     (     __snake_case   ,     __snake_case   ,     __snake_case   ,     unittest.TestCase						):
					lowercase_    :				Optional[int]      =  (CTRLModel, CTRLLMHeadModel, CTRLForSequenceClassification) if is_torch_available() else ()
					lowercase_    :				Optional[Any]      =  (CTRLLMHeadModel,) if is_torch_available() else ()
					lowercase_    :				Dict      =  (
					    {
					        """feature-extraction""": CTRLModel,
					        """text-classification""": CTRLForSequenceClassification,
					        """text-generation""": CTRLLMHeadModel,
					        """zero-shot""": CTRLForSequenceClassification,
					    }
					    if is_torch_available()
					    else {}
					)
					lowercase_    :				Any      =  True
					lowercase_    :				Optional[Any]      =  False
					lowercase_    :				List[Any]      =  False
					def        UpperCAmelCase__ (							self							:	Tuple     , UpperCAmelCase							:	List[str]     , UpperCAmelCase							:	List[str]     , UpperCAmelCase							:	Dict     , UpperCAmelCase							:	List[Any]     , UpperCAmelCase							:	str   )	->       List[str]:
											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        UpperCAmelCase__ (							self							:	int   )	->       int:
											lowerCAmelCase   :str						=			CTRLModelTester(self   )
											lowerCAmelCase   :List[Any]						=			ConfigTester(self     , config_class=UpperCAmelCase     , n_embd=37   )
					def        UpperCAmelCase__ (							self							:	str   )	->       Optional[Any]:
											super().tearDown()
											# clean-up as much as possible GPU memory occupied by PyTorch
											gc.collect()
											torch.cuda.empty_cache()
					def        UpperCAmelCase__ (							self							:	List[Any]   )	->       int:
											self.config_tester.run_common_tests()
					def        UpperCAmelCase__ (							self							:	List[str]   )	->       Union[str, Any]:
											lowerCAmelCase   :List[Any]						=			self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_ctrl_model(*UpperCAmelCase   )
					def        UpperCAmelCase__ (							self							:	Optional[Any]   )	->       Dict:
											lowerCAmelCase   :List[Any]						=			self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_lm_head_model(*UpperCAmelCase   )
					@unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.'   )
					def        UpperCAmelCase__ (							self							:	Optional[Any]   )	->       Tuple:
											pass
					@slow
					def        UpperCAmelCase__ (							self							:	Optional[Any]   )	->       Optional[Any]:
											for model_name in CTRL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																	lowerCAmelCase   :Optional[int]						=			CTRLModel.from_pretrained(UpperCAmelCase   )
																	self.assertIsNotNone(UpperCAmelCase   )
					@unittest.skip('The model doesn\'t support left padding'   )  # and it's not used enough to be worth fixing :)
					def        UpperCAmelCase__ (							self							:	int   )	->       Dict:
											pass




@require_torch
class 						__UpperCamelCase     (     unittest.TestCase						):
					def        UpperCAmelCase__ (							self							:	Optional[int]   )	->       Optional[Any]:
											super().tearDown()
											# clean-up as much as possible GPU memory occupied by PyTorch
											gc.collect()
											torch.cuda.empty_cache()
					@slow
					def        UpperCAmelCase__ (							self							:	List[Any]   )	->       Dict:
											lowerCAmelCase   :Tuple						=			CTRLLMHeadModel.from_pretrained('ctrl'   )
											model.to(UpperCAmelCase   )
											lowerCAmelCase   :Tuple						=			torch.tensor(
											    [[1_1859, 0, 1611, 8]]     , dtype=torch.long     , device=UpperCAmelCase   )  # Legal the president is
											lowerCAmelCase   :Optional[Any]						=			[
											    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

											lowerCAmelCase   :Optional[Any]						=			model.generate(UpperCAmelCase     , do_sample=UpperCAmelCase   )
											self.assertListEqual(output_ids[0].tolist()     , UpperCAmelCase   )

import os
import random
import sys

from . import cryptomath_module as cryptomath
from . import rabin_miller

UpperCamelCase_						:     List[Any]	       =							3



def 		UpperCamelCase     (       _UpperCAmelCase  :   int  )   ->			int:






						'''simple docstring'''

						print("Generating primitive root of p"  )
						while True:
												_lowercase       :	Any           =   random.randrange(3 ,			_UpperCAmelCase  )
												if pow(_UpperCAmelCase ,			2 ,			_UpperCAmelCase  ) == 1:
																		continue
												if pow(_UpperCAmelCase ,			_UpperCAmelCase ,			_UpperCAmelCase  ) == 1:
																		continue
												return g



def 		UpperCamelCase     (       _UpperCAmelCase  :   int  )   ->			tuple[tuple[int, int, int, int], tuple[int, int]]:






						'''simple docstring'''

						print("Generating prime p..."  )
						_lowercase       :	Optional[int]           =   rabin_miller.generate_large_prime(_UpperCAmelCase  )  # select large prime number.
						_lowercase       :	Dict           =   primitive_root(_UpperCAmelCase  )  # one primitive root on modulo p.
						_lowercase       :	Any           =   random.randrange(3 ,			_UpperCAmelCase  )  # private_key -> have to be greater than 2 for safety.
						_lowercase       :	Tuple           =   cryptomath.find_mod_inverse(pow(_UpperCAmelCase ,			_UpperCAmelCase ,			_UpperCAmelCase  ) ,			_UpperCAmelCase  )

						_lowercase       :	List[Any]           =   (key_size, e_a, e_a, p)
						_lowercase       :	Union[str, Any]           =   (key_size, d)

						return public_key, private_key



def 		UpperCamelCase     (       _UpperCAmelCase  :   str ,			_UpperCAmelCase  :   int  )   ->			None:






						'''simple docstring'''

						if os.path.exists(f"""{name}_pubkey.txt"""  ) or os.path.exists(f"""{name}_privkey.txt"""  ):
												print("\nWARNING:"  )
												print(
												    f"""\"{name}_pubkey.txt\" or \"{name}_privkey.txt\" already exists. \n"""
												    "Use a different name or delete these files and re-run this program."  )
												sys.exit()

						_lowercase      ,    _lowercase       :	Optional[Any]           =   generate_key(_UpperCAmelCase  )
						print(f"""\nWriting public key to file {name}_pubkey.txt..."""  )
						with open(f"""{name}_pubkey.txt""" ,			"w"  ) as fo:
												fo.write(f"""{public_key[0]},{public_key[1]},{public_key[2]},{public_key[3]}"""  )

						print(f"""Writing private key to file {name}_privkey.txt..."""  )
						with open(f"""{name}_privkey.txt""" ,			"w"  ) as fo:
												fo.write(f"""{private_key[0]},{private_key[1]}"""  )



def 		UpperCamelCase     (       )   ->			None:






						'''simple docstring'''

						print("Making key files..."  )
						make_key_files("elgamal" ,			2048  )
						print("Key files generation successful"  )


if __name__ == "__main__":
							main()




