


'''simple docstring'''






import unittest

import torch
from torch import nn

from accelerate.test_utils import require_cuda
from accelerate.utils.memory import find_executable_batch_size, release_memory





def      UpperCAmelCase      (		):







		'''simple docstring'''
		raise RuntimeError("""CUDA out of memory.""" )
class 						__UpperCamelCase	(						nn.Module							):





							def __init__(  self		:Dict			):
									super().__init__()
									snake_case_		:							Optional[int]			       =						nn.Linear(3  ,4			)
									snake_case_		:							Union[str, Any]			       =						nn.BatchNormad(4			)
									snake_case_		:							Tuple			       =						nn.Linear(4  ,5			)





							def 		a__   (  self		:List[Any]  ,_UpperCamelCase		:Any			):
									return self.lineara(self.batchnorm(self.lineara(A_			)			)			)





class 						__UpperCamelCase	(						unittest.TestCase							):





							def 		a__   (  self		:int			):
									snake_case_		:							List[str]			       =						[]

									@find_executable_batch_size(starting_batch_size=1_2_8			)
									def mock_training_loop_function(_UpperCamelCase		:Optional[int]			):
											nonlocal batch_sizes
											batch_sizes.append(A_			)
											if batch_size != 8:
													raise_fake_out_of_memory()

									mock_training_loop_function()
									self.assertListEqual(A_  ,[1_2_8, 6_4, 3_2, 1_6, 8]			)





							def 		a__   (  self		:Dict			):
									snake_case_		:							List[str]			       =						[]

									@find_executable_batch_size(starting_batch_size=1_2_8			)
									def mock_training_loop_function(_UpperCamelCase		:int  ,_UpperCamelCase		:Optional[int]			):
											nonlocal batch_sizes
											batch_sizes.append(A_			)
											if batch_size != 8:
													raise_fake_out_of_memory()
											return batch_size, arga

									snake_case_       ,      snake_case_		:							Optional[Any]			       =						mock_training_loop_function("""hello"""			)
									self.assertListEqual(A_  ,[1_2_8, 6_4, 3_2, 1_6, 8]			)
									self.assertListEqual([bs, arga]  ,[8, """hello"""]			)





							def 		a__   (  self		:Optional[int]			):
									@find_executable_batch_size(starting_batch_size=0			)
									def mock_training_loop_function(_UpperCamelCase		:List[str]			):
											pass

									with self.assertRaises(A_			) as cm:
											mock_training_loop_function()
											self.assertIn("""No executable batch size found, reached zero."""  ,cm.exception.args[0]			)





							def 		a__   (  self		:Optional[Any]			):
									@find_executable_batch_size(starting_batch_size=1_6			)
									def mock_training_loop_function(_UpperCamelCase		:Tuple			):
											if batch_size > 0:
													raise_fake_out_of_memory()
											pass

									with self.assertRaises(A_			) as cm:
											mock_training_loop_function()
											self.assertIn("""No executable batch size found, reached zero."""  ,cm.exception.args[0]			)





							def 		a__   (  self		:Union[str, Any]			):
									@find_executable_batch_size(starting_batch_size=1_2_8			)
									def mock_training_loop_function(_UpperCamelCase		:Any  ,_UpperCamelCase		:Any  ,_UpperCamelCase		:str			):
											if batch_size != 8:
													raise raise_fake_out_of_memory()

									with self.assertRaises(A_			) as cm:
											mock_training_loop_function(1_2_8  ,"""hello"""  ,"""world"""			)
											self.assertIn("""Batch size was passed into `f`"""  ,cm.exception.args[0]			)
											self.assertIn("""`f(arg1=\'hello\', arg2=\'world\')"""  ,cm.exception.args[0]			)





							def 		a__   (  self		:List[str]			):
									@find_executable_batch_size(starting_batch_size=1_6			)
									def mock_training_loop_function(_UpperCamelCase		:Optional[Any]			):
											raise ValueError("""Oops, we had an error!"""			)

									with self.assertRaises(A_			) as cm:
											mock_training_loop_function()
											self.assertIn("""Oops, we had an error!"""  ,cm.exception.args[0]			)





							@require_cuda
							def 		a__   (  self		:Tuple			):
									snake_case_		:							Optional[int]			       =						torch.cuda.memory_allocated()
									snake_case_		:							Union[str, Any]			       =						ModelForTest()
									model.cuda()
									self.assertGreater(torch.cuda.memory_allocated()  ,A_			)
									snake_case_		:							Optional[int]			       =						release_memory(A_			)
									self.assertEqual(torch.cuda.memory_allocated()  ,A_			)



