






import subprocess
import sys
import warnings
from argparse import ArgumentParser
from pathlib import Path

from packaging import version

from .. import AutoFeatureExtractor, AutoImageProcessor, AutoProcessor, AutoTokenizer
from ..utils import logging
from ..utils.import_utils import is_optimum_available
from .convert import export, validate_model_outputs
from .features import FeaturesManager
from .utils import get_preprocessor


UpperCamelCase__	=     '1.5.0'

UpperCamelCase__	=     ['vision-encoder-decoder']




def 						__SCREAMING_SNAKE_CASE   (					_UpperCamelCase							):


   """simple docstring"""




   if is_optimum_available():
      from optimum.version import __version__ as optimum_version

      lowercase_		:      List[str]          =       version.parse(A_							)
      if parsed_optimum_version < version.parse(A_							):
         raise RuntimeError(
             F"""transformers.onnx requires optimum >= {MIN_OPTIMUM_VERSION} but {optimum_version} is installed. You """
             "can upgrade optimum by running: pip install -U optimum[exporters]"							)
   else:
      raise RuntimeError(
          "transformers.onnx requires optimum to run, you can install the library by running: pip install "
          "optimum[exporters]"							)
   lowercase_		:      Dict          =       [
       sys.executable,
       "-m",
       "optimum.exporters.onnx",
       F"""--model {args.model}""",
       F"""--task {args.feature}""",
       F"""--framework {args.framework}""" if args.framework is not None else "",
       F"""{args.output}""",
   ]
   lowercase_		:      Tuple          =       subprocess.Popen(" ".join(A_							)  ,						stdout=subprocess.PIPE  ,						shell=A_							)
   proc.wait()

   logger.info(
       "The export was done by optimum.exporters.onnx. We recommend using to use this package directly in future, as "
       "transformers.onnx is deprecated, and will be removed in v5. You can find more information here: "
       "https://huggingface.co/docs/optimum/exporters/onnx/usage_guides/export_a_model."							)




