


"""simple docstring"""


import json
import os
import unittest

from transformers import AutoTokenizer, GPTaTokenizer, GPTaTokenizerFast
from transformers.models.gpta.tokenization_gpta import VOCAB_FILES_NAMES
from transformers.testing_utils import require_tokenizers

from ...test_tokenization_common import TokenizerTesterMixin



@require_tokenizers
class   _a      (      _UpperCamelCase		,		unittest.TestCase ):
    a_    :				Optional[int]             =    GPTaTokenizer
    a_    :				str             =    GPTaTokenizerFast
    a_    :				int             =    True
    a_    :				Optional[Any]             =    {'add_prefix_space': True}
    a_    :				List[str]             =    False
    def      _UpperCamelCase       ( self							:					Any				):
          super().setUp()

          # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt
          lowerCamelCase__           =		[
              "l",
              "o",
              "w",
              "e",
              "r",
              "s",
              "t",
              "i",
              "d",
              "n",
              "\u0120",
              "\u0120l",
              "\u0120n",
              "\u0120lo",
              "\u0120low",
              "er",
              "\u0120lowest",
              "\u0120newer",
              "\u0120wider",
              "<unk>",
              "<|endoftext|>",
          ]
          lowerCamelCase__           =		dict(zip(SCREAMING_SNAKE_CASE__							,					range(len(SCREAMING_SNAKE_CASE__				)				)				)				)
          lowerCamelCase__           =		["#version: 0.2", "\u0120 l", "\u0120l o", "\u0120lo w", "e r", ""]
          lowerCamelCase__           =		{"unk_token": "<unk>"}

          lowerCamelCase__           =		os.path.join(self.tmpdirname							,					VOCAB_FILES_NAMES['vocab_file']				)
          lowerCamelCase__           =		os.path.join(self.tmpdirname							,					VOCAB_FILES_NAMES['merges_file']				)
          with open(self.vocab_file							,					'w'							,					encoding='utf-8'				) as fp:
                fp.write(json.dumps(SCREAMING_SNAKE_CASE__				) + '\n'				)
          with open(self.merges_file							,					'w'							,					encoding='utf-8'				) as fp:
                fp.write('\n'.join(SCREAMING_SNAKE_CASE__				)				)
    def      _UpperCamelCase       ( self							:					Tuple							,					**SCREAMING_SNAKE_CASE__							:					int				):
          kwargs.update(self.special_tokens_map				)
          return GPTaTokenizer.from_pretrained(self.tmpdirname							,					**SCREAMING_SNAKE_CASE__				)
    def      _UpperCamelCase       ( self							:					Dict							,					**SCREAMING_SNAKE_CASE__							:					Union[str, Any]				):
          kwargs.update(self.special_tokens_map				)
          return GPTaTokenizerFast.from_pretrained(self.tmpdirname							,					**SCREAMING_SNAKE_CASE__				)
    def      _UpperCamelCase       ( self							:					List[str]							,					SCREAMING_SNAKE_CASE__							:					Dict				):
          lowerCamelCase__           =		"lower newer"
          lowerCamelCase__           =		"lower newer"
          return input_text, output_text
    def      _UpperCamelCase       ( self							:					Any				):
          lowerCamelCase__           =		GPTaTokenizer(self.vocab_file							,					self.merges_file							,					**self.special_tokens_map				)
          lowerCamelCase__           =		"lower newer"
          lowerCamelCase__           =		["\u0120low", "er", "\u0120", "n", "e", "w", "er"]
          lowerCamelCase__           =		tokenizer.tokenize(SCREAMING_SNAKE_CASE__							,					add_prefix_space=SCREAMING_SNAKE_CASE__				)
          self.assertListEqual(SCREAMING_SNAKE_CASE__							,					SCREAMING_SNAKE_CASE__				)

          lowerCamelCase__           =		tokens + [tokenizer.unk_token]
          lowerCamelCase__           =		[14, 15, 10, 9, 3, 2, 15, 19]
          self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__				)							,					SCREAMING_SNAKE_CASE__				)
    def      _UpperCamelCase       ( self							:					Optional[Any]				):
          if not self.test_rust_tokenizer:
                return

          lowerCamelCase__           =		self.get_tokenizer()
          lowerCamelCase__           =		self.get_rust_tokenizer(add_prefix_space=SCREAMING_SNAKE_CASE__				)

          lowerCamelCase__           =		"lower newer"

          # Testing tokenization
          lowerCamelCase__           =		tokenizer.tokenize(SCREAMING_SNAKE_CASE__							,					add_prefix_space=SCREAMING_SNAKE_CASE__				)
          lowerCamelCase__           =		rust_tokenizer.tokenize(SCREAMING_SNAKE_CASE__				)
          self.assertListEqual(SCREAMING_SNAKE_CASE__							,					SCREAMING_SNAKE_CASE__				)

          # Testing conversion to ids without special tokens
          lowerCamelCase__           =		tokenizer.encode(SCREAMING_SNAKE_CASE__							,					add_special_tokens=SCREAMING_SNAKE_CASE__							,					add_prefix_space=SCREAMING_SNAKE_CASE__				)
          lowerCamelCase__           =		rust_tokenizer.encode(SCREAMING_SNAKE_CASE__							,					add_special_tokens=SCREAMING_SNAKE_CASE__				)
          self.assertListEqual(SCREAMING_SNAKE_CASE__							,					SCREAMING_SNAKE_CASE__				)

          # Testing conversion to ids with special tokens
          lowerCamelCase__           =		self.get_rust_tokenizer(add_prefix_space=SCREAMING_SNAKE_CASE__				)
          lowerCamelCase__           =		tokenizer.encode(SCREAMING_SNAKE_CASE__							,					add_prefix_space=SCREAMING_SNAKE_CASE__				)
          lowerCamelCase__           =		rust_tokenizer.encode(SCREAMING_SNAKE_CASE__				)
          self.assertListEqual(SCREAMING_SNAKE_CASE__							,					SCREAMING_SNAKE_CASE__				)

          # Testing the unknown token
          lowerCamelCase__           =		tokens + [rust_tokenizer.unk_token]
          lowerCamelCase__           =		[14, 15, 10, 9, 3, 2, 15, 19]
          self.assertListEqual(rust_tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__				)							,					SCREAMING_SNAKE_CASE__				)
    def      _UpperCamelCase       ( self							:					str							,					*SCREAMING_SNAKE_CASE__							:					List[str]							,					**SCREAMING_SNAKE_CASE__							:					Optional[Any]				):
          # It's very difficult to mix/test pretokenization with byte-level
          # And get both GPT2 and Roberta to work at the same time (mostly an issue of adding a space before the string)
          pass
    def      _UpperCamelCase       ( self							:					Optional[Any]							,					SCREAMING_SNAKE_CASE__							:					int=15				):
          for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
                with self.subTest(F'{tokenizer.__class__.__name__} ({pretrained_name})'				):
                      lowerCamelCase__           =		self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__							,					**SCREAMING_SNAKE_CASE__				)

                      # Simple input
                      lowerCamelCase__           =		"This is a simple input"
                      lowerCamelCase__           =		["This is a simple input 1", "This is a simple input 2"]
                      lowerCamelCase__           =		("This is a simple input", "This is a pair")
                      lowerCamelCase__           =		[
                          ("This is a simple input 1", "This is a simple input 2"),
                          ("This is a simple pair 1", "This is a simple pair 2"),
                      ]

                      # Simple input tests
                      self.assertRaises(SCREAMING_SNAKE_CASE__							,					tokenizer_r.encode							,					SCREAMING_SNAKE_CASE__							,					max_length=SCREAMING_SNAKE_CASE__							,					padding='max_length'				)

                      # Simple input
                      self.assertRaises(SCREAMING_SNAKE_CASE__							,					tokenizer_r.encode_plus							,					SCREAMING_SNAKE_CASE__							,					max_length=SCREAMING_SNAKE_CASE__							,					padding='max_length'				)

                      # Simple input
                      self.assertRaises(
                          SCREAMING_SNAKE_CASE__							,					tokenizer_r.batch_encode_plus							,					SCREAMING_SNAKE_CASE__							,					max_length=SCREAMING_SNAKE_CASE__							,					padding='max_length'							,					)

                      # Pair input
                      self.assertRaises(SCREAMING_SNAKE_CASE__							,					tokenizer_r.encode							,					SCREAMING_SNAKE_CASE__							,					max_length=SCREAMING_SNAKE_CASE__							,					padding='max_length'				)

                      # Pair input
                      self.assertRaises(SCREAMING_SNAKE_CASE__							,					tokenizer_r.encode_plus							,					SCREAMING_SNAKE_CASE__							,					max_length=SCREAMING_SNAKE_CASE__							,					padding='max_length'				)

                      # Pair input
                      self.assertRaises(
                          SCREAMING_SNAKE_CASE__							,					tokenizer_r.batch_encode_plus							,					SCREAMING_SNAKE_CASE__							,					max_length=SCREAMING_SNAKE_CASE__							,					padding='max_length'							,					)
    def      _UpperCamelCase       ( self							:					Any				):
          lowerCamelCase__           =		GPTaTokenizer.from_pretrained(self.tmpdirname							,					pad_token='<pad>'				)

          # Simple input
          lowerCamelCase__           =		"This is a simple input"
          lowerCamelCase__           =		["This is a simple input looooooooong", "This is a simple input"]
          lowerCamelCase__           =		("This is a simple input", "This is a pair")
          lowerCamelCase__           =		[
              ("This is a simple input loooooong", "This is a simple input"),
              ("This is a simple pair loooooong", "This is a simple pair"),
          ]

          lowerCamelCase__           =		tokenizer.pad_token_id

          lowerCamelCase__           =		tokenizer(SCREAMING_SNAKE_CASE__							,					padding='max_length'							,					max_length=30							,					return_tensors='np'				)
          lowerCamelCase__           =		tokenizer(SCREAMING_SNAKE_CASE__							,					padding=SCREAMING_SNAKE_CASE__							,					truncate=SCREAMING_SNAKE_CASE__							,					return_tensors='np'				)
          lowerCamelCase__           =		tokenizer(*SCREAMING_SNAKE_CASE__							,					padding='max_length'							,					max_length=60							,					return_tensors='np'				)
          lowerCamelCase__           =		tokenizer(SCREAMING_SNAKE_CASE__							,					padding=SCREAMING_SNAKE_CASE__							,					truncate=SCREAMING_SNAKE_CASE__							,					return_tensors='np'				)

          # s
          # test single string max_length padding
          self.assertEqual(out_s['input_ids'].shape[-1]							,					30				)
          self.assertTrue(pad_token_id in out_s['input_ids']				)
          self.assertTrue(0 in out_s['attention_mask']				)

          # s2
          # test automatic padding
          self.assertEqual(out_sa['input_ids'].shape[-1]							,					33				)
          # long slice doesn't have padding
          self.assertFalse(pad_token_id in out_sa['input_ids'][0]				)
          self.assertFalse(0 in out_sa['attention_mask'][0]				)
          # short slice does have padding
          self.assertTrue(pad_token_id in out_sa['input_ids'][1]				)
          self.assertTrue(0 in out_sa['attention_mask'][1]				)

          # p
          # test single pair max_length padding
          self.assertEqual(out_p['input_ids'].shape[-1]							,					60				)
          self.assertTrue(pad_token_id in out_p['input_ids']				)
          self.assertTrue(0 in out_p['attention_mask']				)

          # p2
          # test automatic padding pair
          self.assertEqual(out_pa['input_ids'].shape[-1]							,					52				)
          # long slice pair doesn't have padding
          self.assertFalse(pad_token_id in out_pa['input_ids'][0]				)
          self.assertFalse(0 in out_pa['attention_mask'][0]				)
          # short slice pair does have padding
          self.assertTrue(pad_token_id in out_pa['input_ids'][1]				)
          self.assertTrue(0 in out_pa['attention_mask'][1]				)
    def      _UpperCamelCase       ( self							:					str				):
          lowerCamelCase__           =		"$$$"
          lowerCamelCase__           =		GPTaTokenizer.from_pretrained(self.tmpdirname							,					bos_token=SCREAMING_SNAKE_CASE__							,					add_bos_token=SCREAMING_SNAKE_CASE__				)

          lowerCamelCase__           =		"This is a simple input"
          lowerCamelCase__           =		["This is a simple input 1", "This is a simple input 2"]

          lowerCamelCase__           =		tokenizer.bos_token_id

          lowerCamelCase__           =		tokenizer(SCREAMING_SNAKE_CASE__				)
          lowerCamelCase__           =		tokenizer(SCREAMING_SNAKE_CASE__				)

          self.assertEqual(out_s.input_ids[0]							,					SCREAMING_SNAKE_CASE__				)
          self.assertTrue(all(o[0] == bos_token_id for o in out_sa.input_ids				)				)

          lowerCamelCase__           =		tokenizer.decode(out_s.input_ids				)
          lowerCamelCase__           =		tokenizer.batch_decode(out_sa.input_ids				)

          self.assertEqual(decode_s.split()[0]							,					SCREAMING_SNAKE_CASE__				)
          self.assertTrue(all(d.split()[0] == bos_token for d in decode_sa				)				)
    def      _UpperCamelCase       ( self							:					Optional[int]				):
          pass


    def      _UpperCamelCase       ( self							:					Tuple				):
          # TODO: change to self.get_tokenizers() when the fast version is implemented
          lowerCamelCase__           =		[self.get_tokenizer(do_lower_case=SCREAMING_SNAKE_CASE__							,					add_bos_token=SCREAMING_SNAKE_CASE__				)]
          for tokenizer in tokenizers:
                with self.subTest(F'{tokenizer.__class__.__name__}'				):
                      lowerCamelCase__           =		"Encode this."
                      lowerCamelCase__           =		"This one too please."
                      lowerCamelCase__           =		tokenizer.encode(SCREAMING_SNAKE_CASE__							,					add_special_tokens=SCREAMING_SNAKE_CASE__				)
                      encoded_sequence += tokenizer.encode(SCREAMING_SNAKE_CASE__							,					add_special_tokens=SCREAMING_SNAKE_CASE__				)
                      lowerCamelCase__           =		tokenizer.encode_plus(
                          SCREAMING_SNAKE_CASE__							,					SCREAMING_SNAKE_CASE__							,					add_special_tokens=SCREAMING_SNAKE_CASE__							,					return_special_tokens_mask=SCREAMING_SNAKE_CASE__							,					)
                      lowerCamelCase__           =		encoded_sequence_dict["input_ids"]
                      lowerCamelCase__           =		encoded_sequence_dict["special_tokens_mask"]
                      self.assertEqual(len(SCREAMING_SNAKE_CASE__				)							,					len(SCREAMING_SNAKE_CASE__				)				)

                      lowerCamelCase__           =		[
                          (x if not special_tokens_mask[i] else None) for i, x in enumerate(SCREAMING_SNAKE_CASE__				)
                      ]
                      lowerCamelCase__           =		[x for x in filtered_sequence if x is not None]
                      self.assertEqual(SCREAMING_SNAKE_CASE__							,					SCREAMING_SNAKE_CASE__				)





