






"""simple docstring"""
import unittest

from parameterized import parameterized

from transformers import OpenLlamaConfig, is_torch_available, set_seed
from transformers.testing_utils import require_torch, torch_device

from ...generation.test_utils import GenerationTesterMixin
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 OpenLlamaForCausalLM, OpenLlamaForSequenceClassification, OpenLlamaModel







class      UpperCamelCase_			:





	def __init__( self   :					Union[str, Any]      ,      lowerCAmelCase_   :					Optional[int]      ,      lowerCAmelCase_   :					str=13      ,      lowerCAmelCase_   :					str=7      ,      lowerCAmelCase_   :					Optional[int]=True      ,      lowerCAmelCase_   :					List[Any]=True      ,      lowerCAmelCase_   :					Any=False      ,      lowerCAmelCase_   :					Tuple=True      ,      lowerCAmelCase_   :					Any=99      ,      lowerCAmelCase_   :					Dict=32      ,      lowerCAmelCase_   :					Tuple=5      ,      lowerCAmelCase_   :					List[str]=4      ,      lowerCAmelCase_   :					List[Any]=37      ,      lowerCAmelCase_   :					Dict="gelu"      ,      lowerCAmelCase_   :					List[Any]=0.1      ,      lowerCAmelCase_   :					List[str]=0.1      ,      lowerCAmelCase_   :					Optional[Any]=512      ,      lowerCAmelCase_   :					Any=16      ,      lowerCAmelCase_   :					Tuple=2      ,      lowerCAmelCase_   :					Any=0.0_2      ,      lowerCAmelCase_   :					List[str]=3      ,      lowerCAmelCase_   :					Any=4      ,      lowerCAmelCase_   :					Tuple=None      ,      )		->     Any:
				UpperCAmelCase_	:					str     	=   parent
				UpperCAmelCase_	:					Dict     	=   batch_size
				UpperCAmelCase_	:					List[str]     	=   seq_length
				UpperCAmelCase_	:					Dict     	=   is_training
				UpperCAmelCase_	:					Optional[Any]     	=   use_input_mask
				UpperCAmelCase_	:					List[str]     	=   use_token_type_ids
				UpperCAmelCase_	:					Any     	=   use_labels
				UpperCAmelCase_	:					Dict     	=   vocab_size
				UpperCAmelCase_	:					Optional[Any]     	=   hidden_size
				UpperCAmelCase_	:					Dict     	=   num_hidden_layers
				UpperCAmelCase_	:					Dict     	=   num_attention_heads
				UpperCAmelCase_	:					Dict     	=   intermediate_size
				UpperCAmelCase_	:					Tuple     	=   hidden_act
				UpperCAmelCase_	:					Tuple     	=   hidden_dropout_prob
				UpperCAmelCase_	:					Any     	=   attention_probs_dropout_prob
				UpperCAmelCase_	:					int     	=   max_position_embeddings
				UpperCAmelCase_	:					Optional[int]     	=   type_vocab_size
				UpperCAmelCase_	:					List[Any]     	=   type_sequence_label_size
				UpperCAmelCase_	:					Optional[Any]     	=   initializer_range
				UpperCAmelCase_	:					str     	=   num_labels
				UpperCAmelCase_	:					int     	=   num_choices
				UpperCAmelCase_	:					Dict     	=   scope





	def 	_SCREAMING_SNAKE_CASE ( self   :					Optional[int]		)		->     Dict:
				UpperCAmelCase_	:					Optional[Any]     	=   ids_tensor([self.batch_size, self.seq_length]      ,      self.vocab_size		)

				UpperCAmelCase_	:					List[Any]     	=   None
				if self.use_input_mask:
							UpperCAmelCase_	:					int     	=   random_attention_mask([self.batch_size, self.seq_length]		)

				UpperCAmelCase_	:					Dict     	=   None
				if self.use_token_type_ids:
							UpperCAmelCase_	:					Optional[int]     	=   ids_tensor([self.batch_size, self.seq_length]      ,      self.type_vocab_size		)

				UpperCAmelCase_	:					Optional[int]     	=   None
				UpperCAmelCase_	:					List[Any]     	=   None
				UpperCAmelCase_	:					Any     	=   None
				if self.use_labels:
							UpperCAmelCase_	:					List[Any]     	=   ids_tensor([self.batch_size]      ,      self.type_sequence_label_size		)
							UpperCAmelCase_	:					List[str]     	=   ids_tensor([self.batch_size, self.seq_length]      ,      self.num_labels		)
							UpperCAmelCase_	:					int     	=   ids_tensor([self.batch_size]      ,      self.num_choices		)

				UpperCAmelCase_	:					Optional[Any]     	=   self.get_config()

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





	def 	_SCREAMING_SNAKE_CASE ( self   :					Optional[int]		)		->     Dict:
				return OpenLlamaConfig(
				    vocab_size=self.vocab_size      ,      hidden_size=self.hidden_size      ,      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      ,      is_decoder=lowerCAmelCase_      ,      initializer_range=self.initializer_range      ,      use_stable_embedding=lowerCAmelCase_      ,      )





	def 	_SCREAMING_SNAKE_CASE ( self   :					Union[str, Any]      ,      lowerCAmelCase_   :					List[str]      ,      lowerCAmelCase_   :					int      ,      lowerCAmelCase_   :					Optional[Any]      ,      lowerCAmelCase_   :					List[str]      ,      lowerCAmelCase_   :					str      ,      lowerCAmelCase_   :					List[Any]      ,      lowerCAmelCase_   :					Union[str, Any]		)		->     str:
				UpperCAmelCase_	:					str     	=   OpenLlamaModel(config=lowerCAmelCase_		)
				model.to(lowerCAmelCase_		)
				model.eval()
				UpperCAmelCase_	:					Any     	=   model(lowerCAmelCase_      ,      attention_mask=lowerCAmelCase_		)
				UpperCAmelCase_	:					Optional[int]     	=   model(lowerCAmelCase_		)
				self.parent.assertEqual(result.last_hidden_state.shape      ,      (self.batch_size, self.seq_length, self.hidden_size)		)





	def 	_SCREAMING_SNAKE_CASE ( self   :					Union[str, Any]      ,      lowerCAmelCase_   :					List[Any]      ,      lowerCAmelCase_   :					List[Any]      ,      lowerCAmelCase_   :					List[str]      ,      lowerCAmelCase_   :					Optional[int]      ,      lowerCAmelCase_   :					Optional[Any]      ,      lowerCAmelCase_   :					List[str]      ,      lowerCAmelCase_   :					Dict      ,      lowerCAmelCase_   :					Tuple      ,      lowerCAmelCase_   :					Optional[int]      ,      )		->     Tuple:
				UpperCAmelCase_	:					str     	=   True
				UpperCAmelCase_	:					List[Any]     	=   OpenLlamaModel(lowerCAmelCase_		)
				model.to(lowerCAmelCase_		)
				model.eval()
				UpperCAmelCase_	:					int     	=   model(
				    lowerCAmelCase_      ,      attention_mask=lowerCAmelCase_      ,      encoder_hidden_states=lowerCAmelCase_      ,      encoder_attention_mask=lowerCAmelCase_      ,      )
				UpperCAmelCase_	:					Any     	=   model(
				    lowerCAmelCase_      ,      attention_mask=lowerCAmelCase_      ,      encoder_hidden_states=lowerCAmelCase_      ,      )
				UpperCAmelCase_	:					List[str]     	=   model(lowerCAmelCase_      ,      attention_mask=lowerCAmelCase_		)
				self.parent.assertEqual(result.last_hidden_state.shape      ,      (self.batch_size, self.seq_length, self.hidden_size)		)





	def 	_SCREAMING_SNAKE_CASE ( self   :					str      ,      lowerCAmelCase_   :					Optional[int]      ,      lowerCAmelCase_   :					str      ,      lowerCAmelCase_   :					Tuple      ,      lowerCAmelCase_   :					Dict      ,      lowerCAmelCase_   :					int      ,      lowerCAmelCase_   :					Any      ,      lowerCAmelCase_   :					List[Any]      ,      lowerCAmelCase_   :					Union[str, Any]      ,      lowerCAmelCase_   :					Dict      ,      )		->     Any:
				UpperCAmelCase_	:					str     	=   OpenLlamaForCausalLM(config=lowerCAmelCase_		)
				model.to(lowerCAmelCase_		)
				model.eval()
				UpperCAmelCase_	:					str     	=   model(lowerCAmelCase_      ,      attention_mask=lowerCAmelCase_      ,      labels=lowerCAmelCase_		)
				self.parent.assertEqual(result.logits.shape      ,      (self.batch_size, self.seq_length, self.vocab_size)		)





	def 	_SCREAMING_SNAKE_CASE ( self   :					int      ,      lowerCAmelCase_   :					Optional[int]      ,      lowerCAmelCase_   :					List[Any]      ,      lowerCAmelCase_   :					Optional[int]      ,      lowerCAmelCase_   :					List[Any]      ,      lowerCAmelCase_   :					Dict      ,      lowerCAmelCase_   :					List[Any]      ,      lowerCAmelCase_   :					Dict      ,      lowerCAmelCase_   :					Dict      ,      lowerCAmelCase_   :					Any      ,      )		->     Any:
				UpperCAmelCase_	:					Tuple     	=   True
				UpperCAmelCase_	:					Tuple     	=   True
				UpperCAmelCase_	:					Union[str, Any]     	=   OpenLlamaForCausalLM(config=lowerCAmelCase_		)
				model.to(lowerCAmelCase_		)
				model.eval()

				# first forward pass
				UpperCAmelCase_	:					Union[str, Any]     	=   model(
				    lowerCAmelCase_      ,      attention_mask=lowerCAmelCase_      ,      encoder_hidden_states=lowerCAmelCase_      ,      encoder_attention_mask=lowerCAmelCase_      ,      use_cache=lowerCAmelCase_      ,      )
				UpperCAmelCase_	:					int     	=   outputs.past_key_values

				# create hypothetical multiple next token and extent to next_input_ids
				UpperCAmelCase_	:					int     	=   ids_tensor((self.batch_size, 3)      ,      config.vocab_size		)
				UpperCAmelCase_	:					List[str]     	=   ids_tensor((self.batch_size, 3)      ,      vocab_size=2		)

				# append to next input_ids and
				UpperCAmelCase_	:					List[Any]     	=   torch.cat([input_ids, next_tokens]      ,      dim=-1		)
				UpperCAmelCase_	:					List[str]     	=   torch.cat([input_mask, next_mask]      ,      dim=-1		)

				UpperCAmelCase_	:					int     	=   model(
				    lowerCAmelCase_      ,      attention_mask=lowerCAmelCase_      ,      encoder_hidden_states=lowerCAmelCase_      ,      encoder_attention_mask=lowerCAmelCase_      ,      output_hidden_states=lowerCAmelCase_      ,      )["hidden_states"][0]
				UpperCAmelCase_	:					Dict     	=   model(
				    lowerCAmelCase_      ,      attention_mask=lowerCAmelCase_      ,      encoder_hidden_states=lowerCAmelCase_      ,      encoder_attention_mask=lowerCAmelCase_      ,      past_key_values=lowerCAmelCase_      ,      output_hidden_states=lowerCAmelCase_      ,      )["hidden_states"][0]

				# select random slice
				UpperCAmelCase_	:					Optional[Any]     	=   ids_tensor((1,)      ,      output_from_past.shape[-1]		).item()
				UpperCAmelCase_	:					List[Any]     	=   output_from_no_past[:, -3:, random_slice_idx].detach()
				UpperCAmelCase_	:					Tuple     	=   output_from_past[:, :, random_slice_idx].detach()

				self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1]		)

				# test that outputs are equal for slice
				self.parent.assertTrue(torch.allclose(lowerCAmelCase_      ,      lowerCAmelCase_      ,      atol=1e-3		)		)





	def 	_SCREAMING_SNAKE_CASE ( self   :					Any		)		->     Optional[Any]:
				UpperCAmelCase_	:					int     	=   self.prepare_config_and_inputs()
				(
				    (
				    UpperCAmelCase_
				)	,      (
				    UpperCAmelCase_
				)	,      (
				    UpperCAmelCase_
				)	,      (
				    UpperCAmelCase_
				)	,      (
				    UpperCAmelCase_
				)	,      (
				    UpperCAmelCase_
				)	,      (
				    UpperCAmelCase_
				)	,      
				)	:					Optional[int]     	=   config_and_inputs
				UpperCAmelCase_	:					Union[str, Any]     	=   {"input_ids": input_ids, "attention_mask": input_mask}
				return config, inputs_dict







