



import tempfile
import unittest

import numpy as np

import transformers
from transformers import GPTaTokenizer, GPTJConfig, is_flax_available, is_torch_available
from transformers.testing_utils import is_pt_flax_cross_test, require_flax, tooslow

from ...generation.test_flax_utils import FlaxGenerationTesterMixin
from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask


if is_flax_available():
	import jax
	import jax.numpy as jnp

	from transformers.modeling_flax_pytorch_utils import (
	    convert_pytorch_state_dict_to_flax,
	    load_flax_weights_in_pytorch_model,
	)
	from transformers.models.gptj.modeling_flax_gptj import FlaxGPTJForCausalLM, FlaxGPTJModel

if is_torch_available():
	import torch





class 					__lowerCAmelCase :




				def __init__(							self						,				_snake_case						,				_snake_case=14						,				_snake_case=7						,				_snake_case=True						,				_snake_case=True						,				_snake_case=False						,				_snake_case=True						,				_snake_case=99						,				_snake_case=32						,				_snake_case=4						,				_snake_case=4						,				_snake_case=4						,				_snake_case=37						,				_snake_case="gelu"						,				_snake_case=0.1						,				_snake_case=0.1						,				_snake_case=512						,				_snake_case=0.02						,				):



									"""simple docstring"""





									_lowerCAmelCase						=    parent
									_lowerCAmelCase						=    batch_size
									_lowerCAmelCase						=    seq_length
									_lowerCAmelCase						=    is_training
									_lowerCAmelCase						=    use_input_mask
									_lowerCAmelCase						=    use_token_type_ids
									_lowerCAmelCase						=    use_labels
									_lowerCAmelCase						=    vocab_size
									_lowerCAmelCase						=    hidden_size
									_lowerCAmelCase						=    rotary_dim
									_lowerCAmelCase						=    num_hidden_layers
									_lowerCAmelCase						=    num_attention_heads
									_lowerCAmelCase						=    intermediate_size
									_lowerCAmelCase						=    hidden_act
									_lowerCAmelCase						=    hidden_dropout_prob
									_lowerCAmelCase						=    attention_probs_dropout_prob
									_lowerCAmelCase						=    max_position_embeddings
									_lowerCAmelCase						=    initializer_range
									_lowerCAmelCase						=    None
									_lowerCAmelCase						=    vocab_size - 1
									_lowerCAmelCase						=    vocab_size - 1
									_lowerCAmelCase						=    vocab_size - 1




				def 							snake_case   (							self		):



									"""simple docstring"""





									_lowerCAmelCase						=    ids_tensor([self.batch_size, self.seq_length]						,				self.vocab_size		)

									_lowerCAmelCase						=    None
									if self.use_input_mask:
														_lowerCAmelCase						=    random_attention_mask([self.batch_size, self.seq_length]		)

									_lowerCAmelCase						=    GPTJConfig(
									    vocab_size=self.vocab_size						,				n_embd=self.hidden_size						,				n_layer=self.num_hidden_layers						,				n_head=self.num_attention_heads						,				n_positions=self.max_position_embeddings						,				use_cache=_snake_case						,				bos_token_id=self.bos_token_id						,				eos_token_id=self.eos_token_id						,				pad_token_id=self.pad_token_id						,				rotary_dim=self.rotary_dim						,				)

									return (config, input_ids, input_mask)




				def 							snake_case   (							self		):



									"""simple docstring"""





									_lowerCAmelCase						=    self.prepare_config_and_inputs()
									_lowerCAmelCase	,	_lowerCAmelCase	,	_lowerCAmelCase						=    config_and_inputs
									_lowerCAmelCase						=    {"""input_ids""": input_ids, """attention_mask""": attention_mask}
									return config, inputs_dict




				def 							snake_case   (							self						,				_snake_case						,				_snake_case						,				_snake_case						,				_snake_case		):



									"""simple docstring"""





									_lowerCAmelCase						=    20
									_lowerCAmelCase						=    model_class_name(_snake_case		)

									_lowerCAmelCase						=    model.init_cache(input_ids.shape[0]						,				_snake_case		)
									_lowerCAmelCase						=    jnp.ones((input_ids.shape[0], max_decoder_length)						,				dtype="""i4"""		)

									_lowerCAmelCase						=    jnp.broadcast_to(
									    jnp.arange(input_ids.shape[-1] - 1		)[None, :]						,				(input_ids.shape[0], input_ids.shape[-1] - 1)		)
									_lowerCAmelCase						=    model(
									    input_ids[:, :-1]						,				attention_mask=_snake_case						,				past_key_values=_snake_case						,				position_ids=_snake_case						,				)

									_lowerCAmelCase						=    jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]]						,				dtype="""i4"""		)
									_lowerCAmelCase						=    model(
									    input_ids[:, -1:]						,				attention_mask=_snake_case						,				past_key_values=outputs_cache.past_key_values						,				position_ids=_snake_case						,				)

									_lowerCAmelCase						=    model(_snake_case		)

									_lowerCAmelCase						=    np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])		)		)
									self.parent.assertTrue(diff < 1e-3						,				msg=F'Max diff is {diff}'		)




				def 							snake_case   (							self						,				_snake_case						,				_snake_case						,				_snake_case						,				_snake_case		):



									"""simple docstring"""





									_lowerCAmelCase						=    20
									_lowerCAmelCase						=    model_class_name(_snake_case		)

									_lowerCAmelCase						=    jnp.concatenate(
									    [attention_mask, jnp.zeros((attention_mask.shape[0], max_decoder_length - attention_mask.shape[1])		)]						,				axis=-1						,				)

									_lowerCAmelCase						=    model.init_cache(input_ids.shape[0]						,				_snake_case		)
									_lowerCAmelCase						=    jnp.broadcast_to(
									    jnp.arange(input_ids.shape[-1] - 1		)[None, :]						,				(input_ids.shape[0], input_ids.shape[-1] - 1)		)

									_lowerCAmelCase						=    model(
									    input_ids[:, :-1]						,				attention_mask=_snake_case						,				past_key_values=_snake_case						,				position_ids=_snake_case						,				)
									_lowerCAmelCase						=    jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]]						,				dtype="""i4"""		)
									_lowerCAmelCase						=    model(
									    input_ids[:, -1:]						,				past_key_values=outputs_cache.past_key_values						,				attention_mask=_snake_case						,				position_ids=_snake_case						,				)

									_lowerCAmelCase						=    model(_snake_case						,				attention_mask=_snake_case		)

									_lowerCAmelCase						=    np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])		)		)
									self.parent.assertTrue(diff < 1e-3						,				msg=F'Max diff is {diff}'		)





