

'''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  (   A ,      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       snake_case (				self      :			Any   ):







            """simple docstring"""







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







       @property
       def       snake_case (				self      :			Optional[Any]   ):







            """simple docstring"""







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







       def       snake_case (				self      :			str    ,   __lowercase      :			List[Any]=False   ):







            """simple docstring"""







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

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

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

            return components







       def       snake_case (				self      :			str    ,   __lowercase      :			List[str]    ,   __lowercase      :			int=0   ):







            """simple docstring"""







            if str(__lowercase   ).startswith('mps'   ):
                 __lowercase      		=torch.manual_seed(__lowercase   )
            else:
                 __lowercase      		=torch.Generator(device=__lowercase   ).manual_seed(__lowercase   )

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

            return inputs







       def       snake_case (				self      :			Dict   ):







            """simple docstring"""







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

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

            __lowercase      		=image[0, -3:, -3:, -1]
            __lowercase      		=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       snake_case (				self      :			Optional[Any]   ):







            """simple docstring"""







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

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

            __lowercase      		=image[0, -3:, -3:, -1]
            __lowercase      		=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       snake_case (				self      :			List[str]   ):







            """simple docstring"""







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

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

            __lowercase      		=image[0, -3:, -3:, -1]
            __lowercase      		=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       snake_case (				self      :			Tuple   ):







            """simple docstring"""







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

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

            __lowercase      		=image[0, -3:, -3:, -1]
            __lowercase      		=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       snake_case (				self      :			List[str]   ):







            """simple docstring"""







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







       def       snake_case (				self      :			Any    ,   __lowercase      :			Tuple=0    ,   __lowercase      :			Any=False    ,   __lowercase      :			List[str]="cpu"    ,   __lowercase      :			str=torch.floataa    ,   __lowercase      :			List[str]=(1, 3, 64, 64)   ):







            """simple docstring"""







            __lowercase      		=torch.manual_seed(__lowercase   )

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

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

            return inputs







       def       snake_case (				self      :			List[str]    ,   __lowercase      :			Dict=0    ,   __lowercase      :			List[Any]="cpu"    ,   __lowercase      :			str=torch.floataa    ,   __lowercase      :			Union[str, Any]=(1, 3, 64, 64)   ):







            """simple docstring"""







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







       def       snake_case (				self      :			Any   ):







            """simple docstring"""







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

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

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

            __lowercase      		=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       snake_case (				self      :			Optional[int]   ):







            """simple docstring"""







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

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

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

            __lowercase      		=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       snake_case (				self      :			Union[str, Any]   ):







            """simple docstring"""







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

            __lowercase      		=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   ):
                 __lowercase      		=pipe(**__lowercase   ).images
            assert image.shape == (1, 64, 64, 3)

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

            __lowercase      		=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       snake_case (				self      :			Any   ):







            """simple docstring"""







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

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

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

            __lowercase      		=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'''

from collections import defaultdict
from math import gcd

def 					__UpperCamelCase				(						lowercase__    :	int = 1_50_00_00			):






     '''simple docstring'''





     __lowercase      		=defaultdict(lowercase__			)
     __lowercase      		=2
     while 2 * euclid_m * (euclid_m + 1) <= limit:
          for euclid_n in range((euclid_m % 2) + 1,       lowercase__,       2			):
               if gcd(lowercase__,       lowercase__			) > 1:
                    continue
               __lowercase      		=2 * euclid_m * (euclid_m + euclid_n)
               for perimeter in range(lowercase__,       limit + 1,       lowercase__			):
                    frequencies[perimeter] += 1
          euclid_m += 1
     return sum(1 for frequency in frequencies.values() if frequency == 1			)


if __name__ == "__main__":
       print(F'''{solution() = }''')


