

import gc
import random
import tempfile
import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer

from diffusers import AutoencoderKL, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel
from diffusers.pipelines.stable_diffusion_safe import StableDiffusionPipelineSafe as StableDiffusionPipeline
from diffusers.utils import floats_tensor, nightly, torch_device
from diffusers.utils.testing_utils import require_torch_gpu





class 					__UpperCAmelCase     (       unittest.TestCase						):



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



   @property
   def        __magic_name__    (							self							:     Optional[Any]						):
     UpperCAmelCase       :							Dict  = 1
     UpperCAmelCase       :							Tuple  = 3
     UpperCAmelCase       :							str  = (3_2, 3_2)

     UpperCAmelCase       :							Tuple  = floats_tensor((batch_size, num_channels) + sizes,		rng=random.Random(0						)						).to(_snake_case						)
     return image



   @property
   def        __magic_name__    (							self							:     int						):
     torch.manual_seed(0						)
     UpperCAmelCase       :							str  = UNetaDConditionModel(
         block_out_channels=(3_2, 6_4),		layers_per_block=2,		sample_size=3_2,		in_channels=4,		out_channels=4,		down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D'''),		up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D'''),		cross_attention_dim=3_2,		)
     return model



   @property
   def        __magic_name__    (							self							:     Dict						):
     torch.manual_seed(0						)
     UpperCAmelCase       :							int  = AutoencoderKL(
         block_out_channels=[3_2, 6_4],		in_channels=3,		out_channels=3,		down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''],		up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''],		latent_channels=4,		)
     return model



   @property
   def        __magic_name__    (							self							:     int						):
     torch.manual_seed(0						)
     UpperCAmelCase       :							int  = CLIPTextConfig(
         bos_token_id=0,		eos_token_id=2,		hidden_size=3_2,		intermediate_size=3_7,		layer_norm_eps=1E-05,		num_attention_heads=4,		num_hidden_layers=5,		pad_token_id=1,		vocab_size=1_0_0_0,		)
     return CLIPTextModel(_snake_case						)



   @property
   def        __magic_name__    (							self							:     List[Any]						):



     def extract(*__A							:     int,		**__A							:     int						):





       class 					__UpperCAmelCase     :



          def __init__(							self							:     int						):
            UpperCAmelCase       :							Union[str, Any]  = torch.ones([0]						)





          def        __magic_name__    (							self							:     Optional[Any],		__A							:     List[Any]						):
            self.pixel_values.to(_snake_case						)
            return self






       return Out()

     return extract



   def        __magic_name__    (							self							:     Dict						):
     UpperCAmelCase       :							Tuple  = '''cpu'''  # ensure determinism for the device-dependent torch.Generator
     UpperCAmelCase       :							List[Any]  = self.dummy_cond_unet
     UpperCAmelCase       :							Optional[Any]  = DDIMScheduler(
         beta_start=0.0_0_0_8_5,		beta_end=0.0_1_2,		beta_schedule='''scaled_linear''',		clip_sample=_snake_case,		set_alpha_to_one=_snake_case,		)

     UpperCAmelCase       :							str  = self.dummy_vae
     UpperCAmelCase       :							int  = self.dummy_text_encoder
     UpperCAmelCase       :							Optional[int]  = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''						)

     # make sure here that pndm scheduler skips prk
     UpperCAmelCase       :							str  = StableDiffusionPipeline(
         unet=_snake_case,		scheduler=_snake_case,		vae=_snake_case,		text_encoder=_snake_case,		tokenizer=_snake_case,		safety_checker=_snake_case,		feature_extractor=self.dummy_extractor,		)
     UpperCAmelCase       :							Dict  = sd_pipe.to(_snake_case						)
     sd_pipe.set_progress_bar_config(disable=_snake_case						)

     UpperCAmelCase       :							Dict  = '''A painting of a squirrel eating a burger'''

     UpperCAmelCase       :							List[Any]  = torch.Generator(device=_snake_case						).manual_seed(0						)
     UpperCAmelCase       :							int  = sd_pipe([prompt],		generator=_snake_case,		guidance_scale=6.0,		num_inference_steps=2,		output_type='''np'''						)
     UpperCAmelCase       :							Any  = output.images

     UpperCAmelCase       :							Union[str, Any]  = torch.Generator(device=_snake_case						).manual_seed(0						)
     UpperCAmelCase       :							int  = sd_pipe(
         [prompt],		generator=_snake_case,		guidance_scale=6.0,		num_inference_steps=2,		output_type='''np''',		return_dict=_snake_case,		)[0]

     UpperCAmelCase       :							Union[str, Any]  = image[0, -3:, -3:, -1]
     UpperCAmelCase       :							List[Any]  = image_from_tuple[0, -3:, -3:, -1]

     assert image.shape == (1, 6_4, 6_4, 3)
     UpperCAmelCase       :							Tuple  = np.array([0.5_7_5_6, 0.6_1_1_8, 0.5_0_0_5, 0.5_0_4_1, 0.5_4_7_1, 0.4_7_2_6, 0.4_9_7_6, 0.4_8_6_5, 0.4_8_6_4]						)

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



   def        __magic_name__    (							self							:     Optional[Any]						):
     UpperCAmelCase       :							Tuple  = '''cpu'''  # ensure determinism for the device-dependent torch.Generator
     UpperCAmelCase       :							Union[str, Any]  = self.dummy_cond_unet
     UpperCAmelCase       :							Union[str, Any]  = PNDMScheduler(skip_prk_steps=_snake_case						)
     UpperCAmelCase       :							str  = self.dummy_vae
     UpperCAmelCase       :							int  = self.dummy_text_encoder
     UpperCAmelCase       :							str  = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''						)

     # make sure here that pndm scheduler skips prk
     UpperCAmelCase       :							Optional[int]  = StableDiffusionPipeline(
         unet=_snake_case,		scheduler=_snake_case,		vae=_snake_case,		text_encoder=_snake_case,		tokenizer=_snake_case,		safety_checker=_snake_case,		feature_extractor=self.dummy_extractor,		)
     UpperCAmelCase       :							Any  = sd_pipe.to(_snake_case						)
     sd_pipe.set_progress_bar_config(disable=_snake_case						)

     UpperCAmelCase       :							int  = '''A painting of a squirrel eating a burger'''
     UpperCAmelCase       :							str  = torch.Generator(device=_snake_case						).manual_seed(0						)
     UpperCAmelCase       :							Optional[Any]  = sd_pipe([prompt],		generator=_snake_case,		guidance_scale=6.0,		num_inference_steps=2,		output_type='''np'''						)

     UpperCAmelCase       :							int  = output.images

     UpperCAmelCase       :							Tuple  = torch.Generator(device=_snake_case						).manual_seed(0						)
     UpperCAmelCase       :							int  = sd_pipe(
         [prompt],		generator=_snake_case,		guidance_scale=6.0,		num_inference_steps=2,		output_type='''np''',		return_dict=_snake_case,		)[0]

     UpperCAmelCase       :							List[str]  = image[0, -3:, -3:, -1]
     UpperCAmelCase       :							Any  = image_from_tuple[0, -3:, -3:, -1]

     assert image.shape == (1, 6_4, 6_4, 3)
     UpperCAmelCase       :							int  = np.array([0.5_1_2_5, 0.5_7_1_6, 0.4_8_2_8, 0.5_0_6_0, 0.5_6_5_0, 0.4_7_6_8, 0.5_1_8_5, 0.4_8_9_5, 0.4_9_9_3]						)

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



   def        __magic_name__    (							self							:     Any						):
     UpperCAmelCase       :							List[Any]  = StableDiffusionPipeline.from_pretrained(
         '''hf-internal-testing/tiny-stable-diffusion-lms-pipe''',		safety_checker=_snake_case						)
     assert isinstance(_snake_case,		_snake_case						)
     assert isinstance(pipe.scheduler,		_snake_case						)
     assert pipe.safety_checker is None

     UpperCAmelCase       :							Union[str, Any]  = pipe('''example prompt''',		num_inference_steps=2						).images[0]
     assert image is not None

     # check that there's no error when saving a pipeline with one of the models being None
     with tempfile.TemporaryDirectory() as tmpdirname:
       pipe.save_pretrained(_snake_case						)
       UpperCAmelCase       :							Tuple  = StableDiffusionPipeline.from_pretrained(_snake_case						)

     # sanity check that the pipeline still works
     assert pipe.safety_checker is None
     UpperCAmelCase       :							str  = pipe('''example prompt''',		num_inference_steps=2						).images[0]
     assert image is not None





   @unittest.skipIf(torch_device != '''cuda''',		'''This test requires a GPU'''						)
   def        __magic_name__    (							self							:     str						):
     UpperCAmelCase       :							Any  = self.dummy_cond_unet
     UpperCAmelCase       :							Optional[Any]  = PNDMScheduler(skip_prk_steps=_snake_case						)
     UpperCAmelCase       :							int  = self.dummy_vae
     UpperCAmelCase       :							List[str]  = self.dummy_text_encoder
     UpperCAmelCase       :							List[Any]  = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''						)

     # put models in fp16
     UpperCAmelCase       :							Dict  = unet.half()
     UpperCAmelCase       :							Any  = vae.half()
     UpperCAmelCase       :							Tuple  = bert.half()

     # make sure here that pndm scheduler skips prk
     UpperCAmelCase       :							Union[str, Any]  = StableDiffusionPipeline(
         unet=_snake_case,		scheduler=_snake_case,		vae=_snake_case,		text_encoder=_snake_case,		tokenizer=_snake_case,		safety_checker=_snake_case,		feature_extractor=self.dummy_extractor,		)
     UpperCAmelCase       :							str  = sd_pipe.to(_snake_case						)
     sd_pipe.set_progress_bar_config(disable=_snake_case						)

     UpperCAmelCase       :							Any  = '''A painting of a squirrel eating a burger'''
     UpperCAmelCase       :							Union[str, Any]  = sd_pipe([prompt],		num_inference_steps=2,		output_type='''np'''						).images

     assert image.shape == (1, 6_4, 6_4, 3)






