




'''simple docstring'''



import gc
import unittest

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

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    PNDMScheduler,
    StableDiffusionLDMaDPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import nightly, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS


enable_full_determinism()





class      lowerCAmelCase (			unittest.TestCase):
       __lowercase	:   Any										=      StableDiffusionLDMaDPipeline
       __lowercase	:   Dict										=      TEXT_TO_IMAGE_PARAMS
       __lowercase	:   Optional[Any]										=      TEXT_TO_IMAGE_BATCH_PARAMS
       __lowercase	:   int										=      TEXT_TO_IMAGE_IMAGE_PARAMS


       def    lowerCAmelCase   ( self	)   ->	List[Any]:



            '''simple docstring'''




            torch.manual_seed(0	)
            __snake_case            =	UNetaDConditionModel(
                block_out_channels=(32, 64)     ,	layers_per_block=2     ,	sample_size=32     ,	in_channels=4     ,	out_channels=4     ,	down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''')     ,	up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''')     ,	cross_attention_dim=32     ,	)
            __snake_case            =	DDIMScheduler(
                beta_start=0.00_085     ,	beta_end=0.012     ,	beta_schedule='''scaled_linear'''     ,	clip_sample=__SCREAMING_SNAKE_CASE     ,	set_alpha_to_one=__SCREAMING_SNAKE_CASE     ,	)
            torch.manual_seed(0	)
            __snake_case            =	AutoencoderKL(
                block_out_channels=[32, 64]     ,	in_channels=6     ,	out_channels=6     ,	down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D''']     ,	up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D''']     ,	latent_channels=4     ,	)
            torch.manual_seed(0	)
            __snake_case            =	CLIPTextConfig(
                bos_token_id=0     ,	eos_token_id=2     ,	hidden_size=32     ,	intermediate_size=37     ,	layer_norm_eps=1E-05     ,	num_attention_heads=4     ,	num_hidden_layers=5     ,	pad_token_id=1     ,	vocab_size=1000     ,	)
            __snake_case            =	CLIPTextModel(__SCREAMING_SNAKE_CASE	)
            __snake_case            =	CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''	)

            __snake_case            =	{
                '''unet''': unet,
                '''scheduler''': scheduler,
                '''vae''': vae,
                '''text_encoder''': text_encoder,
                '''tokenizer''': tokenizer,
                '''safety_checker''': None,
                '''feature_extractor''': None,
            }
            return components


       def    lowerCAmelCase   ( self     ,	__SCREAMING_SNAKE_CASE     ,	__SCREAMING_SNAKE_CASE=0	)   ->	Union[str, Any]:



            '''simple docstring'''




            if str(__SCREAMING_SNAKE_CASE	).startswith('''mps'''	):
                 __snake_case            =	torch.manual_seed(__SCREAMING_SNAKE_CASE	)
            else:
                 __snake_case            =	torch.Generator(device=__SCREAMING_SNAKE_CASE	).manual_seed(__SCREAMING_SNAKE_CASE	)
            __snake_case            =	{
                '''prompt''': '''A painting of a squirrel eating a burger''',
                '''generator''': generator,
                '''num_inference_steps''': 2,
                '''guidance_scale''': 6.0,
                '''output_type''': '''numpy''',
            }
            return inputs


       def    lowerCAmelCase   ( self	)   ->	Optional[Any]:



            '''simple docstring'''




            __snake_case            =	'''cpu'''  # ensure determinism for the device-dependent torch.Generator

            __snake_case            =	self.get_dummy_components()
            __snake_case            =	StableDiffusionLDMaDPipeline(**__SCREAMING_SNAKE_CASE	)
            __snake_case            =	ldmad_pipe.to(__SCREAMING_SNAKE_CASE	)
            ldmad_pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE	)

            __snake_case            =	self.get_dummy_inputs(__SCREAMING_SNAKE_CASE	)
            __snake_case            =	ldmad_pipe(**__SCREAMING_SNAKE_CASE	)
            __snake_case       ,     __snake_case            =	output.rgb, output.depth

            __snake_case            =	rgb[0, -3:, -3:, -1]
            __snake_case            =	depth[0, -3:, -1]

            assert rgb.shape == (1, 64, 64, 3)
            assert depth.shape == (1, 64, 64)

            __snake_case            =	np.array(
                [0.37_338_176, 0.70_247, 0.74_203_193, 0.51_643_604, 0.58_256_793, 0.60_932_136, 0.4_181_095, 0.48_355_877, 0.46_535_262]	)
            __snake_case            =	np.array([103.46_727, 85.812_004, 87.849_236]	)

            assert np.abs(image_slice_rgb.flatten() - expected_slice_rgb	).max() < 1E-2
            assert np.abs(image_slice_depth.flatten() - expected_slice_depth	).max() < 1E-2


       def    lowerCAmelCase   ( self	)   ->	Any:



            '''simple docstring'''




            __snake_case            =	self.get_dummy_components()
            __snake_case            =	StableDiffusionLDMaDPipeline(**__SCREAMING_SNAKE_CASE	)
            __snake_case            =	ldmad_pipe.to(__SCREAMING_SNAKE_CASE	)
            ldmad_pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE	)

            __snake_case            =	self.get_dummy_inputs(__SCREAMING_SNAKE_CASE	)
            __snake_case            =	3 * [inputs['''prompt''']]

            # forward
            __snake_case            =	ldmad_pipe(**__SCREAMING_SNAKE_CASE	)
            __snake_case       ,     __snake_case            =	output.rgb, output.depth
            __snake_case            =	rgb_slice_a[0, -3:, -3:, -1]
            __snake_case            =	depth_slice_a[0, -3:, -1]

            __snake_case            =	self.get_dummy_inputs(__SCREAMING_SNAKE_CASE	)
            __snake_case            =	3 * [inputs.pop('''prompt'''	)]

            __snake_case            =	ldmad_pipe.tokenizer(
                __SCREAMING_SNAKE_CASE     ,	padding='''max_length'''     ,	max_length=ldmad_pipe.tokenizer.model_max_length     ,	truncation=__SCREAMING_SNAKE_CASE     ,	return_tensors='''pt'''     ,	)
            __snake_case            =	text_inputs['''input_ids'''].to(__SCREAMING_SNAKE_CASE	)

            __snake_case            =	ldmad_pipe.text_encoder(__SCREAMING_SNAKE_CASE	)[0]

            __snake_case            =	prompt_embeds

            # forward
            __snake_case            =	ldmad_pipe(**__SCREAMING_SNAKE_CASE	)
            __snake_case       ,     __snake_case            =	output.rgb, output.depth
            __snake_case            =	rgb_slice_a[0, -3:, -3:, -1]
            __snake_case            =	depth_slice_a[0, -3:, -1]

            assert np.abs(rgb_slice_a.flatten() - rgb_slice_a.flatten()	).max() < 1E-4
            assert np.abs(depth_slice_a.flatten() - depth_slice_a.flatten()	).max() < 1E-4




       def    lowerCAmelCase   ( self	)   ->	List[Any]:



            '''simple docstring'''




            __snake_case            =	'''cpu'''  # ensure determinism for the device-dependent torch.Generator
            __snake_case            =	self.get_dummy_components()
            __snake_case            =	PNDMScheduler(skip_prk_steps=__SCREAMING_SNAKE_CASE	)
            __snake_case            =	StableDiffusionLDMaDPipeline(**__SCREAMING_SNAKE_CASE	)
            __snake_case            =	ldmad_pipe.to(__SCREAMING_SNAKE_CASE	)
            ldmad_pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE	)

            __snake_case            =	self.get_dummy_inputs(__SCREAMING_SNAKE_CASE	)
            __snake_case            =	'''french fries'''
            __snake_case            =	ldmad_pipe(**__SCREAMING_SNAKE_CASE     ,	negative_prompt=__SCREAMING_SNAKE_CASE	)

            __snake_case       ,     __snake_case            =	output.rgb, output.depth
            __snake_case            =	rgb[0, -3:, -3:, -1]
            __snake_case            =	depth[0, -3:, -1]

            assert rgb.shape == (1, 64, 64, 3)
            assert depth.shape == (1, 64, 64)

            __snake_case            =	np.array(
                [0.37_044, 0.71_811_503, 0.7_223_251, 0.48_603_675, 0.5_638_391, 0.6_364_948, 0.42_833_704, 0.4_901_315, 0.47_926_217]	)
            __snake_case            =	np.array([107.84_738, 84.62_802, 89.962_135]	)
            assert np.abs(rgb_slice.flatten() - expected_slice_rgb	).max() < 1E-2
            assert np.abs(depth_slice.flatten() - expected_slice_depth	).max() < 1E-2





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


       def    lowerCAmelCase   ( self	)   ->	Optional[Any]:



            '''simple docstring'''




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


       def    lowerCAmelCase   ( self     ,	__SCREAMING_SNAKE_CASE     ,	__SCREAMING_SNAKE_CASE="cpu"     ,	__SCREAMING_SNAKE_CASE=torch.floataa     ,	__SCREAMING_SNAKE_CASE=0	)   ->	List[Any]:



            '''simple docstring'''




            __snake_case            =	torch.Generator(device=__SCREAMING_SNAKE_CASE	).manual_seed(__SCREAMING_SNAKE_CASE	)
            __snake_case            =	np.random.RandomState(__SCREAMING_SNAKE_CASE	).standard_normal((1, 4, 64, 64)	)
            __snake_case            =	torch.from_numpy(__SCREAMING_SNAKE_CASE	).to(device=__SCREAMING_SNAKE_CASE     ,	dtype=__SCREAMING_SNAKE_CASE	)
            __snake_case            =	{
                '''prompt''': '''a photograph of an astronaut riding a horse''',
                '''latents''': latents,
                '''generator''': generator,
                '''num_inference_steps''': 3,
                '''guidance_scale''': 7.5,
                '''output_type''': '''numpy''',
            }
            return inputs




       def    lowerCAmelCase   ( self	)   ->	Dict:



            '''simple docstring'''




            __snake_case            =	StableDiffusionLDMaDPipeline.from_pretrained('''Intel/ldm3d'''	)
            __snake_case            =	ldmad_pipe.to(__SCREAMING_SNAKE_CASE	)
            ldmad_pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE	)

            __snake_case            =	self.get_inputs(__SCREAMING_SNAKE_CASE	)
            __snake_case            =	ldmad_pipe(**__SCREAMING_SNAKE_CASE	)
            __snake_case       ,     __snake_case            =	output.rgb, output.depth
            __snake_case            =	rgb[0, -3:, -3:, -1].flatten()
            __snake_case            =	rgb[0, -3:, -1].flatten()

            assert rgb.shape == (1, 512, 512, 3)
            assert depth.shape == (1, 512, 512)

            __snake_case            =	np.array(
                [0.53_805_465, 0.56_707_305, 0.5_486_515, 0.57_012_236, 0.5_814_511, 0.56_253_487, 0.54_843_014, 0.55_092_263, 0.6_459_706]	)
            __snake_case            =	np.array(
                [0.9_263_781, 0.6_678_672, 0.5_486_515, 0.92_202_145, 0.67_831_135, 0.56_253_487, 0.9_241_694, 0.7_551_478, 0.6_459_706]	)
            assert np.abs(rgb_slice - expected_slice_rgb	).max() < 3E-3
            assert np.abs(depth_slice - expected_slice_depth	).max() < 3E-3





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


       def    lowerCAmelCase   ( self	)   ->	Tuple:



            '''simple docstring'''




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


       def    lowerCAmelCase   ( self     ,	__SCREAMING_SNAKE_CASE     ,	__SCREAMING_SNAKE_CASE="cpu"     ,	__SCREAMING_SNAKE_CASE=torch.floataa     ,	__SCREAMING_SNAKE_CASE=0	)   ->	int:



            '''simple docstring'''




            __snake_case            =	torch.Generator(device=__SCREAMING_SNAKE_CASE	).manual_seed(__SCREAMING_SNAKE_CASE	)
            __snake_case            =	np.random.RandomState(__SCREAMING_SNAKE_CASE	).standard_normal((1, 4, 64, 64)	)
            __snake_case            =	torch.from_numpy(__SCREAMING_SNAKE_CASE	).to(device=__SCREAMING_SNAKE_CASE     ,	dtype=__SCREAMING_SNAKE_CASE	)
            __snake_case            =	{
                '''prompt''': '''a photograph of an astronaut riding a horse''',
                '''latents''': latents,
                '''generator''': generator,
                '''num_inference_steps''': 50,
                '''guidance_scale''': 7.5,
                '''output_type''': '''numpy''',
            }
            return inputs


       def    lowerCAmelCase   ( self	)   ->	int:



            '''simple docstring'''




            __snake_case            =	StableDiffusionLDMaDPipeline.from_pretrained('''Intel/ldm3d'''	).to(__SCREAMING_SNAKE_CASE	)
            ldmad_pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE	)

            __snake_case            =	self.get_inputs(__SCREAMING_SNAKE_CASE	)
            __snake_case            =	ldmad_pipe(**__SCREAMING_SNAKE_CASE	)
            __snake_case       ,     __snake_case            =	output.rgb, output.depth

            __snake_case            =	0.495_586
            __snake_case            =	0.33_795_515
            __snake_case            =	112.48_518
            __snake_case            =	98.489_746
            assert np.abs(expected_rgb_mean - rgb.mean()	) < 1E-3
            assert np.abs(expected_rgb_std - rgb.std()	) < 1E-3
            assert np.abs(expected_depth_mean - depth.mean()	) < 1E-3
            assert np.abs(expected_depth_std - depth.std()	) < 1E-3




       def    lowerCAmelCase   ( self	)   ->	Dict:



            '''simple docstring'''




            __snake_case            =	StableDiffusionLDMaDPipeline.from_pretrained('''Intel/ldm3d-4c'''	).to(__SCREAMING_SNAKE_CASE	)
            ldmad_pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE	)

            __snake_case            =	self.get_inputs(__SCREAMING_SNAKE_CASE	)
            __snake_case            =	ldmad_pipe(**__SCREAMING_SNAKE_CASE	)
            __snake_case       ,     __snake_case            =	output.rgb, output.depth

            __snake_case            =	0.4_194_127
            __snake_case            =	0.35_375_586
            __snake_case            =	0.5_638_502
            __snake_case            =	0.34_686_103

            assert rgb.shape == (1, 512, 512, 3)
            assert depth.shape == (1, 512, 512, 1)
            assert np.abs(expected_rgb_mean - rgb.mean()	) < 1E-3
            assert np.abs(expected_rgb_std - rgb.std()	) < 1E-3
            assert np.abs(expected_depth_mean - depth.mean()	) < 1E-3
            assert np.abs(expected_depth_std - depth.std()	) < 1E-3












