

'''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      lowercase_      (enum.Enum ):




  """simple docstring"""




  SCREAMING_SNAKE_CASE       :    Tuple							     =     0
  SCREAMING_SNAKE_CASE       :    int							     =     1
  SCREAMING_SNAKE_CASE       :    int							     =     2






@add_end_docstrings(UpperCAmelCase_ )
class      lowercase_      (UpperCAmelCase_ ):




  """simple docstring"""




  SCREAMING_SNAKE_CASE       :    List[Any]							     =     '\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  :	Dict   ,*lowercase__  :	Tuple   ,**lowercase__  :	Tuple     ):
   super().__init__(*__a   ,**__a     )
   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.
    __lowercase				    =					None
    if self.model.config.prefix is not None:
     __lowercase				    =					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.
     __lowercase				    =					self.XL_PREFIX
    if prefix is not None:
     # Recalculate some generate_kwargs linked to prefix.
     __lowercase    ,      __lowercase    ,      __lowercase				    =					self._sanitize_parameters(prefix=__a   ,**self._forward_params     )
     __lowercase				    =					{**self._preprocess_params, **preprocess_params}
     __lowercase				    =					{**self._forward_params, **forward_params}






  def    SCREAMING_SNAKE_CASE ( self  :	int   ,lowercase__  :	Optional[Any]=None   ,lowercase__  :	int=None   ,lowercase__  :	List[Any]=None   ,lowercase__  :	str=None   ,lowercase__  :	int=None   ,lowercase__  :	Dict=None   ,lowercase__  :	Any=None   ,lowercase__  :	List[str]=None   ,**lowercase__  :	Optional[int]   ,):
   __lowercase				    =					{}
   if prefix is not None:
    __lowercase				    =					prefix
   if prefix:
    __lowercase				    =					self.tokenizer(
        __a   ,padding=__a   ,add_special_tokens=__a   ,return_tensors=self.framework     )
    __lowercase				    =					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\']'''     )
    __lowercase				    =					handle_long_generation

   preprocess_params.update(__a     )
   __lowercase				    =					generate_kwargs

   __lowercase				    =					{}
   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`'''     )
    __lowercase				    =					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`'''     )
    __lowercase				    =					ReturnType.TENSORS
   if return_type is not None:
    __lowercase				    =					return_type
   if clean_up_tokenization_spaces is not None:
    __lowercase				    =					clean_up_tokenization_spaces

   if stop_sequence is not None:
    __lowercase				    =					self.tokenizer.encode(__a   ,add_special_tokens=__a     )
    if len(__a     ) > 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.'''     )
    __lowercase				    =					stop_sequence_ids[0]

   return preprocess_params, forward_params, postprocess_params






  def    SCREAMING_SNAKE_CASE ( self  :	List[str]   ,*lowercase__  :	List[str]   ,**lowercase__  :	str     ):



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

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






  def __call__( self  :	Union[str, Any]   ,lowercase__  :	Tuple   ,**lowercase__  :	Optional[int]     ):
   return super().__call__(__a   ,**__a     )






  def    SCREAMING_SNAKE_CASE ( self  :	List[Any]   ,lowercase__  :	List[str]   ,lowercase__  :	Optional[Any]=""   ,lowercase__  :	Tuple=None   ,**lowercase__  :	Optional[Any]     ):
   __lowercase				    =					self.tokenizer(
       prefix + prompt_text   ,padding=__a   ,add_special_tokens=__a   ,return_tensors=self.framework     )
   __lowercase				    =					prompt_text

   if handle_long_generation == "hole":
    __lowercase				    =					inputs['''input_ids'''].shape[-1]
    if "max_new_tokens" in generate_kwargs:
     __lowercase				    =					generate_kwargs['''max_new_tokens''']
    else:
     __lowercase				    =					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:
     __lowercase				    =					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'''     )

     __lowercase				    =					inputs['''input_ids'''][:, -keep_length:]
     if "attention_mask" in inputs:
      __lowercase				    =					inputs['''attention_mask'''][:, -keep_length:]

   return inputs






  def    SCREAMING_SNAKE_CASE ( self  :	Tuple   ,lowercase__  :	Optional[int]   ,**lowercase__  :	Union[str, Any]     ):
   __lowercase				    =					model_inputs['''input_ids''']
   __lowercase				    =					model_inputs.get('''attention_mask'''   ,__a     )
   # Allow empty prompts
   if input_ids.shape[1] == 0:
    __lowercase				    =					None
    __lowercase				    =					None
    __lowercase				    =					1
   else:
    __lowercase				    =					input_ids.shape[0]
   __lowercase				    =					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.
   __lowercase				    =					generate_kwargs.pop('''prefix_length'''   ,0     )
   if prefix_length > 0:
    __lowercase				    =					'''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:
     __lowercase				    =					generate_kwargs.get('''max_length'''     ) or self.model.config.max_length
     generate_kwargs["max_length"] += prefix_length
    __lowercase				    =					'''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
   __lowercase				    =					self.model.generate(input_ids=__a   ,attention_mask=__a   ,**__a     )
   __lowercase				    =					generated_sequence.shape[0]
   if self.framework == "pt":
    __lowercase				    =					generated_sequence.reshape(__a   ,out_b // in_b   ,*generated_sequence.shape[1:]     )
   elif self.framework == "tf":
    __lowercase				    =					tf.reshape(__a   ,(in_b, out_b // in_b, *generated_sequence.shape[1:])     )
   return {"generated_sequence": generated_sequence, "input_ids": input_ids, "prompt_text": prompt_text}






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

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

     if return_type == ReturnType.FULL_TEXT:
      __lowercase				    =					prompt_text + text[prompt_length:]
     else:
      __lowercase				    =					text[prompt_length:]

     __lowercase				    =					{'''generated_text''': all_text}
    records.append(__a     )

   return records






import gc
import random
import unittest

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

from diffusers import AutoencoderKL, DDIMScheduler, DDPMScheduler, StableDiffusionUpscalePipeline, UNetaDConditionModel
from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu


enable_full_determinism()





class  lowerCamelCase__	(    unittest.TestCase):
     """simple docstring"""



     def     _a   (self     ):






           '''simple docstring'''



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







     @property
     def     _a   (self     ):






           '''simple docstring'''



           lowerCamelCase             =		1
           lowerCamelCase             =		3
           lowerCamelCase             =		(32, 32)

           lowerCamelCase             =		floats_tensor((batch_size, num_channels) + sizes					,      rng=random.Random(0     )     ).to(__a     )
           return image







     @property
     def     _a   (self     ):






           '''simple docstring'''



           torch.manual_seed(0     )
           lowerCamelCase             =		UNetaDConditionModel(
               block_out_channels=(32, 32, 64)					,      layers_per_block=2					,      sample_size=32					,      in_channels=7					,      out_channels=4					,      down_block_types=("DownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D")					,      up_block_types=("CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "UpBlock2D")					,      cross_attention_dim=32					,      attention_head_dim=8					,      use_linear_projection=__a					,      only_cross_attention=(True, True, False)					,      num_class_embeds=1_00					,      )
           return model







     @property
     def     _a   (self     ):






           '''simple docstring'''



           torch.manual_seed(0     )
           lowerCamelCase             =		AutoencoderKL(
               block_out_channels=[32, 32, 64]					,      in_channels=3					,      out_channels=3					,      down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D", "DownEncoderBlock2D"]					,      up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D"]					,      latent_channels=4					,      )
           return model







     @property
     def     _a   (self     ):






           '''simple docstring'''



           torch.manual_seed(0     )
           lowerCamelCase             =		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=10_00					,      hidden_act="gelu"					,      projection_dim=5_12					,      )
           return CLIPTextModel(__a     )







     def     _a   (self     ):






           '''simple docstring'''



           lowerCamelCase             =		"cpu"  # ensure determinism for the device-dependent torch.Generator
           lowerCamelCase             =		self.dummy_cond_unet_upscale
           lowerCamelCase             =		DDPMScheduler()
           lowerCamelCase             =		DDIMScheduler(prediction_type="v_prediction"     )
           lowerCamelCase             =		self.dummy_vae
           lowerCamelCase             =		self.dummy_text_encoder
           lowerCamelCase             =		CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"     )

           lowerCamelCase             =		self.dummy_image.cpu().permute(0					,      2					,      3					,      1     )[0]
           lowerCamelCase             =		Image.fromarray(np.uinta(__a     )     ).convert("RGB"     ).resize((64, 64)     )

           # make sure here that pndm scheduler skips prk
           lowerCamelCase             =		StableDiffusionUpscalePipeline(
               unet=__a					,      low_res_scheduler=__a					,      scheduler=__a					,      vae=__a					,      text_encoder=__a					,      tokenizer=__a					,      max_noise_level=3_50					,      )
           lowerCamelCase             =		sd_pipe.to(__a     )
           sd_pipe.set_progress_bar_config(disable=__a     )

           lowerCamelCase             =		"A painting of a squirrel eating a burger"
           lowerCamelCase             =		torch.Generator(device=__a     ).manual_seed(0     )
           lowerCamelCase             =		sd_pipe(
               [prompt]					,      image=__a					,      generator=__a					,      guidance_scale=6.0					,      noise_level=20					,      num_inference_steps=2					,      output_type="np"					,      )

           lowerCamelCase             =		output.images

           lowerCamelCase             =		torch.Generator(device=__a     ).manual_seed(0     )
           lowerCamelCase             =		sd_pipe(
               [prompt]					,      image=__a					,      generator=__a					,      guidance_scale=6.0					,      noise_level=20					,      num_inference_steps=2					,      output_type="np"					,      return_dict=__a					,      )[0]

           lowerCamelCase             =		image[0, -3:, -3:, -1]
           lowerCamelCase             =		image_from_tuple[0, -3:, -3:, -1]

           lowerCamelCase             =		low_res_image.size[0] * 4
           assert image.shape == (1, expected_height_width, expected_height_width, 3)
           lowerCamelCase             =		np.array([0.3113, 0.3910, 0.4272, 0.4859, 0.5061, 0.4652, 0.5362, 0.5715, 0.5661]     )

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







     def     _a   (self     ):






           '''simple docstring'''



           lowerCamelCase             =		"cpu"  # ensure determinism for the device-dependent torch.Generator
           lowerCamelCase             =		self.dummy_cond_unet_upscale
           lowerCamelCase             =		DDPMScheduler()
           lowerCamelCase             =		DDIMScheduler(prediction_type="v_prediction"     )
           lowerCamelCase             =		self.dummy_vae
           lowerCamelCase             =		self.dummy_text_encoder
           lowerCamelCase             =		CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"     )

           lowerCamelCase             =		self.dummy_image.cpu().permute(0					,      2					,      3					,      1     )[0]
           lowerCamelCase             =		Image.fromarray(np.uinta(__a     )     ).convert("RGB"     ).resize((64, 64)     )

           # make sure here that pndm scheduler skips prk
           lowerCamelCase             =		StableDiffusionUpscalePipeline(
               unet=__a					,      low_res_scheduler=__a					,      scheduler=__a					,      vae=__a					,      text_encoder=__a					,      tokenizer=__a					,      max_noise_level=3_50					,      )
           lowerCamelCase             =		sd_pipe.to(__a     )
           sd_pipe.set_progress_bar_config(disable=__a     )

           lowerCamelCase             =		"A painting of a squirrel eating a burger"
           lowerCamelCase             =		sd_pipe(
               2 * [prompt]					,      image=2 * [low_res_image]					,      guidance_scale=6.0					,      noise_level=20					,      num_inference_steps=2					,      output_type="np"					,      )
           lowerCamelCase             =		output.images
           assert image.shape[0] == 2

           lowerCamelCase             =		torch.Generator(device=__a     ).manual_seed(0     )
           lowerCamelCase             =		sd_pipe(
               [prompt]					,      image=__a					,      generator=__a					,      num_images_per_prompt=2					,      guidance_scale=6.0					,      noise_level=20					,      num_inference_steps=2					,      output_type="np"					,      )
           lowerCamelCase             =		output.images
           assert image.shape[0] == 2







     @unittest.skipIf(torch_device != "cuda"					,      "This test requires a GPU"     )
     def     _a   (self     ):






           '''simple docstring'''



           lowerCamelCase             =		self.dummy_cond_unet_upscale
           lowerCamelCase             =		DDPMScheduler()
           lowerCamelCase             =		DDIMScheduler(prediction_type="v_prediction"     )
           lowerCamelCase             =		self.dummy_vae
           lowerCamelCase             =		self.dummy_text_encoder
           lowerCamelCase             =		CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"     )

           lowerCamelCase             =		self.dummy_image.cpu().permute(0					,      2					,      3					,      1     )[0]
           lowerCamelCase             =		Image.fromarray(np.uinta(__a     )     ).convert("RGB"     ).resize((64, 64)     )

           # put models in fp16, except vae as it overflows in fp16
           lowerCamelCase             =		unet.half()
           lowerCamelCase             =		text_encoder.half()

           # make sure here that pndm scheduler skips prk
           lowerCamelCase             =		StableDiffusionUpscalePipeline(
               unet=__a					,      low_res_scheduler=__a					,      scheduler=__a					,      vae=__a					,      text_encoder=__a					,      tokenizer=__a					,      max_noise_level=3_50					,      )
           lowerCamelCase             =		sd_pipe.to(__a     )
           sd_pipe.set_progress_bar_config(disable=__a     )

           lowerCamelCase             =		"A painting of a squirrel eating a burger"
           lowerCamelCase             =		torch.manual_seed(0     )
           lowerCamelCase             =		sd_pipe(
               [prompt]					,      image=__a					,      generator=__a					,      num_inference_steps=2					,      output_type="np"					,      ).images

           lowerCamelCase             =		low_res_image.size[0] * 4
           assert image.shape == (1, expected_height_width, expected_height_width, 3)





@slow
@require_torch_gpu
class  lowerCamelCase__	(    unittest.TestCase):
     """simple docstring"""



     def     _a   (self     ):






           '''simple docstring'''



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







     def     _a   (self     ):






           '''simple docstring'''



           lowerCamelCase             =		load_image(
               "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
               "/sd2-upscale/low_res_cat.png"     )
           lowerCamelCase             =		load_numpy(
               "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-upscale"
               "/upsampled_cat.npy"     )

           lowerCamelCase             =		"stabilityai/stable-diffusion-x4-upscaler"
           lowerCamelCase             =		StableDiffusionUpscalePipeline.from_pretrained(__a     )
           pipe.to(__a     )
           pipe.set_progress_bar_config(disable=__a     )
           pipe.enable_attention_slicing()

           lowerCamelCase             =		"a cat sitting on a park bench"

           lowerCamelCase             =		torch.manual_seed(0     )
           lowerCamelCase             =		pipe(
               prompt=__a					,      image=__a					,      generator=__a					,      output_type="np"					,      )
           lowerCamelCase             =		output.images[0]

           assert image.shape == (5_12, 5_12, 3)
           assert np.abs(expected_image - image     ).max() < 1E-3







     def     _a   (self     ):






           '''simple docstring'''



           lowerCamelCase             =		load_image(
               "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
               "/sd2-upscale/low_res_cat.png"     )
           lowerCamelCase             =		load_numpy(
               "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-upscale"
               "/upsampled_cat_fp16.npy"     )

           lowerCamelCase             =		"stabilityai/stable-diffusion-x4-upscaler"
           lowerCamelCase             =		StableDiffusionUpscalePipeline.from_pretrained(
               __a					,      torch_dtype=torch.floataa					,      )
           pipe.to(__a     )
           pipe.set_progress_bar_config(disable=__a     )
           pipe.enable_attention_slicing()

           lowerCamelCase             =		"a cat sitting on a park bench"

           lowerCamelCase             =		torch.manual_seed(0     )
           lowerCamelCase             =		pipe(
               prompt=__a					,      image=__a					,      generator=__a					,      output_type="np"					,      )
           lowerCamelCase             =		output.images[0]

           assert image.shape == (5_12, 5_12, 3)
           assert np.abs(expected_image - image     ).max() < 5E-1







     def     _a   (self     ):






           '''simple docstring'''



           torch.cuda.empty_cache()
           torch.cuda.reset_max_memory_allocated()
           torch.cuda.reset_peak_memory_stats()

           lowerCamelCase             =		load_image(
               "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
               "/sd2-upscale/low_res_cat.png"     )

           lowerCamelCase             =		"stabilityai/stable-diffusion-x4-upscaler"
           lowerCamelCase             =		StableDiffusionUpscalePipeline.from_pretrained(
               __a					,      torch_dtype=torch.floataa					,      )
           pipe.to(__a     )
           pipe.set_progress_bar_config(disable=__a     )
           pipe.enable_attention_slicing(1     )
           pipe.enable_sequential_cpu_offload()

           lowerCamelCase             =		"a cat sitting on a park bench"

           lowerCamelCase             =		torch.manual_seed(0     )
           lowerCamelCase             =		pipe(
               prompt=__a					,      image=__a					,      generator=__a					,      num_inference_steps=5					,      output_type="np"					,      )

           lowerCamelCase             =		torch.cuda.max_memory_allocated()
           # make sure that less than 2.9 GB is allocated
           assert mem_bytes < 2.9 * 10**9