



"""simple docstring"""


import unittest

from transformers import is_tf_available
from transformers.testing_utils import require_tf


if is_tf_available():
				import tensorflow as tf
				from tensorflow.python.eager import context
				from tensorflow.python.framework import ops

				from transformers import GradientAccumulator, create_optimizer







@require_tf
class 				A_      (					unittest.TestCase    ):



						"""simple docstring"""






						def      UpperCAmelCase__					( self			:List[str]       ,  lowercase_			:str       ,  lowercase_			:List[Any]       ,  lowercase_			:int )    ->      Union[str, Any]:
												self.assertEqual(len(lowercase_ )       ,  len(lowercase_ ) )
												for a, b in zip(lowercase_       ,  lowercase_ ):
																		self.assertAlmostEqual(lowercase_       ,  lowercase_       ,  delta=lowercase_ )






						def      UpperCAmelCase__					( self			:Union[str, Any] )    ->      int:
												UpperCAmelCase					=			GradientAccumulator()
												accumulator([tf.constant([1.0, 2.0] )] )
												accumulator([tf.constant([-2.0, 1.0] )] )
												accumulator([tf.constant([-1.0, 2.0] )] )
												with self.assertRaises(lowercase_ ):
																		accumulator([tf.constant([1.0, 1.0] ), tf.constant([2.0, 2.0] )] )
												self.assertEqual(accumulator.step       ,  3 )
												self.assertEqual(len(accumulator.gradients )       ,  1 )
												self.assertListAlmostEqual(accumulator.gradients[0].numpy().tolist()       ,  [-2.0, 5.0]       ,  tol=1E-2 )
												accumulator.reset()
												self.assertEqual(accumulator.step       ,  0 )
												self.assertListAlmostEqual(accumulator.gradients[0].numpy().tolist()       ,  [0.0, 0.0]       ,  tol=1E-2 )






						def      UpperCAmelCase__					( self			:Union[str, Any] )    ->      List[Any]:
												UpperCAmelCase					=			None
												ops.enable_eager_execution_internal()
												UpperCAmelCase					=			tf.config.list_physical_devices('CPU' )
												if len(lowercase_ ) == 1:
																		tf.config.set_logical_device_configuration(
																		    physical_devices[0]       ,  [tf.config.LogicalDeviceConfiguration(), tf.config.LogicalDeviceConfiguration()] )
												UpperCAmelCase					=			tf.config.list_logical_devices(device_type='CPU' )
												UpperCAmelCase					=			tf.distribute.MirroredStrategy(devices=devices[:2] )

												with strategy.scope():
																		UpperCAmelCase					=			GradientAccumulator()
																		UpperCAmelCase					=			tf.Variable([4.0, 3.0] )
																		UpperCAmelCase				,   UpperCAmelCase					=			create_optimizer(5E-5       ,  10       ,  5 )
																		UpperCAmelCase					=			tf.Variable([0.0, 0.0]       ,  trainable=lowercase_ )

												def accumulate_on_replica(lowercase_			:Optional[Any] ):
																		accumulator([gradient] )

												def apply_on_replica():
																		optimizer.apply_gradients(list(zip(accumulator.gradients       ,  [variable] ) ) )

												@tf.function
												def accumulate(lowercase_			:int       ,  lowercase_			:int ):
																		with strategy.scope():
																								UpperCAmelCase					=			strategy.experimental_local_results(lowercase_ )
																								local_variables[0].assign(lowercase_ )
																								local_variables[1].assign(lowercase_ )
																								strategy.run(lowercase_       ,  args=(gradient_placeholder,) )

												@tf.function
												def apply_grad():
																		with strategy.scope():
																								strategy.run(lowercase_ )

												def _check_local_values(lowercase_			:Optional[int]       ,  lowercase_			:List[str] ):
																		UpperCAmelCase					=			strategy.experimental_local_results(accumulator._gradients[0] )
																		self.assertListAlmostEqual(values[0].value()       ,  lowercase_       ,  tol=1E-2 )
																		self.assertListAlmostEqual(values[1].value()       ,  lowercase_       ,  tol=1E-2 )

												accumulate([1.0, 2.0]       ,  [-1.0, 1.0] )
												accumulate([3.0, -1.0]       ,  [-1.0, -1.0] )
												accumulate([-2.0, 2.0]       ,  [3.0, -2.0] )
												self.assertEqual(accumulator.step       ,  3 )
												_check_local_values([2.0, 3.0]       ,  [1.0, -2.0] )
												apply_grad()
												self.assertListAlmostEqual(variable.value()       ,  [4.0, 3.0]       ,  tol=1E-2 )
												accumulator.reset()
												self.assertEqual(accumulator.step       ,  0 )
												_check_local_values([0.0, 0.0]       ,  [0.0, 0.0] )










"""simple docstring"""


import os
import random
import sys

from . import cryptomath_module as cryptomath
from . import rabin_miller

snake_case_    					=	3

def 			_lowerCAmelCase				(       lowercase_						):
						print('Generating primitive root of p'						)
						while True:
												UpperCAmelCase					=			random.randrange(3		,     lowercase_						)
												if pow(lowercase_		,     2		,     lowercase_						) == 1:
																		continue
												if pow(lowercase_		,     lowercase_		,     lowercase_						) == 1:
																		continue
												return g

def 			_lowerCAmelCase				(       lowercase_						):
						print('Generating prime p...'						)
						UpperCAmelCase					=			rabin_miller.generate_large_prime(lowercase_						)  # select large prime number.
						UpperCAmelCase					=			primitive_root(lowercase_						)  # one primitive root on modulo p.
						UpperCAmelCase					=			random.randrange(3		,     lowercase_						)  # private_key -> have to be greater than 2 for safety.
						UpperCAmelCase					=			cryptomath.find_mod_inverse(pow(lowercase_		,     lowercase_		,     lowercase_						)		,     lowercase_						)

						UpperCAmelCase					=			(key_size, e_a, e_a, p)
						UpperCAmelCase					=			(key_size, d)

						return public_key, private_key

def 			_lowerCAmelCase				(       lowercase_		,     lowercase_						):
						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()

						UpperCAmelCase				,   UpperCAmelCase					=			generate_key(lowercase_						)
						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 			_lowerCAmelCase				(       ):
						print('Making key files...'						)
						make_key_files('elgamal'		,     2048						)
						print('Key files generation successful'						)


if __name__ == "__main__":
				main()





