



import gc
import math
import unittest

import torch

from diffusers import UNetaDModel
from diffusers.utils import floats_tensor, logging, slow, torch_all_close, torch_device
from diffusers.utils.testing_utils import enable_full_determinism

from .test_modeling_common import ModelTesterMixin, UNetTesterMixin


UpperCamelCase_										=					logging.get_logger(__name__)

enable_full_determinism()







class 	_snake_case							(			lowerCamelCase_      ,				lowerCamelCase_      ,				unittest.TestCase      ):






   '''simple docstring'''






   A__	:      Union[str, Any]    =		UNetaDModel
   A__	:      List[Any]    =		'''sample'''


   @property
   def 	A__  (  self:			Dict				)     ->	Union[str, Any]:
       UpperCAmelCase_			:    int   						= 4
       UpperCAmelCase_			:    str   						= 3
       UpperCAmelCase_			:    Dict   						= (32, 32)

       UpperCAmelCase_			:    Tuple   						= floats_tensor((batch_size, num_channels) + sizes				).to(__snake_case				)
       UpperCAmelCase_			:    str   						= torch.tensor([10]				).to(__snake_case				)

       return {"sample": noise, "timestep": time_step}


   @property
   def 	A__  (  self:			str				)     ->	str:
       return (3, 32, 32)


   @property
   def 	A__  (  self:			Tuple				)     ->	Optional[int]:
       return (3, 32, 32)






   def 	A__  (  self:			Dict				)     ->	Any:
       UpperCAmelCase_			:    str   						= {
           """block_out_channels""": (32, 64),
           """down_block_types""": ("""DownBlock2D""", """AttnDownBlock2D"""),
           """up_block_types""": ("""AttnUpBlock2D""", """UpBlock2D"""),
           """attention_head_dim""": 3,
           """out_channels""": 3,
           """in_channels""": 3,
           """layers_per_block""": 2,
           """sample_size""": 32,
       }
       UpperCAmelCase_			:    List[str]   						= self.dummy_input
       return init_dict, inputs_dict







