
'''simple docstring'''







import numpy as np
import qiskit







def   lowerCAmelCase(  a__    :  str      , a__    :  int      ):







       '''simple docstring'''






       lowerCamelCase__				   =      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__				   =      np.random.randint(1      , 2**num_qubits      )
              # Next, format 'b' as a binary string of length 'n', padded with zeros:
              lowerCamelCase__				   =      format(a__      , 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(a__      ):
                     if bit == "1":
                            oracle_qc.x(a__      )
        # Do the controlled-NOT gates for each qubit, using the output qubit
        # as the target:
              for index in range(a__      ):
                     oracle_qc.cx(a__      , a__      )
              # Next, place the final X-gates
              for index, bit in enumerate(a__      ):
                     if bit == "1":
                            oracle_qc.x(a__      )

    # 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__				   =      np.random.randint(2      )
              if output == 1:
                     oracle_qc.x(a__      )

       lowerCamelCase__				   =      oracle_qc.to_gate()
       lowerCamelCase__				   =      "Oracle"  # To show when we display the circuit
       return oracle_gate







def   lowerCAmelCase(  a__    :  qiskit.QuantumCircuit      , a__    :  int      ):







       '''simple docstring'''






       lowerCamelCase__				   =      qiskit.QuantumCircuit(num_qubits + 1      , a__      )
       # Set up the output qubit:
       dj_circuit.x(a__      )
       dj_circuit.h(a__      )
       # And set up the input register:
       for qubit in range(a__      ):
              dj_circuit.h(a__      )
       # Let's append the oracle gate to our circuit:
       dj_circuit.append(a__      , range(num_qubits + 1      )      )
       # Finally, perform the H-gates again and measure:
       for qubit in range(a__      ):
              dj_circuit.h(a__      )

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

       return dj_circuit







def   lowerCAmelCase(  a__    :  str      , a__    :  int      ):







       '''simple docstring'''






       lowerCamelCase__				   =      qiskit.Aer.get_backend("aer_simulator"      )

       lowerCamelCase__				   =      dj_oracle(a__      , a__      )
       lowerCamelCase__				   =      dj_algorithm(a__      , a__      )

       # Execute the circuit on the simulator
       lowerCamelCase__				   =      qiskit.execute(a__      , a__      , shots=1000      )

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


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



'''simple docstring'''







import os
import tempfile
import unittest

import numpy as np
import torch

from diffusers.models import ModelMixin, UNetaDConditionModel
from diffusers.models.attention_processor import AttnProcessor, LoRAAttnProcessor
from diffusers.utils import (
    floats_tensor,
    logging,
    skip_mps,
    torch_device,
)
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import enable_full_determinism

from .test_modeling_common import ModelTesterMixin, UNetTesterMixin


enable_full_determinism()

lowerCAmelCase_      =   logging.get_logger(__name__)







def   lowerCAmelCase(  a__    :  List[Any]      , a__    :  bool = True      ):







       '''simple docstring'''






       lowerCamelCase__				   =      {}
       for name in model.attn_processors.keys():
              lowerCamelCase__				   =      name.endswith("attn2.processor"      ) and not (
                  name.startswith("transformer_in"      ) or "temp_attentions" in name.split("."      )
              )
              lowerCamelCase__				   =      model.config.cross_attention_dim if has_cross_attention else None
              if name.startswith("mid_block"      ):
                     lowerCamelCase__				   =      model.config.block_out_channels[-1]
              elif name.startswith("up_blocks"      ):
                     lowerCamelCase__				   =      int(name[len("up_blocks."      )]      )
                     lowerCamelCase__				   =      list(reversed(model.config.block_out_channels      )      )[block_id]
              elif name.startswith("down_blocks"      ):
                     lowerCamelCase__				   =      int(name[len("down_blocks."      )]      )
                     lowerCamelCase__				   =      model.config.block_out_channels[block_id]
              elif name.startswith("transformer_in"      ):
                     # Note that the `8 * ...` comes from: https://github.com/huggingface/diffusers/blob/7139f0e874f10b2463caa8cbd585762a309d12d6/src/diffusers/models/unet_3d_condition.py#L148
                     lowerCamelCase__				   =      8 * model.config.attention_head_dim

              lowerCamelCase__				   =      LoRAAttnProcessor(hidden_size=a__      , cross_attention_dim=a__      )
              lowerCamelCase__				   =      lora_attn_procs[name].to(model.device      )

              if mock_weights:
                     # add 1 to weights to mock trained weights
                     with torch.no_grad():
                            lora_attn_procs[name].to_q_lora.up.weight += 1
                            lora_attn_procs[name].to_k_lora.up.weight += 1
                            lora_attn_procs[name].to_v_lora.up.weight += 1
                            lora_attn_procs[name].to_out_lora.up.weight += 1

       return lora_attn_procs







@skip_mps
class 		snake_case_       (						A__		,	A__		,	unittest.TestCase						):



   """simple docstring"""





   __lowerCAmelCase	:							Optional[int]								=UNetaDConditionModel
   __lowerCAmelCase	:							int								='''sample'''







   @property
   def     __UpperCAmelCase      ( self):
          lowerCamelCase__				   =      4
          lowerCamelCase__				   =      4
          lowerCamelCase__				   =      4
          lowerCamelCase__				   =      (32, 32)

          lowerCamelCase__				   =      floats_tensor((batch_size, num_channels, num_frames) + sizes).to(UpperCamelCase)
          lowerCamelCase__				   =      torch.tensor([10]).to(UpperCamelCase)
          lowerCamelCase__				   =      floats_tensor((batch_size, 4, 32)).to(UpperCamelCase)

          return {"sample": noise, "timestep": time_step, "encoder_hidden_states": encoder_hidden_states}







   @property
   def     __UpperCAmelCase      ( self):
          return (4, 4, 32, 32)







   @property
   def     __UpperCAmelCase      ( self):
          return (4, 4, 32, 32)







   def     __UpperCAmelCase      ( self):
          lowerCamelCase__				   =      {
              "block_out_channels": (32, 64),
              "down_block_types": (
                  "CrossAttnDownBlock3D",
                  "DownBlock3D",
              ),
              "up_block_types": ("UpBlock3D", "CrossAttnUpBlock3D"),
              "cross_attention_dim": 32,
              "attention_head_dim": 8,
              "out_channels": 4,
              "in_channels": 4,
              "layers_per_block": 1,
              "sample_size": 32,
          }
          lowerCamelCase__				   =      self.dummy_input
          return init_dict, inputs_dict







   @unittest.skipIf(
       torch_device != "cuda" or not is_xformers_available()			,   reason="XFormers attention is only available with CUDA and `xformers` installed"			,   )
   def     __UpperCAmelCase      ( self):
          lowerCamelCase__   ,		lowerCamelCase__				   =      self.prepare_init_args_and_inputs_for_common()
          lowerCamelCase__				   =      self.model_class(**UpperCamelCase)

          model.enable_xformers_memory_efficient_attention()

          assert (
              model.mid_block.attentions[0].transformer_blocks[0].attna.processor.__class__.__name__
              == "XFormersAttnProcessor"
          ), "xformers is not enabled"







   def     __UpperCAmelCase      ( self):
          lowerCamelCase__   ,		lowerCamelCase__				   =      self.prepare_init_args_and_inputs_for_common()

          lowerCamelCase__				   =      32

          lowerCamelCase__				   =      self.model_class(**UpperCamelCase)
          model.to(UpperCamelCase)
          model.eval()

          with torch.no_grad():
                 lowerCamelCase__				   =      model(**UpperCamelCase)

                 if isinstance(UpperCamelCase			,   UpperCamelCase):
                        lowerCamelCase__				   =      output.sample

          self.assertIsNotNone(UpperCamelCase)
          lowerCamelCase__				   =      inputs_dict["sample"].shape
          self.assertEqual(output.shape			,   UpperCamelCase			,   "Input and output shapes do not match")







   def     __UpperCAmelCase      ( self):
          lowerCamelCase__   ,		lowerCamelCase__				   =      self.prepare_init_args_and_inputs_for_common()
          lowerCamelCase__				   =      self.model_class(**UpperCamelCase)
          model.to(UpperCamelCase)
          model.eval()

          with torch.no_grad():
                 # Warmup pass when using mps (see #372)
                 if torch_device == "mps" and isinstance(UpperCamelCase			,   UpperCamelCase):
                        model(**self.dummy_input)

                 lowerCamelCase__				   =      model(**UpperCamelCase)
                 if isinstance(UpperCamelCase			,   UpperCamelCase):
                        lowerCamelCase__				   =      first.sample

                 lowerCamelCase__				   =      model(**UpperCamelCase)
                 if isinstance(UpperCamelCase			,   UpperCamelCase):
                        lowerCamelCase__				   =      second.sample

          lowerCamelCase__				   =      first.cpu().numpy()
          lowerCamelCase__				   =      second.cpu().numpy()
          lowerCamelCase__				   =      out_a[~np.isnan(UpperCamelCase)]
          lowerCamelCase__				   =      out_a[~np.isnan(UpperCamelCase)]
          lowerCamelCase__				   =      np.amax(np.abs(out_a - out_a))
          self.assertLessEqual(UpperCamelCase			,   1E-5)







   def     __UpperCAmelCase      ( self):
          lowerCamelCase__   ,		lowerCamelCase__				   =      self.prepare_init_args_and_inputs_for_common()

          lowerCamelCase__				   =      8

          lowerCamelCase__				   =      self.model_class(**UpperCamelCase)
          model.to(UpperCamelCase)
          model.eval()

          model.set_attention_slice("auto")
          with torch.no_grad():
                 lowerCamelCase__				   =      model(**UpperCamelCase)
          assert output is not None

          model.set_attention_slice("max")
          with torch.no_grad():
                 lowerCamelCase__				   =      model(**UpperCamelCase)
          assert output is not None

          model.set_attention_slice(2)
          with torch.no_grad():
                 lowerCamelCase__				   =      model(**UpperCamelCase)
          assert output is not None







   def     __UpperCAmelCase      ( self):
          lowerCamelCase__   ,		lowerCamelCase__				   =      self.prepare_init_args_and_inputs_for_common()

          lowerCamelCase__				   =      8

          lowerCamelCase__				   =      self.model_class(**UpperCamelCase)
          model.to(UpperCamelCase)

          with torch.no_grad():
                 lowerCamelCase__				   =      model(**UpperCamelCase).sample

          lowerCamelCase__				   =      create_lora_layers(UpperCamelCase)

          # make sure we can set a list of attention processors
          model.set_attn_processor(UpperCamelCase)
          model.to(UpperCamelCase)

          # test that attn processors can be set to itself
          model.set_attn_processor(model.attn_processors)

          with torch.no_grad():
                 lowerCamelCase__				   =      model(**UpperCamelCase			,   cross_attention_kwargs={"scale": 0.0}).sample
                 lowerCamelCase__				   =      model(**UpperCamelCase			,   cross_attention_kwargs={"scale": 0.5}).sample
                 lowerCamelCase__				   =      model(**UpperCamelCase			,   cross_attention_kwargs={"scale": 0.5}).sample

          assert (samplea - samplea).abs().max() < 3E-3
          assert (samplea - samplea).abs().max() < 3E-3

          # sample 2 and sample 3 should be different
          assert (samplea - samplea).abs().max() > 3E-3







   def     __UpperCAmelCase      ( self):
          lowerCamelCase__   ,		lowerCamelCase__				   =      self.prepare_init_args_and_inputs_for_common()

          lowerCamelCase__				   =      8

          torch.manual_seed(0)
          lowerCamelCase__				   =      self.model_class(**UpperCamelCase)
          model.to(UpperCamelCase)

          with torch.no_grad():
                 lowerCamelCase__				   =      model(**UpperCamelCase).sample

          lowerCamelCase__				   =      create_lora_layers(UpperCamelCase)
          model.set_attn_processor(UpperCamelCase)

          with torch.no_grad():
                 lowerCamelCase__				   =      model(**UpperCamelCase			,   cross_attention_kwargs={"scale": 0.5}).sample

          with tempfile.TemporaryDirectory() as tmpdirname:
                 model.save_attn_procs(UpperCamelCase)
                 self.assertTrue(os.path.isfile(os.path.join(UpperCamelCase			,   "pytorch_lora_weights.bin")))
                 torch.manual_seed(0)
                 lowerCamelCase__				   =      self.model_class(**UpperCamelCase)
                 new_model.to(UpperCamelCase)
                 new_model.load_attn_procs(UpperCamelCase)

          with torch.no_grad():
                 lowerCamelCase__				   =      new_model(**UpperCamelCase			,   cross_attention_kwargs={"scale": 0.5}).sample

          assert (sample - new_sample).abs().max() < 1E-3

          # LoRA and no LoRA should NOT be the same
          assert (sample - old_sample).abs().max() > 1E-4







   def     __UpperCAmelCase      ( self):
          lowerCamelCase__   ,		lowerCamelCase__				   =      self.prepare_init_args_and_inputs_for_common()

          lowerCamelCase__				   =      8

          torch.manual_seed(0)
          lowerCamelCase__				   =      self.model_class(**UpperCamelCase)
          model.to(UpperCamelCase)

          with torch.no_grad():
                 lowerCamelCase__				   =      model(**UpperCamelCase).sample

          lowerCamelCase__				   =      create_lora_layers(UpperCamelCase)
          model.set_attn_processor(UpperCamelCase)

          with torch.no_grad():
                 lowerCamelCase__				   =      model(**UpperCamelCase			,   cross_attention_kwargs={"scale": 0.5}).sample

          with tempfile.TemporaryDirectory() as tmpdirname:
                 model.save_attn_procs(UpperCamelCase			,   safe_serialization=UpperCamelCase)
                 self.assertTrue(os.path.isfile(os.path.join(UpperCamelCase			,   "pytorch_lora_weights.safetensors")))
                 torch.manual_seed(0)
                 lowerCamelCase__				   =      self.model_class(**UpperCamelCase)
                 new_model.to(UpperCamelCase)
                 new_model.load_attn_procs(UpperCamelCase)

          with torch.no_grad():
                 lowerCamelCase__				   =      new_model(**UpperCamelCase			,   cross_attention_kwargs={"scale": 0.5}).sample

          assert (sample - new_sample).abs().max() < 3E-3

          # LoRA and no LoRA should NOT be the same
          assert (sample - old_sample).abs().max() > 1E-4







   def     __UpperCAmelCase      ( self):
          # enable deterministic behavior for gradient checkpointing
          lowerCamelCase__   ,		lowerCamelCase__				   =      self.prepare_init_args_and_inputs_for_common()

          lowerCamelCase__				   =      8

          torch.manual_seed(0)
          lowerCamelCase__				   =      self.model_class(**UpperCamelCase)
          model.to(UpperCamelCase)

          lowerCamelCase__				   =      create_lora_layers(UpperCamelCase			,   mock_weights=UpperCamelCase)
          model.set_attn_processor(UpperCamelCase)
          # Saving as torch, properly reloads with directly filename
          with tempfile.TemporaryDirectory() as tmpdirname:
                 model.save_attn_procs(UpperCamelCase)
                 self.assertTrue(os.path.isfile(os.path.join(UpperCamelCase			,   "pytorch_lora_weights.bin")))
                 torch.manual_seed(0)
                 lowerCamelCase__				   =      self.model_class(**UpperCamelCase)
                 new_model.to(UpperCamelCase)
                 new_model.load_attn_procs(UpperCamelCase			,   weight_name="pytorch_lora_weights.bin")







   def     __UpperCAmelCase      ( self):
          lowerCamelCase__   ,		lowerCamelCase__				   =      self.prepare_init_args_and_inputs_for_common()

          lowerCamelCase__				   =      8

          torch.manual_seed(0)
          lowerCamelCase__				   =      self.model_class(**UpperCamelCase)
          model.to(UpperCamelCase)

          lowerCamelCase__				   =      create_lora_layers(UpperCamelCase			,   mock_weights=UpperCamelCase)
          model.set_attn_processor(UpperCamelCase)
          # Saving as torch, properly reloads with directly filename
          with tempfile.TemporaryDirectory() as tmpdirname:
                 model.save_attn_procs(UpperCamelCase)
                 self.assertTrue(os.path.isfile(os.path.join(UpperCamelCase			,   "pytorch_lora_weights.bin")))
                 torch.manual_seed(0)
                 lowerCamelCase__				   =      self.model_class(**UpperCamelCase)
                 new_model.to(UpperCamelCase)
                 with self.assertRaises(UpperCamelCase) as e:
                        new_model.load_attn_procs(UpperCamelCase			,   use_safetensors=UpperCamelCase)
                 self.assertIn("Error no file named pytorch_lora_weights.safetensors"			,   str(e.exception))







   def     __UpperCAmelCase      ( self):
          lowerCamelCase__   ,		lowerCamelCase__				   =      self.prepare_init_args_and_inputs_for_common()

          lowerCamelCase__				   =      8

          torch.manual_seed(0)
          lowerCamelCase__				   =      self.model_class(**UpperCamelCase)
          model.to(UpperCamelCase)

          with torch.no_grad():
                 lowerCamelCase__				   =      model(**UpperCamelCase).sample

          lowerCamelCase__				   =      create_lora_layers(UpperCamelCase)
          model.set_attn_processor(UpperCamelCase)

          with torch.no_grad():
                 lowerCamelCase__				   =      model(**UpperCamelCase			,   cross_attention_kwargs={"scale": 0.0}).sample

          model.set_attn_processor(AttnProcessor())

          with torch.no_grad():
                 lowerCamelCase__				   =      model(**UpperCamelCase).sample

          assert (sample - new_sample).abs().max() < 1E-4
          assert (sample - old_sample).abs().max() < 3E-3







   @unittest.skipIf(
       torch_device != "cuda" or not is_xformers_available()			,   reason="XFormers attention is only available with CUDA and `xformers` installed"			,   )
   def     __UpperCAmelCase      ( self):
          # enable deterministic behavior for gradient checkpointing
          lowerCamelCase__   ,		lowerCamelCase__				   =      self.prepare_init_args_and_inputs_for_common()

          lowerCamelCase__				   =      4

          torch.manual_seed(0)
          lowerCamelCase__				   =      self.model_class(**UpperCamelCase)
          model.to(UpperCamelCase)
          lowerCamelCase__				   =      create_lora_layers(UpperCamelCase)
          model.set_attn_processor(UpperCamelCase)

          # default
          with torch.no_grad():
                 lowerCamelCase__				   =      model(**UpperCamelCase).sample

                 model.enable_xformers_memory_efficient_attention()
                 lowerCamelCase__				   =      model(**UpperCamelCase).sample

                 model.disable_xformers_memory_efficient_attention()
                 lowerCamelCase__				   =      model(**UpperCamelCase).sample

          assert (sample - on_sample).abs().max() < 1E-4
          assert (sample - off_sample).abs().max() < 1E-4







   def     __UpperCAmelCase      ( self):
          lowerCamelCase__   ,		lowerCamelCase__				   =      self.prepare_init_args_and_inputs_for_common()
          lowerCamelCase__				   =      32

          lowerCamelCase__				   =      self.model_class(**UpperCamelCase)
          model.to(UpperCamelCase)
          model.eval()

          with torch.no_grad():
                 lowerCamelCase__				   =      model(**UpperCamelCase)[0]

          model.enable_forward_chunking()
          with torch.no_grad():
                 lowerCamelCase__				   =      model(**UpperCamelCase)[0]

          self.assertEqual(output.shape			,   output_a.shape			,   "Shape doesn't match")
          assert np.abs(output.cpu() - output_a.cpu()).max() < 1E-2


# (todo: sayakpaul) implement SLOW tests.