@require_tokenizers
class   _a      (      unittest.TestCase ):
    def      _UpperCamelCase       ( self							:					Union[str, Any]				):
          # More context:
          # https://huggingface.co/wjmcat/opt-350m-paddle/discussions/1
          # https://huggingface.slack.com/archives/C01N44FJDHT/p1653511495183519
          # https://github.com/huggingface/transformers/pull/17088#discussion_r871246439

          lowerCamelCase__           =		AutoTokenizer.from_pretrained('facebook/opt-350m'							,					from_slow=SCREAMING_SNAKE_CASE__				)
          lowerCamelCase__           =		"A photo of a cat"

          lowerCamelCase__           =		tokenizer.encode(
              SCREAMING_SNAKE_CASE__							,					)
          self.assertEqual(SCREAMING_SNAKE_CASE__							,					[2, 2_50, 13_45, 9, 10, 47_58]				)
          tokenizer.save_pretrained('test_opt'				)

          lowerCamelCase__           =		AutoTokenizer.from_pretrained('./test_opt'				)
          lowerCamelCase__           =		tokenizer.encode(
              SCREAMING_SNAKE_CASE__							,					)
          self.assertEqual(SCREAMING_SNAKE_CASE__							,					[2, 2_50, 13_45, 9, 10, 47_58]				)
    def      _UpperCamelCase       ( self							:					Union[str, Any]				):
          lowerCamelCase__           =		AutoTokenizer.from_pretrained('facebook/opt-350m'							,					use_slow=SCREAMING_SNAKE_CASE__				)
          lowerCamelCase__           =		"A photo of a cat"

          lowerCamelCase__           =		tokenizer.encode(
              SCREAMING_SNAKE_CASE__							,					)
          # Same as above
          self.assertEqual(SCREAMING_SNAKE_CASE__							,					[2, 2_50, 13_45, 9, 10, 47_58]				)


    @unittest.skip('This test is failing because of a bug in the fast tokenizer'				)
    def      _UpperCamelCase       ( self							:					Tuple				):
          lowerCamelCase__           =		AutoTokenizer.from_pretrained('facebook/opt-350m'							,					from_slow=SCREAMING_SNAKE_CASE__				)

          lowerCamelCase__           =		"bos"
          lowerCamelCase__           =		tokenizer.get_vocab()["bos"]

          lowerCamelCase__           =		"A photo of a cat"
          lowerCamelCase__           =		tokenizer.encode(
              SCREAMING_SNAKE_CASE__							,					)
          # We changed the bos token
          self.assertEqual(SCREAMING_SNAKE_CASE__							,					[3_19_57, 2_50, 13_45, 9, 10, 47_58]				)
          tokenizer.save_pretrained('./tok'				)
          lowerCamelCase__           =		AutoTokenizer.from_pretrained('./tok'				)
          self.assertTrue(tokenizer.is_fast				)
          lowerCamelCase__           =		tokenizer.encode(
              SCREAMING_SNAKE_CASE__							,					)
          self.assertEqual(SCREAMING_SNAKE_CASE__							,					[3_19_57, 2_50, 13_45, 9, 10, 47_58]				)