def 						__SCREAMING_SNAKE_CASE   (					_UpperCamelCase							):


   """simple docstring"""




   lowercase_		:      Any          =       args.output if args.output.is_file() else args.output.joinpath("model.onnx"							)
   if not args.output.parent.exists():
      args.output.parent.mkdir(parents=A_							)

   # Allocate the model
   lowercase_		:      Union[str, Any]          =       FeaturesManager.get_model_from_feature(
       args.feature  ,						args.model  ,						framework=args.framework  ,						cache_dir=args.cache_dir							)

   lowercase_      ,						lowercase_		:      Optional[int]          =       FeaturesManager.check_supported_model_or_raise(A_  ,						feature=args.feature							)
   lowercase_		:      List[Any]          =       model_onnx_config(model.config							)

   if model_kind in ENCODER_DECODER_MODELS:
      lowercase_		:      List[str]          =       model.get_encoder()
      lowercase_		:      Optional[int]          =       model.get_decoder()

      lowercase_		:      Union[str, Any]          =       onnx_config.get_encoder_config(encoder_model.config							)
      lowercase_		:      int          =       onnx_config.get_decoder_config(
          encoder_model.config  ,						decoder_model.config  ,						feature=args.feature							)

      if args.opset is None:
         lowercase_		:      Optional[Any]          =       max(encoder_onnx_config.default_onnx_opset  ,						decoder_onnx_config.default_onnx_opset							)

      if args.opset < min(encoder_onnx_config.default_onnx_opset  ,						decoder_onnx_config.default_onnx_opset							):
         raise ValueError(
             F"""Opset {args.opset} is not sufficient to export {model_kind}. At least """
             F""" {min(encoder_onnx_config.default_onnx_opset  ,						decoder_onnx_config.default_onnx_opset							)} is required."""							)

      lowercase_		:      Any          =       AutoFeatureExtractor.from_pretrained(args.model							)

      lowercase_      ,						lowercase_		:      int          =       export(
          A_  ,						A_  ,						A_  ,						args.opset  ,						args.output.parent.joinpath("encoder_model.onnx"							)  ,						)

      validate_model_outputs(
          A_  ,						A_  ,						A_  ,						args.output.parent.joinpath("encoder_model.onnx"							)  ,						A_  ,						args.atol if args.atol else encoder_onnx_config.atol_for_validation  ,						)

      lowercase_		:      Union[str, Any]          =       AutoTokenizer.from_pretrained(args.model							)

      lowercase_      ,						lowercase_		:      List[Any]          =       export(
          A_  ,						A_  ,						A_  ,						args.opset  ,						args.output.parent.joinpath("decoder_model.onnx"							)  ,						)

      validate_model_outputs(
          A_  ,						A_  ,						A_  ,						args.output.parent.joinpath("decoder_model.onnx"							)  ,						A_  ,						args.atol if args.atol else decoder_onnx_config.atol_for_validation  ,						)
      logger.info(
          F"""All good, model saved at: {args.output.parent.joinpath("encoder_model.onnx"							).as_posix()},"""
          F""" {args.output.parent.joinpath("decoder_model.onnx"							).as_posix()}"""							)

   else:
      # Instantiate the appropriate preprocessor
      if args.preprocessor == "auto":
         lowercase_		:      Union[str, Any]          =       get_preprocessor(args.model							)
      elif args.preprocessor == "tokenizer":
         lowercase_		:      Any          =       AutoTokenizer.from_pretrained(args.model							)
      elif args.preprocessor == "image_processor":
         lowercase_		:      Optional[int]          =       AutoImageProcessor.from_pretrained(args.model							)
      elif args.preprocessor == "feature_extractor":
         lowercase_		:      Any          =       AutoFeatureExtractor.from_pretrained(args.model							)
      elif args.preprocessor == "processor":
         lowercase_		:      Any          =       AutoProcessor.from_pretrained(args.model							)
      else:
         raise ValueError(F"""Unknown preprocessor type \'{args.preprocessor}\'"""							)

      # Ensure the requested opset is sufficient
      if args.opset is None:
         lowercase_		:      Union[str, Any]          =       onnx_config.default_onnx_opset

      if args.opset < onnx_config.default_onnx_opset:
         raise ValueError(
             F"""Opset {args.opset} is not sufficient to export {model_kind}. """
             F"""At least  {onnx_config.default_onnx_opset} is required."""							)

      lowercase_      ,						lowercase_		:      Union[str, Any]          =       export(
          A_  ,						A_  ,						A_  ,						args.opset  ,						args.output  ,						)

      if args.atol is None:
         lowercase_		:      str          =       onnx_config.atol_for_validation

      validate_model_outputs(A_  ,						A_  ,						A_  ,						args.output  ,						A_  ,						args.atol							)
      logger.info(F"""All good, model saved at: {args.output.as_posix()}"""							)
      warnings.warn(
          "The export was done by transformers.onnx which is deprecated and will be removed in v5. We recommend"
          " using optimum.exporters.onnx in future. You can find more information here:"
          " https://huggingface.co/docs/optimum/exporters/onnx/usage_guides/export_a_model."  ,						A_  ,						)




def 						__SCREAMING_SNAKE_CASE   (					):


   """simple docstring"""




   lowercase_		:      Optional[Any]          =       ArgumentParser("Hugging Face Transformers ONNX exporter"							)
   parser.add_argument(
       "-m"  ,						"--model"  ,						type=A_  ,						required=A_  ,						help="Model ID on huggingface.co or path on disk to load model from."							)
   parser.add_argument(
       "--feature"  ,						default="default"  ,						help="The type of features to export the model with."  ,						)
   parser.add_argument("--opset"  ,						type=A_  ,						default=A_  ,						help="ONNX opset version to export the model with."							)
   parser.add_argument(
       "--atol"  ,						type=A_  ,						default=A_  ,						help="Absolute difference tolerance when validating the model."							)
   parser.add_argument(
       "--framework"  ,						type=A_  ,						choices=["pt", "tf"]  ,						default=A_  ,						help=(
           "The framework to use for the ONNX export."
           " If not provided, will attempt to use the local checkpoint's original framework"
           " or what is available in the environment."
       )  ,						)
   parser.add_argument("output"  ,						type=A_  ,						help="Path indicating where to store generated ONNX model."							)
   parser.add_argument("--cache_dir"  ,						type=A_  ,						default=A_  ,						help="Path indicating where to store cache."							)
   parser.add_argument(
       "--preprocessor"  ,						type=A_  ,						choices=["auto", "tokenizer", "feature_extractor", "image_processor", "processor"]  ,						default="auto"  ,						help="Which type of preprocessor to use. 'auto' tries to automatically detect it."  ,						)
   parser.add_argument(
       "--export_with_transformers"  ,						action="store_true"  ,						help=(
           "Whether to use transformers.onnx instead of optimum.exporters.onnx to perform the ONNX export. It can be "
           "useful when exporting a model supported in transformers but not in optimum, otherwise it is not "
           "recommended."
       )  ,						)

   lowercase_		:      Any          =       parser.parse_args()
   if args.export_with_transformers or not is_optimum_available():
      export_with_transformers(A_							)
   else:
      export_with_optimum(A_							)


