




'''simple docstring'''






import types
from typing import List, Optional, Tuple, Union

import torch
from transformers import CLIPTextModelWithProjection, CLIPTokenizer
from transformers.models.clip.modeling_clip import CLIPTextModelOutput

from diffusers.models import PriorTransformer
from diffusers.pipelines import DiffusionPipeline, StableDiffusionImageVariationPipeline
from diffusers.schedulers import UnCLIPScheduler
from diffusers.utils import logging, randn_tensor


_lowerCAmelCase				     = logging.get_logger(__name__)  # pylint: disable=invalid-name

def       __lowerCAmelCase (   self ,				snake_case__ ,				snake_case__ ,				snake_case__ ,				snake_case__						):
			__UpperCamelCase				:      Tuple									=       image.to(device=snake_case__						)
			__UpperCamelCase				:      Union[str, Any]									=       image  # take image as image_embeddings
			__UpperCamelCase				:      Optional[int]									=       image_embeddings.unsqueeze(1						)

			# duplicate image embeddings for each generation per prompt, using mps friendly method
			__UpperCamelCase				:      List[str]									=       image_embeddings.shape
			__UpperCamelCase				:      str									=       image_embeddings.repeat(1 ,				snake_case__ ,				1						)
			__UpperCamelCase				:      Any									=       image_embeddings.view(bs_embed * num_images_per_prompt ,				snake_case__ ,				-1						)

			if do_classifier_free_guidance:
						__UpperCamelCase				:      Optional[Any]									=       torch.zeros_like(snake_case__						)

						# For classifier free guidance, we need to do two forward passes.
						# Here we concatenate the unconditional and text embeddings into a single batch
						# to avoid doing two forward passes
						__UpperCamelCase				:      Any									=       torch.cat([uncond_embeddings, image_embeddings]						)

			return image_embeddings




