


"""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__						(   UpperCAmelCase_							,    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 __a						(							self   :    Any		):
								A					       = UNetaDModel.from_pretrained(
								    'diffusers/consistency-models-test'			,			subfolder='test_unet'			,			)
								return unet







						@property
						def __a						(							self   :    int		):
								A					       = UNetaDModel.from_pretrained(
								    'diffusers/consistency-models-test'			,			subfolder='test_unet_class_cond'			,			)
								return unet







						def __a						(							self   :    Any			,			_lowercase   :    str=False		):
								if class_cond:
										A					       = self.dummy_cond_unet
								else:
										A					       = self.dummy_uncond_unet

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

								A					       = {
								    'unet': unet,
								    'scheduler': scheduler,
								}

								return components







						def __a						(							self   :    Dict			,			_lowercase   :    List[Any]			,			_lowercase   :    Optional[int]=0		):
								if str(_lowercase		).startswith('mps'		):
										A					       = torch.manual_seed(_lowercase		)
								else:
										A					       = torch.Generator(device=_lowercase		).manual_seed(_lowercase		)

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

								return inputs







						def __a						(							self   :    Dict		):
								A					       = 'cpu'  # ensure determinism for the device-dependent torch.Generator
								A					       = self.get_dummy_components()
								A					       = ConsistencyModelPipeline(**_lowercase		)
								A					       = pipe.to(_lowercase		)
								pipe.set_progress_bar_config(disable=_lowercase		)

								A					       = self.get_dummy_inputs(_lowercase		)
								A					       = pipe(**_lowercase		).images
								assert image.shape == (1, 32, 32, 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   :    Any		):
								A					       = 'cpu'  # ensure determinism for the device-dependent torch.Generator
								A					       = self.get_dummy_components(class_cond=_lowercase		)
								A					       = ConsistencyModelPipeline(**_lowercase		)
								A					       = pipe.to(_lowercase		)
								pipe.set_progress_bar_config(disable=_lowercase		)

								A					       = self.get_dummy_inputs(_lowercase		)
								A					       = 0
								A					       = pipe(**_lowercase		).images
								assert image.shape == (1, 32, 32, 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		):
								A					       = 'cpu'  # ensure determinism for the device-dependent torch.Generator
								A					       = self.get_dummy_components()
								A					       = ConsistencyModelPipeline(**_lowercase		)
								A					       = pipe.to(_lowercase		)
								pipe.set_progress_bar_config(disable=_lowercase		)

								A					       = self.get_dummy_inputs(_lowercase		)
								A					       = 1
								A					       = None
								A					       = pipe(**_lowercase		).images
								assert image.shape == (1, 32, 32, 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   :    Union[str, Any]		):
								A					       = 'cpu'  # ensure determinism for the device-dependent torch.Generator
								A					       = self.get_dummy_components(class_cond=_lowercase		)
								A					       = ConsistencyModelPipeline(**_lowercase		)
								A					       = pipe.to(_lowercase		)
								pipe.set_progress_bar_config(disable=_lowercase		)

								A					       = self.get_dummy_inputs(_lowercase		)
								A					       = 1
								A					       = None
								A					       = 0
								A					       = pipe(**_lowercase		).images
								assert image.shape == (1, 32, 32, 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			):







						def __a						(							self   :    Optional[Any]		):
								super().tearDown()
								gc.collect()
								torch.cuda.empty_cache()







						def __a						(							self   :    Dict			,			_lowercase   :    List[str]=0			,			_lowercase   :    int=False			,			_lowercase   :    Tuple="cpu"			,			_lowercase   :    Optional[int]=torch.floataa			,			_lowercase   :    Tuple=(1, 3, 64, 64)		):
								A					       = torch.manual_seed(_lowercase		)

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

								if get_fixed_latents:
										A					       = self.get_fixed_latents(seed=_lowercase			,			device=_lowercase			,			dtype=_lowercase			,			shape=_lowercase		)
										A					       = latents

								return inputs







						def __a						(							self   :    Union[str, Any]			,			_lowercase   :    List[Any]=0			,			_lowercase   :    Any="cpu"			,			_lowercase   :    int=torch.floataa			,			_lowercase   :    int=(1, 3, 64, 64)		):
								if type(_lowercase		) == str:
										A					       = torch.device(_lowercase		)
								A					       = torch.Generator(device=_lowercase		).manual_seed(_lowercase		)
								A					       = randn_tensor(_lowercase			,			generator=_lowercase			,			device=_lowercase			,			dtype=_lowercase		)
								return latents







						def __a						(							self   :    Tuple		):
								A					       = UNetaDModel.from_pretrained('diffusers/consistency_models'			,			subfolder='diffusers_cd_imagenet64_l2'		)
								A					       = CMStochasticIterativeScheduler(
								    num_train_timesteps=40			,			sigma_min=0.0_0_2			,			sigma_max=8_0.0			,			)
								A					       = ConsistencyModelPipeline(unet=_lowercase			,			scheduler=_lowercase		)
								pipe.to(torch_device=_lowercase		)
								pipe.set_progress_bar_config(disable=_lowercase		)

								A					       = self.get_inputs()
								A					       = pipe(**_lowercase		).images
								assert image.shape == (1, 64, 64, 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   :    Dict		):
								A					       = UNetaDModel.from_pretrained('diffusers/consistency_models'			,			subfolder='diffusers_cd_imagenet64_l2'		)
								A					       = CMStochasticIterativeScheduler(
								    num_train_timesteps=40			,			sigma_min=0.0_0_2			,			sigma_max=8_0.0			,			)
								A					       = ConsistencyModelPipeline(unet=_lowercase			,			scheduler=_lowercase		)
								pipe.to(torch_device=_lowercase		)
								pipe.set_progress_bar_config(disable=_lowercase		)

								A					       = self.get_inputs()
								A					       = 1
								A					       = None
								A					       = pipe(**_lowercase		).images
								assert image.shape == (1, 64, 64, 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   :    Any		):
								A					       = UNetaDModel.from_pretrained('diffusers/consistency_models'			,			subfolder='diffusers_cd_imagenet64_l2'		)
								A					       = CMStochasticIterativeScheduler(
								    num_train_timesteps=40			,			sigma_min=0.0_0_2			,			sigma_max=8_0.0			,			)
								A					       = ConsistencyModelPipeline(unet=_lowercase			,			scheduler=_lowercase		)
								pipe.to(torch_device=_lowercase			,			torch_dtype=torch.floataa		)
								pipe.set_progress_bar_config(disable=_lowercase		)

								A					       = 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		):
										A					       = pipe(**_lowercase		).images
								assert image.shape == (1, 64, 64, 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   :    Dict		):
								A					       = UNetaDModel.from_pretrained('diffusers/consistency_models'			,			subfolder='diffusers_cd_imagenet64_l2'		)
								A					       = CMStochasticIterativeScheduler(
								    num_train_timesteps=40			,			sigma_min=0.0_0_2			,			sigma_max=8_0.0			,			)
								A					       = ConsistencyModelPipeline(unet=_lowercase			,			scheduler=_lowercase		)
								pipe.to(torch_device=_lowercase			,			torch_dtype=torch.floataa		)
								pipe.set_progress_bar_config(disable=_lowercase		)

								A					       = self.get_inputs(get_fixed_latents=_lowercase			,			device=_lowercase		)
								A					       = 1
								A					       = None
								# Ensure usage of flash attention in torch 2.0
								with sdp_kernel(enable_flash=_lowercase			,			enable_math=_lowercase			,			enable_mem_efficient=_lowercase		):
										A					       = pipe(**_lowercase		).images
								assert image.shape == (1, 64, 64, 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









"""simple docstring"""


import json
import os
import subprocess
import unittest
from ast import literal_eval

import pytest
from parameterized import parameterized, parameterized_class

from . import is_sagemaker_available


if is_sagemaker_available():
	from sagemaker import Session, TrainingJobAnalytics
	from sagemaker.huggingface import HuggingFace



@pytest.mark.skipif(
    literal_eval(os.getenv("""TEST_SAGEMAKER"""							,    """False"""			)			) is not True							,    reason="""Skipping test because should only be run when releasing minor transformers version"""							,    )
@pytest.mark.usefixtures("""sm_env"""			)
@parameterized_class(
    [
        {
            """framework""": """pytorch""",
            """script""": """run_glue.py""",
            """model_name_or_path""": """distilbert-base-cased""",
            """instance_type""": """ml.p3.16xlarge""",
            """results""": {"""train_runtime""": 650, """eval_accuracy""": 0.7, """eval_loss""": 0.6},
        },
        {
            """framework""": """pytorch""",
            """script""": """run_ddp.py""",
            """model_name_or_path""": """distilbert-base-cased""",
            """instance_type""": """ml.p3.16xlarge""",
            """results""": {"""train_runtime""": 600, """eval_accuracy""": 0.7, """eval_loss""": 0.6},
        },
        {
            """framework""": """tensorflow""",
            """script""": """run_tf_dist.py""",
            """model_name_or_path""": """distilbert-base-cased""",
            """instance_type""": """ml.p3.16xlarge""",
            """results""": {"""train_runtime""": 600, """eval_accuracy""": 0.6, """eval_loss""": 0.7},
        },
    ]			)
class 			lowerCamelCase__						(   unittest.TestCase			):







						def __a						(							self   :    int		):
								if self.framework == "pytorch":
										subprocess.run(
										    f'cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py'.split()			,			encoding='utf-8'			,			check=_lowercase			,			)
								assert hasattr(self			,			'env'		)







						def __a						(							self   :    Optional[int]			,			_lowercase   :    int		):
								A					       = f'{self.env.base_job_name}-{instance_count}-{"ddp" if "ddp" in self.script else "smd"}'
								# distributed data settings
								A					       = {'smdistributed': {'dataparallel': {'enabled': True}}} if self.script != 'run_ddp.py' else None

								# creates estimator
								return HuggingFace(
								    entry_point=self.script			,			source_dir=self.env.test_path			,			role=self.env.role			,			image_uri=self.env.image_uri			,			base_job_name=_lowercase			,			instance_count=_lowercase			,			instance_type=self.instance_type			,			debugger_hook_config=_lowercase			,			hyperparameters={**self.env.distributed_hyperparameters, 'model_name_or_path': self.model_name_or_path}			,			metric_definitions=self.env.metric_definitions			,			distribution=_lowercase			,			py_version='py36'			,			)







						def __a						(							self   :    Tuple			,			_lowercase   :    List[str]		):
								TrainingJobAnalytics(_lowercase		).export_csv(f'{self.env.test_path}/{job_name}_metrics.csv'		)







						@parameterized.expand([(2,)]		)
						def __a						(							self   :    List[Any]			,			_lowercase   :    Union[str, Any]		):
								# create estimator
								A					       = self.create_estimator(_lowercase		)

								# run training
								estimator.fit()

								# result dataframe
								A					       = TrainingJobAnalytics(estimator.latest_training_job.name		).dataframe()

								# extract kpis
								A					       = list(result_metrics_df[result_metrics_df.metric_name == 'eval_accuracy']['value']		)
								A					       = list(result_metrics_df[result_metrics_df.metric_name == 'eval_loss']['value']		)
								# get train time from SageMaker job, this includes starting, preprocessing, stopping
								A					       = (
								    Session().describe_training_job(estimator.latest_training_job.name		).get('TrainingTimeInSeconds'			,			999_999		)
								)

								# assert kpis
								assert train_runtime <= self.results["train_runtime"]
								assert all(t >= self.results['eval_accuracy'] for t in eval_accuracy		)
								assert all(t <= self.results['eval_loss'] for t in eval_loss		)

								# dump tests result into json file to share in PR
								with open(f'{estimator.latest_training_job.name}.json'			,			'w'		) as outfile:
										json.dump({'train_time': train_runtime, 'eval_accuracy': eval_accuracy, 'eval_loss': eval_loss}			,			_lowercase		)