if __name__ == "__main__":
 UpperCamelCase__	=     logging.get_logger('transformers.onnx')  # pylint: disable=invalid-name
 logger.setLevel(logging.INFO)
 main()












'''simple docstring'''
import inspect
from typing import List, Optional, Union

import torch
from torch import nn
from torch.nn import functional as F
from torchvision import transforms
from transformers import CLIPImageProcessor, CLIPModel, CLIPTextModel, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    DiffusionPipeline,
    DPMSolverMultistepScheduler,
    LMSDiscreteScheduler,
    PNDMScheduler,
    UNetaDConditionModel,
)
from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput


class     _UpperCAmelCase  (						nn.Module     ):




    def __init__(     self					:    str					,       a					:    Any					,       a					:    Optional[Any]=1.0     ):






       '''simple docstring'''






       super().__init__()

       lowercase_		:      int          =       cut_size
       lowercase_		:      Optional[Any]          =       cut_power





    def 			lowerCAmelCase__			(     self					:    Union[str, Any]					,       a					:    Optional[Any]					,       a					:    Optional[int]     ):






       '''simple docstring'''






       lowercase_      ,						lowercase_		:      int          =       pixel_values.shape[2:4]
       lowercase_		:      Union[str, Any]          =       min(a					,       a     )
       lowercase_		:      str          =       min(a					,       a					,       self.cut_size     )
       lowercase_		:      Dict          =       []
       for _ in range(a     ):
          lowercase_		:      Optional[int]          =       int(torch.rand([]     ) ** self.cut_power * (max_size - min_size) + min_size     )
          lowercase_		:      Union[str, Any]          =       torch.randint(0					,       sideX - size + 1					,       ()     )
          lowercase_		:      List[str]          =       torch.randint(0					,       sideY - size + 1					,       ()     )
          lowercase_		:      Optional[int]          =       pixel_values[:, :, offsety : offsety + size, offsetx : offsetx + size]
          cutouts.append(F.adaptive_avg_poolad(a					,       self.cut_size     )     )
       return torch.cat(a     )




def 						__SCREAMING_SNAKE_CASE   (					_UpperCamelCase  ,						_UpperCamelCase							):


   """simple docstring"""




   lowercase_		:      List[Any]          =       F.normalize(_UpperCamelCase  ,						dim=-1							)
   lowercase_		:      Any          =       F.normalize(_UpperCamelCase  ,						dim=-1							)
   return (x - y).norm(dim=-1							).div(2							).arcsin().pow(2							).mul(2							)




def 						__SCREAMING_SNAKE_CASE   (					_UpperCamelCase  ,						_UpperCamelCase							):


   """simple docstring"""




   for param in model.parameters():
      lowercase_		:      List[str]          =       value





