
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        _SCREAMING_SNAKE_CASE	( snake_case_     ,			unittest.TestCase		):
	lowerCAmelCase__   =					ConsistencyModelPipeline
	lowerCAmelCase__   =					UNCONDITIONAL_IMAGE_GENERATION_PARAMS
	lowerCAmelCase__   =					UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS

	# Override required_optional_params to remove num_images_per_prompt
	lowerCAmelCase__   =					frozenset(
	    [
	        'num_inference_steps',
	        'generator',
	        'latents',
	        'output_type',
	        'return_dict',
	        'callback',
	        'callback_steps',
	    ]		)



	@property
	def        SCREAMING_SNAKE_CASE_(       self					)							->			Optional[int]:
					lowerCamelCase_         =     UNetaDModel.from_pretrained(
					    "diffusers/consistency-models-test"		,    subfolder="test_unet"		,    )
					return unet



	@property
	def        SCREAMING_SNAKE_CASE_(       self					)							->			Union[str, Any]:
					lowerCamelCase_         =     UNetaDModel.from_pretrained(
					    "diffusers/consistency-models-test"		,    subfolder="test_unet_class_cond"		,    )
					return unet



	def        SCREAMING_SNAKE_CASE_(       self		,    lowercase=False					)							->			Any:
					if class_cond:
									lowerCamelCase_         =     self.dummy_cond_unet
					else:
									lowerCamelCase_         =     self.dummy_uncond_unet

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

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

					return components



	def        SCREAMING_SNAKE_CASE_(       self		,    lowercase		,    lowercase=0					)							->			Optional[int]:
					if str(lowercase					).startswith("mps"					):
									lowerCamelCase_         =     torch.manual_seed(lowercase					)
					else:
									lowerCamelCase_         =     torch.Generator(device=lowercase					).manual_seed(lowercase					)

					lowerCamelCase_         =     {
					    "batch_size": 1,
					    "num_inference_steps": None,
					    "timesteps": [22, 0],
					    "generator": generator,
					    "output_type": "np",
					}

					return inputs



	def        SCREAMING_SNAKE_CASE_(       self					)							->			Tuple:
					lowerCamelCase_         =     "cpu"  # ensure determinism for the device-dependent torch.Generator
					lowerCamelCase_         =     self.get_dummy_components()
					lowerCamelCase_         =     ConsistencyModelPipeline(**lowercase					)
					lowerCamelCase_         =     pipe.to(lowercase					)
					pipe.set_progress_bar_config(disable=lowercase					)

					lowerCamelCase_         =     self.get_dummy_inputs(lowercase					)
					lowerCamelCase_         =     pipe(**lowercase					).images
					assert image.shape == (1, 32, 32, 3)

					lowerCamelCase_         =     image[0, -3:, -3:, -1]
					lowerCamelCase_         =     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        SCREAMING_SNAKE_CASE_(       self					)							->			Dict:
					lowerCamelCase_         =     "cpu"  # ensure determinism for the device-dependent torch.Generator
					lowerCamelCase_         =     self.get_dummy_components(class_cond=lowercase					)
					lowerCamelCase_         =     ConsistencyModelPipeline(**lowercase					)
					lowerCamelCase_         =     pipe.to(lowercase					)
					pipe.set_progress_bar_config(disable=lowercase					)

					lowerCamelCase_         =     self.get_dummy_inputs(lowercase					)
					lowerCamelCase_         =     0
					lowerCamelCase_         =     pipe(**lowercase					).images
					assert image.shape == (1, 32, 32, 3)

					lowerCamelCase_         =     image[0, -3:, -3:, -1]
					lowerCamelCase_         =     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        SCREAMING_SNAKE_CASE_(       self					)							->			List[str]:
					lowerCamelCase_         =     "cpu"  # ensure determinism for the device-dependent torch.Generator
					lowerCamelCase_         =     self.get_dummy_components()
					lowerCamelCase_         =     ConsistencyModelPipeline(**lowercase					)
					lowerCamelCase_         =     pipe.to(lowercase					)
					pipe.set_progress_bar_config(disable=lowercase					)

					lowerCamelCase_         =     self.get_dummy_inputs(lowercase					)
					lowerCamelCase_         =     1
					lowerCamelCase_         =     None
					lowerCamelCase_         =     pipe(**lowercase					).images
					assert image.shape == (1, 32, 32, 3)

					lowerCamelCase_         =     image[0, -3:, -3:, -1]
					lowerCamelCase_         =     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        SCREAMING_SNAKE_CASE_(       self					)							->			str:
					lowerCamelCase_         =     "cpu"  # ensure determinism for the device-dependent torch.Generator
					lowerCamelCase_         =     self.get_dummy_components(class_cond=lowercase					)
					lowerCamelCase_         =     ConsistencyModelPipeline(**lowercase					)
					lowerCamelCase_         =     pipe.to(lowercase					)
					pipe.set_progress_bar_config(disable=lowercase					)

					lowerCamelCase_         =     self.get_dummy_inputs(lowercase					)
					lowerCamelCase_         =     1
					lowerCamelCase_         =     None
					lowerCamelCase_         =     0
					lowerCamelCase_         =     pipe(**lowercase					).images
					assert image.shape == (1, 32, 32, 3)

					lowerCamelCase_         =     image[0, -3:, -3:, -1]
					lowerCamelCase_         =     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        _SCREAMING_SNAKE_CASE	( unittest.TestCase		):



	def        SCREAMING_SNAKE_CASE_(       self					)							->			Optional[int]:
					super().tearDown()
					gc.collect()
					torch.cuda.empty_cache()



	def        SCREAMING_SNAKE_CASE_(       self		,    lowercase=0		,    lowercase=False		,    lowercase="cpu"		,    lowercase=torch.floataa		,    lowercase=(1, 3, 64, 64)					)							->			Optional[int]:
					lowerCamelCase_         =     torch.manual_seed(lowercase					)

					lowerCamelCase_         =     {
					    "num_inference_steps": None,
					    "timesteps": [22, 0],
					    "class_labels": 0,
					    "generator": generator,
					    "output_type": "np",
					}

					if get_fixed_latents:
									lowerCamelCase_         =     self.get_fixed_latents(seed=lowercase		,    device=lowercase		,    dtype=lowercase		,    shape=lowercase					)
									lowerCamelCase_         =     latents

					return inputs



	def        SCREAMING_SNAKE_CASE_(       self		,    lowercase=0		,    lowercase="cpu"		,    lowercase=torch.floataa		,    lowercase=(1, 3, 64, 64)					)							->			Any:
					if type(lowercase					) == str:
									lowerCamelCase_         =     torch.device(lowercase					)
					lowerCamelCase_         =     torch.Generator(device=lowercase					).manual_seed(lowercase					)
					lowerCamelCase_         =     randn_tensor(lowercase		,    generator=lowercase		,    device=lowercase		,    dtype=lowercase					)
					return latents



	def        SCREAMING_SNAKE_CASE_(       self					)							->			int:
					lowerCamelCase_         =     UNetaDModel.from_pretrained("diffusers/consistency_models"		,    subfolder="diffusers_cd_imagenet64_l2"					)
					lowerCamelCase_         =     CMStochasticIterativeScheduler(
					    num_train_timesteps=40		,    sigma_min=0.0_0_2		,    sigma_max=8_0.0		,    )
					lowerCamelCase_         =     ConsistencyModelPipeline(unet=lowercase		,    scheduler=lowercase					)
					pipe.to(torch_device=lowercase					)
					pipe.set_progress_bar_config(disable=lowercase					)

					lowerCamelCase_         =     self.get_inputs()
					lowerCamelCase_         =     pipe(**lowercase					).images
					assert image.shape == (1, 64, 64, 3)

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

					lowerCamelCase_         =     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        SCREAMING_SNAKE_CASE_(       self					)							->			Optional[int]:
					lowerCamelCase_         =     UNetaDModel.from_pretrained("diffusers/consistency_models"		,    subfolder="diffusers_cd_imagenet64_l2"					)
					lowerCamelCase_         =     CMStochasticIterativeScheduler(
					    num_train_timesteps=40		,    sigma_min=0.0_0_2		,    sigma_max=8_0.0		,    )
					lowerCamelCase_         =     ConsistencyModelPipeline(unet=lowercase		,    scheduler=lowercase					)
					pipe.to(torch_device=lowercase					)
					pipe.set_progress_bar_config(disable=lowercase					)

					lowerCamelCase_         =     self.get_inputs()
					lowerCamelCase_         =     1
					lowerCamelCase_         =     None
					lowerCamelCase_         =     pipe(**lowercase					).images
					assert image.shape == (1, 64, 64, 3)

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

					lowerCamelCase_         =     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        SCREAMING_SNAKE_CASE_(       self					)							->			Optional[Any]:
					lowerCamelCase_         =     UNetaDModel.from_pretrained("diffusers/consistency_models"		,    subfolder="diffusers_cd_imagenet64_l2"					)
					lowerCamelCase_         =     CMStochasticIterativeScheduler(
					    num_train_timesteps=40		,    sigma_min=0.0_0_2		,    sigma_max=8_0.0		,    )
					lowerCamelCase_         =     ConsistencyModelPipeline(unet=lowercase		,    scheduler=lowercase					)
					pipe.to(torch_device=lowercase		,    torch_dtype=torch.floataa					)
					pipe.set_progress_bar_config(disable=lowercase					)

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

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

					lowerCamelCase_         =     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        SCREAMING_SNAKE_CASE_(       self					)							->			Tuple:
					lowerCamelCase_         =     UNetaDModel.from_pretrained("diffusers/consistency_models"		,    subfolder="diffusers_cd_imagenet64_l2"					)
					lowerCamelCase_         =     CMStochasticIterativeScheduler(
					    num_train_timesteps=40		,    sigma_min=0.0_0_2		,    sigma_max=8_0.0		,    )
					lowerCamelCase_         =     ConsistencyModelPipeline(unet=lowercase		,    scheduler=lowercase					)
					pipe.to(torch_device=lowercase		,    torch_dtype=torch.floataa					)
					pipe.set_progress_bar_config(disable=lowercase					)

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

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

					lowerCamelCase_         =     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