@nightly
@require_torch_gpu
class 					__UpperCAmelCase     (       unittest.TestCase						):



   def        __magic_name__    (							self							:     Any						):
     super().tearDown()
     gc.collect()
     torch.cuda.empty_cache()



   def        __magic_name__    (							self							:     Optional[Any]						):
     UpperCAmelCase       :							int  = StableDiffusionPipeline.from_pretrained('''runwayml/stable-diffusion-v1-5''',		safety_checker=_snake_case						)
     UpperCAmelCase       :							Union[str, Any]  = LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config						)
     UpperCAmelCase       :							str  = sd_pipe.to(_snake_case						)
     sd_pipe.set_progress_bar_config(disable=_snake_case						)

     UpperCAmelCase       :							Optional[int]  = (
         '''portrait of girl with smokey eyes makeup in abandoned hotel, grange clothes, redshift, wide high angle'''
         ''' coloured polaroid photograph with flash, kodak film, hyper real, stunning moody cinematography, with'''
         ''' anamorphic lenses, by maripol, fallen angels by wong kar - wai, style of suspiria and neon demon and'''
         ''' children from bahnhof zoo, detailed '''
     )
     UpperCAmelCase       :							List[Any]  = 4_0_0_3_6_6_0_3_4_6
     UpperCAmelCase       :							List[Any]  = 7

     # without safety guidance (sld_guidance_scale = 0)
     UpperCAmelCase       :							Optional[Any]  = torch.manual_seed(_snake_case						)
     UpperCAmelCase       :							str  = sd_pipe(
         [prompt],		generator=_snake_case,		guidance_scale=_snake_case,		num_inference_steps=5_0,		output_type='''np''',		width=5_1_2,		height=5_1_2,		sld_guidance_scale=0,		)

     UpperCAmelCase       :							Dict  = output.images
     UpperCAmelCase       :							Union[str, Any]  = image[0, -3:, -3:, -1]
     UpperCAmelCase       :							int  = [0.2_2_7_8, 0.2_2_3_1, 0.2_2_4_9, 0.2_3_3_3, 0.2_3_0_3, 0.1_8_8_5, 0.2_2_7_3, 0.2_1_4_4, 0.2_1_7_6]

     assert image.shape == (1, 5_1_2, 5_1_2, 3)

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

     # without safety guidance (strong configuration)
     UpperCAmelCase       :							Optional[int]  = torch.manual_seed(_snake_case						)
     UpperCAmelCase       :							Optional[Any]  = sd_pipe(
         [prompt],		generator=_snake_case,		guidance_scale=_snake_case,		num_inference_steps=5_0,		output_type='''np''',		width=5_1_2,		height=5_1_2,		sld_guidance_scale=2_0_0_0,		sld_warmup_steps=7,		sld_threshold=0.0_2_5,		sld_momentum_scale=0.5,		sld_mom_beta=0.7,		)

     UpperCAmelCase       :							List[Any]  = output.images
     UpperCAmelCase       :							Dict  = image[0, -3:, -3:, -1]
     UpperCAmelCase       :							Optional[Any]  = [0.2_3_8_3, 0.2_2_7_6, 0.2_3_6, 0.2_1_9_2, 0.2_1_8_6, 0.2_0_5_3, 0.1_9_7_1, 0.1_9_0_1, 0.1_7_1_9]

     assert image.shape == (1, 5_1_2, 5_1_2, 3)

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



   def        __magic_name__    (							self							:     Any						):
     UpperCAmelCase       :							Optional[Any]  = StableDiffusionPipeline.from_pretrained('''runwayml/stable-diffusion-v1-5''',		safety_checker=_snake_case						)
     UpperCAmelCase       :							Optional[Any]  = LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config						)
     UpperCAmelCase       :							Optional[Any]  = sd_pipe.to(_snake_case						)
     sd_pipe.set_progress_bar_config(disable=_snake_case						)

     UpperCAmelCase       :							List[Any]  = '''padme amidala taking a bath artwork, safe for work, no nudity'''
     UpperCAmelCase       :							Tuple  = 2_7_3_4_9_7_1_7_5_5
     UpperCAmelCase       :							List[str]  = 7

     UpperCAmelCase       :							Dict  = torch.manual_seed(_snake_case						)
     UpperCAmelCase       :							Union[str, Any]  = sd_pipe(
         [prompt],		generator=_snake_case,		guidance_scale=_snake_case,		num_inference_steps=5_0,		output_type='''np''',		width=5_1_2,		height=5_1_2,		sld_guidance_scale=0,		)

     UpperCAmelCase       :							str  = output.images
     UpperCAmelCase       :							List[Any]  = image[0, -3:, -3:, -1]
     UpperCAmelCase       :							Optional[Any]  = [0.3_5_0_2, 0.3_6_2_2, 0.3_3_9_6, 0.3_6_4_2, 0.3_4_7_8, 0.3_3_1_8, 0.3_5, 0.3_3_4_8, 0.3_2_9_7]

     assert image.shape == (1, 5_1_2, 5_1_2, 3)

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

     UpperCAmelCase       :							Tuple  = torch.manual_seed(_snake_case						)
     UpperCAmelCase       :							Union[str, Any]  = sd_pipe(
         [prompt],		generator=_snake_case,		guidance_scale=_snake_case,		num_inference_steps=5_0,		output_type='''np''',		width=5_1_2,		height=5_1_2,		sld_guidance_scale=2_0_0_0,		sld_warmup_steps=7,		sld_threshold=0.0_2_5,		sld_momentum_scale=0.5,		sld_mom_beta=0.7,		)

     UpperCAmelCase       :							int  = output.images
     UpperCAmelCase       :							Dict  = image[0, -3:, -3:, -1]
     UpperCAmelCase       :							Optional[int]  = [0.5_5_3_1, 0.5_2_0_6, 0.4_8_9_5, 0.5_1_5_6, 0.5_1_8_2, 0.4_7_5_1, 0.4_8_0_2, 0.4_8_0_3, 0.4_4_4_3]

     assert image.shape == (1, 5_1_2, 5_1_2, 3)

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





   def        __magic_name__    (							self							:     Tuple						):
     UpperCAmelCase       :							str  = StableDiffusionPipeline.from_pretrained('''runwayml/stable-diffusion-v1-5'''						)
     UpperCAmelCase       :							int  = sd_pipe.to(_snake_case						)
     sd_pipe.set_progress_bar_config(disable=_snake_case						)

     UpperCAmelCase       :							Optional[int]  = (
         '''the four horsewomen of the apocalypse, painting by tom of finland, gaston bussiere, craig mullins, j. c.'''
         ''' leyendecker'''
     )
     UpperCAmelCase       :							List[Any]  = 1_0_4_4_3_5_5_2_3_4
     UpperCAmelCase       :							Optional[int]  = 1_2

     UpperCAmelCase       :							List[Any]  = torch.manual_seed(_snake_case						)
     UpperCAmelCase       :							Dict  = sd_pipe(
         [prompt],		generator=_snake_case,		guidance_scale=_snake_case,		num_inference_steps=5_0,		output_type='''np''',		width=5_1_2,		height=5_1_2,		sld_guidance_scale=0,		)

     UpperCAmelCase       :							str  = output.images
     UpperCAmelCase       :							Optional[Any]  = image[0, -3:, -3:, -1]
     UpperCAmelCase       :							List[str]  = np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]						)

     assert image.shape == (1, 5_1_2, 5_1_2, 3)

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

     UpperCAmelCase       :							Optional[int]  = torch.manual_seed(_snake_case						)
     UpperCAmelCase       :							Any  = sd_pipe(
         [prompt],		generator=_snake_case,		guidance_scale=_snake_case,		num_inference_steps=5_0,		output_type='''np''',		width=5_1_2,		height=5_1_2,		sld_guidance_scale=2_0_0_0,		sld_warmup_steps=7,		sld_threshold=0.0_2_5,		sld_momentum_scale=0.5,		sld_mom_beta=0.7,		)

     UpperCAmelCase       :							Dict  = output.images
     UpperCAmelCase       :							Dict  = image[0, -3:, -3:, -1]
     UpperCAmelCase       :							Dict  = np.array([0.5_8_1_8, 0.6_2_8_5, 0.6_8_3_5, 0.6_0_1_9, 0.6_2_5, 0.6_7_5_4, 0.6_0_9_6, 0.6_3_3_4, 0.6_5_6_1]						)
     assert image.shape == (1, 5_1_2, 5_1_2, 3)

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