class  A		(			SCREAMING_SNAKE_CASE__		):




				'''simple docstring'''





				def __init__(self			,  _UpperCAmelCase			,  _UpperCAmelCase			,  _UpperCAmelCase			,  _UpperCAmelCase			,  _UpperCAmelCase = None			,  )     ->	int:
							super().__init__()

							__UpperCamelCase				:      Any									=       {"image_encoder": None} if decoder_pipe_kwargs is None else decoder_pipe_kwargs

							__UpperCamelCase				:      Tuple									=       decoder_pipe_kwargs.get("torch_dtype"			,  _UpperCAmelCase      ) or prior.dtype

							__UpperCamelCase				:      List[str]									=       StableDiffusionImageVariationPipeline.from_pretrained(
							    "lambdalabs/sd-image-variations-diffusers"			,  **_UpperCAmelCase      )

							# replace `_encode_image` method
							__UpperCamelCase				:      str									=       types.MethodType(_encode_image			,  self.decoder_pipe      )

							self.register_modules(
							    prior=_UpperCAmelCase			,  tokenizer=_UpperCAmelCase			,  text_encoder=_UpperCAmelCase			,  prior_scheduler=_UpperCAmelCase			,  )
				def 	a_	(self			,  _UpperCAmelCase			,  _UpperCAmelCase			,  _UpperCAmelCase			,  _UpperCAmelCase			,  _UpperCAmelCase = None			,  _UpperCAmelCase = None			,  )     ->	List[Any]:
							if text_model_output is None:
										__UpperCamelCase				:      Dict									=       len(_UpperCAmelCase      ) if isinstance(_UpperCAmelCase			,  _UpperCAmelCase      ) else 1
										# get prompt text embeddings
										__UpperCamelCase				:      List[str]									=       self.tokenizer(
										    _UpperCAmelCase			,  padding="max_length"			,  max_length=self.tokenizer.model_max_length			,  return_tensors="pt"			,  )
										__UpperCamelCase				:      List[str]									=       text_inputs.input_ids
										__UpperCamelCase				:      Any									=       text_inputs.attention_mask.bool().to(_UpperCAmelCase      )

										if text_input_ids.shape[-1] > self.tokenizer.model_max_length:
													__UpperCamelCase				:      Union[str, Any]									=       self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :]      )
													logger.warning(
													    "The following part of your input was truncated because CLIP can only handle sequences up to"
													    f" {self.tokenizer.model_max_length} tokens: {removed_text}"      )
													__UpperCamelCase				:      Optional[int]									=       text_input_ids[:, : self.tokenizer.model_max_length]

										__UpperCamelCase				:      Dict									=       self.text_encoder(text_input_ids.to(_UpperCAmelCase      )      )

										__UpperCamelCase				:      Optional[Any]									=       text_encoder_output.text_embeds
										__UpperCamelCase				:      Union[str, Any]									=       text_encoder_output.last_hidden_state

							else:
										__UpperCamelCase				:      Tuple									=       text_model_output[0].shape[0]
										__UpperCamelCase				:      List[str]									=       text_model_output[0], text_model_output[1]
										__UpperCamelCase				:      str									=       text_attention_mask

							__UpperCamelCase				:      Optional[Any]									=       text_embeddings.repeat_interleave(_UpperCAmelCase			,  dim=0      )
							__UpperCamelCase				:      Optional[int]									=       text_encoder_hidden_states.repeat_interleave(_UpperCAmelCase			,  dim=0      )
							__UpperCamelCase				:      Optional[int]									=       text_mask.repeat_interleave(_UpperCAmelCase			,  dim=0      )

							if do_classifier_free_guidance:
										__UpperCamelCase				:      List[str]									=       [""] * batch_size

										__UpperCamelCase				:      Optional[Any]									=       self.tokenizer(
										    _UpperCAmelCase			,  padding="max_length"			,  max_length=self.tokenizer.model_max_length			,  truncation=_UpperCAmelCase			,  return_tensors="pt"			,  )
										__UpperCamelCase				:      Optional[Any]									=       uncond_input.attention_mask.bool().to(_UpperCAmelCase      )
										__UpperCamelCase				:      Union[str, Any]									=       self.text_encoder(uncond_input.input_ids.to(_UpperCAmelCase      )      )

										__UpperCamelCase				:      Optional[int]									=       uncond_embeddings_text_encoder_output.text_embeds
										__UpperCamelCase				:      Optional[Any]									=       uncond_embeddings_text_encoder_output.last_hidden_state

										# duplicate unconditional embeddings for each generation per prompt, using mps friendly method

										__UpperCamelCase				:      Optional[Any]									=       uncond_embeddings.shape[1]
										__UpperCamelCase				:      Dict									=       uncond_embeddings.repeat(1			,  _UpperCAmelCase      )
										__UpperCamelCase				:      List[str]									=       uncond_embeddings.view(batch_size * num_images_per_prompt			,  _UpperCAmelCase      )

										__UpperCamelCase				:      Union[str, Any]									=       uncond_text_encoder_hidden_states.shape[1]
										__UpperCamelCase				:      Optional[int]									=       uncond_text_encoder_hidden_states.repeat(1			,  _UpperCAmelCase			,  1      )
										__UpperCamelCase				:      Dict									=       uncond_text_encoder_hidden_states.view(
										    batch_size * num_images_per_prompt			,  _UpperCAmelCase			,  -1      )
										__UpperCamelCase				:      str									=       uncond_text_mask.repeat_interleave(_UpperCAmelCase			,  dim=0      )

										# done duplicates

										# For classifier free guidance, we need to do two forward passes.
										# Here we concatenate the unconditional and text embeddings into a single batch
										# to avoid doing two forward passes
										__UpperCamelCase				:      List[Any]									=       torch.cat([uncond_embeddings, text_embeddings]      )
										__UpperCamelCase				:      Optional[int]									=       torch.cat([uncond_text_encoder_hidden_states, text_encoder_hidden_states]      )

										__UpperCamelCase				:      List[Any]									=       torch.cat([uncond_text_mask, text_mask]      )

							return text_embeddings, text_encoder_hidden_states, text_mask
				@property
				def 	a_	(self      )     ->	List[str]:
							if self.device != torch.device("meta"      ) or not hasattr(self.prior			,  "_hf_hook"      ):
										return self.device
							for module in self.prior.modules():
										if (
										    hasattr(_UpperCAmelCase			,  "_hf_hook"      )
										    and hasattr(module._hf_hook			,  "execution_device"      )
										    and module._hf_hook.execution_device is not None
										):
													return torch.device(module._hf_hook.execution_device      )
							return self.device
				def 	a_	(self			,  _UpperCAmelCase			,  _UpperCAmelCase			,  _UpperCAmelCase			,  _UpperCAmelCase			,  _UpperCAmelCase			,  _UpperCAmelCase      )     ->	Tuple:
							if latents is None:
										__UpperCamelCase				:      Union[str, Any]									=       randn_tensor(_UpperCAmelCase			,  generator=_UpperCAmelCase			,  device=_UpperCAmelCase			,  dtype=_UpperCAmelCase      )
							else:
										if latents.shape != shape:
													raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {shape}"      )
										__UpperCamelCase				:      Tuple									=       latents.to(_UpperCAmelCase      )

							__UpperCamelCase				:      Union[str, Any]									=       latents * scheduler.init_noise_sigma
							return latents
				def 	a_	(self			,  _UpperCAmelCase = None      )     ->	Union[str, Any]:
							self.decoder_pipe.to(_UpperCAmelCase      )
							super().to(_UpperCAmelCase      )





				@torch.no_grad()
				def __call__(self			,  _UpperCAmelCase = None			,  _UpperCAmelCase = None			,  _UpperCAmelCase = None			,  _UpperCAmelCase = 1			,  _UpperCAmelCase = 2_5			,  _UpperCAmelCase = None			,  _UpperCAmelCase = None			,  _UpperCAmelCase = None			,  _UpperCAmelCase = None			,  _UpperCAmelCase = 4.0			,  _UpperCAmelCase = 8.0			,  _UpperCAmelCase = 5_0			,  _UpperCAmelCase = 1			,  _UpperCAmelCase = 0.0			,  _UpperCAmelCase = "pil"			,  _UpperCAmelCase = True			,  )     ->	List[Any]:
							if prompt is not None:
										if isinstance(_UpperCAmelCase			,  _UpperCAmelCase      ):
													__UpperCamelCase				:      List[Any]									=       1
										elif isinstance(_UpperCAmelCase			,  _UpperCAmelCase      ):
													__UpperCamelCase				:      Any									=       len(_UpperCAmelCase      )
										else:
													raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(_UpperCAmelCase      )}"      )
							else:
										__UpperCamelCase				:      List[Any]									=       text_model_output[0].shape[0]

							__UpperCamelCase				:      int									=       self._execution_device

							__UpperCamelCase				:      Union[str, Any]									=       batch_size * num_images_per_prompt

							__UpperCamelCase				:      Tuple									=       prior_guidance_scale > 1.0 or decoder_guidance_scale > 1.0

							__UpperCamelCase				:      Dict									=       self._encode_prompt(
							    _UpperCAmelCase			,  _UpperCAmelCase			,  _UpperCAmelCase			,  _UpperCAmelCase			,  _UpperCAmelCase			,  _UpperCAmelCase      )

							# prior

							self.prior_scheduler.set_timesteps(_UpperCAmelCase			,  device=_UpperCAmelCase      )
							__UpperCamelCase				:      Optional[Any]									=       self.prior_scheduler.timesteps

							__UpperCamelCase				:      int									=       self.prior.config.embedding_dim

							__UpperCamelCase				:      List[Any]									=       self.prepare_latents(
							    (batch_size, embedding_dim)			,  text_embeddings.dtype			,  _UpperCAmelCase			,  _UpperCAmelCase			,  _UpperCAmelCase			,  self.prior_scheduler			,  )

							for i, t in enumerate(self.progress_bar(_UpperCAmelCase      )      ):
										# expand the latents if we are doing classifier free guidance
										__UpperCamelCase				:      int									=       torch.cat([prior_latents] * 2      ) if do_classifier_free_guidance else prior_latents

										__UpperCamelCase				:      Union[str, Any]									=       self.prior(
										    _UpperCAmelCase			,  timestep=_UpperCAmelCase			,  proj_embedding=_UpperCAmelCase			,  encoder_hidden_states=_UpperCAmelCase			,  attention_mask=_UpperCAmelCase			,  ).predicted_image_embedding

										if do_classifier_free_guidance:
													__UpperCamelCase				:      str									=       predicted_image_embedding.chunk(2      )
													__UpperCamelCase				:      List[Any]									=       predicted_image_embedding_uncond + prior_guidance_scale * (
													    predicted_image_embedding_text - predicted_image_embedding_uncond
													)

										if i + 1 == prior_timesteps_tensor.shape[0]:
													__UpperCamelCase				:      Optional[int]									=       None
										else:
													__UpperCamelCase				:      Any									=       prior_timesteps_tensor[i + 1]

										__UpperCamelCase				:      Optional[int]									=       self.prior_scheduler.step(
										    _UpperCAmelCase			,  timestep=_UpperCAmelCase			,  sample=_UpperCAmelCase			,  generator=_UpperCAmelCase			,  prev_timestep=_UpperCAmelCase			,  ).prev_sample

							__UpperCamelCase				:      Union[str, Any]									=       self.prior.post_process_latents(_UpperCAmelCase      )

							__UpperCamelCase				:      Optional[Any]									=       prior_latents

							__UpperCamelCase				:      List[Any]									=       self.decoder_pipe(
							    image=_UpperCAmelCase			,  height=_UpperCAmelCase			,  width=_UpperCAmelCase			,  num_inference_steps=_UpperCAmelCase			,  guidance_scale=_UpperCAmelCase			,  generator=_UpperCAmelCase			,  output_type=_UpperCAmelCase			,  return_dict=_UpperCAmelCase			,  num_images_per_prompt=_UpperCAmelCase			,  eta=_UpperCAmelCase			,  )
							return output








