


import gc
import unittest

import numpy as np
import torch

from diffusers import StableDiffusionKDiffusionPipeline
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu


enable_full_determinism()







@slow
@require_torch_gpu
class  snake_case_     (unittest.TestCase   ):
     def 				lowerCamelCase__(   self     :Optional[Any]   )      ->					Union[str, Any]:
            # clean up the VRAM after each test
            super().tearDown()
            gc.collect()
            torch.cuda.empty_cache()
     def 				lowerCamelCase__(   self     :Optional[int]   )      ->					Tuple:
            a__    =  StableDiffusionKDiffusionPipeline.from_pretrained('CompVis/stable-diffusion-v1-4'   )
            a__    =  sd_pipe.to(__snake_case   )
            sd_pipe.set_progress_bar_config(disable=__snake_case   )

            sd_pipe.set_scheduler('sample_euler'   )

            a__    =  'A painting of a squirrel eating a burger'
            a__    =  torch.manual_seed(0   )
            a__    =  sd_pipe([prompt]    ,generator=__snake_case    ,guidance_scale=9.0    ,num_inference_steps=20    ,output_type='np'   )

            a__    =  output.images

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

            assert image.shape == (1, 5_12, 5_12, 3)
            a__    =  np.array([0.04_47, 0.04_92, 0.04_68, 0.04_08, 0.03_83, 0.04_08, 0.03_54, 0.03_80, 0.03_39]   )

            assert np.abs(image_slice.flatten() - expected_slice   ).max() < 1E-2
     def 				lowerCamelCase__(   self     :str   )      ->					Any:
            a__    =  StableDiffusionKDiffusionPipeline.from_pretrained('stabilityai/stable-diffusion-2-1-base'   )
            a__    =  sd_pipe.to(__snake_case   )
            sd_pipe.set_progress_bar_config(disable=__snake_case   )

            sd_pipe.set_scheduler('sample_euler'   )

            a__    =  'A painting of a squirrel eating a burger'
            a__    =  torch.manual_seed(0   )
            a__    =  sd_pipe([prompt]    ,generator=__snake_case    ,guidance_scale=9.0    ,num_inference_steps=20    ,output_type='np'   )

            a__    =  output.images

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

            assert image.shape == (1, 5_12, 5_12, 3)
            a__    =  np.array([0.12_37, 0.13_20, 0.14_38, 0.13_59, 0.13_90, 0.11_32, 0.12_77, 0.11_75, 0.11_12]   )

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



     def 				lowerCamelCase__(   self     :Dict   )      ->					Tuple:
            a__    =  StableDiffusionKDiffusionPipeline.from_pretrained('stabilityai/stable-diffusion-2-1-base'   )
            a__    =  sd_pipe.to(__snake_case   )
            sd_pipe.set_progress_bar_config(disable=__snake_case   )

            sd_pipe.set_scheduler('sample_dpmpp_2m'   )

            a__    =  'A painting of a squirrel eating a burger'
            a__    =  torch.manual_seed(0   )
            a__    =  sd_pipe(
                [prompt]    ,generator=__snake_case    ,guidance_scale=7.5    ,num_inference_steps=15    ,output_type='np'    ,use_karras_sigmas=__snake_case    ,)

            a__    =  output.images

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

            assert image.shape == (1, 5_12, 5_12, 3)
            a__    =  np.array(
                [0.11_38_16_89, 0.12_11_29_21, 0.1_38_94_57, 0.12_54_96_06, 0.1_24_49_64, 0.10_83_15_17, 0.11_56_28_66, 0.10_86_78_16, 0.10_49_90_48]   )

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








def 							__lowercase     (				__lowerCAmelCase							:       int     ):
							a__    =  generate_pascal_triangle(__lowerCAmelCase     )
							for row_idx in range(__lowerCAmelCase     ):
														# Print left spaces
														for _ in range(num_rows - row_idx - 1     ):
																					print(end=' '     )
														# Print row values
														for col_idx in range(row_idx + 1     ):
																					if col_idx != row_idx:
																												print(triangle[row_idx][col_idx]      ,					end=' '     )
																					else:
																												print(triangle[row_idx][col_idx]      ,					end=''     )
														print()






def 							__lowercase     (				__lowerCAmelCase							:       int     ):

							if not isinstance(__lowerCAmelCase      ,					__lowerCAmelCase     ):
														raise TypeError('The input value of \'num_rows\' should be \'int\''     )

							if num_rows == 0:
														return []
							elif num_rows < 0:
														raise ValueError(
														    'The input value of \'num_rows\' should be greater than or equal to 0'     )

							a__    =  []
							for current_row_idx in range(__lowerCAmelCase     ):
														a__    =  populate_current_row(__lowerCAmelCase      ,					__lowerCAmelCase     )
														triangle.append(__lowerCAmelCase     )
							return triangle






def 							__lowercase     (				__lowerCAmelCase							:       list[list[int]]      ,					__lowerCAmelCase							:       int     ):
							a__    =  [-1] * (current_row_idx + 1)
							# first and last elements of current row are equal to 1
							a__   ,      a__    =  1, 1
							for current_col_idx in range(1      ,					__lowerCAmelCase     ):
														calculate_current_element(
														    __lowerCAmelCase      ,					__lowerCAmelCase      ,					__lowerCAmelCase      ,					__lowerCAmelCase     )
							return current_row






def 							__lowercase     (				__lowerCAmelCase							:       list[list[int]]      ,					__lowerCAmelCase							:       list[int]      ,					__lowerCAmelCase							:       int      ,					__lowerCAmelCase							:       int      ,					):
							a__    =  triangle[current_row_idx - 1][current_col_idx - 1]
							a__    =  triangle[current_row_idx - 1][current_col_idx]
							a__    =  above_to_left_elt + above_to_right_elt






def 							__lowercase     (				__lowerCAmelCase							:       int     ):

							if not isinstance(__lowerCAmelCase      ,					__lowerCAmelCase     ):
														raise TypeError('The input value of \'num_rows\' should be \'int\''     )

							if num_rows == 0:
														return []
							elif num_rows < 0:
														raise ValueError(
														    'The input value of \'num_rows\' should be greater than or equal to 0'     )

							a__    =  [[1]]

							for row_index in range(1      ,					__lowerCAmelCase     ):
														a__    =  [0] + result[-1] + [0]
														a__    =  row_index + 1
														# Calculate the number of distinct elements in a row
														a__    =  sum(divmod(__lowerCAmelCase      ,					2     )     )
														a__    =  [
														    temp_row[i - 1] + temp_row[i] for i in range(1      ,					distinct_elements + 1     )
														]
														a__    =  row_first_half[: (row_index + 1) // 2]
														row_second_half.reverse()
														a__    =  row_first_half + row_second_half
														result.append(__lowerCAmelCase     )

							return result






def 							__lowercase     (				):
							from collections.abc import Callable
							from timeit import timeit

							def benchmark_a_function(__lowerCAmelCase							:       Callable      ,					__lowerCAmelCase							:       int     ) -> None:
														a__    =  F'{func.__name__}({value})'
														a__    =  timeit(F'__main__.{call}'      ,					setup='import __main__'     )
														# print(f"{call:38} = {func(value)} -- {timing:.4f} seconds")
														print(F'{call:38} -- {timing:.4f} seconds'     )

							for value in range(1_5     ):  # (1, 7, 14):
														for func in (generate_pascal_triangle, generate_pascal_triangle_optimized):
																					benchmark_a_function(__lowerCAmelCase      ,					__lowerCAmelCase     )
														print()


if __name__ == "__main__":
						import doctest

						doctest.testmod()
						benchmark()




