




from __future__ import annotations

import unittest

from transformers import CTRLConfig, is_tf_available
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
       import tensorflow as tf

       from transformers.models.ctrl.modeling_tf_ctrl import (
           TF_CTRL_PRETRAINED_MODEL_ARCHIVE_LIST,
           TFCTRLForSequenceClassification,
           TFCTRLLMHeadModel,
           TFCTRLModel,
       )




class 		UpperCamelCase__     (lowerCAmelCase__					):

    '''simple docstring'''



    def __init__(   self					,  UpperCamelCase__					,  )					->				Optional[int]:
           lowerCamelCase       :				Optional[Any]      			= parent
           lowerCamelCase       :				int      			= 13
           lowerCamelCase       :				int      			= 7
           lowerCamelCase       :				str      			= True
           lowerCamelCase       :				Dict      			= True
           lowerCamelCase       :				Dict      			= True
           lowerCamelCase       :				Union[str, Any]      			= True
           lowerCamelCase       :				str      			= True
           lowerCamelCase       :				List[Any]      			= 99
           lowerCamelCase       :				Optional[int]      			= 32
           lowerCamelCase       :				List[str]      			= 2
           lowerCamelCase       :				Tuple      			= 4
           lowerCamelCase       :				str      			= 37
           lowerCamelCase       :				List[str]      			= "gelu"
           lowerCamelCase       :				str      			= 0.1
           lowerCamelCase       :				List[str]      			= 0.1
           lowerCamelCase       :				Optional[Any]      			= 512
           lowerCamelCase       :				str      			= 16
           lowerCamelCase       :				Dict      			= 2
           lowerCamelCase       :				Union[str, Any]      			= 0.02
           lowerCamelCase       :				int      			= 3
           lowerCamelCase       :				Optional[int]      			= 4
           lowerCamelCase       :				Union[str, Any]      			= None
           lowerCamelCase       :				Tuple      			= self.vocab_size - 1







    def    _lowercase					(   self					)					->				Dict:
           lowerCamelCase       :				Dict      			= ids_tensor([self.batch_size, self.seq_length]					,  self.vocab_size					)

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

           lowerCamelCase       :				Optional[Any]      			= None
           if self.use_token_type_ids:
                  lowerCamelCase       :				Tuple      			= ids_tensor([self.batch_size, self.seq_length]					,  self.type_vocab_size					)

           lowerCamelCase       :				Optional[Any]      			= None
           if self.use_mc_token_ids:
                  lowerCamelCase       :				Tuple      			= ids_tensor([self.batch_size, self.num_choices]					,  self.seq_length					)

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

           lowerCamelCase       :				Union[str, Any]      			= CTRLConfig(
               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					,  pad_token_id=self.pad_token_id					,  )

           lowerCamelCase       :				Union[str, Any]      			= ids_tensor([self.num_hidden_layers, self.num_attention_heads]					,  2					)

           return (
               config,
               input_ids,
               input_mask,
               head_mask,
               token_type_ids,
               mc_token_ids,
               sequence_labels,
               token_labels,
               choice_labels,
           )







    def    _lowercase					(   self					,  UpperCamelCase__					,  UpperCamelCase__					,  UpperCamelCase__					,  UpperCamelCase__					,  UpperCamelCase__					,  *UpperCamelCase__					)					->				Dict:
           lowerCamelCase       :				int      			= TFCTRLModel(config=UpperCamelCase__					)
           lowerCamelCase       :				Optional[Any]      			= {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}
           lowerCamelCase       :				Tuple      			= model(UpperCamelCase__					)

           lowerCamelCase       :				List[str]      			= [input_ids, None, input_mask]  # None is the input for 'past'
           lowerCamelCase       :				Tuple      			= model(UpperCamelCase__					)

           lowerCamelCase       :				Optional[Any]      			= model(UpperCamelCase__					)

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







    def    _lowercase					(   self					,  UpperCamelCase__					,  UpperCamelCase__					,  UpperCamelCase__					,  UpperCamelCase__					,  UpperCamelCase__					,  *UpperCamelCase__					)					->				Tuple:
           lowerCamelCase       :				Any      			= TFCTRLLMHeadModel(config=UpperCamelCase__					)
           lowerCamelCase       :				Dict      			= {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}
           lowerCamelCase       :				Any      			= model(UpperCamelCase__					)
           self.parent.assertEqual(result.logits.shape					,  (self.batch_size, self.seq_length, self.vocab_size)					)







    def    _lowercase					(   self					,  UpperCamelCase__					,  UpperCamelCase__					,  UpperCamelCase__					,  UpperCamelCase__					,  UpperCamelCase__					,  *UpperCamelCase__					)					->				Tuple:
           lowerCamelCase       :				List[Any]      			= self.num_labels
           lowerCamelCase       :				Any      			= ids_tensor([self.batch_size]					,  self.type_sequence_label_size					)
           lowerCamelCase       :				Tuple      			= {
               "input_ids": input_ids,
               "token_type_ids": token_type_ids,
               "labels": sequence_labels,
           }
           lowerCamelCase       :				Union[str, Any]      			= TFCTRLForSequenceClassification(UpperCamelCase__					)
           lowerCamelCase       :				Tuple      			= model(UpperCamelCase__					)
           self.parent.assertEqual(result.logits.shape					,  (self.batch_size, self.num_labels)					)







    def    _lowercase					(   self					)					->				List[str]:
           lowerCamelCase       :				Optional[Any]      			= self.prepare_config_and_inputs()

           (
               (
               lowerCamelCase
           )			,				(
               lowerCamelCase
           )			,				(
               lowerCamelCase
           )			,				(
               lowerCamelCase
           )			,				(
               lowerCamelCase
           )			,				(
               lowerCamelCase
           )			,				(
               lowerCamelCase
           )			,				(
               lowerCamelCase
           )			,				(
               lowerCamelCase
           )			,				
           )       :				Tuple      			= config_and_inputs

           lowerCamelCase       :				Tuple      			= {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask}
           return config, inputs_dict