import json
import os
from pathlib import Path

import pytest

from datasets.download.download_config import DownloadConfig
from datasets.download.download_manager import DownloadManager
from datasets.utils.file_utils import hash_url_to_filename


__A							='''http://www.mocksite.com/file1.txt'''
__A							='''"text": ["foo", "foo"]'''
__A							='''6d8ce9aa78a471c7477201efbeabd3bb01ac2e7d100a6dc024ba1608361f90a8'''




class        _SCREAMING_SNAKE_CASE	:
	lowerCAmelCase__   =					2_00
	lowerCAmelCase__   =					{'Content-Length': '100'}
	lowerCAmelCase__   =					{}



	def        SCREAMING_SNAKE_CASE_(       self		,    **lowercase					)							->			int:
					return [bytes(lowercase		,    "utf-8"					)]





def      lowerCamelCase_					(							*lowerCamelCase__      ,					**lowerCamelCase__       ):
				return MockResponse()





@pytest.mark.parametrize("urls_type"      ,					[str, list, dict]       )
def      lowerCamelCase_					(							lowerCamelCase__      ,					lowerCamelCase__      ,					lowerCamelCase__       ):
				import requests

				monkeypatch.setattr(lowerCamelCase__      ,					"request"      ,					lowerCamelCase__       )

				lowerCamelCase_         =     URL
				if issubclass(lowerCamelCase__      ,					lowerCamelCase__       ):
								lowerCamelCase_         =     url
				elif issubclass(lowerCamelCase__      ,					lowerCamelCase__       ):
								lowerCamelCase_         =     [url]
				elif issubclass(lowerCamelCase__      ,					lowerCamelCase__       ):
								lowerCamelCase_         =     {"train": url}
				lowerCamelCase_         =     "dummy"
				lowerCamelCase_         =     "downloads"
				lowerCamelCase_         =     tmp_path
				lowerCamelCase_         =     DownloadConfig(
				    cache_dir=os.path.join(lowerCamelCase__      ,					lowerCamelCase__       )      ,					use_etag=lowerCamelCase__      ,					)
				lowerCamelCase_         =     DownloadManager(dataset_name=lowerCamelCase__      ,					download_config=lowerCamelCase__       )
				lowerCamelCase_         =     dl_manager.download(lowerCamelCase__       )
				lowerCamelCase_         =     urls
				for downloaded_paths in [downloaded_paths]:
								if isinstance(lowerCamelCase__      ,					lowerCamelCase__       ):
												lowerCamelCase_         =     [downloaded_paths]
												lowerCamelCase_         =     [urls]
								elif isinstance(lowerCamelCase__      ,					lowerCamelCase__       ):
												assert "train" in downloaded_paths.keys()
												lowerCamelCase_         =     downloaded_paths.values()
												lowerCamelCase_         =     urls.values()
								assert downloaded_paths
								for downloaded_path, input_url in zip(lowerCamelCase__      ,					lowerCamelCase__       ):
												assert downloaded_path == dl_manager.downloaded_paths[input_url]
												lowerCamelCase_         =     Path(lowerCamelCase__       )
												lowerCamelCase_         =     downloaded_path.parts
												assert parts[-1] == HASH
												assert parts[-2] == cache_subdir
												assert downloaded_path.exists()
												lowerCamelCase_         =     downloaded_path.read_text()
												assert content == CONTENT
												lowerCamelCase_         =     downloaded_path.with_suffix(".json"       )
												assert metadata_downloaded_path.exists()
												lowerCamelCase_         =     json.loads(metadata_downloaded_path.read_text()       )
												assert metadata_content == {"url": URL, "etag": None}