"""simple docstring"""


from dataclasses import dataclass
from typing import List, Optional, Union

import numpy as np
import PIL
import torch
from transformers import CLIPImageProcessor, CLIPVisionModel

from ...models import PriorTransformer
from ...pipelines import DiffusionPipeline
from ...schedulers import HeunDiscreteScheduler
from ...utils import (
    BaseOutput,
    is_accelerate_available,
    logging,
    randn_tensor,
    replace_example_docstring,
)
from .renderer import ShapERenderer


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

_snake_case          =							"\n    Examples:\n        ```py\n        >>> from PIL import Image\n        >>> import torch\n        >>> from diffusers import DiffusionPipeline\n        >>> from diffusers.utils import export_to_gif, load_image\n\n        >>> device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n        >>> repo = \"openai/shap-e-img2img\"\n        >>> pipe = DiffusionPipeline.from_pretrained(repo, torch_dtype=torch.float16)\n        >>> pipe = pipe.to(device)\n\n        >>> guidance_scale = 3.0\n        >>> image_url = \"https://hf.co/datasets/diffusers/docs-images/resolve/main/shap-e/corgi.png\"\n        >>> image = load_image(image_url).convert(\"RGB\")\n\n        >>> images = pipe(\n        ...     image,\n        ...     guidance_scale=guidance_scale,\n        ...     num_inference_steps=64,\n        ...     frame_size=256,\n        ... ).images\n\n        >>> gif_path = export_to_gif(images[0], \"corgi_3d.gif\")\n        ```\n"