@require_torch
class      UpperCamelCase_			(__A							,		__A							,		__A							,		unittest.TestCase	):
	__magic_name__       =							(
	    (OpenLlamaModel, OpenLlamaForCausalLM, OpenLlamaForSequenceClassification) if is_torch_available() else ()
	)
	__magic_name__       =							(OpenLlamaForCausalLM,) if is_torch_available() else ()
	__magic_name__       =							(
	    {
	        '''feature-extraction''': OpenLlamaModel,
	        '''text-classification''': OpenLlamaForSequenceClassification,
	        '''text-generation''': OpenLlamaForCausalLM,
	        '''zero-shot''': OpenLlamaForSequenceClassification,
	    }
	    if is_torch_available()
	    else {}
	)
	__magic_name__       =							False
	__magic_name__       =							False





	def 	_SCREAMING_SNAKE_CASE ( self   :					List[str]		)		->     Optional[int]:
				UpperCAmelCase_	:					Union[str, Any]     	=   OpenLlamaModelTester(self		)
				UpperCAmelCase_	:					str     	=   ConfigTester(self      ,      config_class=lowerCAmelCase_      ,      hidden_size=37		)





	def 	_SCREAMING_SNAKE_CASE ( self   :					List[Any]		)		->     List[Any]:
				self.config_tester.run_common_tests()





	def 	_SCREAMING_SNAKE_CASE ( self   :					int		)		->     Optional[Any]:
				UpperCAmelCase_	:					Optional[Any]     	=   self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_model(*lowerCAmelCase_		)





	def 	_SCREAMING_SNAKE_CASE ( self   :					Union[str, Any]		)		->     List[Any]:
				UpperCAmelCase_	:					List[str]     	=   self.model_tester.prepare_config_and_inputs()
				for type in ["absolute", "relative_key", "relative_key_query"]:
							UpperCAmelCase_	:					int     	=   type
							self.model_tester.create_and_check_model(*lowerCAmelCase_		)





	def 	_SCREAMING_SNAKE_CASE ( self   :					Any		)		->     Optional[int]:
				UpperCAmelCase_	,      UpperCAmelCase_	:					Union[str, Any]     	=   self.model_tester.prepare_config_and_inputs_for_common()
				UpperCAmelCase_	:					Union[str, Any]     	=   3
				UpperCAmelCase_	:					Tuple     	=   input_dict["input_ids"]
				UpperCAmelCase_	:					Optional[int]     	=   input_ids.ne(1		).to(lowerCAmelCase_		)
				UpperCAmelCase_	:					Any     	=   ids_tensor([self.model_tester.batch_size]      ,      self.model_tester.type_sequence_label_size		)
				UpperCAmelCase_	:					Union[str, Any]     	=   OpenLlamaForSequenceClassification(lowerCAmelCase_		)
				model.to(lowerCAmelCase_		)
				model.eval()
				UpperCAmelCase_	:					Optional[int]     	=   model(lowerCAmelCase_      ,      attention_mask=lowerCAmelCase_      ,      labels=lowerCAmelCase_		)
				self.assertEqual(result.logits.shape      ,      (self.model_tester.batch_size, self.model_tester.num_labels)		)





	def 	_SCREAMING_SNAKE_CASE ( self   :					int		)		->     Dict:
				UpperCAmelCase_	,      UpperCAmelCase_	:					Optional[Any]     	=   self.model_tester.prepare_config_and_inputs_for_common()
				UpperCAmelCase_	:					Optional[Any]     	=   3
				UpperCAmelCase_	:					Optional[Any]     	=   "single_label_classification"
				UpperCAmelCase_	:					Any     	=   input_dict["input_ids"]
				UpperCAmelCase_	:					Any     	=   input_ids.ne(1		).to(lowerCAmelCase_		)
				UpperCAmelCase_	:					List[str]     	=   ids_tensor([self.model_tester.batch_size]      ,      self.model_tester.type_sequence_label_size		)
				UpperCAmelCase_	:					Union[str, Any]     	=   OpenLlamaForSequenceClassification(lowerCAmelCase_		)
				model.to(lowerCAmelCase_		)
				model.eval()
				UpperCAmelCase_	:					Tuple     	=   model(lowerCAmelCase_      ,      attention_mask=lowerCAmelCase_      ,      labels=lowerCAmelCase_		)
				self.assertEqual(result.logits.shape      ,      (self.model_tester.batch_size, self.model_tester.num_labels)		)





	def 	_SCREAMING_SNAKE_CASE ( self   :					int		)		->     List[Any]:
				UpperCAmelCase_	,      UpperCAmelCase_	:					List[str]     	=   self.model_tester.prepare_config_and_inputs_for_common()
				UpperCAmelCase_	:					Union[str, Any]     	=   3
				UpperCAmelCase_	:					str     	=   "multi_label_classification"
				UpperCAmelCase_	:					List[Any]     	=   input_dict["input_ids"]
				UpperCAmelCase_	:					Union[str, Any]     	=   input_ids.ne(1		).to(lowerCAmelCase_		)
				UpperCAmelCase_	:					Any     	=   ids_tensor(
				    [self.model_tester.batch_size, config.num_labels]      ,      self.model_tester.type_sequence_label_size		).to(torch.float		)
				UpperCAmelCase_	:					Dict     	=   OpenLlamaForSequenceClassification(lowerCAmelCase_		)
				model.to(lowerCAmelCase_		)
				model.eval()
				UpperCAmelCase_	:					List[Any]     	=   model(lowerCAmelCase_      ,      attention_mask=lowerCAmelCase_      ,      labels=lowerCAmelCase_		)
				self.assertEqual(result.logits.shape      ,      (self.model_tester.batch_size, self.model_tester.num_labels)		)





	@unittest.skip("Open-Llama buffers include complex numbers, which breaks this test"		)
	def 	_SCREAMING_SNAKE_CASE ( self   :					Tuple		)		->     Optional[Any]:
				pass





	@parameterized.expand([("linear",), ("dynamic",)]		)
	def 	_SCREAMING_SNAKE_CASE ( self   :					Tuple      ,      lowerCAmelCase_   :					int		)		->     Dict:
				UpperCAmelCase_	,      UpperCAmelCase_	:					Optional[Any]     	=   self.model_tester.prepare_config_and_inputs_for_common()
				UpperCAmelCase_	:					Any     	=   ids_tensor([1, 10]      ,      config.vocab_size		)
				UpperCAmelCase_	:					Optional[int]     	=   ids_tensor([1, int(config.max_position_embeddings * 1.5		)]      ,      config.vocab_size		)

				set_seed(42		)  # Fixed seed at init time so the two models get the same random weights
				UpperCAmelCase_	:					int     	=   OpenLlamaModel(lowerCAmelCase_		)
				original_model.to(lowerCAmelCase_		)
				original_model.eval()
				UpperCAmelCase_	:					List[Any]     	=   original_model(lowerCAmelCase_		).last_hidden_state
				UpperCAmelCase_	:					Any     	=   original_model(lowerCAmelCase_		).last_hidden_state

				set_seed(42		)  # Fixed seed at init time so the two models get the same random weights
				UpperCAmelCase_	:					Any     	=   {"type": scaling_type, "factor": 1_0.0}
				UpperCAmelCase_	:					str     	=   OpenLlamaModel(lowerCAmelCase_		)
				scaled_model.to(lowerCAmelCase_		)
				scaled_model.eval()
				UpperCAmelCase_	:					Optional[int]     	=   scaled_model(lowerCAmelCase_		).last_hidden_state
				UpperCAmelCase_	:					Tuple     	=   scaled_model(lowerCAmelCase_		).last_hidden_state

				# Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original
				# maximum sequence length, so the outputs for the short input should match.
				if scaling_type == "dynamic":
							self.assertTrue(torch.allclose(lowerCAmelCase_      ,      lowerCAmelCase_      ,      atol=1e-5		)		)
				else:
							self.assertFalse(torch.allclose(lowerCAmelCase_      ,      lowerCAmelCase_      ,      atol=1e-5		)		)

				# The output should be different for long inputs
				self.assertFalse(torch.allclose(lowerCAmelCase_      ,      lowerCAmelCase_      ,      atol=1e-5		)		)










import numpy as np
import qiskit



def 						A_							(	_lowerCAmelCase = 8				,  _lowerCAmelCase = None	)		->					str:
 UpperCamelCase      :   Tuple			      =  np.random.default_rng(seed=_lowerCAmelCase	)

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

 # Quantum Circuit to simulate BB84
 UpperCamelCase      :   List[Any]			      =  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.
 UpperCamelCase      :   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.
 UpperCamelCase      :   Tuple			      =  qiskit.execute(_lowerCAmelCase				,  _lowerCAmelCase				,  shots=1				,  seed_simulator=_lowerCAmelCase	)
 # Returns the result of measurement.
 UpperCamelCase      :   Optional[Any]			      =  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.
 UpperCamelCase      :   Tuple			      =  "".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.
 UpperCamelCase      :   Tuple			      =  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()
