
"""simple docstring"""



import argparse

import torch
from safetensors.torch import load_file

from diffusers import StableDiffusionPipeline
def 					_UpperCAmelCase      ( __lowerCamelCase   :       Optional[Any] ,					__lowerCamelCase   :       Tuple ,					__lowerCamelCase   :       Dict ,					__lowerCamelCase   :       Union[str, Any] ,					__lowerCamelCase   :       Union[str, Any]		)     ->					Tuple:
  # load base model
  _snake_case					     =       StableDiffusionPipeline.from_pretrained(__lowerCamelCase ,					torch_dtype=torch.floataa		)

  # load LoRA weight from .safetensors
  _snake_case					     =       load_file(__lowerCamelCase		)

  _snake_case					     =       []

  # directly update weight in diffusers model
  for key in state_dict:
    # it is suggested to print out the key, it usually will be something like below
    # "lora_te_text_model_encoder_layers_0_self_attn_k_proj.lora_down.weight"

    # as we have set the alpha beforehand, so just skip
    if ".alpha" in key or key in visited:
      continue

    if "text" in key:
      _snake_case					     =       key.split('''.'''		)[0].split(LORA_PREFIX_TEXT_ENCODER + '''_'''		)[-1].split('''_'''		)
      _snake_case					     =       pipeline.text_encoder
    else:
      _snake_case					     =       key.split('''.'''		)[0].split(LORA_PREFIX_UNET + '''_'''		)[-1].split('''_'''		)
      _snake_case					     =       pipeline.unet

    # find the target layer
    _snake_case					     =       layer_infos.pop(0		)
    while len(__lowerCamelCase		) > -1:
      try:
        _snake_case					     =       curr_layer.__getattr__(__lowerCamelCase		)
        if len(__lowerCamelCase		) > 0:
          _snake_case					     =       layer_infos.pop(0		)
        elif len(__lowerCamelCase		) == 0:
          break
      except Exception:
        if len(__lowerCamelCase		) > 0:
          temp_name += "_" + layer_infos.pop(0		)
        else:
          _snake_case					     =       layer_infos.pop(0		)

    _snake_case					     =       []
    if "lora_down" in key:
      pair_keys.append(key.replace('''lora_down''' ,					'''lora_up'''		)		)
      pair_keys.append(__lowerCamelCase		)
    else:
      pair_keys.append(__lowerCamelCase		)
      pair_keys.append(key.replace('''lora_up''' ,					'''lora_down'''		)		)

    # update weight
    if len(state_dict[pair_keys[0]].shape		) == 4:
      _snake_case					     =       state_dict[pair_keys[0]].squeeze(3		).squeeze(2		).to(torch.floataa		)
      _snake_case					     =       state_dict[pair_keys[1]].squeeze(3		).squeeze(2		).to(torch.floataa		)
      curr_layer.weight.data += alpha * torch.mm(__lowerCamelCase ,					__lowerCamelCase		).unsqueeze(2		).unsqueeze(3		)
    else:
      _snake_case					     =       state_dict[pair_keys[0]].to(torch.floataa		)
      _snake_case					     =       state_dict[pair_keys[1]].to(torch.floataa		)
      curr_layer.weight.data += alpha * torch.mm(__lowerCamelCase ,					__lowerCamelCase		)

    # update visited list
    for item in pair_keys:
      visited.append(__lowerCamelCase		)

  return pipeline


if __name__ == "__main__":
 UpperCAmelCase__          = argparse.ArgumentParser()

 parser.add_argument(
     '--base_model_path', default=None, type=str, required=True, help='Path to the base model in diffusers format.'
 )
 parser.add_argument(
     '--checkpoint_path', default=None, type=str, required=True, help='Path to the checkpoint to convert.'
 )
 parser.add_argument('--dump_path', default=None, type=str, required=True, help='Path to the output model.')
 parser.add_argument(
     '--lora_prefix_unet', default='lora_unet', type=str, help='The prefix of UNet weight in safetensors'
 )
 parser.add_argument(
     '--lora_prefix_text_encoder',
     default='lora_te',
     type=str,
     help='The prefix of text encoder weight in safetensors',
 )
 parser.add_argument('--alpha', default=0.75, type=float, help='The merging ratio in W = W0 + alpha * deltaW')
 parser.add_argument(
     '--to_safetensors', action='store_true', help='Whether to store pipeline in safetensors format or not.'
 )
 parser.add_argument('--device', type=str, help='Device to use (e.g. cpu, cuda:0, cuda:1, etc.)')

 UpperCAmelCase__          = parser.parse_args()

 UpperCAmelCase__          = args.base_model_path
 UpperCAmelCase__          = args.checkpoint_path
 UpperCAmelCase__          = args.dump_path
 UpperCAmelCase__          = args.lora_prefix_unet
 UpperCAmelCase__          = args.lora_prefix_text_encoder
 UpperCAmelCase__          = args.alpha

 UpperCAmelCase__          = convert(base_model_path, checkpoint_path, lora_prefix_unet, lora_prefix_text_encoder, alpha)

 UpperCAmelCase__          = pipe.to(args.device)
 pipe.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)





"""simple docstring"""



import math

import numpy as np
import qiskit
from qiskit import Aer, ClassicalRegister, QuantumCircuit, QuantumRegister, execute
def 					_UpperCAmelCase      ( __lowerCamelCase   :       int = 3		)     ->					qiskit.result.counts.Counts:
  if isinstance(__lowerCamelCase ,					__lowerCamelCase		):
    raise TypeError('''number of qubits must be a integer.'''		)
  if number_of_qubits <= 0:
    raise ValueError('''number of qubits must be > 0.'''		)
  if math.floor(__lowerCamelCase		) != number_of_qubits:
    raise ValueError('''number of qubits must be exact integer.'''		)
  if number_of_qubits > 10:
    raise ValueError('''number of qubits too large to simulate(>10).'''		)

  _snake_case					     =       QuantumRegister(__lowerCamelCase ,					'''qr'''		)
  _snake_case					     =       ClassicalRegister(__lowerCamelCase ,					'''cr'''		)

  _snake_case					     =       QuantumCircuit(__lowerCamelCase ,					__lowerCamelCase		)

  _snake_case					     =       number_of_qubits

  for i in range(__lowerCamelCase		):
    quantum_circuit.h(number_of_qubits - i - 1		)
    counter -= 1
    for j in range(__lowerCamelCase		):
      quantum_circuit.cp(np.pi / 2 ** (counter - j) ,					__lowerCamelCase ,					__lowerCamelCase		)

  for k in range(number_of_qubits // 2		):
    quantum_circuit.swap(__lowerCamelCase ,					number_of_qubits - k - 1		)

  # measure all the qubits
  quantum_circuit.measure(__lowerCamelCase ,					__lowerCamelCase		)
  # simulate with 10000 shots
  _snake_case					     =       Aer.get_backend('''qasm_simulator'''		)
  _snake_case					     =       execute(__lowerCamelCase ,					__lowerCamelCase ,					shots=1_00_00		)

  return job.result().get_counts(__lowerCamelCase		)


if __name__ == "__main__":
 print(
     F"Total count for quantum fourier transform state is: \
    {quantum_fourier_transform(3)}"
 )