class 	_snake_case							(			lowerCamelCase_      ,				lowerCamelCase_      ,				unittest.TestCase      ):






   '''simple docstring'''






   A__	:      Tuple    =		UNetaDModel
   A__	:      Union[str, Any]    =		'''sample'''


   @property
   def 	A__  (  self:			Dict				)     ->	Union[str, Any]:
       UpperCAmelCase_			:    Any   						= 4
       UpperCAmelCase_			:    Optional[Any]   						= 4
       UpperCAmelCase_			:    str   						= (32, 32)

       UpperCAmelCase_			:    Union[str, Any]   						= floats_tensor((batch_size, num_channels) + sizes				).to(__snake_case				)
       UpperCAmelCase_			:    Optional[Any]   						= torch.tensor([10]				).to(__snake_case				)

       return {"sample": noise, "timestep": time_step}


   @property
   def 	A__  (  self:			int				)     ->	Optional[int]:
       return (4, 32, 32)


   @property
   def 	A__  (  self:			Optional[int]				)     ->	List[Any]:
       return (4, 32, 32)


   def 	A__  (  self:			str				)     ->	Any:
       UpperCAmelCase_			:    List[Any]   						= {
           """sample_size""": 32,
           """in_channels""": 4,
           """out_channels""": 4,
           """layers_per_block""": 2,
           """block_out_channels""": (32, 64),
           """attention_head_dim""": 32,
           """down_block_types""": ("""DownBlock2D""", """DownBlock2D"""),
           """up_block_types""": ("""UpBlock2D""", """UpBlock2D"""),
       }
       UpperCAmelCase_			:    Dict   						= self.dummy_input
       return init_dict, inputs_dict


   def 	A__  (  self:			Tuple				)     ->	List[str]:
       UpperCAmelCase_						,      UpperCAmelCase_			:    List[Any]   						= UNetaDModel.from_pretrained("""fusing/unet-ldm-dummy-update"""   ,output_loading_info=__snake_case				)

       self.assertIsNotNone(__snake_case				)
       self.assertEqual(len(loading_info["""missing_keys"""]				)   ,0				)

       model.to(__snake_case				)
       UpperCAmelCase_			:    str   						= model(**self.dummy_input				).sample

       assert image is not None, "Make sure output is not None"


   @unittest.skipIf(torch_device != """cuda"""   ,"""This test is supposed to run on GPU"""				)
   def 	A__  (  self:			List[Any]				)     ->	Any:
       UpperCAmelCase_						,      UpperCAmelCase_			:    int   						= UNetaDModel.from_pretrained("""fusing/unet-ldm-dummy-update"""   ,output_loading_info=__snake_case				)
       model.to(__snake_case				)
       UpperCAmelCase_			:    int   						= model(**self.dummy_input				).sample

       assert image is not None, "Make sure output is not None"


   @unittest.skipIf(torch_device != """cuda"""   ,"""This test is supposed to run on GPU"""				)
   def 	A__  (  self:			Tuple				)     ->	List[Any]:
       # by defautl model loading will use accelerate as `low_cpu_mem_usage=True`
       UpperCAmelCase_						,      UpperCAmelCase_			:    List[Any]   						= UNetaDModel.from_pretrained("""fusing/unet-ldm-dummy-update"""   ,output_loading_info=__snake_case				)
       model_accelerate.to(__snake_case				)
       model_accelerate.eval()

       UpperCAmelCase_			:    Union[str, Any]   						= torch.randn(
           1   ,model_accelerate.config.in_channels   ,model_accelerate.config.sample_size   ,model_accelerate.config.sample_size   ,generator=torch.manual_seed(0				)   ,)
       UpperCAmelCase_			:    List[str]   						= noise.to(__snake_case				)
       UpperCAmelCase_			:    Tuple   						= torch.tensor([10] * noise.shape[0]				).to(__snake_case				)

       UpperCAmelCase_			:    str   						= model_accelerate(__snake_case   ,__snake_case				)["""sample"""]

       # two models don't need to stay in the device at the same time
       del model_accelerate
       torch.cuda.empty_cache()
       gc.collect()

       UpperCAmelCase_						,      UpperCAmelCase_			:    Optional[Any]   						= UNetaDModel.from_pretrained(
           """fusing/unet-ldm-dummy-update"""   ,output_loading_info=__snake_case   ,low_cpu_mem_usage=__snake_case				)
       model_normal_load.to(__snake_case				)
       model_normal_load.eval()
       UpperCAmelCase_			:    Optional[Any]   						= model_normal_load(__snake_case   ,__snake_case				)["""sample"""]

       assert torch_all_close(__snake_case   ,__snake_case   ,rtol=1e-3				)






   def 	A__  (  self:			List[Any]				)     ->	Optional[int]:
       UpperCAmelCase_			:    List[Any]   						= UNetaDModel.from_pretrained("""fusing/unet-ldm-dummy-update"""				)
       model.eval()
       model.to(__snake_case				)

       UpperCAmelCase_			:    int   						= torch.randn(
           1   ,model.config.in_channels   ,model.config.sample_size   ,model.config.sample_size   ,generator=torch.manual_seed(0				)   ,)
       UpperCAmelCase_			:    Tuple   						= noise.to(__snake_case				)
       UpperCAmelCase_			:    int   						= torch.tensor([10] * noise.shape[0]				).to(__snake_case				)

       with torch.no_grad():
           UpperCAmelCase_			:    int   						= model(__snake_case   ,__snake_case				).sample

       UpperCAmelCase_			:    Any   						= output[0, -1, -3:, -3:].flatten().cpu()
       # fmt: off
       UpperCAmelCase_			:    Any   						= torch.tensor([-1_3.3_2_5_8, -2_0.1_1_0_0, -1_5.9_8_7_3, -1_7.6_6_1_7, -2_3.0_5_9_6, -1_7.9_4_1_9, -1_3.3_6_7_5, -1_6.1_8_8_9, -1_2.3_8_0_0]				)
       # fmt: on

       self.assertTrue(torch_all_close(__snake_case   ,__snake_case   ,rtol=1e-3				)				)