@require_tf
class 		UpperCamelCase__     (lowerCAmelCase__   ,    lowerCAmelCase__   ,    unittest.TestCase					):

    '''simple docstring'''



    lowerCamelCase_				:     int     					=				(TFCTRLModel, TFCTRLLMHeadModel, TFCTRLForSequenceClassification) if is_tf_available() else ()
    lowerCamelCase_				:     Any     					=				(TFCTRLLMHeadModel,) if is_tf_available() else ()
    lowerCamelCase_				:     Union[str, Any]     					=				(
        {
            """feature-extraction""": TFCTRLModel,
            """text-classification""": TFCTRLForSequenceClassification,
            """text-generation""": TFCTRLLMHeadModel,
            """zero-shot""": TFCTRLForSequenceClassification,
        }
        if is_tf_available()
        else {}
    )
    lowerCamelCase_				:     Any     					=				False
    lowerCamelCase_				:     List[Any]     					=				False







    def    _lowercase					(   self					,  UpperCamelCase__					,  UpperCamelCase__					,  UpperCamelCase__					,  UpperCamelCase__					,  UpperCamelCase__					)					->				List[Any]:
           if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests":
                  # Get `tokenizer does not have a padding token` error for both fast/slow tokenizers.
                  # `CTRLConfig` was never used in pipeline tests, either because of a missing checkpoint or because a tiny
                  # config could not be created.
                  return True

           return False







    def    _lowercase					(   self					)					->				str:
           lowerCamelCase       :				Union[str, Any]      			= TFCTRLModelTester(self					)
           lowerCamelCase       :				int      			= ConfigTester(self					,  config_class=UpperCamelCase__					,  n_embd=37					)







    def    _lowercase					(   self					)					->				Optional[int]:
           self.config_tester.run_common_tests()







    def    _lowercase					(   self					)					->				List[Any]:
           lowerCamelCase       :				Tuple      			= self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_ctrl_model(*UpperCamelCase__					)







    def    _lowercase					(   self					)					->				List[str]:
           lowerCamelCase       :				Dict      			= self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_ctrl_lm_head(*UpperCamelCase__					)







    def    _lowercase					(   self					)					->				List[str]:
           lowerCamelCase       :				Tuple      			= self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_ctrl_for_sequence_classification(*UpperCamelCase__					)







    def    _lowercase					(   self					)					->				List[str]:
           lowerCamelCase			,				lowerCamelCase       :				List[str]      			= self.model_tester.prepare_config_and_inputs_for_common()
           lowerCamelCase       :				Union[str, Any]      			= [TFCTRLLMHeadModel]
           lowerCamelCase       :				int      			= [TFCTRLForSequenceClassification]

           for model_class in self.all_model_classes:
                  lowerCamelCase       :				List[Any]      			= model_class(UpperCamelCase__					)
                  model.build()  # may be needed for the get_bias() call below
                  assert isinstance(model.get_input_embeddings()					,  tf.keras.layers.Layer					)

                  if model_class in list_lm_models:
                         lowerCamelCase       :				List[str]      			= model.get_output_embeddings()
                         assert isinstance(UpperCamelCase__					,  tf.keras.layers.Layer					)
                         lowerCamelCase       :				Dict      			= model.get_bias()
                         assert isinstance(UpperCamelCase__					,  UpperCamelCase__					)
                         for k, v in name.items():
                                assert isinstance(UpperCamelCase__					,  tf.Variable					)
                  elif model_class in list_other_models_with_output_ebd:
                         lowerCamelCase       :				Dict      			= model.get_output_embeddings()
                         assert isinstance(UpperCamelCase__					,  tf.keras.layers.Layer					)
                         lowerCamelCase       :				Any      			= model.get_bias()
                         assert name is None
                  else:
                         lowerCamelCase       :				List[str]      			= model.get_output_embeddings()
                         assert x is None
                         lowerCamelCase       :				Any      			= model.get_bias()
                         assert name is None







    @slow
    def    _lowercase					(   self					)					->				Optional[Any]:
           for model_name in TF_CTRL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                  lowerCamelCase       :				Optional[Any]      			= TFCTRLModel.from_pretrained(UpperCamelCase__					)
                  self.assertIsNotNone(UpperCamelCase__					)