@require_flax
class 					__lowerCAmelCase (     lowerCamelCase__       ,						lowerCamelCase__       ,						unittest.TestCase       ):
				__lowerCamelCase =				(FlaxGPTJModel, FlaxGPTJForCausalLM) if is_flax_available() else ()
				__lowerCamelCase =				(FlaxGPTJForCausalLM,) if is_flax_available() else ()




				def 							snake_case   (							self		):



									"""simple docstring"""





									_lowerCAmelCase						=    FlaxGPTJModelTester(self		)




				def 							snake_case   (							self		):



									"""simple docstring"""





									for model_class_name in self.all_model_classes:
														_lowerCAmelCase	,	_lowerCAmelCase	,	_lowerCAmelCase						=    self.model_tester.prepare_config_and_inputs()
														self.model_tester.check_use_cache_forward(_snake_case						,				_snake_case						,				_snake_case						,				_snake_case		)




				def 							snake_case   (							self		):



									"""simple docstring"""





									for model_class_name in self.all_model_classes:
														_lowerCAmelCase	,	_lowerCAmelCase	,	_lowerCAmelCase						=    self.model_tester.prepare_config_and_inputs()
														self.model_tester.check_use_cache_forward_with_attn_mask(
														    _snake_case						,				_snake_case						,				_snake_case						,				_snake_case		)




				@tooslow
				def 							snake_case   (							self		):



									"""simple docstring"""





									_lowerCAmelCase						=    GPTaTokenizer.from_pretrained("""gpt2"""						,				pad_token="""<|endoftext|>"""						,				padding_side="""left"""		)
									_lowerCAmelCase						=    tokenizer(["""Hello this is a long string""", """Hey"""]						,				return_tensors="""np"""						,				padding=_snake_case						,				truncation=_snake_case		)

									_lowerCAmelCase						=    FlaxGPTJForCausalLM.from_pretrained("""EleutherAI/gpt-j-6B"""		)
									_lowerCAmelCase						=    False
									_lowerCAmelCase						=    model.config.eos_token_id

									_lowerCAmelCase						=    jax.jit(model.generate		)

									_lowerCAmelCase						=    jit_generate(
									    inputs["""input_ids"""]						,				attention_mask=inputs["""attention_mask"""]						,				pad_token_id=tokenizer.pad_token_id		).sequences

									_lowerCAmelCase						=    tokenizer.batch_decode(_snake_case						,				skip_special_tokens=_snake_case		)

									_lowerCAmelCase						=    [
									    """Hello this is a long string of text.\n\nI'm trying to get the text of the""",
									    """Hey, I'm a little late to the party. I'm going to""",
									]

									self.assertListEqual(_snake_case						,				_snake_case		)




				@is_pt_flax_cross_test
				def 							snake_case   (							self		):



									"""simple docstring"""





									_lowerCAmelCase	,	_lowerCAmelCase						=    self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
														with self.subTest(model_class.__name__		):
																			# prepare inputs
																			_lowerCAmelCase						=    self._prepare_for_class(_snake_case						,				_snake_case		)
																			_lowerCAmelCase						=    {k: torch.tensor(v.tolist()		) for k, v in prepared_inputs_dict.items()}

																			# load corresponding PyTorch class
																			_lowerCAmelCase						=    model_class.__name__[4:]  # Skip the "Flax" at the beginning
																			_lowerCAmelCase						=    getattr(_snake_case						,				_snake_case		)

																			_lowerCAmelCase	,	_lowerCAmelCase						=    pt_inputs["""input_ids"""].shape
																			_lowerCAmelCase						=    np.random.randint(0						,				seq_length - 1						,				size=(batch_size,)		)
																			for batch_idx, start_index in enumerate(_snake_case		):
																								_lowerCAmelCase						=    0
																								_lowerCAmelCase						=    1
																								_lowerCAmelCase						=    0
																								_lowerCAmelCase						=    1
																			_lowerCAmelCase						=    pt_model_class(_snake_case		).eval()
																			_lowerCAmelCase						=    model_class(_snake_case						,				dtype=jnp.floataa		)

																			_lowerCAmelCase						=    convert_pytorch_state_dict_to_flax(pt_model.state_dict()						,				_snake_case		)
																			_lowerCAmelCase						=    fx_state

																			with torch.no_grad():
																								_lowerCAmelCase						=    pt_model(**_snake_case		).to_tuple()

																			_lowerCAmelCase						=    fx_model(**_snake_case		).to_tuple()
																			self.assertEqual(len(_snake_case		)						,				len(_snake_case		)						,				"""Output lengths differ between Flax and PyTorch"""		)
																			for fx_output, pt_output in zip(_snake_case						,				_snake_case		):
																								self.assert_almost_equals(fx_output[:, -1]						,				pt_output[:, -1].numpy()						,				4e-2		)

																			with tempfile.TemporaryDirectory() as tmpdirname:
																								pt_model.save_pretrained(_snake_case		)
																								_lowerCAmelCase						=    model_class.from_pretrained(_snake_case						,				from_pt=_snake_case		)

																			_lowerCAmelCase						=    fx_model_loaded(**_snake_case		).to_tuple()
																			self.assertEqual(
																			    len(_snake_case		)						,				len(_snake_case		)						,				"""Output lengths differ between Flax and PyTorch"""		)
																			for fx_output_loaded, pt_output in zip(_snake_case						,				_snake_case		):
																								self.assert_almost_equals(fx_output_loaded[:, -1]						,				pt_output[:, -1].numpy()						,				4e-2		)




				@is_pt_flax_cross_test
				def 							snake_case   (							self		):



									"""simple docstring"""





									_lowerCAmelCase	,	_lowerCAmelCase						=    self.model_tester.prepare_config_and_inputs_for_common()
									for model_class in self.all_model_classes:
														with self.subTest(model_class.__name__		):
																			# prepare inputs
																			_lowerCAmelCase						=    self._prepare_for_class(_snake_case						,				_snake_case		)
																			_lowerCAmelCase						=    {k: torch.tensor(v.tolist()		) for k, v in prepared_inputs_dict.items()}

																			# load corresponding PyTorch class
																			_lowerCAmelCase						=    model_class.__name__[4:]  # Skip the "Flax" at the beginning
																			_lowerCAmelCase						=    getattr(_snake_case						,				_snake_case		)

																			_lowerCAmelCase						=    pt_model_class(_snake_case		).eval()
																			_lowerCAmelCase						=    model_class(_snake_case						,				dtype=jnp.floataa		)

																			_lowerCAmelCase						=    load_flax_weights_in_pytorch_model(_snake_case						,				fx_model.params		)
																			_lowerCAmelCase	,	_lowerCAmelCase						=    pt_inputs["""input_ids"""].shape
																			_lowerCAmelCase						=    np.random.randint(0						,				seq_length - 1						,				size=(batch_size,)		)
																			for batch_idx, start_index in enumerate(_snake_case		):
																								_lowerCAmelCase						=    0
																								_lowerCAmelCase						=    1
																								_lowerCAmelCase						=    0
																								_lowerCAmelCase						=    1

																			# make sure weights are tied in PyTorch
																			pt_model.tie_weights()

																			with torch.no_grad():
																								_lowerCAmelCase						=    pt_model(**_snake_case		).to_tuple()

																			_lowerCAmelCase						=    fx_model(**_snake_case		).to_tuple()
																			self.assertEqual(len(_snake_case		)						,				len(_snake_case		)						,				"""Output lengths differ between Flax and PyTorch"""		)
																			for fx_output, pt_output in zip(_snake_case						,				_snake_case		):
																								self.assert_almost_equals(fx_output[:, -1]						,				pt_output[:, -1].numpy()						,				4e-2		)

																			with tempfile.TemporaryDirectory() as tmpdirname:
																								fx_model.save_pretrained(_snake_case		)
																								_lowerCAmelCase						=    pt_model_class.from_pretrained(_snake_case						,				from_flax=_snake_case		)

																			with torch.no_grad():
																								_lowerCAmelCase						=    pt_model_loaded(**_snake_case		).to_tuple()

																			self.assertEqual(
																			    len(_snake_case		)						,				len(_snake_case		)						,				"""Output lengths differ between Flax and PyTorch"""		)
																			for fx_output, pt_output in zip(_snake_case						,				_snake_case		):
																								self.assert_almost_equals(fx_output[:, -1]						,				pt_output[:, -1].numpy()						,				4e-2		)




				@tooslow
				def 							snake_case   (							self		):



									"""simple docstring"""





									for model_class_name in self.all_model_classes:
														_lowerCAmelCase						=    model_class_name.from_pretrained("""EleutherAI/gpt-j-6B"""		)
														_lowerCAmelCase						=    model(np.ones((1, 1)		)		)
														self.assertIsNotNone(_snake_case		)