'''simple docstring'''






import numpy as np
import qiskit





def      UpperCAmelCase      (		lowerCamelCase_  :int = 8				,      lowerCamelCase_  :int | None = None ):







		'''simple docstring'''
		snake_case_		:							Tuple			       =						np.random.default_rng(seed=lowerCamelCase_ )

		# Roughly 25% of the qubits will contribute to the key.
		# So we take more than we need.
		snake_case_		:							Union[str, Any]			       =						6 * key_len
		# Measurement basis for Alice's qubits.
		snake_case_		:							Tuple			       =						rng.integers(2				,      size=lowerCamelCase_ )
		# The set of states Alice will prepare.
		snake_case_		:							Tuple			       =						rng.integers(2				,      size=lowerCamelCase_ )
		# Measurement basis for Bob's qubits.
		snake_case_		:							List[Any]			       =						rng.integers(2				,      size=lowerCamelCase_ )

		# Quantum Circuit to simulate BB84
		snake_case_		:							Optional[int]			       =						qiskit.QuantumCircuit(lowerCamelCase_				,      name="""BB84""" )

		# Alice prepares her qubits according to rules above.
		for index, _ in enumerate(lowerCamelCase_ ):
				if alice_state[index] == 1:
						bbaa_circ.x(lowerCamelCase_ )
				if alice_basis[index] == 1:
						bbaa_circ.h(lowerCamelCase_ )
		bbaa_circ.barrier()

		# Bob measures the received qubits according to rules above.
		for index, _ in enumerate(lowerCamelCase_ ):
				if bob_basis[index] == 1:
						bbaa_circ.h(lowerCamelCase_ )

		bbaa_circ.barrier()
		bbaa_circ.measure_all()

		# Simulate the quantum circuit.
		snake_case_		:							Union[str, Any]			       =						qiskit.Aer.get_backend("""aer_simulator""" )
		# We only need to run one shot because the key is unique.
		# Multiple shots will produce the same key.
		snake_case_		:							Tuple			       =						qiskit.execute(lowerCamelCase_				,      lowerCamelCase_				,      shots=1				,      seed_simulator=lowerCamelCase_ )
		# Returns the result of measurement.
		snake_case_		:							Tuple			       =						job.result().get_counts(lowerCamelCase_ ).most_frequent()

		# Extracting the generated key from the simulation results.
		# Only keep measurement results where Alice and Bob chose the same basis.
		snake_case_		:							Optional[Any]			       =						"""""".join(
		    [
		        result_bit
		        for alice_basis_bit, bob_basis_bit, result_bit in zip(
		            lowerCamelCase_				,      lowerCamelCase_				,      lowerCamelCase_ )
		        if alice_basis_bit == bob_basis_bit
		    ] )

		# Get final key. Pad with 0 if too short, otherwise truncate.
		snake_case_		:							str			       =						gen_key[:key_len] if len(lowerCamelCase_ ) >= key_len else gen_key.ljust(lowerCamelCase_				,      """0""" )
		return key


if __name__ == "__main__":
							print(F'The generated key is : {bbaa(8, seed=0)}')
							from doctest import testmod

							testmod()