


'''simple docstring'''






import unittest

from transformers import EsmConfig, is_torch_available
from transformers.testing_utils import TestCasePlus, require_torch, slow, torch_device

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 EsmForMaskedLM, EsmForSequenceClassification, EsmForTokenClassification, EsmModel
							from transformers.models.esm.modeling_esm import (
							    ESM_PRETRAINED_MODEL_ARCHIVE_LIST,
							    EsmEmbeddings,
							    create_position_ids_from_input_ids,
							)
class 						__UpperCamelCase	:





							def __init__(  self		:Union[str, Any]  ,_UpperCamelCase		:int  ,_UpperCamelCase		:str=1_3  ,_UpperCamelCase		:Tuple=7  ,_UpperCamelCase		:Tuple=False  ,_UpperCamelCase		:Tuple=True  ,_UpperCamelCase		:Union[str, Any]=False  ,_UpperCamelCase		:int=True  ,_UpperCamelCase		:List[str]=3_3  ,_UpperCamelCase		:Any=3_2  ,_UpperCamelCase		:Any=5  ,_UpperCamelCase		:List[str]=4  ,_UpperCamelCase		:Tuple=3_7  ,_UpperCamelCase		:Optional[Any]="gelu"  ,_UpperCamelCase		:Any=0.1  ,_UpperCamelCase		:List[Any]=0.1  ,_UpperCamelCase		:Any=5_1_2  ,_UpperCamelCase		:Tuple=1_6  ,_UpperCamelCase		:Any=2  ,_UpperCamelCase		:Optional[Any]=0.02  ,_UpperCamelCase		:List[str]=3  ,_UpperCamelCase		:Union[str, Any]=4  ,_UpperCamelCase		:Dict=None  ,):
									snake_case_		:							Tuple			       =						parent
									snake_case_		:							List[str]			       =						batch_size
									snake_case_		:							List[str]			       =						seq_length
									snake_case_		:							Any			       =						is_training
									snake_case_		:							List[Any]			       =						use_input_mask
									snake_case_		:							int			       =						use_token_type_ids
									snake_case_		:							Optional[int]			       =						use_labels
									snake_case_		:							List[str]			       =						vocab_size
									snake_case_		:							Dict			       =						hidden_size
									snake_case_		:							Optional[int]			       =						num_hidden_layers
									snake_case_		:							Optional[Any]			       =						num_attention_heads
									snake_case_		:							int			       =						intermediate_size
									snake_case_		:							Optional[Any]			       =						hidden_act
									snake_case_		:							int			       =						hidden_dropout_prob
									snake_case_		:							Optional[int]			       =						attention_probs_dropout_prob
									snake_case_		:							Optional[int]			       =						max_position_embeddings
									snake_case_		:							List[str]			       =						type_vocab_size
									snake_case_		:							int			       =						type_sequence_label_size
									snake_case_		:							Dict			       =						initializer_range
									snake_case_		:							Any			       =						num_labels
									snake_case_		:							Any			       =						num_choices
									snake_case_		:							Tuple			       =						scope





							def 		a__   (  self		:str			):
									snake_case_		:							Dict			       =						ids_tensor([self.batch_size, self.seq_length]  ,self.vocab_size			)

									snake_case_		:							str			       =						None
									if self.use_input_mask:
											snake_case_		:							Optional[int]			       =						random_attention_mask([self.batch_size, self.seq_length]			)

									snake_case_		:							Dict			       =						None
									snake_case_		:							List[str]			       =						None
									snake_case_		:							Tuple			       =						None
									if self.use_labels:
											snake_case_		:							Dict			       =						ids_tensor([self.batch_size]  ,self.type_sequence_label_size			)
											snake_case_		:							Any			       =						ids_tensor([self.batch_size, self.seq_length]  ,self.num_labels			)
											snake_case_		:							Union[str, Any]			       =						ids_tensor([self.batch_size]  ,self.num_choices			)

									snake_case_		:							Dict			       =						self.get_config()

									return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels





							def 		a__   (  self		:Optional[Any]			):
									return EsmConfig(
									    vocab_size=self.vocab_size  ,hidden_size=self.hidden_size  ,pad_token_id=1  ,num_hidden_layers=self.num_hidden_layers  ,num_attention_heads=self.num_attention_heads  ,intermediate_size=self.intermediate_size  ,hidden_act=self.hidden_act  ,hidden_dropout_prob=self.hidden_dropout_prob  ,attention_probs_dropout_prob=self.attention_probs_dropout_prob  ,max_position_embeddings=self.max_position_embeddings  ,type_vocab_size=self.type_vocab_size  ,initializer_range=self.initializer_range  ,)





							def 		a__   (  self		:str  ,_UpperCamelCase		:List[Any]  ,_UpperCamelCase		:List[str]  ,_UpperCamelCase		:Any  ,_UpperCamelCase		:Optional[int]  ,_UpperCamelCase		:List[Any]  ,_UpperCamelCase		:Optional[int]			):
									snake_case_		:							Union[str, Any]			       =						EsmModel(config=_UpperCamelCase			)
									model.to(_UpperCamelCase			)
									model.eval()
									snake_case_		:							int			       =						model(_UpperCamelCase  ,attention_mask=_UpperCamelCase			)
									snake_case_		:							str			       =						model(_UpperCamelCase			)
									snake_case_		:							Optional[int]			       =						model(_UpperCamelCase			)

									self.parent.assertEqual(result.last_hidden_state.shape  ,(self.batch_size, self.seq_length, self.hidden_size)			)
									self.parent.assertEqual(result.pooler_output.shape  ,(self.batch_size, self.hidden_size)			)





							def 		a__   (  self		:Any  ,_UpperCamelCase		:Optional[Any]  ,_UpperCamelCase		:Optional[Any]  ,_UpperCamelCase		:Any  ,_UpperCamelCase		:Dict  ,_UpperCamelCase		:Union[str, Any]  ,_UpperCamelCase		:Optional[int]			):
									snake_case_		:							str			       =						EsmForMaskedLM(config=_UpperCamelCase			)
									model.to(_UpperCamelCase			)
									model.eval()
									snake_case_		:							Dict			       =						model(_UpperCamelCase  ,attention_mask=_UpperCamelCase  ,labels=_UpperCamelCase			)
									self.parent.assertEqual(result.logits.shape  ,(self.batch_size, self.seq_length, self.vocab_size)			)





							def 		a__   (  self		:Optional[int]  ,_UpperCamelCase		:Optional[Any]  ,_UpperCamelCase		:List[str]  ,_UpperCamelCase		:Union[str, Any]  ,_UpperCamelCase		:Union[str, Any]  ,_UpperCamelCase		:Union[str, Any]  ,_UpperCamelCase		:Any			):
									snake_case_		:							List[Any]			       =						self.num_labels
									snake_case_		:							int			       =						EsmForTokenClassification(config=_UpperCamelCase			)
									model.to(_UpperCamelCase			)
									model.eval()
									snake_case_		:							int			       =						model(_UpperCamelCase  ,attention_mask=_UpperCamelCase  ,labels=_UpperCamelCase			)
									self.parent.assertEqual(result.logits.shape  ,(self.batch_size, self.seq_length, self.num_labels)			)





							def 		a__   (  self		:Union[str, Any]			):
									snake_case_		:							Dict			       =						self.prepare_config_and_inputs()
									(
									    (
									    snake_case_
									)       ,      (
									    snake_case_
									)       ,      (
									    snake_case_
									)       ,      (
									    snake_case_
									)       ,      (
									    snake_case_
									)       ,      (
									    snake_case_
									)       ,      
									)		:							Optional[int]			       =						config_and_inputs
									snake_case_		:							List[str]			       =						{"""input_ids""": input_ids, """attention_mask""": input_mask}
									return config, inputs_dict





