


'''simple docstring'''







from typing import Dict, Iterable, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import normalize, rescale, resize, to_channel_dimension_format, to_pil_image
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_pytesseract_available, is_vision_available, logging, requires_backends


if is_vision_available():
 import PIL

# soft dependency
if is_pytesseract_available():
 import pytesseract

SCREAMING_SNAKE_CASE_      =			logging.get_logger(__name__)




def        __lowercase						(      __SCREAMING_SNAKE_CASE				,  __SCREAMING_SNAKE_CASE				,  __SCREAMING_SNAKE_CASE		)				->					Optional[int]:
     """simple docstring"""




     return [
         int(1000 * (box[0] / width)		),
         int(1000 * (box[1] / height)		),
         int(1000 * (box[2] / width)		),
         int(1000 * (box[3] / height)		),
     ]




def        __lowercase						(      __SCREAMING_SNAKE_CASE				,  __SCREAMING_SNAKE_CASE				,  __SCREAMING_SNAKE_CASE		)				->					int:
     """simple docstring"""




     __a       =   to_pil_image(__SCREAMING_SNAKE_CASE		)
     __a ,						__a       =   pil_image.size
     __a       =   pytesseract.image_to_data(__SCREAMING_SNAKE_CASE				,  lang=__SCREAMING_SNAKE_CASE				,  output_type="""dict"""				,  config=__SCREAMING_SNAKE_CASE		)
     __a ,						__a ,						__a ,						__a ,						__a       =   data["""text"""], data["""left"""], data["""top"""], data["""width"""], data["""height"""]

     # filter empty words and corresponding coordinates
     __a       =   [idx for idx, word in enumerate(__SCREAMING_SNAKE_CASE		) if not word.strip()]
     __a       =   [word for idx, word in enumerate(__SCREAMING_SNAKE_CASE		) if idx not in irrelevant_indices]
     __a       =   [coord for idx, coord in enumerate(__SCREAMING_SNAKE_CASE		) if idx not in irrelevant_indices]
     __a       =   [coord for idx, coord in enumerate(__SCREAMING_SNAKE_CASE		) if idx not in irrelevant_indices]
     __a       =   [coord for idx, coord in enumerate(__SCREAMING_SNAKE_CASE		) if idx not in irrelevant_indices]
     __a       =   [coord for idx, coord in enumerate(__SCREAMING_SNAKE_CASE		) if idx not in irrelevant_indices]

     # turn coordinates into (left, top, left+width, top+height) format
     __a       =   []
     for x, y, w, h in zip(__SCREAMING_SNAKE_CASE				,  __SCREAMING_SNAKE_CASE				,  __SCREAMING_SNAKE_CASE				,  __SCREAMING_SNAKE_CASE		):
          __a       =   [x, y, x + w, y + h]
          actual_boxes.append(__SCREAMING_SNAKE_CASE		)

     # finally, normalize the bounding boxes
     __a       =   []
     for box in actual_boxes:
          normalized_boxes.append(normalize_box(__SCREAMING_SNAKE_CASE				,  __SCREAMING_SNAKE_CASE				,  __SCREAMING_SNAKE_CASE		)		)

     assert len(__SCREAMING_SNAKE_CASE		) == len(__SCREAMING_SNAKE_CASE		), "Not as many words as there are bounding boxes"

     return words, normalized_boxes