@require_tf
class 		UpperCamelCase__     (unittest.TestCase					):

    '''simple docstring'''



    @slow
    def    _lowercase					(   self					)					->				Dict:
           lowerCamelCase       :				Optional[int]      			= TFCTRLLMHeadModel.from_pretrained("ctrl"					)
           lowerCamelCase       :				List[str]      			= tf.convert_to_tensor([[1_1859, 0, 1611, 8]]					,  dtype=tf.intaa					)  # Legal the president is
           lowerCamelCase       :				int      			= [
               1_1859,
               0,
               1611,
               8,
               5,
               150,
               2_6449,
               2,
               19,
               348,
               469,
               3,
               2595,
               48,
               2_0740,
               24_6533,
               24_6533,
               19,
               30,
               5,
           ]  # Legal the president is a good guy and I don't want to lose my job. \n \n I have a

           lowerCamelCase       :				Optional[Any]      			= model.generate(UpperCamelCase__					,  do_sample=UpperCamelCase__					)
           self.assertListEqual(output_ids[0].numpy().tolist()					,  UpperCamelCase__					)












import numpy as np
import qiskit

def 					A				(				_SCREAMING_SNAKE_CASE			,_SCREAMING_SNAKE_CASE   )     ->			qiskit.QuantumCircuit:
       lowerCamelCase       :				Optional[int]      			= qiskit.QuantumCircuit(num_qubits + 1   )

       # First, let's deal with the case in which oracle is balanced
       if case == "balanced":
              # First generate a random number that tells us which CNOTs to
              # wrap in X-gates:
              lowerCamelCase       :				Optional[int]      			= np.random.randint(1			,2**num_qubits   )
              # Next, format 'b' as a binary string of length 'n', padded with zeros:
              lowerCamelCase       :				str      			= format(_SCREAMING_SNAKE_CASE			,f'''0{num_qubits}b'''   )
              # Next, we place the first X-gates. Each digit in our binary string
              # corresponds to a qubit, if the digit is 0, we do nothing, if it's 1
              # we apply an X-gate to that qubit:
              for index, bit in enumerate(_SCREAMING_SNAKE_CASE   ):
                     if bit == "1":
                            oracle_qc.x(_SCREAMING_SNAKE_CASE   )
        # Do the controlled-NOT gates for each qubit, using the output qubit
        # as the target:
              for index in range(_SCREAMING_SNAKE_CASE   ):
                     oracle_qc.cx(_SCREAMING_SNAKE_CASE			,_SCREAMING_SNAKE_CASE   )
              # Next, place the final X-gates
              for index, bit in enumerate(_SCREAMING_SNAKE_CASE   ):
                     if bit == "1":
                            oracle_qc.x(_SCREAMING_SNAKE_CASE   )

    # Case in which oracle is constant
       if case == "constant":
              # First decide what the fixed output of the oracle will be
              # (either always 0 or always 1)
              lowerCamelCase       :				str      			= np.random.randint(2   )
              if output == 1:
                     oracle_qc.x(_SCREAMING_SNAKE_CASE   )

       lowerCamelCase       :				int      			= oracle_qc.to_gate()
       lowerCamelCase       :				Tuple      			= "Oracle"  # To show when we display the circuit
       return oracle_gate