'''simple docstring'''




import math

import qiskit






def        _lowerCAmelCase			(  __snake_case  : int = 1 ,							__snake_case  : int = 1 ,							__snake_case  : int = 1			)     ->     qiskit.result.counts.Counts:
     if (
         isinstance(__snake_case ,							__snake_case			)
         or isinstance(__snake_case ,							__snake_case			)
         or isinstance(__snake_case ,							__snake_case			)
     ):
          raise TypeError('inputs must be integers.'			)

     if (input_a < 0) or (input_a < 0) or (carry_in < 0):
          raise ValueError('inputs must be positive.'			)

     if (
         (math.floor(__snake_case			) != input_a)
         or (math.floor(__snake_case			) != input_a)
         or (math.floor(__snake_case			) != carry_in)
     ):
          raise ValueError('inputs must be exact integers.'			)

     if (input_a > 2) or (input_a > 2) or (carry_in > 2):
          raise ValueError('inputs must be less or equal to 2.'			)

     # build registers
     __A						: int      =       qiskit.QuantumRegister(4 ,							'qr'			)
     __A						: Optional[int]      =       qiskit.ClassicalRegister(2 ,							'cr'			)
     # list the entries
     __A						: Union[str, Any]      =       [input_a, input_a, carry_in]

     __A						: Dict      =       qiskit.QuantumCircuit(__snake_case ,							__snake_case			)

     for i in range(0 ,							3			):
          if entry[i] == 2:
               quantum_circuit.h(__snake_case			)  # for hadamard entries
          elif entry[i] == 1:
               quantum_circuit.x(__snake_case			)  # for 1 entries
          elif entry[i] == 0:
               quantum_circuit.i(__snake_case			)  # for 0 entries

    # build the circuit
     quantum_circuit.ccx(0 ,							1 ,							3			)  # ccx = toffoli gate
     quantum_circuit.cx(0 ,							1			)
     quantum_circuit.ccx(1 ,							2 ,							3			)
     quantum_circuit.cx(1 ,							2			)
     quantum_circuit.cx(0 ,							1			)

     quantum_circuit.measure([2, 3] ,							__snake_case			)  # measure the last two qbits

     __A						: str      =       qiskit.Aer.get_backend('aer_simulator'			)
     __A						: Any      =       qiskit.execute(__snake_case ,							__snake_case ,							shots=10_00			)

     return job.result().get_counts(__snake_case			)


if __name__ == "__main__":
  print(f"""Total sum count for state is: {quantum_full_adder(1, 1, 1)}""")