class  lowerCAmelCase_						(       snake_case__      ):





  """simple docstring"""



  a_       :List[Any]												=["""pixel_values"""]

  def __init__(					self     :							str				,							SCREAMING_SNAKE_CASE__     :							bool = True				,							SCREAMING_SNAKE_CASE__     :							Dict[str, int] = None				,							SCREAMING_SNAKE_CASE__     :							PILImageResampling = PILImageResampling.BILINEAR				,							SCREAMING_SNAKE_CASE__     :							bool = True				,							SCREAMING_SNAKE_CASE__     :							float = 1 / 2_5_5				,							SCREAMING_SNAKE_CASE__     :							bool = True				,							SCREAMING_SNAKE_CASE__     :							Union[float, Iterable[float]] = None				,							SCREAMING_SNAKE_CASE__     :							Union[float, Iterable[float]] = None				,							SCREAMING_SNAKE_CASE__     :							bool = True				,							SCREAMING_SNAKE_CASE__     :							Optional[str] = None				,							SCREAMING_SNAKE_CASE__     :							Optional[str] = ""				,							**SCREAMING_SNAKE_CASE__     :							int				,							):





       '''simple docstring'''

       super().__init__(**SCREAMING_SNAKE_CASE__						)
       __a       =   size if size is not None else {"""height""": 2_2_4, """width""": 2_2_4}
       __a       =   get_size_dict(SCREAMING_SNAKE_CASE__						)

       __a       =   do_resize
       __a       =   size
       __a       =   resample
       __a       =   do_rescale
       __a       =   rescale_value
       __a       =   do_normalize
       __a       =   image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
       __a       =   image_std if image_std is not None else IMAGENET_STANDARD_STD
       __a       =   apply_ocr
       __a       =   ocr_lang
       __a       =   tesseract_config

  def __a						(					self     :							Tuple				,							SCREAMING_SNAKE_CASE__     :							np.ndarray				,							SCREAMING_SNAKE_CASE__     :							Dict[str, int]				,							SCREAMING_SNAKE_CASE__     :							PILImageResampling = PILImageResampling.BILINEAR				,							SCREAMING_SNAKE_CASE__     :							Optional[Union[str, ChannelDimension]] = None				,							**SCREAMING_SNAKE_CASE__     :							Any				,							):





       '''simple docstring'''

       __a       =   get_size_dict(SCREAMING_SNAKE_CASE__						)
       if "height" not in size or "width" not in size:
            raise ValueError(f'''The size dictionary must contain the keys \'height\' and \'width\'. Got {size.keys()}'''						)
       __a       =   (size["""height"""], size["""width"""])
       return resize(SCREAMING_SNAKE_CASE__				,							size=SCREAMING_SNAKE_CASE__				,							resample=SCREAMING_SNAKE_CASE__				,							data_format=SCREAMING_SNAKE_CASE__				,							**SCREAMING_SNAKE_CASE__						)

  def __a						(					self     :							str				,							SCREAMING_SNAKE_CASE__     :							np.ndarray				,							SCREAMING_SNAKE_CASE__     :							Union[int, float]				,							SCREAMING_SNAKE_CASE__     :							Optional[Union[str, ChannelDimension]] = None				,							**SCREAMING_SNAKE_CASE__     :							Optional[Any]				,							):





       '''simple docstring'''

       return rescale(SCREAMING_SNAKE_CASE__				,							scale=SCREAMING_SNAKE_CASE__				,							data_format=SCREAMING_SNAKE_CASE__				,							**SCREAMING_SNAKE_CASE__						)

  def __a						(					self     :							Union[str, Any]				,							SCREAMING_SNAKE_CASE__     :							np.ndarray				,							SCREAMING_SNAKE_CASE__     :							Union[float, Iterable[float]]				,							SCREAMING_SNAKE_CASE__     :							Union[float, Iterable[float]]				,							SCREAMING_SNAKE_CASE__     :							Optional[Union[str, ChannelDimension]] = None				,							**SCREAMING_SNAKE_CASE__     :							str				,							):





       '''simple docstring'''

       return normalize(SCREAMING_SNAKE_CASE__				,							mean=SCREAMING_SNAKE_CASE__				,							std=SCREAMING_SNAKE_CASE__				,							data_format=SCREAMING_SNAKE_CASE__				,							**SCREAMING_SNAKE_CASE__						)


  def __a						(					self     :							Any				,							SCREAMING_SNAKE_CASE__     :							ImageInput				,							SCREAMING_SNAKE_CASE__     :							bool = None				,							SCREAMING_SNAKE_CASE__     :							Dict[str, int] = None				,							SCREAMING_SNAKE_CASE__     :							Union[str, Any]=None				,							SCREAMING_SNAKE_CASE__     :							bool = None				,							SCREAMING_SNAKE_CASE__     :							float = None				,							SCREAMING_SNAKE_CASE__     :							bool = None				,							SCREAMING_SNAKE_CASE__     :							Union[float, Iterable[float]] = None				,							SCREAMING_SNAKE_CASE__     :							Union[float, Iterable[float]] = None				,							SCREAMING_SNAKE_CASE__     :							bool = None				,							SCREAMING_SNAKE_CASE__     :							Optional[str] = None				,							SCREAMING_SNAKE_CASE__     :							Optional[str] = None				,							SCREAMING_SNAKE_CASE__     :							Optional[Union[str, TensorType]] = None				,							SCREAMING_SNAKE_CASE__     :							ChannelDimension = ChannelDimension.FIRST				,							**SCREAMING_SNAKE_CASE__     :							Optional[int]				,							):





       '''simple docstring'''

       __a       =   do_resize if do_resize is not None else self.do_resize
       __a       =   size if size is not None else self.size
       __a       =   get_size_dict(SCREAMING_SNAKE_CASE__						)
       __a       =   resample if resample is not None else self.resample
       __a       =   do_rescale if do_rescale is not None else self.do_rescale
       __a       =   rescale_factor if rescale_factor is not None else self.rescale_factor
       __a       =   do_normalize if do_normalize is not None else self.do_normalize
       __a       =   image_mean if image_mean is not None else self.image_mean
       __a       =   image_std if image_std is not None else self.image_std
       __a       =   apply_ocr if apply_ocr is not None else self.apply_ocr
       __a       =   ocr_lang if ocr_lang is not None else self.ocr_lang
       __a       =   tesseract_config if tesseract_config is not None else self.tesseract_config

       __a       =   make_list_of_images(SCREAMING_SNAKE_CASE__						)

       if not valid_images(SCREAMING_SNAKE_CASE__						):
            raise ValueError(
                """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """
                """torch.Tensor, tf.Tensor or jax.ndarray."""						)

       if do_resize and size is None:
            raise ValueError("""Size must be specified if do_resize is True."""						)

       if do_rescale and rescale_factor is None:
            raise ValueError("""Rescale factor must be specified if do_rescale is True."""						)

       if do_normalize and (image_mean is None or image_std is None):
            raise ValueError("""If do_normalize is True, image_mean and image_std must be specified."""						)

       # All transformations expect numpy arrays.
       __a       =   [to_numpy_array(SCREAMING_SNAKE_CASE__						) for image in images]

       # Tesseract OCR to get words + normalized bounding boxes
       if apply_ocr:
            requires_backends(self				,							"""pytesseract"""						)
            __a       =   []
            __a       =   []
            for image in images:
                 __a ,						__a       =   apply_tesseract(SCREAMING_SNAKE_CASE__				,							SCREAMING_SNAKE_CASE__				,							SCREAMING_SNAKE_CASE__						)
                 words_batch.append(SCREAMING_SNAKE_CASE__						)
                 boxes_batch.append(SCREAMING_SNAKE_CASE__						)

       if do_resize:
            __a       =   [self.resize(image=SCREAMING_SNAKE_CASE__				,							size=SCREAMING_SNAKE_CASE__				,							resample=SCREAMING_SNAKE_CASE__						) for image in images]

       if do_rescale:
            __a       =   [self.rescale(image=SCREAMING_SNAKE_CASE__				,							scale=SCREAMING_SNAKE_CASE__						) for image in images]

       if do_normalize:
            __a       =   [self.normalize(image=SCREAMING_SNAKE_CASE__				,							mean=SCREAMING_SNAKE_CASE__				,							std=SCREAMING_SNAKE_CASE__						) for image in images]

       __a       =   [to_channel_dimension_format(SCREAMING_SNAKE_CASE__				,							SCREAMING_SNAKE_CASE__						) for image in images]

       __a       =   BatchFeature(data={"""pixel_values""": images}				,							tensor_type=SCREAMING_SNAKE_CASE__						)

       if apply_ocr:
            __a       =   words_batch
            __a       =   boxes_batch
       return data










