


'''simple docstring'''






import argparse
from pathlib import Path

import torch
from packaging import version
from torch.onnx import export

from diffusers import AutoencoderKL


__A	:	int     =     version.parse(version.parse(torch.__version__).base_version) < version.parse('1.11')





def      UpperCAmelCase      (		lowerCamelCase_  :Tuple				,      lowerCamelCase_  :tuple				,      lowerCamelCase_  :Path				,      lowerCamelCase_  :Union[str, Any]				,      lowerCamelCase_  :Union[str, Any]				,      lowerCamelCase_  :Union[str, Any]				,      lowerCamelCase_  :Optional[int]				,      lowerCamelCase_  :List[str]=False				,      ):







		'''simple docstring'''
		output_path.parent.mkdir(parents=lowerCamelCase_				,      exist_ok=lowerCamelCase_ )
		# PyTorch deprecated the `enable_onnx_checker` and `use_external_data_format` arguments in v1.11,
		# so we check the torch version for backwards compatibility
		if is_torch_less_than_1_11:
				export(
				    lowerCamelCase_				,      lowerCamelCase_				,      f=output_path.as_posix()				,      input_names=lowerCamelCase_				,      output_names=lowerCamelCase_				,      dynamic_axes=lowerCamelCase_				,      do_constant_folding=lowerCamelCase_				,      use_external_data_format=lowerCamelCase_				,      enable_onnx_checker=lowerCamelCase_				,      opset_version=lowerCamelCase_				,      )
		else:
				export(
				    lowerCamelCase_				,      lowerCamelCase_				,      f=output_path.as_posix()				,      input_names=lowerCamelCase_				,      output_names=lowerCamelCase_				,      dynamic_axes=lowerCamelCase_				,      do_constant_folding=lowerCamelCase_				,      opset_version=lowerCamelCase_				,      )





@torch.no_grad()
def      UpperCAmelCase      (		lowerCamelCase_  :str				,      lowerCamelCase_  :str				,      lowerCamelCase_  :int				,      lowerCamelCase_  :bool = False ):







		'''simple docstring'''
		snake_case_		:							Optional[Any]			       =						torch.floataa if fpaa else torch.floataa
		if fpaa and torch.cuda.is_available():
				snake_case_		:							Tuple			       =						'''cuda'''
		elif fpaa and not torch.cuda.is_available():
				raise ValueError("""`float16` model export is only supported on GPUs with CUDA""" )
		else:
				snake_case_		:							Tuple			       =						'''cpu'''
		snake_case_		:							Dict			       =						Path(lowerCamelCase_ )

		# VAE DECODER
		snake_case_		:							List[Any]			       =						AutoencoderKL.from_pretrained(model_path + """/vae""" )
		snake_case_		:							Any			       =						vae_decoder.config.latent_channels
		# forward only through the decoder part
		snake_case_		:							Dict			       =						vae_decoder.decode
		onnx_export(
		    lowerCamelCase_				,      model_args=(
		        torch.randn(1				,      lowerCamelCase_				,      25				,      25 ).to(device=lowerCamelCase_				,      dtype=lowerCamelCase_ ),
		        False,
		    )				,      output_path=output_path / """vae_decoder""" / """model.onnx"""				,      ordered_input_names=["""latent_sample""", """return_dict"""]				,      output_names=["""sample"""]				,      dynamic_axes={
		        """latent_sample""": {0: """batch""", 1: """channels""", 2: """height""", 3: """width"""},
		    }				,      opset=lowerCamelCase_				,      )
		del vae_decoder


if __name__ == "__main__":
				__A	:	Any     =     argparse.ArgumentParser()

				parser.add_argument(
				    '--model_path',
				    type=str,
				    required=True,
				    help='Path to the `diffusers` checkpoint to convert (either a local directory or on the Hub).',
				)

				parser.add_argument('--output_path', type=str, required=True, help='Path to the output model.')
				parser.add_argument(
				    '--opset',
				    default=14,
				    type=int,
				    help='The version of the ONNX operator set to use.',
				)
				parser.add_argument('--fp16', action='store_true', default=False, help='Export the models in `float16` mode')

				__A	:	List[Any]     =     parser.parse_args()
				print(args.output_path)
				convert_models(args.model_path, args.output_path, args.opset, args.fpaa)
				print('SD: Done: ONNX')



'''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()