'''simple docstring'''



from collections import deque







def       _UpperCamelCase			(_lowerCamelCase				:  Union[str, Any]						)-> Optional[int]:




     '''simple docstring'''





     __snake_case            =	len(_lowerCamelCase						)
     __snake_case            =	deque()
     __snake_case            =	[False for _ in range(_lowerCamelCase						)]
     __snake_case            =	[-1 for _ in range(_lowerCamelCase						)]
     __snake_case            =	index_of[:]

     def strong_connect(_lowerCamelCase				:  Any ,						_lowerCamelCase				:  Dict ,						_lowerCamelCase				:  List[str]						):
          __snake_case            =	index  # the number when this node is seen
          __snake_case            =	index  # lowest rank node reachable from here
          index += 1
          stack.append(_lowerCamelCase						)
          __snake_case            =	True

          for w in g[v]:
               if index_of[w] == -1:
                    __snake_case            =	strong_connect(_lowerCamelCase ,						_lowerCamelCase ,						_lowerCamelCase						)
                    __snake_case            =	(
                        lowlink_of[w] if lowlink_of[w] < lowlink_of[v] else lowlink_of[v]
                    )
               elif on_stack[w]:
                    __snake_case            =	(
                        lowlink_of[w] if lowlink_of[w] < lowlink_of[v] else lowlink_of[v]
                    )

          if lowlink_of[v] == index_of[v]:
               __snake_case            =	[]
               __snake_case            =	stack.pop()
               __snake_case            =	False
               component.append(_lowerCamelCase						)
               while w != v:
                    __snake_case            =	stack.pop()
                    __snake_case            =	False
                    component.append(_lowerCamelCase						)
               components.append(_lowerCamelCase						)
          return index

     __snake_case            =	[]
     for v in range(_lowerCamelCase						):
          if index_of[v] == -1:
               strong_connect(_lowerCamelCase ,						0 ,						_lowerCamelCase						)

     return components







def       _UpperCamelCase			(_lowerCamelCase				:  Tuple ,						_lowerCamelCase				:  Optional[Any]						)-> Dict:




     '''simple docstring'''





     __snake_case            =	[[] for _ in range(_lowerCamelCase						)]
     for u, v in edges:
          g[u].append(_lowerCamelCase						)
     return g


if __name__ == "__main__":
     # Test
     UpperCAmelCase_							:	List[str]	     =		7
     UpperCAmelCase_							:	int	     =		[0, 0, 1, 2, 3, 3, 4, 4, 6]
     UpperCAmelCase_							:	Dict	     =		[1, 3, 2, 0, 1, 4, 5, 6, 5]
     UpperCAmelCase_							:	List[str]	     =		[(u, v) for u, v in zip(source, target)]
     UpperCAmelCase_							:	Tuple	     =		create_graph(n_vertices, edges)

     assert [[5], [6], [4], [3, 2, 1, 0]] == tarjan(g)