'''simple docstring'''






import math

import qiskit
from qiskit import Aer, ClassicalRegister, QuantumCircuit, QuantumRegister, execute

def       __lowerCAmelCase (   snake_case__ = 1 ,				snake_case__ = 1						):
			if isinstance(snake_case__ ,				snake_case__						) or isinstance(snake_case__ ,				snake_case__						):
						raise TypeError("inputs must be integers."						)
			if (bit_a < 0) or (bit_a < 0):
						raise ValueError("inputs must be positive."						)
			if (math.floor(snake_case__						) != bit_a) or (math.floor(snake_case__						) != bit_a):
						raise ValueError("inputs must be exact integers."						)
			if (bit_a > 1) or (bit_a > 1):
						raise ValueError("inputs must be less or equal to 1."						)

			# build registers
			__UpperCamelCase				:      Tuple									=       QuantumRegister(2 ,				"qr"						)
			__UpperCamelCase				:      Dict									=       ClassicalRegister(2 ,				"cr"						)

			__UpperCamelCase				:      str									=       QuantumCircuit(snake_case__ ,				snake_case__						)

			# entanglement the qubits
			quantum_circuit.h(1						)
			quantum_circuit.cx(1 ,				0						)

			# send the information
			__UpperCamelCase				:      Optional[Any]									=       str(snake_case__						) + str(snake_case__						)

			if c_information == "11":
						quantum_circuit.x(1						)
						quantum_circuit.z(1						)
			elif c_information == "10":
						quantum_circuit.z(1						)
			elif c_information == "01":
						quantum_circuit.x(1						)
			else:
						quantum_circuit.i(1						)

			# unentangled the circuit
			quantum_circuit.cx(1 ,				0						)
			quantum_circuit.h(1						)

			# measure the circuit
			quantum_circuit.measure(snake_case__ ,				snake_case__						)

			__UpperCamelCase				:      Dict									=       Aer.get_backend("aer_simulator"						)
			__UpperCamelCase				:      Tuple									=       execute(snake_case__ ,				snake_case__ ,				shots=1_000						)

			return job.result().get_counts(snake_case__						)


if __name__ == "__main__":
				print(f'Counts for classical state send: {superdense_coding(1,1)}')