@dataclass
class   _a      (      SCREAMING_SNAKE_CASE_ ):
    a_    :				Union[PIL.Image.Image, np.ndarray]





class   _a      (      SCREAMING_SNAKE_CASE_ ):
    def __init__( self							:					Tuple							,					SCREAMING_SNAKE_CASE__							:					PriorTransformer							,					SCREAMING_SNAKE_CASE__							:					CLIPVisionModel							,					SCREAMING_SNAKE_CASE__							:					CLIPImageProcessor							,					SCREAMING_SNAKE_CASE__							:					HeunDiscreteScheduler							,					SCREAMING_SNAKE_CASE__							:					ShapERenderer							,					):
          super().__init__()

          self.register_modules(
              prior=SCREAMING_SNAKE_CASE__							,					image_encoder=SCREAMING_SNAKE_CASE__							,					image_processor=SCREAMING_SNAKE_CASE__							,					scheduler=SCREAMING_SNAKE_CASE__							,					renderer=SCREAMING_SNAKE_CASE__							,					)
    def      _UpperCamelCase       ( self							:					str							,					SCREAMING_SNAKE_CASE__							:					List[str]							,					SCREAMING_SNAKE_CASE__							:					Optional[int]							,					SCREAMING_SNAKE_CASE__							:					int							,					SCREAMING_SNAKE_CASE__							:					str							,					SCREAMING_SNAKE_CASE__							:					List[str]							,					SCREAMING_SNAKE_CASE__							:					List[str]				):
          if latents is None:
                lowerCamelCase__           =		randn_tensor(SCREAMING_SNAKE_CASE__							,					generator=SCREAMING_SNAKE_CASE__							,					device=SCREAMING_SNAKE_CASE__							,					dtype=SCREAMING_SNAKE_CASE__				)
          else:
                if latents.shape != shape:
                      raise ValueError(F'Unexpected latents shape, got {latents.shape}, expected {shape}'				)
                lowerCamelCase__           =		latents.to(SCREAMING_SNAKE_CASE__				)

          lowerCamelCase__           =		latents * scheduler.init_noise_sigma
          return latents
    def      _UpperCamelCase       ( self							:					List[Any]							,					SCREAMING_SNAKE_CASE__							:					List[str]=0				):
          if is_accelerate_available():
                from accelerate import cpu_offload
          else:
                raise ImportError('Please install accelerate via `pip install accelerate`'				)

          lowerCamelCase__           =		torch.device(F'cuda:{gpu_id}'				)

          lowerCamelCase__           =		[self.image_encoder, self.prior]
          for cpu_offloaded_model in models:
                if cpu_offloaded_model is not None:
                      cpu_offload(SCREAMING_SNAKE_CASE__							,					SCREAMING_SNAKE_CASE__				)
    @property
    def      _UpperCamelCase       ( self							:					Dict				):
          if self.device != torch.device('meta'				) or not hasattr(self.image_encoder							,					'_hf_hook'				):
                return self.device
          for module in self.image_encoder.modules():
                if (
                    hasattr(SCREAMING_SNAKE_CASE__							,					'_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							:					Optional[int]							,					SCREAMING_SNAKE_CASE__							:					List[str]							,					SCREAMING_SNAKE_CASE__							:					Dict							,					SCREAMING_SNAKE_CASE__							:					Optional[Any]							,					SCREAMING_SNAKE_CASE__							:					int							,					):
          if isinstance(SCREAMING_SNAKE_CASE__							,					SCREAMING_SNAKE_CASE__				) and isinstance(image[0]							,					torch.Tensor				):
                lowerCamelCase__           =		torch.cat(SCREAMING_SNAKE_CASE__							,					axis=0				) if image[0].ndim == 4 else torch.stack(SCREAMING_SNAKE_CASE__							,					axis=0				)

          if not isinstance(SCREAMING_SNAKE_CASE__							,					torch.Tensor				):
                lowerCamelCase__           =		self.image_processor(SCREAMING_SNAKE_CASE__							,					return_tensors='pt'				).pixel_values[0].unsqueeze(0				)

          lowerCamelCase__           =		image.to(dtype=self.image_encoder.dtype							,					device=SCREAMING_SNAKE_CASE__				)

          lowerCamelCase__           =		self.image_encoder(SCREAMING_SNAKE_CASE__				)['last_hidden_state']
          lowerCamelCase__           =		image_embeds[:, 1:, :].contiguous()  # batch_size, dim, 256

          lowerCamelCase__           =		image_embeds.repeat_interleave(SCREAMING_SNAKE_CASE__							,					dim=0				)

          if do_classifier_free_guidance:
                lowerCamelCase__           =		torch.zeros_like(SCREAMING_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
                lowerCamelCase__           =		torch.cat([negative_image_embeds, image_embeds]				)

          return image_embeds


    @torch.no_grad()
    @replace_example_docstring(SCREAMING_SNAKE_CASE__				)
    def __call__( self							:					List[Any]							,					SCREAMING_SNAKE_CASE__							:					Union[PIL.Image.Image, List[PIL.Image.Image]]							,					SCREAMING_SNAKE_CASE__							:					int = 1							,					SCREAMING_SNAKE_CASE__							:					int = 25							,					SCREAMING_SNAKE_CASE__							:					Optional[Union[torch.Generator, List[torch.Generator]]] = None							,					SCREAMING_SNAKE_CASE__							:					Optional[torch.FloatTensor] = None							,					SCREAMING_SNAKE_CASE__							:					float = 4.0							,					SCREAMING_SNAKE_CASE__							:					int = 64							,					SCREAMING_SNAKE_CASE__							:					Optional[str] = "pil"							,					SCREAMING_SNAKE_CASE__							:					bool = True							,					):

          if isinstance(SCREAMING_SNAKE_CASE__							,					PIL.Image.Image				):
                lowerCamelCase__           =		1
          elif isinstance(SCREAMING_SNAKE_CASE__							,					torch.Tensor				):
                lowerCamelCase__           =		image.shape[0]
          elif isinstance(SCREAMING_SNAKE_CASE__							,					SCREAMING_SNAKE_CASE__				) and isinstance(image[0]							,					(torch.Tensor, PIL.Image.Image)				):
                lowerCamelCase__           =		len(SCREAMING_SNAKE_CASE__				)
          else:
                raise ValueError(
                    F'`image` has to be of type `PIL.Image.Image`, `torch.Tensor`, `List[PIL.Image.Image]` or `List[torch.Tensor]` but is {type(SCREAMING_SNAKE_CASE__				)}'				)

          lowerCamelCase__           =		self._execution_device

          lowerCamelCase__           =		batch_size * num_images_per_prompt

          lowerCamelCase__           =		guidance_scale > 1.0
          lowerCamelCase__           =		self._encode_image(SCREAMING_SNAKE_CASE__							,					SCREAMING_SNAKE_CASE__							,					SCREAMING_SNAKE_CASE__							,					SCREAMING_SNAKE_CASE__				)

          # prior

          self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE__							,					device=SCREAMING_SNAKE_CASE__				)
          lowerCamelCase__           =		self.scheduler.timesteps

          lowerCamelCase__           =		self.prior.config.num_embeddings
          lowerCamelCase__           =		self.prior.config.embedding_dim

          lowerCamelCase__           =		self.prepare_latents(
              (batch_size, num_embeddings * embedding_dim)							,					image_embeds.dtype							,					SCREAMING_SNAKE_CASE__							,					SCREAMING_SNAKE_CASE__							,					SCREAMING_SNAKE_CASE__							,					self.scheduler							,					)

          # YiYi notes: for testing only to match ldm, we can directly create a latents with desired shape: batch_size, num_embeddings, embedding_dim
          lowerCamelCase__           =		latents.reshape(latents.shape[0]							,					SCREAMING_SNAKE_CASE__							,					SCREAMING_SNAKE_CASE__				)

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

                lowerCamelCase__           =		self.prior(
                    SCREAMING_SNAKE_CASE__							,					timestep=SCREAMING_SNAKE_CASE__							,					proj_embedding=SCREAMING_SNAKE_CASE__							,					).predicted_image_embedding

                # remove the variance
                lowerCamelCase__    ,  lowerCamelCase__           =		noise_pred.split(
                    scaled_model_input.shape[2]							,					dim=2				)  # batch_size, num_embeddings, embedding_dim

                if do_classifier_free_guidance is not None:
                      lowerCamelCase__    ,  lowerCamelCase__           =		noise_pred.chunk(2				)
                      lowerCamelCase__           =		noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)

                lowerCamelCase__           =		self.scheduler.step(
                    SCREAMING_SNAKE_CASE__							,					timestep=SCREAMING_SNAKE_CASE__							,					sample=SCREAMING_SNAKE_CASE__							,					).prev_sample

          if output_type == "latent":
                return ShapEPipelineOutput(images=SCREAMING_SNAKE_CASE__				)

          lowerCamelCase__           =		[]
          for i, latent in enumerate(SCREAMING_SNAKE_CASE__				):
                print()
                lowerCamelCase__           =		self.renderer.decode(
                    latent[None, :]							,					SCREAMING_SNAKE_CASE__							,					size=SCREAMING_SNAKE_CASE__							,					ray_batch_size=40_96							,					n_coarse_samples=64							,					n_fine_samples=1_28							,					)

                images.append(SCREAMING_SNAKE_CASE__				)

          lowerCamelCase__           =		torch.stack(SCREAMING_SNAKE_CASE__				)

          if output_type not in ["np", "pil"]:
                raise ValueError(F'Only the output types `pil` and `np` are supported not output_type={output_type}'				)

          lowerCamelCase__           =		images.cpu().numpy()

          if output_type == "pil":
                lowerCamelCase__           =		[self.numpy_to_pil(SCREAMING_SNAKE_CASE__				) for image in images]

          # Offload last model to CPU
          if hasattr(self							,					'final_offload_hook'				) and self.final_offload_hook is not None:
                self.final_offload_hook.offload()

          if not return_dict:
                return (images,)

          return ShapEPipelineOutput(images=SCREAMING_SNAKE_CASE__				)