'''simple docstring'''







import gc
import unittest

import numpy as np
import torch
from torch.backends.cuda import sdp_kernel

from diffusers import (
    CMStochasticIterativeScheduler,
    ConsistencyModelPipeline,
    UNetaDModel,
)
from diffusers.utils import randn_tensor, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_a, require_torch_gpu

from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()


class  lowerCAmelCase_						(       snake_case__		,    unittest.TestCase      ):





  """simple docstring"""



  a_       :Optional[int]												=ConsistencyModelPipeline
  a_       :List[Any]												=UNCONDITIONAL_IMAGE_GENERATION_PARAMS
  a_       :Optional[int]												=UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS

  # Override required_optional_params to remove num_images_per_prompt
  a_       :Optional[Any]												=frozenset(
      [
          """num_inference_steps""",
          """generator""",
          """latents""",
          """output_type""",
          """return_dict""",
          """callback""",
          """callback_steps""",
      ]      )

  @property
  def __a						(					self     :							Dict						):





       '''simple docstring'''

       __a       =   UNetaDModel.from_pretrained(
           """diffusers/consistency-models-test"""				,							subfolder="""test_unet"""				,							)
       return unet

  @property
  def __a						(					self     :							Tuple						):





       '''simple docstring'''

       __a       =   UNetaDModel.from_pretrained(
           """diffusers/consistency-models-test"""				,							subfolder="""test_unet_class_cond"""				,							)
       return unet

  def __a						(					self     :							str				,							SCREAMING_SNAKE_CASE__     :							int=False						):





       '''simple docstring'''

       if class_cond:
            __a       =   self.dummy_cond_unet
       else:
            __a       =   self.dummy_uncond_unet

       # Default to CM multistep sampler
       __a       =   CMStochasticIterativeScheduler(
           num_train_timesteps=4_0				,							sigma_min=0.0_0_2				,							sigma_max=8_0.0				,							)

       __a       =   {
           """unet""": unet,
           """scheduler""": scheduler,
       }

       return components

  def __a						(					self     :							Union[str, Any]				,							SCREAMING_SNAKE_CASE__     :							Dict				,							SCREAMING_SNAKE_CASE__     :							int=0						):





       '''simple docstring'''

       if str(SCREAMING_SNAKE_CASE__						).startswith("""mps"""						):
            __a       =   torch.manual_seed(SCREAMING_SNAKE_CASE__						)
       else:
            __a       =   torch.Generator(device=SCREAMING_SNAKE_CASE__						).manual_seed(SCREAMING_SNAKE_CASE__						)

       __a       =   {
           """batch_size""": 1,
           """num_inference_steps""": None,
           """timesteps""": [2_2, 0],
           """generator""": generator,
           """output_type""": """np""",
       }

       return inputs

  def __a						(					self     :							str						):





       '''simple docstring'''

       __a       =   """cpu"""  # ensure determinism for the device-dependent torch.Generator
       __a       =   self.get_dummy_components()
       __a       =   ConsistencyModelPipeline(**SCREAMING_SNAKE_CASE__						)
       __a       =   pipe.to(SCREAMING_SNAKE_CASE__						)
       pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__						)

       __a       =   self.get_dummy_inputs(SCREAMING_SNAKE_CASE__						)
       __a       =   pipe(**SCREAMING_SNAKE_CASE__						).images
       assert image.shape == (1, 3_2, 3_2, 3)

       __a       =   image[0, -3:, -3:, -1]
       __a       =   np.array([0.3_5_7_2, 0.6_2_7_3, 0.4_0_3_1, 0.3_9_6_1, 0.4_3_2_1, 0.5_7_3_0, 0.5_2_6_6, 0.4_7_8_0, 0.5_0_0_4]						)

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

  def __a						(					self     :							int						):





       '''simple docstring'''

       __a       =   """cpu"""  # ensure determinism for the device-dependent torch.Generator
       __a       =   self.get_dummy_components(class_cond=SCREAMING_SNAKE_CASE__						)
       __a       =   ConsistencyModelPipeline(**SCREAMING_SNAKE_CASE__						)
       __a       =   pipe.to(SCREAMING_SNAKE_CASE__						)
       pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__						)

       __a       =   self.get_dummy_inputs(SCREAMING_SNAKE_CASE__						)
       __a       =   0
       __a       =   pipe(**SCREAMING_SNAKE_CASE__						).images
       assert image.shape == (1, 3_2, 3_2, 3)

       __a       =   image[0, -3:, -3:, -1]
       __a       =   np.array([0.3_5_7_2, 0.6_2_7_3, 0.4_0_3_1, 0.3_9_6_1, 0.4_3_2_1, 0.5_7_3_0, 0.5_2_6_6, 0.4_7_8_0, 0.5_0_0_4]						)

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

  def __a						(					self     :							str						):





       '''simple docstring'''

       __a       =   """cpu"""  # ensure determinism for the device-dependent torch.Generator
       __a       =   self.get_dummy_components()
       __a       =   ConsistencyModelPipeline(**SCREAMING_SNAKE_CASE__						)
       __a       =   pipe.to(SCREAMING_SNAKE_CASE__						)
       pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__						)

       __a       =   self.get_dummy_inputs(SCREAMING_SNAKE_CASE__						)
       __a       =   1
       __a       =   None
       __a       =   pipe(**SCREAMING_SNAKE_CASE__						).images
       assert image.shape == (1, 3_2, 3_2, 3)

       __a       =   image[0, -3:, -3:, -1]
       __a       =   np.array([0.5_0_0_4, 0.5_0_0_4, 0.4_9_9_4, 0.5_0_0_8, 0.4_9_7_6, 0.5_0_1_8, 0.4_9_9_0, 0.4_9_8_2, 0.4_9_8_7]						)

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


  def __a						(					self     :							List[Any]						):





       '''simple docstring'''

       __a       =   """cpu"""  # ensure determinism for the device-dependent torch.Generator
       __a       =   self.get_dummy_components(class_cond=SCREAMING_SNAKE_CASE__						)
       __a       =   ConsistencyModelPipeline(**SCREAMING_SNAKE_CASE__						)
       __a       =   pipe.to(SCREAMING_SNAKE_CASE__						)
       pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__						)

       __a       =   self.get_dummy_inputs(SCREAMING_SNAKE_CASE__						)
       __a       =   1
       __a       =   None
       __a       =   0
       __a       =   pipe(**SCREAMING_SNAKE_CASE__						).images
       assert image.shape == (1, 3_2, 3_2, 3)

       __a       =   image[0, -3:, -3:, -1]
       __a       =   np.array([0.5_0_0_4, 0.5_0_0_4, 0.4_9_9_4, 0.5_0_0_8, 0.4_9_7_6, 0.5_0_1_8, 0.4_9_9_0, 0.4_9_8_2, 0.4_9_8_7]						)

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


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





  """simple docstring"""



  def __a						(					self     :							int						):





       '''simple docstring'''

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

  def __a						(					self     :							Union[str, Any]				,							SCREAMING_SNAKE_CASE__     :							Dict=0				,							SCREAMING_SNAKE_CASE__     :							str=False				,							SCREAMING_SNAKE_CASE__     :							int="cpu"				,							SCREAMING_SNAKE_CASE__     :							Union[str, Any]=torch.floataa				,							SCREAMING_SNAKE_CASE__     :							Union[str, Any]=(1, 3, 6_4, 6_4)						):





       '''simple docstring'''

       __a       =   torch.manual_seed(SCREAMING_SNAKE_CASE__						)

       __a       =   {
           """num_inference_steps""": None,
           """timesteps""": [2_2, 0],
           """class_labels""": 0,
           """generator""": generator,
           """output_type""": """np""",
       }

       if get_fixed_latents:
            __a       =   self.get_fixed_latents(seed=SCREAMING_SNAKE_CASE__				,							device=SCREAMING_SNAKE_CASE__				,							dtype=SCREAMING_SNAKE_CASE__				,							shape=SCREAMING_SNAKE_CASE__						)
            __a       =   latents

       return inputs

  def __a						(					self     :							Optional[int]				,							SCREAMING_SNAKE_CASE__     :							str=0				,							SCREAMING_SNAKE_CASE__     :							List[str]="cpu"				,							SCREAMING_SNAKE_CASE__     :							List[str]=torch.floataa				,							SCREAMING_SNAKE_CASE__     :							List[str]=(1, 3, 6_4, 6_4)						):





       '''simple docstring'''

       if type(SCREAMING_SNAKE_CASE__						) == str:
            __a       =   torch.device(SCREAMING_SNAKE_CASE__						)
       __a       =   torch.Generator(device=SCREAMING_SNAKE_CASE__						).manual_seed(SCREAMING_SNAKE_CASE__						)
       __a       =   randn_tensor(SCREAMING_SNAKE_CASE__				,							generator=SCREAMING_SNAKE_CASE__				,							device=SCREAMING_SNAKE_CASE__				,							dtype=SCREAMING_SNAKE_CASE__						)
       return latents

  def __a						(					self     :							str						):





       '''simple docstring'''

       __a       =   UNetaDModel.from_pretrained("""diffusers/consistency_models"""				,							subfolder="""diffusers_cd_imagenet64_l2"""						)
       __a       =   CMStochasticIterativeScheduler(
           num_train_timesteps=4_0				,							sigma_min=0.0_0_2				,							sigma_max=8_0.0				,							)
       __a       =   ConsistencyModelPipeline(unet=SCREAMING_SNAKE_CASE__				,							scheduler=SCREAMING_SNAKE_CASE__						)
       pipe.to(torch_device=SCREAMING_SNAKE_CASE__						)
       pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__						)

       __a       =   self.get_inputs()
       __a       =   pipe(**SCREAMING_SNAKE_CASE__						).images
       assert image.shape == (1, 6_4, 6_4, 3)

       __a       =   image[0, -3:, -3:, -1]

       __a       =   np.array([0.0_8_8_8, 0.0_8_8_1, 0.0_6_6_6, 0.0_4_7_9, 0.0_2_9_2, 0.0_1_9_5, 0.0_2_0_1, 0.0_1_6_3, 0.0_2_5_4]						)

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

  def __a						(					self     :							List[Any]						):





       '''simple docstring'''

       __a       =   UNetaDModel.from_pretrained("""diffusers/consistency_models"""				,							subfolder="""diffusers_cd_imagenet64_l2"""						)
       __a       =   CMStochasticIterativeScheduler(
           num_train_timesteps=4_0				,							sigma_min=0.0_0_2				,							sigma_max=8_0.0				,							)
       __a       =   ConsistencyModelPipeline(unet=SCREAMING_SNAKE_CASE__				,							scheduler=SCREAMING_SNAKE_CASE__						)
       pipe.to(torch_device=SCREAMING_SNAKE_CASE__						)
       pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__						)

       __a       =   self.get_inputs()
       __a       =   1
       __a       =   None
       __a       =   pipe(**SCREAMING_SNAKE_CASE__						).images
       assert image.shape == (1, 6_4, 6_4, 3)

       __a       =   image[0, -3:, -3:, -1]

       __a       =   np.array([0.0_3_4_0, 0.0_1_5_2, 0.0_0_6_3, 0.0_2_6_7, 0.0_2_2_1, 0.0_1_0_7, 0.0_4_1_6, 0.0_1_8_6, 0.0_2_1_7]						)

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

  @require_torch_a
  def __a						(					self     :							Tuple						):





       '''simple docstring'''

       __a       =   UNetaDModel.from_pretrained("""diffusers/consistency_models"""				,							subfolder="""diffusers_cd_imagenet64_l2"""						)
       __a       =   CMStochasticIterativeScheduler(
           num_train_timesteps=4_0				,							sigma_min=0.0_0_2				,							sigma_max=8_0.0				,							)
       __a       =   ConsistencyModelPipeline(unet=SCREAMING_SNAKE_CASE__				,							scheduler=SCREAMING_SNAKE_CASE__						)
       pipe.to(torch_device=SCREAMING_SNAKE_CASE__				,							torch_dtype=torch.floataa						)
       pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__						)

       __a       =   self.get_inputs(get_fixed_latents=SCREAMING_SNAKE_CASE__				,							device=SCREAMING_SNAKE_CASE__						)
       # Ensure usage of flash attention in torch 2.0
       with sdp_kernel(enable_flash=SCREAMING_SNAKE_CASE__				,							enable_math=SCREAMING_SNAKE_CASE__				,							enable_mem_efficient=SCREAMING_SNAKE_CASE__						):
            __a       =   pipe(**SCREAMING_SNAKE_CASE__						).images
       assert image.shape == (1, 6_4, 6_4, 3)

       __a       =   image[0, -3:, -3:, -1]

       __a       =   np.array([0.1_8_7_5, 0.1_4_2_8, 0.1_2_8_9, 0.2_1_5_1, 0.2_0_9_2, 0.1_4_7_7, 0.1_8_7_7, 0.1_6_4_1, 0.1_3_5_3]						)

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


  @require_torch_a
  def __a						(					self     :							Optional[Any]						):





       '''simple docstring'''

       __a       =   UNetaDModel.from_pretrained("""diffusers/consistency_models"""				,							subfolder="""diffusers_cd_imagenet64_l2"""						)
       __a       =   CMStochasticIterativeScheduler(
           num_train_timesteps=4_0				,							sigma_min=0.0_0_2				,							sigma_max=8_0.0				,							)
       __a       =   ConsistencyModelPipeline(unet=SCREAMING_SNAKE_CASE__				,							scheduler=SCREAMING_SNAKE_CASE__						)
       pipe.to(torch_device=SCREAMING_SNAKE_CASE__				,							torch_dtype=torch.floataa						)
       pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__						)

       __a       =   self.get_inputs(get_fixed_latents=SCREAMING_SNAKE_CASE__				,							device=SCREAMING_SNAKE_CASE__						)
       __a       =   1
       __a       =   None
       # Ensure usage of flash attention in torch 2.0
       with sdp_kernel(enable_flash=SCREAMING_SNAKE_CASE__				,							enable_math=SCREAMING_SNAKE_CASE__				,							enable_mem_efficient=SCREAMING_SNAKE_CASE__						):
            __a       =   pipe(**SCREAMING_SNAKE_CASE__						).images
       assert image.shape == (1, 6_4, 6_4, 3)

       __a       =   image[0, -3:, -3:, -1]

       __a       =   np.array([0.1_6_6_3, 0.1_9_4_8, 0.2_2_7_5, 0.1_6_8_0, 0.1_2_0_4, 0.1_2_4_5, 0.1_8_5_8, 0.1_3_3_8, 0.2_0_9_5]						)

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






