

"""simple docstring"""






import enum
import warnings

from .. import MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING
from ..utils import add_end_docstrings, is_tf_available
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_tf_available():
 import tensorflow as tf







class 	__UpperCamelCase    (    enum.Enum						):
  _UpperCAmelCase          =		0
  _UpperCAmelCase          =		1
  _UpperCAmelCase          =		2







@add_end_docstrings(a__						)
class 	__UpperCamelCase    (    a__						):
  _UpperCAmelCase          =		"\n    In 1991, the remains of Russian Tsar Nicholas II and his family (except for Alexei and Maria) are discovered. The\n    voice of Nicholas's young son, Tsarevich Alexei Nikolaevich, narrates the remainder of the story. 1883 Western\n    Siberia, a young Grigori Rasputin is asked by his father and a group of men to perform magic. Rasputin has a vision\n    and denounces one of the men as a horse thief. Although his father initially slaps him for making such an\n    accusation, Rasputin watches as the man is chased outside and beaten. Twenty years later, Rasputin sees a vision of\n    the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous, with people, even a bishop,\n    begging for his blessing. <eod> </s> <eos>\n    "

  def __init__(		self    ,*_A    ,**_A      ):
      '''simple docstring'''

      super().__init__(*__UpperCamelCase    ,**__UpperCamelCase      )
      self.check_model_type(
          TF_MODEL_FOR_CAUSAL_LM_MAPPING if self.framework == 'tf' else MODEL_FOR_CAUSAL_LM_MAPPING      )
      if "prefix" not in self._preprocess_params:
          # This is very specific. The logic is quite complex and needs to be done
          # as a "default".
          # It also defines both some preprocess_kwargs and generate_kwargs
          # which is why we cannot put them in their respective methods.
          _lowerCAmelCase       :   Dict  =    None
          if self.model.config.prefix is not None:
              _lowerCAmelCase       :   Optional[int]  =    self.model.config.prefix
          if prefix is None and self.model.__class__.__name__ in [
              "XLNetLMHeadModel",
              "TransfoXLLMHeadModel",
              "TFXLNetLMHeadModel",
              "TFTransfoXLLMHeadModel",
          ]:
              # For XLNet and TransformerXL we add an article to the prompt to give more state to the model.
              _lowerCAmelCase       :   str  =    self.XL_PREFIX
          if prefix is not None:
              # Recalculate some generate_kwargs linked to prefix.
              _lowerCAmelCase,					_lowerCAmelCase,					_lowerCAmelCase       :   Optional[Any]  =    self._sanitize_parameters(prefix=__UpperCamelCase    ,**self._forward_params      )
              _lowerCAmelCase       :   str  =    {**self._preprocess_params, **preprocess_params}
              _lowerCAmelCase       :   Union[str, Any]  =    {**self._forward_params, **forward_params}

  def __lowerCamelCase		(		self    ,_A=None    ,_A=None    ,_A=None    ,_A=None    ,_A=None    ,_A=None    ,_A=None    ,_A=None    ,**_A    ,):
      '''simple docstring'''

      _lowerCAmelCase       :   str  =    {}
      if prefix is not None:
          _lowerCAmelCase       :   Optional[int]  =    prefix
      if prefix:
          _lowerCAmelCase       :   Union[str, Any]  =    self.tokenizer(
              __UpperCamelCase    ,padding=__UpperCamelCase    ,add_special_tokens=__UpperCamelCase    ,return_tensors=self.framework      )
          _lowerCAmelCase       :   Optional[int]  =    prefix_inputs['input_ids'].shape[-1]

      if handle_long_generation is not None:
          if handle_long_generation not in {"hole"}:
              raise ValueError(
                  F"""{handle_long_generation} is not a valid value for `handle_long_generation` parameter expected"""
                  ' [None, \'hole\']'      )
          _lowerCAmelCase       :   Optional[Any]  =    handle_long_generation

      preprocess_params.update(__UpperCamelCase      )
      _lowerCAmelCase       :   str  =    generate_kwargs

      _lowerCAmelCase       :   int  =    {}
      if return_full_text is not None and return_type is None:
          if return_text is not None:
              raise ValueError('`return_text` is mutually exclusive with `return_full_text`'      )
          if return_tensors is not None:
              raise ValueError('`return_full_text` is mutually exclusive with `return_tensors`'      )
          _lowerCAmelCase       :   Union[str, Any]  =    ReturnType.FULL_TEXT if return_full_text else ReturnType.NEW_TEXT
      if return_tensors is not None and return_type is None:
          if return_text is not None:
              raise ValueError('`return_text` is mutually exclusive with `return_tensors`'      )
          _lowerCAmelCase       :   Optional[Any]  =    ReturnType.TENSORS
      if return_type is not None:
          _lowerCAmelCase       :   Union[str, Any]  =    return_type
      if clean_up_tokenization_spaces is not None:
          _lowerCAmelCase       :   str  =    clean_up_tokenization_spaces

      if stop_sequence is not None:
          _lowerCAmelCase       :   Union[str, Any]  =    self.tokenizer.encode(__UpperCamelCase    ,add_special_tokens=__UpperCamelCase      )
          if len(__UpperCamelCase      ) > 1:
              warnings.warn(
                  'Stopping on a multiple token sequence is not yet supported on transformers. The first token of'
                  ' the stop sequence will be used as the stop sequence string in the interim.'      )
          _lowerCAmelCase       :   Dict  =    stop_sequence_ids[0]

      return preprocess_params, forward_params, postprocess_params

  def __lowerCamelCase		(		self    ,*_A    ,**_A      ):
      '''simple docstring'''

      if self.model.__class__.__name__ in ["TransfoXLLMHeadModel"]:
          kwargs.update({'add_space_before_punct_symbol': True}      )

      return super()._parse_and_tokenize(*__UpperCamelCase    ,**__UpperCamelCase      )

  def __call__(		self    ,_A    ,**_A      ):
      '''simple docstring'''

      return super().__call__(__UpperCamelCase    ,**__UpperCamelCase      )

  def __lowerCamelCase		(		self    ,_A    ,_A=""    ,_A=None    ,**_A      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Optional[int]  =    self.tokenizer(
          prefix + prompt_text    ,padding=__UpperCamelCase    ,add_special_tokens=__UpperCamelCase    ,return_tensors=self.framework      )
      _lowerCAmelCase       :   int  =    prompt_text

      if handle_long_generation == "hole":
          _lowerCAmelCase       :   int  =    inputs['input_ids'].shape[-1]
          if "max_new_tokens" in generate_kwargs:
              _lowerCAmelCase       :   Union[str, Any]  =    generate_kwargs['max_new_tokens']
          else:
              _lowerCAmelCase       :   str  =    generate_kwargs.get('max_length'    ,self.model.config.max_length      ) - cur_len
              if new_tokens < 0:
                  raise ValueError('We cannot infer how many new tokens are expected'      )
          if cur_len + new_tokens > self.tokenizer.model_max_length:
              _lowerCAmelCase       :   List[Any]  =    self.tokenizer.model_max_length - new_tokens
              if keep_length <= 0:
                  raise ValueError(
                      'We cannot use `hole` to handle this generation the number of desired tokens exceeds the'
                      ' models max length'      )

              _lowerCAmelCase       :   List[Any]  =    inputs['input_ids'][:, -keep_length:]
              if "attention_mask" in inputs:
                  _lowerCAmelCase       :   Tuple  =    inputs['attention_mask'][:, -keep_length:]

      return inputs

  def __lowerCamelCase		(		self    ,_A    ,**_A      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Optional[Any]  =    model_inputs['input_ids']
      _lowerCAmelCase       :   Dict  =    model_inputs.get('attention_mask'    ,__UpperCamelCase      )
      # Allow empty prompts
      if input_ids.shape[1] == 0:
          _lowerCAmelCase       :   List[str]  =    None
          _lowerCAmelCase       :   int  =    None
          _lowerCAmelCase       :   Optional[Any]  =    1
      else:
          _lowerCAmelCase       :   int  =    input_ids.shape[0]
      _lowerCAmelCase       :   Tuple  =    model_inputs.pop('prompt_text'      )

      # If there is a prefix, we may need to adjust the generation length. Do so without permanently modifying
      # generate_kwargs, as some of the parameterization may come from the initialization of the pipeline.
      _lowerCAmelCase       :   List[Any]  =    generate_kwargs.pop('prefix_length'    ,0      )
      if prefix_length > 0:
          _lowerCAmelCase       :   Tuple  =    'max_new_tokens' in generate_kwargs or (
              'generation_config' in generate_kwargs
              and generate_kwargs['generation_config'].max_new_tokens is not None
          )
          if not has_max_new_tokens:
              _lowerCAmelCase       :   Union[str, Any]  =    generate_kwargs.get('max_length'      ) or self.model.config.max_length
              generate_kwargs["max_length"] += prefix_length
          _lowerCAmelCase       :   Any  =    'min_new_tokens' in generate_kwargs or (
              'generation_config' in generate_kwargs
              and generate_kwargs['generation_config'].min_new_tokens is not None
          )
          if not has_min_new_tokens and "min_length" in generate_kwargs:
              generate_kwargs["min_length"] += prefix_length

        # BS x SL
      _lowerCAmelCase       :   int  =    self.model.generate(input_ids=__UpperCamelCase    ,attention_mask=__UpperCamelCase    ,**__UpperCamelCase      )
      _lowerCAmelCase       :   str  =    generated_sequence.shape[0]
      if self.framework == "pt":
          _lowerCAmelCase       :   int  =    generated_sequence.reshape(__UpperCamelCase    ,out_b // in_b    ,*generated_sequence.shape[1:]      )
      elif self.framework == "tf":
          _lowerCAmelCase       :   Optional[int]  =    tf.reshape(__UpperCamelCase    ,(in_b, out_b // in_b, *generated_sequence.shape[1:])      )
      return {"generated_sequence": generated_sequence, "input_ids": input_ids, "prompt_text": prompt_text}







  def __lowerCamelCase		(		self    ,_A    ,_A=ReturnType.FULL_TEXT    ,_A=True      ):
      '''simple docstring'''

      _lowerCAmelCase       :   int  =    model_outputs['generated_sequence'][0]
      _lowerCAmelCase       :   Union[str, Any]  =    model_outputs['input_ids']
      _lowerCAmelCase       :   Optional[Any]  =    model_outputs['prompt_text']
      _lowerCAmelCase       :   Tuple  =    generated_sequence.numpy().tolist()
      _lowerCAmelCase       :   int  =    []
      for sequence in generated_sequence:
          if return_type == ReturnType.TENSORS:
              _lowerCAmelCase       :   Tuple  =    {'generated_token_ids': sequence}
          elif return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}:
              # Decode text
              _lowerCAmelCase       :   Dict  =    self.tokenizer.decode(
                  __UpperCamelCase    ,skip_special_tokens=__UpperCamelCase    ,clean_up_tokenization_spaces=__UpperCamelCase    ,)

              # Remove PADDING prompt of the sequence if XLNet or Transfo-XL model is used
              if input_ids is None:
                  _lowerCAmelCase       :   List[Any]  =    0
              else:
                  _lowerCAmelCase       :   Tuple  =    len(
                      self.tokenizer.decode(
                          input_ids[0]    ,skip_special_tokens=__UpperCamelCase    ,clean_up_tokenization_spaces=__UpperCamelCase    ,)      )

              if return_type == ReturnType.FULL_TEXT:
                  _lowerCAmelCase       :   Any  =    prompt_text + text[prompt_length:]
              else:
                  _lowerCAmelCase       :   str  =    text[prompt_length:]

              _lowerCAmelCase       :   str  =    {'generated_text': all_text}
          records.append(__UpperCamelCase      )

      return records








"""simple docstring"""






import gc
import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer

from diffusers import AutoencoderKL, DDIMScheduler, LDMTextToImagePipeline, UNetaDConditionModel
from diffusers.utils.testing_utils import (
    enable_full_determinism,
    load_numpy,
    nightly,
    require_torch_gpu,
    slow,
    torch_device,
)

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()







class 	__UpperCamelCase    (    a__							,							unittest.TestCase						):
  _UpperCAmelCase          =		LDMTextToImagePipeline
  _UpperCAmelCase          =		TEXT_TO_IMAGE_PARAMS - {
      "negative_prompt",
      "negative_prompt_embeds",
      "cross_attention_kwargs",
      "prompt_embeds",
  }
  _UpperCAmelCase          =		PipelineTesterMixin.required_optional_params - {
      "num_images_per_prompt",
      "callback",
      "callback_steps",
  }
  _UpperCAmelCase          =		TEXT_TO_IMAGE_BATCH_PARAMS
  _UpperCAmelCase          =		False

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      torch.manual_seed(0      )
      _lowerCAmelCase       :   Optional[int]  =    UNetaDConditionModel(
          block_out_channels=(32, 64)    ,layers_per_block=2    ,sample_size=32    ,in_channels=4    ,out_channels=4    ,down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D')    ,up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D')    ,cross_attention_dim=32    ,)
      _lowerCAmelCase       :   Union[str, Any]  =    DDIMScheduler(
          beta_start=0.0_0_0_8_5    ,beta_end=0.0_1_2    ,beta_schedule='scaled_linear'    ,clip_sample=_A    ,set_alpha_to_one=_A    ,)
      torch.manual_seed(0      )
      _lowerCAmelCase       :   Union[str, Any]  =    AutoencoderKL(
          block_out_channels=(32, 64)    ,in_channels=3    ,out_channels=3    ,down_block_types=('DownEncoderBlock2D', 'DownEncoderBlock2D')    ,up_block_types=('UpDecoderBlock2D', 'UpDecoderBlock2D')    ,latent_channels=4    ,)
      torch.manual_seed(0      )
      _lowerCAmelCase       :   Dict  =    CLIPTextConfig(
          bos_token_id=0    ,eos_token_id=2    ,hidden_size=32    ,intermediate_size=37    ,layer_norm_eps=1E-05    ,num_attention_heads=4    ,num_hidden_layers=5    ,pad_token_id=1    ,vocab_size=1000    ,)
      _lowerCAmelCase       :   Tuple  =    CLIPTextModel(_A      )
      _lowerCAmelCase       :   Any  =    CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'      )

      _lowerCAmelCase       :   List[str]  =    {
          'unet': unet,
          'scheduler': scheduler,
          'vqvae': vae,
          'bert': text_encoder,
          'tokenizer': tokenizer,
      }
      return components

  def __lowerCamelCase		(		self    ,_A    ,_A=0      ):
      '''simple docstring'''

      if str(_A      ).startswith('mps'      ):
          _lowerCAmelCase       :   int  =    torch.manual_seed(_A      )
      else:
          _lowerCAmelCase       :   Optional[Any]  =    torch.Generator(device=_A      ).manual_seed(_A      )
      _lowerCAmelCase       :   List[Any]  =    {
          'prompt': 'A painting of a squirrel eating a burger',
          'generator': generator,
          'num_inference_steps': 2,
          'guidance_scale': 6.0,
          'output_type': 'numpy',
      }
      return inputs







  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Optional[int]  =    'cpu'  # ensure determinism for the device-dependent torch.Generator

      _lowerCAmelCase       :   int  =    self.get_dummy_components()
      _lowerCAmelCase       :   str  =    LDMTextToImagePipeline(**_A      )
      pipe.to(_A      )
      pipe.set_progress_bar_config(disable=_A      )

      _lowerCAmelCase       :   List[Any]  =    self.get_dummy_inputs(_A      )
      _lowerCAmelCase       :   Any  =    pipe(**_A      ).images
      _lowerCAmelCase       :   Optional[int]  =    image[0, -3:, -3:, -1]

      assert image.shape == (1, 16, 16, 3)
      _lowerCAmelCase       :   Tuple  =    np.array([0.6_1_0_1, 0.6_1_5_6, 0.5_6_2_2, 0.4_8_9_5, 0.6_6_6_1, 0.3_8_0_4, 0.5_7_4_8, 0.6_1_3_6, 0.5_0_1_4]      )

      assert np.abs(image_slice.flatten() - expected_slice      ).max() < 1E-3







@slow
@require_torch_gpu
class 	__UpperCamelCase    (    unittest.TestCase						):

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      super().tearDown()
      gc.collect()
      torch.cuda.empty_cache()

  def __lowerCamelCase		(		self    ,_A    ,_A=torch.floataa    ,_A=0      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Optional[Any]  =    torch.manual_seed(_A      )
      _lowerCAmelCase       :   Union[str, Any]  =    np.random.RandomState(_A      ).standard_normal((1, 4, 32, 32)      )
      _lowerCAmelCase       :   Optional[Any]  =    torch.from_numpy(_A      ).to(device=_A    ,dtype=_A      )
      _lowerCAmelCase       :   List[str]  =    {
          'prompt': 'A painting of a squirrel eating a burger',
          'latents': latents,
          'generator': generator,
          'num_inference_steps': 3,
          'guidance_scale': 6.0,
          'output_type': 'numpy',
      }
      return inputs







  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   List[str]  =    LDMTextToImagePipeline.from_pretrained('CompVis/ldm-text2im-large-256'      ).to(_A      )
      pipe.set_progress_bar_config(disable=_A      )

      _lowerCAmelCase       :   Optional[Any]  =    self.get_inputs(_A      )
      _lowerCAmelCase       :   List[Any]  =    pipe(**_A      ).images
      _lowerCAmelCase       :   Dict  =    image[0, -3:, -3:, -1].flatten()

      assert image.shape == (1, 256, 256, 3)
      _lowerCAmelCase       :   str  =    np.array([0.5_1_8_2_5, 0.5_2_8_5_0, 0.5_2_5_4_3, 0.5_4_2_5_8, 0.5_2_3_0_4, 0.5_2_5_6_9, 0.5_4_3_6_3, 0.5_5_2_7_6, 0.5_6_8_7_8]      )
      _lowerCAmelCase       :   Dict  =    np.abs(expected_slice - image_slice      ).max()
      assert max_diff < 1E-3







@nightly
@require_torch_gpu
class 	__UpperCamelCase    (    unittest.TestCase						):

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      super().tearDown()
      gc.collect()
      torch.cuda.empty_cache()

  def __lowerCamelCase		(		self    ,_A    ,_A=torch.floataa    ,_A=0      ):
      '''simple docstring'''

      _lowerCAmelCase       :   List[str]  =    torch.manual_seed(_A      )
      _lowerCAmelCase       :   Optional[int]  =    np.random.RandomState(_A      ).standard_normal((1, 4, 32, 32)      )
      _lowerCAmelCase       :   List[Any]  =    torch.from_numpy(_A      ).to(device=_A    ,dtype=_A      )
      _lowerCAmelCase       :   int  =    {
          'prompt': 'A painting of a squirrel eating a burger',
          'latents': latents,
          'generator': generator,
          'num_inference_steps': 50,
          'guidance_scale': 6.0,
          'output_type': 'numpy',
      }
      return inputs







  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   List[str]  =    LDMTextToImagePipeline.from_pretrained('CompVis/ldm-text2im-large-256'      ).to(_A      )
      pipe.set_progress_bar_config(disable=_A      )

      _lowerCAmelCase       :   str  =    self.get_inputs(_A      )
      _lowerCAmelCase       :   Union[str, Any]  =    pipe(**_A      ).images[0]

      _lowerCAmelCase       :   int  =    load_numpy(
          'https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/ldm_text2img/ldm_large_256_ddim.npy'      )
      _lowerCAmelCase       :   List[str]  =    np.abs(expected_image - image      ).max()
      assert max_diff < 1E-3