class 	_snake_case							(			lowerCamelCase_      ,				lowerCamelCase_      ,				unittest.TestCase      ):






   '''simple docstring'''






   A__	:      Tuple    =		UNetaDModel
   A__	:      Optional[int]    =		'''sample'''


   @property
   def 	A__  (  self:			Tuple   ,lowerCamelCase_:			Optional[int]=(32, 32)				)     ->	Union[str, Any]:
       UpperCAmelCase_			:    Tuple   						= 4
       UpperCAmelCase_			:    List[Any]   						= 3

       UpperCAmelCase_			:    Optional[int]   						= floats_tensor((batch_size, num_channels) + sizes				).to(__snake_case				)
       UpperCAmelCase_			:    Optional[Any]   						= torch.tensor(batch_size * [10]				).to(dtype=torch.intaa   ,device=__snake_case				)

       return {"sample": noise, "timestep": time_step}


   @property
   def 	A__  (  self:			Optional[Any]				)     ->	int:
       return (3, 32, 32)


   @property
   def 	A__  (  self:			Optional[int]				)     ->	str:
       return (3, 32, 32)


   def 	A__  (  self:			Optional[int]				)     ->	Optional[Any]:
       UpperCAmelCase_			:    str   						= {
           """block_out_channels""": [32, 64, 64, 64],
           """in_channels""": 3,
           """layers_per_block""": 1,
           """out_channels""": 3,
           """time_embedding_type""": """fourier""",
           """norm_eps""": 1e-6,
           """mid_block_scale_factor""": math.sqrt(2.0				),
           """norm_num_groups""": None,
           """down_block_types""": [
               """SkipDownBlock2D""",
               """AttnSkipDownBlock2D""",
               """SkipDownBlock2D""",
               """SkipDownBlock2D""",
           ],
           """up_block_types""": [
               """SkipUpBlock2D""",
               """SkipUpBlock2D""",
               """AttnSkipUpBlock2D""",
               """SkipUpBlock2D""",
           ],
       }
       UpperCAmelCase_			:    Optional[int]   						= self.dummy_input
       return init_dict, inputs_dict


   @slow
   def 	A__  (  self:			int				)     ->	List[str]:
       UpperCAmelCase_						,      UpperCAmelCase_			:    List[Any]   						= UNetaDModel.from_pretrained("""google/ncsnpp-celebahq-256"""   ,output_loading_info=__snake_case				)
       self.assertIsNotNone(__snake_case				)
       self.assertEqual(len(loading_info["""missing_keys"""]				)   ,0				)

       model.to(__snake_case				)
       UpperCAmelCase_			:    str   						= self.dummy_input
       UpperCAmelCase_			:    Tuple   						= floats_tensor((4, 3) + (256, 256)				).to(__snake_case				)
       UpperCAmelCase_			:    Optional[Any]   						= noise
       UpperCAmelCase_			:    Optional[Any]   						= model(**__snake_case				)

       assert image is not None, "Make sure output is not None"


   @slow
   def 	A__  (  self:			Union[str, Any]				)     ->	Union[str, Any]:
       UpperCAmelCase_			:    List[Any]   						= UNetaDModel.from_pretrained("""google/ncsnpp-celebahq-256"""				)
       model.to(__snake_case				)

       UpperCAmelCase_			:    int   						= 4
       UpperCAmelCase_			:    Optional[Any]   						= 3
       UpperCAmelCase_			:    Any   						= (256, 256)

       UpperCAmelCase_			:    List[Any]   						= torch.ones((batch_size, num_channels) + sizes				).to(__snake_case				)
       UpperCAmelCase_			:    Union[str, Any]   						= torch.tensor(batch_size * [1e-4]				).to(__snake_case				)

       with torch.no_grad():
           UpperCAmelCase_			:    Dict   						= model(__snake_case   ,__snake_case				).sample

       UpperCAmelCase_			:    Tuple   						= output[0, -3:, -3:, -1].flatten().cpu()
       # fmt: off
       UpperCAmelCase_			:    Dict   						= torch.tensor([-4842.8691, -6499.6631, -3800.1953, -7978.2686, -10980.7129, -20028.8535, 8148.2822, 2342.2905, 567.7608]				)
       # fmt: on

       self.assertTrue(torch_all_close(__snake_case   ,__snake_case   ,rtol=1e-2				)				)


   def 	A__  (  self:			Tuple				)     ->	Dict:
       UpperCAmelCase_			:    List[str]   						= UNetaDModel.from_pretrained("""fusing/ncsnpp-ffhq-ve-dummy-update"""				)
       model.to(__snake_case				)

       UpperCAmelCase_			:    Union[str, Any]   						= 4
       UpperCAmelCase_			:    Tuple   						= 3
       UpperCAmelCase_			:    str   						= (32, 32)

       UpperCAmelCase_			:    Dict   						= torch.ones((batch_size, num_channels) + sizes				).to(__snake_case				)
       UpperCAmelCase_			:    List[Any]   						= torch.tensor(batch_size * [1e-4]				).to(__snake_case				)

       with torch.no_grad():
           UpperCAmelCase_			:    int   						= model(__snake_case   ,__snake_case				).sample

       UpperCAmelCase_			:    Any   						= output[0, -3:, -3:, -1].flatten().cpu()
       # fmt: off
       UpperCAmelCase_			:    int   						= torch.tensor([-0.0_3_2_5, -0.0_9_0_0, -0.0_8_6_9, -0.0_3_3_2, -0.0_7_2_5, -0.0_2_7_0, -0.0_1_0_1, 0.0_2_2_7, 0.0_2_5_6]				)
       # fmt: on

       self.assertTrue(torch_all_close(__snake_case   ,__snake_case   ,rtol=1e-2				)				)






   def 	A__  (  self:			Optional[int]				)     ->	List[Any]:
       # not required for this model
       pass




def 							__lowercase   ( __lowerCAmelCase							:				int					,    __lowerCAmelCase							:				float					,    __lowerCAmelCase							:				float   ):
							return round(float(moles / volume   ) * nfactor   )






def 							__lowercase   ( __lowerCAmelCase							:				float					,    __lowerCAmelCase							:				float					,    __lowerCAmelCase							:				float   ):
							return round(float((moles * 0.0_821 * temperature) / (volume)   )   )






def 							__lowercase   ( __lowerCAmelCase							:				float					,    __lowerCAmelCase							:				float					,    __lowerCAmelCase							:				float   ):
							return round(float((moles * 0.0_821 * temperature) / (pressure)   )   )






def 							__lowercase   ( __lowerCAmelCase							:				float					,    __lowerCAmelCase							:				float					,    __lowerCAmelCase							:				float   ):
							return round(float((pressure * volume) / (0.0_821 * moles)   )   )


if __name__ == "__main__":
						import doctest

						doctest.testmod()