@pytest.mark.parametrize("paths_type"      ,					[str, list, dict]       )
def      lowerCamelCase_					(							lowerCamelCase__      ,					lowerCamelCase__      ,					lowerCamelCase__       ):
				lowerCamelCase_         =     str(lowerCamelCase__       )
				if issubclass(lowerCamelCase__      ,					lowerCamelCase__       ):
								lowerCamelCase_         =     filename
				elif issubclass(lowerCamelCase__      ,					lowerCamelCase__       ):
								lowerCamelCase_         =     [filename]
				elif issubclass(lowerCamelCase__      ,					lowerCamelCase__       ):
								lowerCamelCase_         =     {"train": filename}
				lowerCamelCase_         =     "dummy"
				lowerCamelCase_         =     xz_file.parent
				lowerCamelCase_         =     "extracted"
				lowerCamelCase_         =     DownloadConfig(
				    cache_dir=lowerCamelCase__      ,					use_etag=lowerCamelCase__      ,					)
				lowerCamelCase_         =     DownloadManager(dataset_name=lowerCamelCase__      ,					download_config=lowerCamelCase__       )
				lowerCamelCase_         =     dl_manager.extract(lowerCamelCase__       )
				lowerCamelCase_         =     paths
				for extracted_paths in [extracted_paths]:
								if isinstance(lowerCamelCase__      ,					lowerCamelCase__       ):
												lowerCamelCase_         =     [extracted_paths]
												lowerCamelCase_         =     [paths]
								elif isinstance(lowerCamelCase__      ,					lowerCamelCase__       ):
												assert "train" in extracted_paths.keys()
												lowerCamelCase_         =     extracted_paths.values()
												lowerCamelCase_         =     paths.values()
								assert extracted_paths
								for extracted_path, input_path in zip(lowerCamelCase__      ,					lowerCamelCase__       ):
												assert extracted_path == dl_manager.extracted_paths[input_path]
												lowerCamelCase_         =     Path(lowerCamelCase__       )
												lowerCamelCase_         =     extracted_path.parts
												assert parts[-1] == hash_url_to_filename(lowerCamelCase__      ,					etag=lowerCamelCase__       )
												assert parts[-2] == extracted_subdir
												assert extracted_path.exists()
												lowerCamelCase_         =     extracted_path.read_text()
												lowerCamelCase_         =     text_file.read_text()
												assert extracted_file_content == expected_file_content





