


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


A      = logging.get_logger(__name__)

enable_full_determinism()


class     lowercase__  (					__a					,							__a					,							unittest.TestCase		):
		A__=  UNetaDModel
		A__=  '''sample'''






		@property
		def 			_UpperCAmelCase  (					self      :					str ):




									"""simple docstring"""







									UpperCAmelCase__										=     4
									UpperCAmelCase__										=     3
									UpperCAmelCase__										=     (32, 32)

									UpperCAmelCase__										=     floats_tensor((batch_size, num_channels) + sizes ).to(snake_case__ )
									UpperCAmelCase__										=     torch.tensor([10] ).to(snake_case__ )

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






		@property
		def 			_UpperCAmelCase  (					self      :					List[str] ):




									"""simple docstring"""







									return (3, 32, 32)






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




									"""simple docstring"""







									return (3, 32, 32)






		def 			_UpperCAmelCase  (					self      :					int ):




									"""simple docstring"""







									UpperCAmelCase__										=     {
									    "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__										=     self.dummy_input
									return init_dict, inputs_dict




class     lowercase__  (					__a					,							__a					,							unittest.TestCase		):
		A__=  UNetaDModel
		A__=  '''sample'''






		@property
		def 			_UpperCAmelCase  (					self      :					Optional[int] ):




									"""simple docstring"""







									UpperCAmelCase__										=     4
									UpperCAmelCase__										=     4
									UpperCAmelCase__										=     (32, 32)

									UpperCAmelCase__										=     floats_tensor((batch_size, num_channels) + sizes ).to(snake_case__ )
									UpperCAmelCase__										=     torch.tensor([10] ).to(snake_case__ )

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






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




									"""simple docstring"""







									return (4, 32, 32)






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




									"""simple docstring"""







									return (4, 32, 32)






		def 			_UpperCAmelCase  (					self      :					Union[str, Any] ):




									"""simple docstring"""







									UpperCAmelCase__										=     {
									    "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__										=     self.dummy_input
									return init_dict, inputs_dict






		def 			_UpperCAmelCase  (					self      :					Optional[Any] ):




									"""simple docstring"""







									UpperCAmelCase__						,			UpperCAmelCase__										=     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__										=     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 			_UpperCAmelCase  (					self      :					str ):




									"""simple docstring"""







									UpperCAmelCase__						,			UpperCAmelCase__										=     UNetaDModel.from_pretrained("fusing/unet-ldm-dummy-update"		,						output_loading_info=snake_case__ )
									model.to(snake_case__ )
									UpperCAmelCase__										=     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 			_UpperCAmelCase  (					self      :					int ):




									"""simple docstring"""







									UpperCAmelCase__						,			UpperCAmelCase__										=     UNetaDModel.from_pretrained("fusing/unet-ldm-dummy-update"		,						output_loading_info=snake_case__ )
									model_accelerate.to(snake_case__ )
									model_accelerate.eval()

									UpperCAmelCase__										=     torch.randn(
									    1		,						model_accelerate.config.in_channels		,						model_accelerate.config.sample_size		,						model_accelerate.config.sample_size		,						generator=torch.manual_seed(0 )		,						)
									UpperCAmelCase__										=     noise.to(snake_case__ )
									UpperCAmelCase__										=     torch.tensor([10] * noise.shape[0] ).to(snake_case__ )

									UpperCAmelCase__										=     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__										=     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__										=     model_normal_load(snake_case__		,						snake_case__ )["sample"]

									assert torch_all_close(snake_case__		,						snake_case__		,						rtol=1E-3 )






		def 			_UpperCAmelCase  (					self      :					List[str] ):




									"""simple docstring"""







									UpperCAmelCase__										=     UNetaDModel.from_pretrained("fusing/unet-ldm-dummy-update" )
									model.eval()
									model.to(snake_case__ )

									UpperCAmelCase__										=     torch.randn(
									    1		,						model.config.in_channels		,						model.config.sample_size		,						model.config.sample_size		,						generator=torch.manual_seed(0 )		,						)
									UpperCAmelCase__										=     noise.to(snake_case__ )
									UpperCAmelCase__										=     torch.tensor([10] * noise.shape[0] ).to(snake_case__ )

									with torch.no_grad():
																UpperCAmelCase__										=     model(snake_case__		,						snake_case__ ).sample

									UpperCAmelCase__										=     output[0, -1, -3:, -3:].flatten().cpu()
									# fmt: off
									UpperCAmelCase__										=     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     lowercase__  (					__a					,							__a					,							unittest.TestCase		):
		A__=  UNetaDModel
		A__=  '''sample'''






		@property
		def 			_UpperCAmelCase  (					self      :					List[str]		,						_lowercase      :					Optional[Any]=(32, 32) ):




									"""simple docstring"""







									UpperCAmelCase__										=     4
									UpperCAmelCase__										=     3

									UpperCAmelCase__										=     floats_tensor((batch_size, num_channels) + sizes ).to(snake_case__ )
									UpperCAmelCase__										=     torch.tensor(batch_size * [10] ).to(dtype=torch.intaa		,						device=snake_case__ )

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






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




									"""simple docstring"""







									return (3, 32, 32)






		@property
		def 			_UpperCAmelCase  (					self      :					int ):




									"""simple docstring"""







									return (3, 32, 32)






		def 			_UpperCAmelCase  (					self      :					List[str] ):




									"""simple docstring"""







									UpperCAmelCase__										=     {
									    "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__										=     self.dummy_input
									return init_dict, inputs_dict






		@slow
		def 			_UpperCAmelCase  (					self      :					Optional[Any] ):




									"""simple docstring"""







									UpperCAmelCase__						,			UpperCAmelCase__										=     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__										=     self.dummy_input
									UpperCAmelCase__										=     floats_tensor((4, 3) + (2_56, 2_56) ).to(snake_case__ )
									UpperCAmelCase__										=     noise
									UpperCAmelCase__										=     model(**snake_case__ )

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






		@slow
		def 			_UpperCAmelCase  (					self      :					Dict ):




									"""simple docstring"""







									UpperCAmelCase__										=     UNetaDModel.from_pretrained("google/ncsnpp-celebahq-256" )
									model.to(snake_case__ )

									UpperCAmelCase__										=     4
									UpperCAmelCase__										=     3
									UpperCAmelCase__										=     (2_56, 2_56)

									UpperCAmelCase__										=     torch.ones((batch_size, num_channels) + sizes ).to(snake_case__ )
									UpperCAmelCase__										=     torch.tensor(batch_size * [1E-4] ).to(snake_case__ )

									with torch.no_grad():
																UpperCAmelCase__										=     model(snake_case__		,						snake_case__ ).sample

									UpperCAmelCase__										=     output[0, -3:, -3:, -1].flatten().cpu()
									# fmt: off
									UpperCAmelCase__										=     torch.tensor([-48_42.86_91, -64_99.66_31, -38_00.19_53, -79_78.26_86, -1_09_80.71_29, -2_00_28.85_35, 81_48.28_22, 23_42.29_05, 5_6_7.7_6_0_8] )
									# fmt: on

									self.assertTrue(torch_all_close(snake_case__		,						snake_case__		,						rtol=1E-2 ) )






		def 			_UpperCAmelCase  (					self      :					Optional[int] ):




									"""simple docstring"""







									UpperCAmelCase__										=     UNetaDModel.from_pretrained("fusing/ncsnpp-ffhq-ve-dummy-update" )
									model.to(snake_case__ )

									UpperCAmelCase__										=     4
									UpperCAmelCase__										=     3
									UpperCAmelCase__										=     (32, 32)

									UpperCAmelCase__										=     torch.ones((batch_size, num_channels) + sizes ).to(snake_case__ )
									UpperCAmelCase__										=     torch.tensor(batch_size * [1E-4] ).to(snake_case__ )

									with torch.no_grad():
																UpperCAmelCase__										=     model(snake_case__		,						snake_case__ ).sample

									UpperCAmelCase__										=     output[0, -3:, -3:, -1].flatten().cpu()
									# fmt: off
									UpperCAmelCase__										=     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 			_UpperCAmelCase  (					self      :					Optional[int] ):




									"""simple docstring"""







									pass









from __future__ import annotations





def __UpperCAmelCase       (		__A ,						__A ,						__A ,						)						->					tuple:



       '''simple docstring'''





       if (electron_conc, hole_conc, intrinsic_conc).count(0			) != 1:
              raise ValueError("You cannot supply more or less than 2 values"			)
       elif electron_conc < 0:
              raise ValueError("Electron concentration cannot be negative in a semiconductor"			)
       elif hole_conc < 0:
              raise ValueError("Hole concentration cannot be negative in a semiconductor"			)
       elif intrinsic_conc < 0:
              raise ValueError(
                  "Intrinsic concentration cannot be negative in a semiconductor"			)
       elif electron_conc == 0:
              return (
                  "electron_conc",
                  intrinsic_conc**2 / hole_conc,
              )
       elif hole_conc == 0:
              return (
                  "hole_conc",
                  intrinsic_conc**2 / electron_conc,
              )
       elif intrinsic_conc == 0:
              return (
                  "intrinsic_conc",
                  (electron_conc * hole_conc) ** 0.5,
              )
       else:
              return (-1, -1)


if __name__ == "__main__":
    import doctest

    doctest.testmod()





