"""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 		UpperCamelCase      (   lowercase				,     unittest.TestCase						):
				UpperCAmelCase    :				int   =		ConsistencyModelPipeline
				UpperCAmelCase    :				Union[str, Any]   =		UNCONDITIONAL_IMAGE_GENERATION_PARAMS
				UpperCAmelCase    :				Optional[int]   =		UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS

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



				@property
				def  _lowercase					(self    :				Any)   ->     List[str]:
					__snake_case      :							Optional[int]						=			UNetaDModel.from_pretrained(
					    'diffusers/consistency-models-test'     ,  subfolder='test_unet'     ,  )
					return unet



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



				def  _lowercase					(self    :				str     ,  _A    :				Optional[int]=False)   ->     Tuple:
					if class_cond:
						__snake_case      :							List[Any]						=			self.dummy_cond_unet
					else:
						__snake_case      :							Tuple						=			self.dummy_uncond_unet

					# Default to CM multistep sampler
					__snake_case      :							Union[str, Any]						=			CMStochasticIterativeScheduler(
					    num_train_timesteps=40     ,  sigma_min=0.002     ,  sigma_max=80.0     ,  )

					__snake_case      :							Dict						=			{
					    'unet': unet,
					    'scheduler': scheduler,
					}

					return components



				def  _lowercase					(self    :				List[Any]     ,  _A    :				str     ,  _A    :				Union[str, Any]=0)   ->     List[str]:
					if str(_A).startswith('mps'):
						__snake_case      :							str						=			torch.manual_seed(_A)
					else:
						__snake_case      :							List[str]						=			torch.Generator(device=_A).manual_seed(_A)

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

					return inputs



				def  _lowercase					(self    :				Union[str, Any])   ->     List[str]:
					__snake_case      :							Optional[Any]						=			'cpu'  # ensure determinism for the device-dependent torch.Generator
					__snake_case      :							List[Any]						=			self.get_dummy_components()
					__snake_case      :							Dict						=			ConsistencyModelPipeline(**_A)
					__snake_case      :							Optional[Any]						=			pipe.to(_A)
					pipe.set_progress_bar_config(disable=_A)

					__snake_case      :							Tuple						=			self.get_dummy_inputs(_A)
					__snake_case      :							Optional[Any]						=			pipe(**_A).images
					assert image.shape == (1, 32, 32, 3)

					__snake_case      :							Union[str, Any]						=			image[0, -3:, -3:, -1]
					__snake_case      :							List[str]						=			np.array([0.3_572, 0.6_273, 0.4_031, 0.3_961, 0.4_321, 0.5_730, 0.5_266, 0.4_780, 0.5_004])

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



				def  _lowercase					(self    :				Dict)   ->     int:
					__snake_case      :							int						=			'cpu'  # ensure determinism for the device-dependent torch.Generator
					__snake_case      :							Dict						=			self.get_dummy_components(class_cond=_A)
					__snake_case      :							Union[str, Any]						=			ConsistencyModelPipeline(**_A)
					__snake_case      :							List[Any]						=			pipe.to(_A)
					pipe.set_progress_bar_config(disable=_A)

					__snake_case      :							str						=			self.get_dummy_inputs(_A)
					__snake_case      :							Union[str, Any]						=			0
					__snake_case      :							Union[str, Any]						=			pipe(**_A).images
					assert image.shape == (1, 32, 32, 3)

					__snake_case      :							Union[str, Any]						=			image[0, -3:, -3:, -1]
					__snake_case      :							List[str]						=			np.array([0.3_572, 0.6_273, 0.4_031, 0.3_961, 0.4_321, 0.5_730, 0.5_266, 0.4_780, 0.5_004])

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



				def  _lowercase					(self    :				Any)   ->     Optional[int]:
					__snake_case      :							Tuple						=			'cpu'  # ensure determinism for the device-dependent torch.Generator
					__snake_case      :							int						=			self.get_dummy_components()
					__snake_case      :							Optional[Any]						=			ConsistencyModelPipeline(**_A)
					__snake_case      :							List[Any]						=			pipe.to(_A)
					pipe.set_progress_bar_config(disable=_A)

					__snake_case      :							List[str]						=			self.get_dummy_inputs(_A)
					__snake_case      :							Optional[int]						=			1
					__snake_case      :							Any						=			None
					__snake_case      :							Optional[Any]						=			pipe(**_A).images
					assert image.shape == (1, 32, 32, 3)

					__snake_case      :							Union[str, Any]						=			image[0, -3:, -3:, -1]
					__snake_case      :							int						=			np.array([0.5_004, 0.5_004, 0.4_994, 0.5_008, 0.4_976, 0.5_018, 0.4_990, 0.4_982, 0.4_987])

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






				def  _lowercase					(self    :				List[str])   ->     int:
					__snake_case      :							Any						=			'cpu'  # ensure determinism for the device-dependent torch.Generator
					__snake_case      :							Optional[Any]						=			self.get_dummy_components(class_cond=_A)
					__snake_case      :							List[str]						=			ConsistencyModelPipeline(**_A)
					__snake_case      :							Dict						=			pipe.to(_A)
					pipe.set_progress_bar_config(disable=_A)

					__snake_case      :							Optional[int]						=			self.get_dummy_inputs(_A)
					__snake_case      :							Optional[int]						=			1
					__snake_case      :							List[Any]						=			None
					__snake_case      :							Optional[int]						=			0
					__snake_case      :							Tuple						=			pipe(**_A).images
					assert image.shape == (1, 32, 32, 3)

					__snake_case      :							Dict						=			image[0, -3:, -3:, -1]
					__snake_case      :							Dict						=			np.array([0.5_004, 0.5_004, 0.4_994, 0.5_008, 0.4_976, 0.5_018, 0.4_990, 0.4_982, 0.4_987])

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







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



				def  _lowercase					(self    :				Optional[Any])   ->     Tuple:
					super().tearDown()
					gc.collect()
					torch.cuda.empty_cache()



				def  _lowercase					(self    :				int     ,  _A    :				Any=0     ,  _A    :				Optional[int]=False     ,  _A    :				List[Any]="cpu"     ,  _A    :				Dict=torch.floataa     ,  _A    :				Optional[Any]=(1, 3, 64, 64))   ->     Dict:
					__snake_case      :							Tuple						=			torch.manual_seed(_A)

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

					if get_fixed_latents:
						__snake_case      :							Union[str, Any]						=			self.get_fixed_latents(seed=_A     ,  device=_A     ,  dtype=_A     ,  shape=_A)
						__snake_case      :							Any						=			latents

					return inputs



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



				def  _lowercase					(self    :				str)   ->     int:
					__snake_case      :							int						=			UNetaDModel.from_pretrained('diffusers/consistency_models'     ,  subfolder='diffusers_cd_imagenet64_l2')
					__snake_case      :							Tuple						=			CMStochasticIterativeScheduler(
					    num_train_timesteps=40     ,  sigma_min=0.002     ,  sigma_max=80.0     ,  )
					__snake_case      :							Any						=			ConsistencyModelPipeline(unet=_A     ,  scheduler=_A)
					pipe.to(torch_device=_A)
					pipe.set_progress_bar_config(disable=_A)

					__snake_case      :							Union[str, Any]						=			self.get_inputs()
					__snake_case      :							Union[str, Any]						=			pipe(**_A).images
					assert image.shape == (1, 64, 64, 3)

					__snake_case      :							List[Any]						=			image[0, -3:, -3:, -1]

					__snake_case      :							Any						=			np.array([0.0_888, 0.0_881, 0.0_666, 0.0_479, 0.0_292, 0.0_195, 0.0_201, 0.0_163, 0.0_254])

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



				def  _lowercase					(self    :				Optional[Any])   ->     Optional[int]:
					__snake_case      :							Tuple						=			UNetaDModel.from_pretrained('diffusers/consistency_models'     ,  subfolder='diffusers_cd_imagenet64_l2')
					__snake_case      :							str						=			CMStochasticIterativeScheduler(
					    num_train_timesteps=40     ,  sigma_min=0.002     ,  sigma_max=80.0     ,  )
					__snake_case      :							Tuple						=			ConsistencyModelPipeline(unet=_A     ,  scheduler=_A)
					pipe.to(torch_device=_A)
					pipe.set_progress_bar_config(disable=_A)

					__snake_case      :							Dict						=			self.get_inputs()
					__snake_case      :							int						=			1
					__snake_case      :							Optional[Any]						=			None
					__snake_case      :							Optional[Any]						=			pipe(**_A).images
					assert image.shape == (1, 64, 64, 3)

					__snake_case      :							List[str]						=			image[0, -3:, -3:, -1]

					__snake_case      :							Union[str, Any]						=			np.array([0.0_340, 0.0_152, 0.0_063, 0.0_267, 0.0_221, 0.0_107, 0.0_416, 0.0_186, 0.0_217])

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



				@require_torch_a
				def  _lowercase					(self    :				List[Any])   ->     Optional[Any]:
					__snake_case      :							List[Any]						=			UNetaDModel.from_pretrained('diffusers/consistency_models'     ,  subfolder='diffusers_cd_imagenet64_l2')
					__snake_case      :							str						=			CMStochasticIterativeScheduler(
					    num_train_timesteps=40     ,  sigma_min=0.002     ,  sigma_max=80.0     ,  )
					__snake_case      :							int						=			ConsistencyModelPipeline(unet=_A     ,  scheduler=_A)
					pipe.to(torch_device=_A     ,  torch_dtype=torch.floataa)
					pipe.set_progress_bar_config(disable=_A)

					__snake_case      :							Optional[int]						=			self.get_inputs(get_fixed_latents=_A     ,  device=_A)
					# Ensure usage of flash attention in torch 2.0
					with sdp_kernel(enable_flash=_A     ,  enable_math=_A     ,  enable_mem_efficient=_A):
						__snake_case      :							str						=			pipe(**_A).images
					assert image.shape == (1, 64, 64, 3)

					__snake_case      :							List[Any]						=			image[0, -3:, -3:, -1]

					__snake_case      :							Optional[int]						=			np.array([0.1_875, 0.1_428, 0.1_289, 0.2_151, 0.2_092, 0.1_477, 0.1_877, 0.1_641, 0.1_353])

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






				@require_torch_a
				def  _lowercase					(self    :				List[str])   ->     int:
					__snake_case      :							Any						=			UNetaDModel.from_pretrained('diffusers/consistency_models'     ,  subfolder='diffusers_cd_imagenet64_l2')
					__snake_case      :							Optional[int]						=			CMStochasticIterativeScheduler(
					    num_train_timesteps=40     ,  sigma_min=0.002     ,  sigma_max=80.0     ,  )
					__snake_case      :							Any						=			ConsistencyModelPipeline(unet=_A     ,  scheduler=_A)
					pipe.to(torch_device=_A     ,  torch_dtype=torch.floataa)
					pipe.set_progress_bar_config(disable=_A)

					__snake_case      :							Optional[Any]						=			self.get_inputs(get_fixed_latents=_A     ,  device=_A)
					__snake_case      :							Optional[Any]						=			1
					__snake_case      :							Optional[int]						=			None
					# Ensure usage of flash attention in torch 2.0
					with sdp_kernel(enable_flash=_A     ,  enable_math=_A     ,  enable_mem_efficient=_A):
						__snake_case      :							List[str]						=			pipe(**_A).images
					assert image.shape == (1, 64, 64, 3)

					__snake_case      :							Union[str, Any]						=			image[0, -3:, -3:, -1]

					__snake_case      :							Union[str, Any]						=			np.array([0.1_663, 0.1_948, 0.2_275, 0.1_680, 0.1_204, 0.1_245, 0.1_858, 0.1_338, 0.2_095])

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






"""simple docstring"""







from decimal import Decimal, getcontext
from math import ceil, factorial
def   __UpperCAmelCase    (   UpperCAmelCase_   :    int  )							->      str:

	'''simple docstring'''





	if not isinstance(UpperCAmelCase_      ,							UpperCAmelCase_  ):
		raise TypeError('Undefined for non-integers'  )
	elif precision < 1:
		raise ValueError('Undefined for non-natural numbers'  )

	__snake_case      :							Any						=			precision
	__snake_case      :							Optional[int]						=			ceil(precision / 14  )
	__snake_case      :							List[Any]						=			42_68_80 * Decimal(1_00_05  ).sqrt()
	__snake_case      :							Optional[Any]						=			1
	__snake_case      :							Union[str, Any]						=			13_59_14_09
	__snake_case      :							int						=			Decimal(UpperCAmelCase_  )
	for k in range(1      ,							UpperCAmelCase_  ):
		__snake_case      :							Union[str, Any]						=			factorial(6 * k  ) // (factorial(3 * k  ) * factorial(UpperCAmelCase_  ) ** 3)
		linear_term += 5_45_14_01_34
		exponential_term *= -26_25_37_41_26_40_76_80_00
		partial_sum += Decimal(multinomial_term * linear_term  ) / exponential_term
	return str(constant_term / partial_sum  )[:-1]


if __name__ == "__main__":
	_a					:					List[Any]=			50
	print(f'''The first {n} digits of pi is: {pi(n)}''')