@require_torch
class 						__UpperCamelCase	(						lowercase__						,  lowercase__						,  unittest.TestCase							):
							lowercase			:		Optional[int]   		=  False

							lowercase			:		List[str]   		=  (
							    (
							        EsmForMaskedLM,
							        EsmModel,
							        EsmForSequenceClassification,
							        EsmForTokenClassification,
							    )
							    if is_torch_available()
							    else ()
							)
							lowercase			:		int   		=  ()
							lowercase			:		List[str]   		=  (
							    {
							        'feature-extraction': EsmModel,
							        'fill-mask': EsmForMaskedLM,
							        'text-classification': EsmForSequenceClassification,
							        'token-classification': EsmForTokenClassification,
							        'zero-shot': EsmForSequenceClassification,
							    }
							    if is_torch_available()
							    else {}
							)
							lowercase			:		str   		=  True





							def 		a__   (  self		:Any			):
									snake_case_		:							Any			       =						EsmModelTester(self			)
									snake_case_		:							str			       =						ConfigTester(self  ,config_class=_UpperCamelCase  ,hidden_size=3_7			)





							def 		a__   (  self		:Optional[Any]			):
									self.config_tester.run_common_tests()





							def 		a__   (  self		:Optional[Any]			):
									snake_case_		:							str			       =						self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*_UpperCamelCase			)





							def 		a__   (  self		:Dict			):
									snake_case_		:							Dict			       =						self.model_tester.prepare_config_and_inputs()
									for type in ["absolute", "relative_key", "relative_key_query"]:
											snake_case_		:							int			       =						type
											self.model_tester.create_and_check_model(*_UpperCamelCase			)





							def 		a__   (  self		:Dict			):
									snake_case_		:							str			       =						self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_masked_lm(*_UpperCamelCase			)





							def 		a__   (  self		:List[str]			):
									snake_case_		:							List[str]			       =						self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_token_classification(*_UpperCamelCase			)





							@slow
							def 		a__   (  self		:Union[str, Any]			):
									for model_name in ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
											snake_case_		:							int			       =						EsmModel.from_pretrained(_UpperCamelCase			)
											self.assertIsNotNone(_UpperCamelCase			)





							def 		a__   (  self		:Tuple			):
									snake_case_		:							Dict			       =						self.model_tester.prepare_config_and_inputs()[0]
									snake_case_		:							Optional[int]			       =						EsmEmbeddings(config=_UpperCamelCase			)

									snake_case_		:							List[Any]			       =						torch.as_tensor([[1_2, 3_1, 1_3, model.padding_idx]]			)
									snake_case_		:							Union[str, Any]			       =						torch.as_tensor(
									    [
									        [
									            0 + model.padding_idx + 1,
									            1 + model.padding_idx + 1,
									            2 + model.padding_idx + 1,
									            model.padding_idx,
									        ]
									    ]			)
									snake_case_		:							Optional[Any]			       =						create_position_ids_from_input_ids(_UpperCamelCase  ,model.padding_idx			)
									self.assertEqual(position_ids.shape  ,expected_positions.shape			)
									self.assertTrue(torch.all(torch.eq(_UpperCamelCase  ,_UpperCamelCase			)			)			)





							def 		a__   (  self		:List[Any]			):
									snake_case_		:							Union[str, Any]			       =						self.model_tester.prepare_config_and_inputs()[0]
									snake_case_		:							List[Any]			       =						EsmEmbeddings(config=_UpperCamelCase			)

									snake_case_		:							Dict			       =						torch.empty(2  ,4  ,3_0			)
									snake_case_		:							List[Any]			       =						[
									    0 + embeddings.padding_idx + 1,
									    1 + embeddings.padding_idx + 1,
									    2 + embeddings.padding_idx + 1,
									    3 + embeddings.padding_idx + 1,
									]
									snake_case_		:							Any			       =						torch.as_tensor([expected_single_positions, expected_single_positions]			)
									snake_case_		:							str			       =						embeddings.create_position_ids_from_inputs_embeds(_UpperCamelCase			)
									self.assertEqual(position_ids.shape  ,expected_positions.shape			)
									self.assertTrue(torch.all(torch.eq(_UpperCamelCase  ,_UpperCamelCase			)			)			)





							@unittest.skip("""Esm does not support embedding resizing"""			)
							def 		a__   (  self		:Optional[Any]			):
									pass





							@unittest.skip("""Esm does not support embedding resizing"""			)
							def 		a__   (  self		:Optional[int]			):
									pass





							@unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests."""			)
							def 		a__   (  self		:Optional[int]			):
									pass





@require_torch
class 						__UpperCamelCase	(						lowercase__							):





							@slow
							def 		a__   (  self		:Any			):
									with torch.no_grad():
											snake_case_		:							Optional[Any]			       =						EsmForMaskedLM.from_pretrained("""facebook/esm2_t6_8M_UR50D"""			)
											model.eval()
											snake_case_		:							List[Any]			       =						torch.tensor([[0, 1, 2, 3, 4, 5]]			)
											snake_case_		:							Dict			       =						model(_UpperCamelCase			)[0]

											snake_case_		:							Optional[int]			       =						3_3

											snake_case_		:							List[Any]			       =						torch.Size((1, 6, vocab_size)			)
											self.assertEqual(output.shape  ,_UpperCamelCase			)

											snake_case_		:							Union[str, Any]			       =						torch.tensor(
											    [[[8.92_15, -10.58_98, -6.46_71], [-6.39_67, -13.91_14, -1.12_12], [-7.78_12, -13.95_16, -3.74_06]]]			)
											self.assertTrue(torch.allclose(output[:, :3, :3]  ,_UpperCamelCase  ,atol=1E-4			)			)





							@slow
							def 		a__   (  self		:List[Any]			):
									with torch.no_grad():
											snake_case_		:							List[Any]			       =						EsmModel.from_pretrained("""facebook/esm2_t6_8M_UR50D"""			)
											model.eval()

											snake_case_		:							str			       =						torch.tensor([[0, 6, 4, 1_3, 5, 4, 1_6, 1_2, 1_1, 7, 2]]			)
											snake_case_		:							Optional[Any]			       =						model(_UpperCamelCase			)[0]
											# compare the actual values for a slice.
											snake_case_		:							List[str]			       =						torch.tensor(
											    [[[0.14_44, 0.54_13, 0.32_48], [0.30_34, 0.00_53, 0.31_08], [0.32_28, -0.24_99, 0.34_15]]]			)
											self.assertTrue(torch.allclose(output[:, :3, :3]  ,_UpperCamelCase  ,atol=1E-4			)			)



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