




"""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


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





def     __snake_case   (							self ,_lowercase ,_lowercase ,_lowercase ,_lowercase						):


    """simple docstring"""







    UpperCamelCase										=  image.to(device=_lowercase						)
    UpperCamelCase										=  image  # take image as image_embeddings
    UpperCamelCase										=  image_embeddings.unsqueeze(1						)

    # duplicate image embeddings for each generation per prompt, using mps friendly method
    UpperCamelCase					,  UpperCamelCase					,  UpperCamelCase										=  image_embeddings.shape
    UpperCamelCase										=  image_embeddings.repeat(1 ,_lowercase ,1						)
    UpperCamelCase										=  image_embeddings.view(bs_embed * num_images_per_prompt ,_lowercase ,-1						)

    if do_classifier_free_guidance:
        UpperCamelCase										=  torch.zeros_like(_lowercase						)

        # 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										=  torch.cat([uncond_embeddings, image_embeddings]						)

    return image_embeddings


class 							snake_case_ (				lowerCamelCase_ ):







   """simple docstring"""




   def __init__(		self					,				lowerCamelCase_					,				lowerCamelCase_					,				lowerCamelCase_					,				lowerCamelCase_					,				lowerCamelCase_ = None					,				)							->      List[str]:
       super().__init__()

       UpperCamelCase										=  {'''image_encoder''': None} if decoder_pipe_kwargs is None else decoder_pipe_kwargs

       UpperCamelCase										=  decoder_pipe_kwargs.get('''torch_dtype'''					,				lowerCamelCase_) or prior.dtype

       UpperCamelCase										=  StableDiffusionImageVariationPipeline.from_pretrained(
           '''lambdalabs/sd-image-variations-diffusers'''					,				**lowerCamelCase_)

       # replace `_encode_image` method
       UpperCamelCase										=  types.MethodType(_encode_image					,				self.decoder_pipe)

       self.register_modules(
           prior=lowerCamelCase_					,				tokenizer=lowerCamelCase_					,				text_encoder=lowerCamelCase_					,				prior_scheduler=lowerCamelCase_					,				)







   def      UpperCAmelCase__ (		self					,				lowerCamelCase_					,				lowerCamelCase_					,				lowerCamelCase_					,				lowerCamelCase_					,				lowerCamelCase_ = None					,				lowerCamelCase_ = None					,				)							->      Union[str, Any]:
       if text_model_output is None:
           UpperCamelCase										=  len(lowerCamelCase_) if isinstance(lowerCamelCase_					,				lowerCamelCase_) else 1
           # get prompt text embeddings
           UpperCamelCase										=  self.tokenizer(
               lowerCamelCase_					,				padding='''max_length'''					,				max_length=self.tokenizer.model_max_length					,				return_tensors='''pt'''					,				)
           UpperCamelCase										=  text_inputs.input_ids
           UpperCamelCase										=  text_inputs.attention_mask.bool().to(lowerCamelCase_)

           if text_input_ids.shape[-1] > self.tokenizer.model_max_length:
               UpperCamelCase										=  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										=  text_input_ids[:, : self.tokenizer.model_max_length]

           UpperCamelCase										=  self.text_encoder(text_input_ids.to(lowerCamelCase_))

           UpperCamelCase										=  text_encoder_output.text_embeds
           UpperCamelCase										=  text_encoder_output.last_hidden_state

       else:
           UpperCamelCase										=  text_model_output[0].shape[0]
           UpperCamelCase					,  UpperCamelCase										=  text_model_output[0], text_model_output[1]
           UpperCamelCase										=  text_attention_mask

       UpperCamelCase										=  text_embeddings.repeat_interleave(lowerCamelCase_					,				dim=0)
       UpperCamelCase										=  text_encoder_hidden_states.repeat_interleave(lowerCamelCase_					,				dim=0)
       UpperCamelCase										=  text_mask.repeat_interleave(lowerCamelCase_					,				dim=0)

       if do_classifier_free_guidance:
           UpperCamelCase										=  [''''''] * batch_size

           UpperCamelCase										=  self.tokenizer(
               lowerCamelCase_					,				padding='''max_length'''					,				max_length=self.tokenizer.model_max_length					,				truncation=lowerCamelCase_					,				return_tensors='''pt'''					,				)
           UpperCamelCase										=  uncond_input.attention_mask.bool().to(lowerCamelCase_)
           UpperCamelCase										=  self.text_encoder(uncond_input.input_ids.to(lowerCamelCase_))

           UpperCamelCase										=  uncond_embeddings_text_encoder_output.text_embeds
           UpperCamelCase										=  uncond_embeddings_text_encoder_output.last_hidden_state

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

           UpperCamelCase										=  uncond_embeddings.shape[1]
           UpperCamelCase										=  uncond_embeddings.repeat(1					,				lowerCamelCase_)
           UpperCamelCase										=  uncond_embeddings.view(batch_size * num_images_per_prompt					,				lowerCamelCase_)

           UpperCamelCase										=  uncond_text_encoder_hidden_states.shape[1]
           UpperCamelCase										=  uncond_text_encoder_hidden_states.repeat(1					,				lowerCamelCase_					,				1)
           UpperCamelCase										=  uncond_text_encoder_hidden_states.view(
               batch_size * num_images_per_prompt					,				lowerCamelCase_					,				-1)
           UpperCamelCase										=  uncond_text_mask.repeat_interleave(lowerCamelCase_					,				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										=  torch.cat([uncond_embeddings, text_embeddings])
           UpperCamelCase										=  torch.cat([uncond_text_encoder_hidden_states, text_encoder_hidden_states])

           UpperCamelCase										=  torch.cat([uncond_text_mask, text_mask])

       return text_embeddings, text_encoder_hidden_states, text_mask







   @property
   def      UpperCAmelCase__ (		self)							->      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(lowerCamelCase_					,				'''_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      UpperCAmelCase__ (		self					,				lowerCamelCase_					,				lowerCamelCase_					,				lowerCamelCase_					,				lowerCamelCase_					,				lowerCamelCase_					,				lowerCamelCase_)							->      Any:
       if latents is None:
           UpperCamelCase										=  randn_tensor(lowerCamelCase_					,				generator=lowerCamelCase_					,				device=lowerCamelCase_					,				dtype=lowerCamelCase_)
       else:
           if latents.shape != shape:
               raise ValueError(F'Unexpected latents shape, got {latents.shape}, expected {shape}')
           UpperCamelCase										=  latents.to(lowerCamelCase_)

       UpperCamelCase										=  latents * scheduler.init_noise_sigma
       return latents







   def      UpperCAmelCase__ (		self					,				lowerCamelCase_ = None)							->      Union[str, Any]:
       self.decoder_pipe.to(lowerCamelCase_)
       super().to(lowerCamelCase_)







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

       UpperCamelCase										=  self._execution_device

       UpperCamelCase										=  batch_size * num_images_per_prompt

       UpperCamelCase										=  prior_guidance_scale > 1.0 or decoder_guidance_scale > 1.0

       UpperCamelCase					,  UpperCamelCase					,  UpperCamelCase										=  self._encode_prompt(
           lowerCamelCase_					,				lowerCamelCase_					,				lowerCamelCase_					,				lowerCamelCase_					,				lowerCamelCase_					,				lowerCamelCase_)

       # prior

       self.prior_scheduler.set_timesteps(lowerCamelCase_					,				device=lowerCamelCase_)
       UpperCamelCase										=  self.prior_scheduler.timesteps

       UpperCamelCase										=  self.prior.config.embedding_dim

       UpperCamelCase										=  self.prepare_latents(
           (batch_size, embedding_dim)					,				text_embeddings.dtype					,				lowerCamelCase_					,				lowerCamelCase_					,				lowerCamelCase_					,				self.prior_scheduler					,				)

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

           UpperCamelCase										=  self.prior(
               lowerCamelCase_					,				timestep=lowerCamelCase_					,				proj_embedding=lowerCamelCase_					,				encoder_hidden_states=lowerCamelCase_					,				attention_mask=lowerCamelCase_					,				).predicted_image_embedding

           if do_classifier_free_guidance:
               UpperCamelCase					,  UpperCamelCase										=  predicted_image_embedding.chunk(2)
               UpperCamelCase										=  predicted_image_embedding_uncond + prior_guidance_scale * (
                   predicted_image_embedding_text - predicted_image_embedding_uncond
               )

           if i + 1 == prior_timesteps_tensor.shape[0]:
               UpperCamelCase										=  None
           else:
               UpperCamelCase										=  prior_timesteps_tensor[i + 1]

           UpperCamelCase										=  self.prior_scheduler.step(
               lowerCamelCase_					,				timestep=lowerCamelCase_					,				sample=lowerCamelCase_					,				generator=lowerCamelCase_					,				prev_timestep=lowerCamelCase_					,				).prev_sample

       UpperCamelCase										=  self.prior.post_process_latents(lowerCamelCase_)

       UpperCamelCase										=  prior_latents

       UpperCamelCase										=  self.decoder_pipe(
           image=lowerCamelCase_					,				height=lowerCamelCase_					,				width=lowerCamelCase_					,				num_inference_steps=lowerCamelCase_					,				guidance_scale=lowerCamelCase_					,				generator=lowerCamelCase_					,				output_type=lowerCamelCase_					,				return_dict=lowerCamelCase_					,				num_images_per_prompt=lowerCamelCase_					,				eta=lowerCamelCase_					,				)
       return output





"""simple docstring"""







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 							snake_case_ (				lowerCamelCase_ ):







   """simple docstring"""




   def __init__(		self					,				lowerCamelCase_					,				)							->      Any:
       UpperCamelCase										=  parent
       UpperCamelCase										=  1_3
       UpperCamelCase										=  7
       UpperCamelCase										=  True
       UpperCamelCase										=  True
       UpperCamelCase										=  True
       UpperCamelCase										=  True
       UpperCamelCase										=  True
       UpperCamelCase										=  9_9
       UpperCamelCase										=  3_2
       UpperCamelCase										=  2
       UpperCamelCase										=  4
       UpperCamelCase										=  3_7
       UpperCamelCase										=  '''gelu'''
       UpperCamelCase										=  0.1
       UpperCamelCase										=  0.1
       UpperCamelCase										=  5_1_2
       UpperCamelCase										=  1_6
       UpperCamelCase										=  2
       UpperCamelCase										=  0.02
       UpperCamelCase										=  3
       UpperCamelCase										=  4
       UpperCamelCase										=  None
       UpperCamelCase										=  self.vocab_size - 1







   def      UpperCAmelCase__ (		self)							->      int:
       UpperCamelCase										=  ids_tensor([self.batch_size, self.seq_length]					,				self.vocab_size)

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

       UpperCamelCase										=  None
       if self.use_token_type_ids:
           UpperCamelCase										=  ids_tensor([self.batch_size, self.seq_length]					,				self.type_vocab_size)

       UpperCamelCase										=  None
       if self.use_mc_token_ids:
           UpperCamelCase										=  ids_tensor([self.batch_size, self.num_choices]					,				self.seq_length)

       UpperCamelCase										=  None
       UpperCamelCase										=  None
       UpperCamelCase										=  None
       if self.use_labels:
           UpperCamelCase										=  ids_tensor([self.batch_size]					,				self.type_sequence_label_size)
           UpperCamelCase										=  ids_tensor([self.batch_size, self.seq_length]					,				self.num_labels)
           UpperCamelCase										=  ids_tensor([self.batch_size]					,				self.num_choices)

       UpperCamelCase										=  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					,				)

       UpperCamelCase										=  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      UpperCAmelCase__ (		self					,				lowerCamelCase_					,				lowerCamelCase_					,				lowerCamelCase_					,				lowerCamelCase_					,				lowerCamelCase_					,				*lowerCamelCase_)							->      Optional[Any]:
       UpperCamelCase										=  TFCTRLModel(config=lowerCamelCase_)
       UpperCamelCase										=  {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}
       UpperCamelCase										=  model(lowerCamelCase_)

       UpperCamelCase										=  [input_ids, None, input_mask]  # None is the input for 'past'
       UpperCamelCase										=  model(lowerCamelCase_)

       UpperCamelCase										=  model(lowerCamelCase_)

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







   def      UpperCAmelCase__ (		self					,				lowerCamelCase_					,				lowerCamelCase_					,				lowerCamelCase_					,				lowerCamelCase_					,				lowerCamelCase_					,				*lowerCamelCase_)							->      int:
       UpperCamelCase										=  TFCTRLLMHeadModel(config=lowerCamelCase_)
       UpperCamelCase										=  {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}
       UpperCamelCase										=  model(lowerCamelCase_)
       self.parent.assertEqual(result.logits.shape					,				(self.batch_size, self.seq_length, self.vocab_size))







   def      UpperCAmelCase__ (		self					,				lowerCamelCase_					,				lowerCamelCase_					,				lowerCamelCase_					,				lowerCamelCase_					,				lowerCamelCase_					,				*lowerCamelCase_)							->      List[str]:
       UpperCamelCase										=  self.num_labels
       UpperCamelCase										=  ids_tensor([self.batch_size]					,				self.type_sequence_label_size)
       UpperCamelCase										=  {
           '''input_ids''': input_ids,
           '''token_type_ids''': token_type_ids,
           '''labels''': sequence_labels,
       }
       UpperCamelCase										=  TFCTRLForSequenceClassification(lowerCamelCase_)
       UpperCamelCase										=  model(lowerCamelCase_)
       self.parent.assertEqual(result.logits.shape					,				(self.batch_size, self.num_labels))







   def      UpperCAmelCase__ (		self)							->      str:
       UpperCamelCase										=  self.prepare_config_and_inputs()

       (
           (
           UpperCamelCase
       )					,  (
           UpperCamelCase
       )					,  (
           UpperCamelCase
       )					,  (
           UpperCamelCase
       )					,  (
           UpperCamelCase
       )					,  (
           UpperCamelCase
       )					,  (
           UpperCamelCase
       )					,  (
           UpperCamelCase
       )					,  (
           UpperCamelCase
       )					,  
       )										=  config_and_inputs

       UpperCamelCase										=  {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask}
       return config, inputs_dict

@require_tf
class 							snake_case_ (				lowerCamelCase_  ,   lowerCamelCase_  ,   unittest.TestCase ):







   """simple docstring"""




   A_										=					(TFCTRLModel, TFCTRLLMHeadModel, TFCTRLForSequenceClassification) if is_tf_available() else ()
   A_										=					(TFCTRLLMHeadModel,) if is_tf_available() else ()
   A_										=					(
       {
           '''feature-extraction''': TFCTRLModel,
           '''text-classification''': TFCTRLForSequenceClassification,
           '''text-generation''': TFCTRLLMHeadModel,
           '''zero-shot''': TFCTRLForSequenceClassification,
       }
       if is_tf_available()
       else {}
   )
   A_										=					False
   A_										=					False







   def      UpperCAmelCase__ (		self					,				lowerCamelCase_					,				lowerCamelCase_					,				lowerCamelCase_					,				lowerCamelCase_					,				lowerCamelCase_)							->      int:
       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      UpperCAmelCase__ (		self)							->      int:
       UpperCamelCase										=  TFCTRLModelTester(self)
       UpperCamelCase										=  ConfigTester(self					,				config_class=lowerCamelCase_					,				n_embd=3_7)







   def      UpperCAmelCase__ (		self)							->      int:
       self.config_tester.run_common_tests()







   def      UpperCAmelCase__ (		self)							->      Union[str, Any]:
       UpperCamelCase										=  self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_ctrl_model(*lowerCamelCase_)







   def      UpperCAmelCase__ (		self)							->      List[Any]:
       UpperCamelCase										=  self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_ctrl_lm_head(*lowerCamelCase_)







   def      UpperCAmelCase__ (		self)							->      List[Any]:
       UpperCamelCase										=  self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_ctrl_for_sequence_classification(*lowerCamelCase_)







   def      UpperCAmelCase__ (		self)							->      List[str]:
       UpperCamelCase					,  UpperCamelCase										=  self.model_tester.prepare_config_and_inputs_for_common()
       UpperCamelCase										=  [TFCTRLLMHeadModel]
       UpperCamelCase										=  [TFCTRLForSequenceClassification]

       for model_class in self.all_model_classes:
           UpperCamelCase										=  model_class(lowerCamelCase_)
           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:
               UpperCamelCase										=  model.get_output_embeddings()
               assert isinstance(lowerCamelCase_					,				tf.keras.layers.Layer)
               UpperCamelCase										=  model.get_bias()
               assert isinstance(lowerCamelCase_					,				lowerCamelCase_)
               for k, v in name.items():
                   assert isinstance(lowerCamelCase_					,				tf.Variable)
           elif model_class in list_other_models_with_output_ebd:
               UpperCamelCase										=  model.get_output_embeddings()
               assert isinstance(lowerCamelCase_					,				tf.keras.layers.Layer)
               UpperCamelCase										=  model.get_bias()
               assert name is None
           else:
               UpperCamelCase										=  model.get_output_embeddings()
               assert x is None
               UpperCamelCase										=  model.get_bias()
               assert name is None







   @slow
   def      UpperCAmelCase__ (		self)							->      List[Any]:
       for model_name in TF_CTRL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           UpperCamelCase										=  TFCTRLModel.from_pretrained(lowerCamelCase_)
           self.assertIsNotNone(lowerCamelCase_)

@require_tf
class 							snake_case_ (				unittest.TestCase ):







   """simple docstring"""




   @slow
   def      UpperCAmelCase__ (		self)							->      str:
       UpperCamelCase										=  TFCTRLLMHeadModel.from_pretrained('''ctrl''')
       UpperCamelCase										=  tf.convert_to_tensor([[1_1_8_5_9, 0, 1_6_1_1, 8]]					,				dtype=tf.intaa)  # Legal the president is
       UpperCamelCase										=  [
           1_1_8_5_9,
           0,
           1_6_1_1,
           8,
           5,
           1_5_0,
           2_6_4_4_9,
           2,
           1_9,
           3_4_8,
           4_6_9,
           3,
           2_5_9_5,
           4_8,
           2_0_7_4_0,
           2_4_6_5_3_3,
           2_4_6_5_3_3,
           1_9,
           3_0,
           5,
       ]  # Legal the president is a good guy and I don't want to lose my job. \n \n I have a

       UpperCamelCase										=  model.generate(lowerCamelCase_					,				do_sample=lowerCamelCase_)
       self.assertListEqual(output_ids[0].numpy().tolist()					,				lowerCamelCase_)