


'''simple docstring'''






import os
import socket
from contextlib import contextmanager

import torch

from ..commands.config.default import write_basic_config  # noqa: F401
from ..state import PartialState
from .dataclasses import DistributedType
from .imports import is_deepspeed_available, is_tpu_available
from .transformer_engine import convert_model
from .versions import is_torch_version


if is_deepspeed_available():
						from deepspeed import DeepSpeedEngine

if is_tpu_available(check_device=False):
						import torch_xla.core.xla_model as xm


def       _snake_case     (  A )		->					Optional[Any]:
							if is_torch_version('''<'''				,					'''2.0.0''' ) or not hasattr(A				,					'''_dynamo''' ):
														return False
							return isinstance(A				,					torch._dynamo.eval_frame.OptimizedModule )


def       _snake_case     (  A				,					A = True )		->					List[str]:
							lowerCAmelCase__      =			(torch.nn.parallel.DistributedDataParallel, torch.nn.DataParallel)

							lowerCAmelCase__      =			is_compiled_module(A )
							if is_compiled:
														lowerCAmelCase__      =			model
														lowerCAmelCase__      =			model._orig_mod

							if is_deepspeed_available():
														options += (DeepSpeedEngine,)

							while isinstance(A				,					A ):
														lowerCAmelCase__      =			model.module

							if not keep_fpaa_wrapper:
														lowerCAmelCase__      =			getattr(A				,					'''forward''' )
														lowerCAmelCase__      =			model.__dict__.pop('''_original_forward'''				,					A )
														if original_forward is not None:
																					while hasattr(A				,					'''__wrapped__''' ):
																												lowerCAmelCase__      =			forward.__wrapped__
																												if forward == original_forward:
																																			break
																					lowerCAmelCase__      =			forward
														if getattr(A				,					'''_converted_to_transformer_engine'''				,					A ):
																					convert_model(A				,					to_transformer_engine=A )

							if is_compiled:
														lowerCAmelCase__      =			model
														lowerCAmelCase__      =			compiled_model

							return model


def       _snake_case     (  )		->					Optional[Any]:
							PartialState().wait_for_everyone()


def       _snake_case     (  A				,					A )		->					Dict:
							if PartialState().distributed_type == DistributedType.TPU:
														xm.save(A				,					A )
							elif PartialState().local_process_index == 0:
														torch.save(A				,					A )


@contextmanager
def       _snake_case     (  **A )		->					List[Any]:
							for key, value in kwargs.items():
														lowerCAmelCase__      =			str(A )

							yield

							for key in kwargs:
														if key.upper() in os.environ:
																					del os.environ[key.upper()]


def       _snake_case     (  A )		->					Tuple:
							if not hasattr(A				,					'''__qualname__''' ) and not hasattr(A				,					'''__name__''' ):
														lowerCAmelCase__      =			getattr(A				,					'''__class__'''				,					A )
							if hasattr(A				,					'''__qualname__''' ):
														return obj.__qualname__
							if hasattr(A				,					'''__name__''' ):
														return obj.__name__
							return str(A )


def       _snake_case     (  A				,					A )		->					Dict:
							for key, value in source.items():
														if isinstance(A				,					A ):
																					lowerCAmelCase__      =			destination.setdefault(A				,					{} )
																					merge_dicts(A				,					A )
														else:
																					lowerCAmelCase__      =			value

							return destination






def       _snake_case     (  A = None )		->					Optional[int]:
							if port is None:
														lowerCAmelCase__      =			29500
							with socket.socket(socket.AF_INET				,					socket.SOCK_STREAM ) as s:
														return s.connect_ex(('''localhost''', port) ) == 0



'''simple docstring'''






import numpy as np
import qiskit


def       _snake_case     (  A = 8				,					A = None )		->					str:
							lowerCAmelCase__      =			np.random.default_rng(seed=A )

							# Roughly 25% of the qubits will contribute to the key.
							# So we take more than we need.
							lowerCAmelCase__      =			6 * key_len
							# Measurement basis for Alice's qubits.
							lowerCAmelCase__      =			rng.integers(2				,					size=A )
							# The set of states Alice will prepare.
							lowerCAmelCase__      =			rng.integers(2				,					size=A )
							# Measurement basis for Bob's qubits.
							lowerCAmelCase__      =			rng.integers(2				,					size=A )

							# Quantum Circuit to simulate BB84
							lowerCAmelCase__      =			qiskit.QuantumCircuit(A				,					name='''BB84''' )

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

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

							bbaa_circ.barrier()
							bbaa_circ.measure_all()

							# Simulate the quantum circuit.
							lowerCAmelCase__      =			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.
							lowerCAmelCase__      =			qiskit.execute(A				,					A				,					shots=1				,					seed_simulator=A )
							# Returns the result of measurement.
							lowerCAmelCase__      =			job.result().get_counts(A ).most_frequent()

							# Extracting the generated key from the simulation results.
							# Only keep measurement results where Alice and Bob chose the same basis.
							lowerCAmelCase__      =			''''''.join(
							    [
							        result_bit
							        for alice_basis_bit, bob_basis_bit, result_bit in zip(
							            A				,					A				,					A )
							        if alice_basis_bit == bob_basis_bit
							    ] )

							# Get final key. Pad with 0 if too short, otherwise truncate.
							lowerCAmelCase__      =			gen_key[:key_len] if len(A ) >= key_len else gen_key.ljust(A				,					'''0''' )
							return key


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

		testmod()