class     _UpperCAmelCase  (						snake_case     ):




    def __init__(     self					:    int					,       a					:    AutoencoderKL					,       a					:    CLIPTextModel					,       a					:    CLIPModel					,       a					:    CLIPTokenizer					,       a					:    UNetaDConditionModel					,       a					:    Union[PNDMScheduler, LMSDiscreteScheduler, DDIMScheduler, DPMSolverMultistepScheduler]					,       a					:    CLIPImageProcessor					,       ):






       '''simple docstring'''






       super().__init__()
       self.register_modules(
           vae=a					,       text_encoder=a					,       clip_model=a					,       tokenizer=a					,       unet=a					,       scheduler=a					,       feature_extractor=a					,       )

       lowercase_		:      Union[str, Any]          =       transforms.Normalize(mean=feature_extractor.image_mean					,       std=feature_extractor.image_std     )
       lowercase_		:      Optional[int]          =       (
           feature_extractor.size
           if isinstance(feature_extractor.size					,       a     )
           else feature_extractor.size["shortest_edge"]
       )
       lowercase_		:      Union[str, Any]          =       MakeCutouts(self.cut_out_size     )

       set_requires_grad(self.text_encoder					,       a     )
       set_requires_grad(self.clip_model					,       a     )




    def 			lowerCAmelCase__			(     self					:    Union[str, Any]					,       a					:    Optional[Union[str, int]] = "auto"     ):






       '''simple docstring'''






       if slice_size == "auto":
          # half the attention head size is usually a good trade-off between
          # speed and memory
          lowercase_		:      Tuple          =       self.unet.config.attention_head_dim // 2
       self.unet.set_attention_slice(a     )




    def 			lowerCAmelCase__			(     self					:    int     ):






       '''simple docstring'''






       self.enable_attention_slicing(a     )




    def 			lowerCAmelCase__			(     self					:    List[str]     ):






       '''simple docstring'''






       set_requires_grad(self.vae					,       a     )




    def 			lowerCAmelCase__			(     self					:    Optional[Any]     ):






       '''simple docstring'''






       set_requires_grad(self.vae					,       a     )




    def 			lowerCAmelCase__			(     self					:    Any     ):






       '''simple docstring'''






       set_requires_grad(self.unet					,       a     )




    def 			lowerCAmelCase__			(     self					:    Dict     ):






       '''simple docstring'''






       set_requires_grad(self.unet					,       a     )




    @torch.enable_grad()
    def 			lowerCAmelCase__			(     self					:    int					,       a					:    int					,       a					:    str					,       a					:    Dict					,       a					:    str					,       a					:    Dict					,       a					:    Dict					,       a					:    Tuple					,       a					:    Dict					,       a					:    str=True					,       ):






       '''simple docstring'''






       lowercase_		:      Dict          =       latents.detach().requires_grad_()

       lowercase_		:      List[Any]          =       self.scheduler.scale_model_input(a					,       a     )

       # predict the noise residual
       lowercase_		:      List[Any]          =       self.unet(a					,       a					,       encoder_hidden_states=a     ).sample

       if isinstance(self.scheduler					,       (PNDMScheduler, DDIMScheduler, DPMSolverMultistepScheduler)     ):
          lowercase_		:      str          =       self.scheduler.alphas_cumprod[timestep]
          lowercase_		:      str          =       1 - alpha_prod_t
          # compute predicted original sample from predicted noise also called
          # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
          lowercase_		:      List[str]          =       (latents - beta_prod_t ** 0.5 * noise_pred) / alpha_prod_t ** 0.5

          lowercase_		:      Tuple          =       torch.sqrt(a     )
          lowercase_		:      Optional[int]          =       pred_original_sample * (fac) + latents * (1 - fac)
       elif isinstance(self.scheduler					,       a     ):
          lowercase_		:      Any          =       self.scheduler.sigmas[index]
          lowercase_		:      Union[str, Any]          =       latents - sigma * noise_pred
       else:
          raise ValueError(f"""scheduler type {type(self.scheduler     )} not supported"""     )

       lowercase_		:      List[str]          =       1 / self.vae.config.scaling_factor * sample
       lowercase_		:      int          =       self.vae.decode(a     ).sample
       lowercase_		:      int          =       (image / 2 + 0.5).clamp(0					,       1     )

       if use_cutouts:
          lowercase_		:      Optional[int]          =       self.make_cutouts(a					,       a     )
       else:
          lowercase_		:      Optional[Any]          =       transforms.Resize(self.cut_out_size     )(a     )
       lowercase_		:      Union[str, Any]          =       self.normalize(a     ).to(latents.dtype     )

       lowercase_		:      int          =       self.clip_model.get_image_features(a     )
       lowercase_		:      Any          =       image_embeddings_clip / image_embeddings_clip.norm(p=2					,       dim=-1					,       keepdim=a     )

       if use_cutouts:
          lowercase_		:      Dict          =       spherical_dist_loss(a					,       a     )
          lowercase_		:      int          =       dists.view([num_cutouts, sample.shape[0], -1]     )
          lowercase_		:      str          =       dists.sum(2     ).mean(0     ).sum() * clip_guidance_scale
       else:
          lowercase_		:      List[Any]          =       spherical_dist_loss(a					,       a     ).mean() * clip_guidance_scale

       lowercase_		:      Tuple          =       -torch.autograd.grad(a					,       a     )[0]

       if isinstance(self.scheduler					,       a     ):
          lowercase_		:      Optional[int]          =       latents.detach() + grads * (sigma**2)
          lowercase_		:      List[str]          =       noise_pred_original
       else:
          lowercase_		:      List[Any]          =       noise_pred_original - torch.sqrt(a     ) * grads
       return noise_pred, latents





    @torch.no_grad()
    def __call__(     self					:    Tuple					,       a					:    Union[str, List[str]]					,       a					:    Optional[int] = 5_1_2					,       a					:    Optional[int] = 5_1_2					,       a					:    Optional[int] = 5_0					,       a					:    Optional[float] = 7.5					,       a					:    Optional[int] = 1					,       a					:    float = 0.0					,       a					:    Optional[float] = 1_0_0					,       a					:    Optional[Union[str, List[str]]] = None					,       a					:    Optional[int] = 4					,       a					:    Optional[bool] = True					,       a					:    Optional[torch.Generator] = None					,       a					:    Optional[torch.FloatTensor] = None					,       a					:    Optional[str] = "pil"					,       a					:    bool = True					,       ):






       '''simple docstring'''






       if isinstance(a					,       a     ):
          lowercase_		:      str          =       1
       elif isinstance(a					,       a     ):
          lowercase_		:      Any          =       len(a     )
       else:
          raise ValueError(f"""`prompt` has to be of type `str` or `list` but is {type(a     )}"""     )

       if height % 8 != 0 or width % 8 != 0:
          raise ValueError(f"""`height` and `width` have to be divisible by 8 but are {height} and {width}."""     )

       # get prompt text embeddings
       lowercase_		:      str          =       self.tokenizer(
           a					,       padding="max_length"					,       max_length=self.tokenizer.model_max_length					,       truncation=a					,       return_tensors="pt"					,       )
       lowercase_		:      List[Any]          =       self.text_encoder(text_input.input_ids.to(self.device     )     )[0]
       # duplicate text embeddings for each generation per prompt
       lowercase_		:      Union[str, Any]          =       text_embeddings.repeat_interleave(a					,       dim=0     )

       if clip_guidance_scale > 0:
          if clip_prompt is not None:
             lowercase_		:      List[Any]          =       self.tokenizer(
                 a					,       padding="max_length"					,       max_length=self.tokenizer.model_max_length					,       truncation=a					,       return_tensors="pt"					,       ).input_ids.to(self.device     )
          else:
             lowercase_		:      Optional[Any]          =       text_input.input_ids.to(self.device     )
          lowercase_		:      Union[str, Any]          =       self.clip_model.get_text_features(a     )
          lowercase_		:      Dict          =       text_embeddings_clip / text_embeddings_clip.norm(p=2					,       dim=-1					,       keepdim=a     )
          # duplicate text embeddings clip for each generation per prompt
          lowercase_		:      int          =       text_embeddings_clip.repeat_interleave(a					,       dim=0     )

       # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
       # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
       # corresponds to doing no classifier free guidance.
       lowercase_		:      Union[str, Any]          =       guidance_scale > 1.0
       # get unconditional embeddings for classifier free guidance
       if do_classifier_free_guidance:
          lowercase_		:      List[Any]          =       text_input.input_ids.shape[-1]
          lowercase_		:      str          =       self.tokenizer([""]					,       padding="max_length"					,       max_length=a					,       return_tensors="pt"     )
          lowercase_		:      str          =       self.text_encoder(uncond_input.input_ids.to(self.device     )     )[0]
          # duplicate unconditional embeddings for each generation per prompt
          lowercase_		:      Dict          =       uncond_embeddings.repeat_interleave(a					,       dim=0     )

          # 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
          lowercase_		:      Dict          =       torch.cat([uncond_embeddings, text_embeddings]     )

       # get the initial random noise unless the user supplied it

       # Unlike in other pipelines, latents need to be generated in the target device
       # for 1-to-1 results reproducibility with the CompVis implementation.
       # However this currently doesn't work in `mps`.
       lowercase_		:      Optional[Any]          =       (batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8)
       lowercase_		:      str          =       text_embeddings.dtype
       if latents is None:
          if self.device.type == "mps":
             # randn does not work reproducibly on mps
             lowercase_		:      Any          =       torch.randn(a					,       generator=a					,       device="cpu"					,       dtype=a     ).to(
                 self.device     )
          else:
             lowercase_		:      int          =       torch.randn(a					,       generator=a					,       device=self.device					,       dtype=a     )
       else:
          if latents.shape != latents_shape:
             raise ValueError(f"""Unexpected latents shape, got {latents.shape}, expected {latents_shape}"""     )
          lowercase_		:      List[str]          =       latents.to(self.device     )

       # set timesteps
       lowercase_		:      str          =       "offset" in set(inspect.signature(self.scheduler.set_timesteps     ).parameters.keys()     )
       lowercase_		:      List[Any]          =       {}
       if accepts_offset:
          lowercase_		:      Any          =       1

       self.scheduler.set_timesteps(a					,       **a     )

       # Some schedulers like PNDM have timesteps as arrays
       # It's more optimized to move all timesteps to correct device beforehand
       lowercase_		:      Union[str, Any]          =       self.scheduler.timesteps.to(self.device     )

       # scale the initial noise by the standard deviation required by the scheduler
       lowercase_		:      int          =       latents * self.scheduler.init_noise_sigma

       # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
       # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
       # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
       # and should be between [0, 1]
       lowercase_		:      List[str]          =       "eta" in set(inspect.signature(self.scheduler.step     ).parameters.keys()     )
       lowercase_		:      List[Any]          =       {}
       if accepts_eta:
          lowercase_		:      Tuple          =       eta

       # check if the scheduler accepts generator
       lowercase_		:      str          =       "generator" in set(inspect.signature(self.scheduler.step     ).parameters.keys()     )
       if accepts_generator:
          lowercase_		:      List[Any]          =       generator

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

          # predict the noise residual
          lowercase_		:      List[Any]          =       self.unet(a					,       a					,       encoder_hidden_states=a     ).sample

          # perform classifier free guidance
          if do_classifier_free_guidance:
             lowercase_      ,						lowercase_		:      List[Any]          =       noise_pred.chunk(2     )
             lowercase_		:      Optional[int]          =       noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)

          # perform clip guidance
          if clip_guidance_scale > 0:
             lowercase_		:      List[str]          =       (
                 text_embeddings.chunk(2     )[1] if do_classifier_free_guidance else text_embeddings
             )
             lowercase_      ,						lowercase_		:      List[Any]          =       self.cond_fn(
                 a					,       a					,       a					,       a					,       a					,       a					,       a					,       a					,       a					,       )

          # compute the previous noisy sample x_t -> x_t-1
          lowercase_		:      int          =       self.scheduler.step(a					,       a					,       a					,       **a     ).prev_sample

       # scale and decode the image latents with vae
       lowercase_		:      int          =       1 / self.vae.config.scaling_factor * latents
       lowercase_		:      List[str]          =       self.vae.decode(a     ).sample

       lowercase_		:      int          =       (image / 2 + 0.5).clamp(0					,       1     )
       lowercase_		:      Optional[Any]          =       image.cpu().permute(0					,       2					,       3					,       1     ).numpy()

       if output_type == "pil":
          lowercase_		:      List[Any]          =       self.numpy_to_pil(a     )

       if not return_dict:
          return (image, None)

       return StableDiffusionPipelineOutput(images=a					,       nsfw_content_detected=a     )