def      lowerCamelCase_					(							lowerCamelCase__      ,					lowerCamelCase__       ):
				assert path.endswith(".jsonl"       )
				for num_items, line in enumerate(lowerCamelCase__      ,					start=1       ):
								lowerCamelCase_         =     json.loads(line.decode("utf-8"       )       )
								assert item.keys() == {"col_1", "col_2", "col_3"}
				assert num_items == 4





@pytest.mark.parametrize("archive_jsonl"      ,					["tar_jsonl_path", "zip_jsonl_path"]       )
def      lowerCamelCase_					(							lowerCamelCase__      ,					lowerCamelCase__       ):
				lowerCamelCase_         =     request.getfixturevalue(lowerCamelCase__       )
				lowerCamelCase_         =     DownloadManager()
				for num_jsonl, (path, file) in enumerate(dl_manager.iter_archive(lowerCamelCase__       )      ,					start=1       ):
								_test_jsonl(lowerCamelCase__      ,					lowerCamelCase__       )
				assert num_jsonl == 2





@pytest.mark.parametrize("archive_nested_jsonl"      ,					["tar_nested_jsonl_path", "zip_nested_jsonl_path"]       )
def      lowerCamelCase_					(							lowerCamelCase__      ,					lowerCamelCase__       ):
				lowerCamelCase_         =     request.getfixturevalue(lowerCamelCase__       )
				lowerCamelCase_         =     DownloadManager()
				for num_tar, (path, file) in enumerate(dl_manager.iter_archive(lowerCamelCase__       )      ,					start=1       ):
								for num_jsonl, (subpath, subfile) in enumerate(dl_manager.iter_archive(lowerCamelCase__       )      ,					start=1       ):
												_test_jsonl(lowerCamelCase__      ,					lowerCamelCase__       )
				assert num_tar == 1
				assert num_jsonl == 2





def      lowerCamelCase_					(							lowerCamelCase__       ):
				lowerCamelCase_         =     DownloadManager()
				for num_file, file in enumerate(dl_manager.iter_files(lowerCamelCase__       )      ,					start=1       ):
								assert os.path.basename(lowerCamelCase__       ) == ("test.txt" if num_file == 1 else "train.txt")
				assert num_file == 2