def 					A				(				_SCREAMING_SNAKE_CASE			,_SCREAMING_SNAKE_CASE   )     ->			qiskit.QuantumCircuit:
       lowerCamelCase       :				Union[str, Any]      			= qiskit.QuantumCircuit(num_qubits + 1			,_SCREAMING_SNAKE_CASE   )
       # Set up the output qubit:
       dj_circuit.x(_SCREAMING_SNAKE_CASE   )
       dj_circuit.h(_SCREAMING_SNAKE_CASE   )
       # And set up the input register:
       for qubit in range(_SCREAMING_SNAKE_CASE   ):
              dj_circuit.h(_SCREAMING_SNAKE_CASE   )
       # Let's append the oracle gate to our circuit:
       dj_circuit.append(_SCREAMING_SNAKE_CASE			,range(num_qubits + 1   )   )
       # Finally, perform the H-gates again and measure:
       for qubit in range(_SCREAMING_SNAKE_CASE   ):
              dj_circuit.h(_SCREAMING_SNAKE_CASE   )

       for i in range(_SCREAMING_SNAKE_CASE   ):
              dj_circuit.measure(_SCREAMING_SNAKE_CASE			,_SCREAMING_SNAKE_CASE   )

       return dj_circuit

def 					A				(				_SCREAMING_SNAKE_CASE			,_SCREAMING_SNAKE_CASE   )     ->			qiskit.result.counts.Counts:
       lowerCamelCase       :				Tuple      			= qiskit.Aer.get_backend("aer_simulator"   )

       lowerCamelCase       :				Tuple      			= dj_oracle(_SCREAMING_SNAKE_CASE			,_SCREAMING_SNAKE_CASE   )
       lowerCamelCase       :				List[Any]      			= dj_algorithm(_SCREAMING_SNAKE_CASE			,_SCREAMING_SNAKE_CASE   )

       # Execute the circuit on the simulator
       lowerCamelCase       :				List[Any]      			= qiskit.execute(_SCREAMING_SNAKE_CASE			,_SCREAMING_SNAKE_CASE			,shots=1000   )

       # Return the histogram data of the results of the experiment.
       return job.result().get_counts(_SCREAMING_SNAKE_CASE   )


if __name__ == "__main__":
       print(f'''Deutsch Jozsa - Constant Oracle: {deutsch_jozsa("constant", 3)}''')
       print(f'''Deutsch Jozsa - Balanced Oracle: {deutsch_jozsa("balanced", 3)}''')