"""simple docstring"""







import os
from argparse import ArgumentParser
from typing import List

import torch.utils.data

from datasets import Dataset, IterableDataset
from datasets.distributed import split_dataset_by_node


lowerCAmelCase_   						=   4
lowerCAmelCase_   						=   3
class        __A       (	A_    ):







		'''simple docstring'''





		pass





def      __UpperCAmelCase      (    __lowerCamelCase	)							->      Dict:
		for shard in shards:
				for i in range(__lowerCamelCase	):
						yield {"i": i, "shard": shard}



def      __UpperCAmelCase      (    )							->      Tuple:
		lowercase__   :    int				=			int(os.environ['''RANK''']	)
		lowercase__   :    str				=			int(os.environ['''WORLD_SIZE''']	)

		lowercase__   :    List[Any]				=			ArgumentParser()
		parser.add_argument('''--streaming'''						,     type=__lowerCamelCase	)
		parser.add_argument('''--local_rank'''						,     type=__lowerCamelCase	)
		parser.add_argument('''--num_workers'''						,     type=__lowerCamelCase						,     default=0	)
		lowercase__   :    int				=			parser.parse_args()
		lowercase__   :    Optional[Any]				=			args.streaming
		lowercase__   :    List[Any]				=			args.num_workers

		lowercase__   :    Optional[Any]				=			{'''shards''': [f"""shard_{shard_idx}""" for shard_idx in range(__lowerCamelCase	)]}
		lowercase__   :    Dict				=			IterableDataset.from_generator(__lowerCamelCase						,     gen_kwargs=__lowerCamelCase	)
		if not streaming:
				lowercase__   :    int				=			Dataset.from_list(list(__lowerCamelCase	)	)

		lowercase__   :    int				=			split_dataset_by_node(__lowerCamelCase						,     rank=__lowerCamelCase						,     world_size=__lowerCamelCase	)
		lowercase__   :    Optional[Any]				=			torch.utils.data.DataLoader(__lowerCamelCase						,     num_workers=__lowerCamelCase	)

		lowercase__   :    Optional[Any]				=			NUM_SHARDS * NUM_ITEMS_PER_SHARD
		lowercase__   :    str				=			full_size // world_size
		expected_local_size += int(rank < (full_size % world_size)	)

		lowercase__   :    str				=			sum(1 for _ in dataloader	)
		if local_size != expected_local_size:
				raise FailedTestError(f"""local_size {local_size} != expected_local_size {expected_local_size}"""	)


if __name__ == "__main__":
							main()
