
import gc
import unittest

import torch
from parameterized import parameterized

from diffusers import AutoencoderKL
from diffusers.utils import floats_tensor, load_hf_numpy, require_torch_gpu, slow, torch_all_close, torch_device
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import enable_full_determinism

from .test_modeling_common import ModelTesterMixin, UNetTesterMixin


enable_full_determinism()






class UpperCAmelCase   (						SCREAMING_SNAKE_CASE__							,							SCREAMING_SNAKE_CASE__							,							unittest.TestCase   ):





   '''simple docstring'''
   __UpperCamelCase		:    Tuple 				=    AutoencoderKL
   __UpperCamelCase		:    str 				=    '''sample'''
   __UpperCamelCase		:    List[Any] 				=    1E-2


   @property
   def  __magic_name__				(					self     :							Union[str, Any]     ):

      """simple docstring"""
      _A:  List[str]					=       4
      _A:  List[str]					=       3
      _A:  str					=       (3_2, 3_2)

      _A:  Tuple					=       floats_tensor((batch_size, num_channels) + sizes     ).to(lowerCAmelCase_     )

      return {"sample": image}


   @property
   def  __magic_name__				(					self     :							Union[str, Any]     ):

      """simple docstring"""
      return (3, 3_2, 3_2)


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

      """simple docstring"""
      return (3, 3_2, 3_2)


   def  __magic_name__				(					self     :							int     ):

      """simple docstring"""
      _A:  Dict					=       {
          '''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,
      }
      _A:  List[str]					=       self.dummy_input
      return init_dict, inputs_dict


   def  __magic_name__				(					self     :							Optional[int]     ):

      """simple docstring"""
      pass


   def  __magic_name__				(					self     :							List[str]     ):

      """simple docstring"""
      pass


   @unittest.skipIf(torch_device == '''mps'''			,			'''Gradient checkpointing skipped on MPS'''     )
   def  __magic_name__				(					self     :							Union[str, Any]     ):

      """simple docstring"""
      # enable deterministic behavior for gradient checkpointing
      _A			,  _A:  Optional[int]					=       self.prepare_init_args_and_inputs_for_common()
      _A:  Tuple					=       self.model_class(**lowerCAmelCase_     )
      model.to(lowerCAmelCase_     )

      assert not model.is_gradient_checkpointing and model.training

      _A:  str					=       model(**lowerCAmelCase_     ).sample
      # run the backwards pass on the model. For backwards pass, for simplicity purpose,
      # we won't calculate the loss and rather backprop on out.sum()
      model.zero_grad()

      _A:  Optional[Any]					=       torch.randn_like(lowerCAmelCase_     )
      _A:  List[Any]					=       (out - labels).mean()
      loss.backward()

      # re-instantiate the model now enabling gradient checkpointing
      _A:  Union[str, Any]					=       self.model_class(**lowerCAmelCase_     )
      # clone model
      model_a.load_state_dict(model.state_dict()     )
      model_a.to(lowerCAmelCase_     )
      model_a.enable_gradient_checkpointing()

      assert model_a.is_gradient_checkpointing and model_a.training

      _A:  List[str]					=       model_a(**lowerCAmelCase_     ).sample
      # run the backwards pass on the model. For backwards pass, for simplicity purpose,
      # we won't calculate the loss and rather backprop on out.sum()
      model_a.zero_grad()
      _A:  int					=       (out_a - labels).mean()
      loss_a.backward()

      # compare the output and parameters gradients
      self.assertTrue((loss - loss_a).abs() < 1e-5     )
      _A:  Optional[Any]					=       dict(model.named_parameters()     )
      _A:  str					=       dict(model_a.named_parameters()     )
      for name, param in named_params.items():
         self.assertTrue(torch_all_close(param.grad.data			,			named_params_a[name].grad.data			,			atol=5e-5     )     )


   def  __magic_name__				(					self     :							str     ):

      """simple docstring"""
      _A			,  _A:  Optional[Any]					=       AutoencoderKL.from_pretrained('''fusing/autoencoder-kl-dummy'''			,			output_loading_info=lowerCAmelCase_     )
      self.assertIsNotNone(lowerCAmelCase_     )
      self.assertEqual(len(loading_info['''missing_keys''']     )			,			0     )

      model.to(lowerCAmelCase_     )
      _A:  int					=       model(**self.dummy_input     )

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


   def  __magic_name__				(					self     :							str     ):

      """simple docstring"""
      _A:  Any					=       AutoencoderKL.from_pretrained('''fusing/autoencoder-kl-dummy'''     )
      _A:  Tuple					=       model.to(lowerCAmelCase_     )
      model.eval()

      if torch_device == "mps":
         _A:  Tuple					=       torch.manual_seed(0     )
      else:
         _A:  Optional[Any]					=       torch.Generator(device=lowerCAmelCase_     ).manual_seed(0     )

      _A:  List[Any]					=       torch.randn(
          1			,			model.config.in_channels			,			model.config.sample_size			,			model.config.sample_size			,			generator=torch.manual_seed(0     )			,			)
      _A:  Union[str, Any]					=       image.to(lowerCAmelCase_     )
      with torch.no_grad():
         _A:  Optional[Any]					=       model(lowerCAmelCase_			,			sample_posterior=lowerCAmelCase_			,			generator=lowerCAmelCase_     ).sample

      _A:  List[str]					=       output[0, -1, -3:, -3:].flatten().cpu()

      # Since the VAE Gaussian prior's generator is seeded on the appropriate device,
      # the expected output slices are not the same for CPU and GPU.
      if torch_device == "mps":
         _A:  Any					=       torch.tensor(
             [
                 -4.0078e-01,
                 -3.8323e-04,
                 -1.2681e-01,
                 -1.1462e-01,
                 2.0095e-01,
                 1.0893e-01,
                 -8.8247e-02,
                 -3.0361e-01,
                 -9.8644e-03,
             ]     )
      elif torch_device == "cpu":
         _A:  Union[str, Any]					=       torch.tensor(
             [-0.1352, 0.0878, 0.0419, -0.0818, -0.1069, 0.0688, -0.1458, -0.4446, -0.0026]     )
      else:
         _A:  Any					=       torch.tensor(
             [-0.2421, 0.4642, 0.2507, -0.0438, 0.0682, 0.3160, -0.2018, -0.0727, 0.2485]     )

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






@slow
class UpperCAmelCase   (						unittest.TestCase   ):





   '''simple docstring'''


   def  __magic_name__				(					self     :							Optional[Any]			,			lowerCAmelCase_     :							str			,			lowerCAmelCase_     :							Optional[Any]     ):

      """simple docstring"""
      return F"""gaussian_noise_s={seed}_shape={'_'.join([str(lowerCAmelCase_     ) for s in shape]     )}.npy"""


   def  __magic_name__				(					self     :							Optional[Any]     ):

      """simple docstring"""
      # clean up the VRAM after each test
      super().tearDown()
      gc.collect()
      torch.cuda.empty_cache()


   def  __magic_name__				(					self     :							Tuple			,			lowerCAmelCase_     :							List[Any]=0			,			lowerCAmelCase_     :							Tuple=(4, 3, 5_1_2, 5_1_2)			,			lowerCAmelCase_     :							List[str]=False     ):

      """simple docstring"""
      _A:  Any					=       torch.floataa if fpaa else torch.floataa
      _A:  List[str]					=       torch.from_numpy(load_hf_numpy(self.get_file_format(lowerCAmelCase_			,			lowerCAmelCase_     )     )     ).to(lowerCAmelCase_     ).to(lowerCAmelCase_     )
      return image


   def  __magic_name__				(					self     :							List[str]			,			lowerCAmelCase_     :							Any="CompVis/stable-diffusion-v1-4"			,			lowerCAmelCase_     :							Tuple=False     ):

      """simple docstring"""
      _A:  Optional[Any]					=       '''fp16''' if fpaa else None
      _A:  List[str]					=       torch.floataa if fpaa else torch.floataa

      _A:  List[Any]					=       AutoencoderKL.from_pretrained(
          lowerCAmelCase_			,			subfolder='''vae'''			,			torch_dtype=lowerCAmelCase_			,			revision=lowerCAmelCase_			,			)
      model.to(lowerCAmelCase_     ).eval()

      return model


   def  __magic_name__				(					self     :							Optional[int]			,			lowerCAmelCase_     :							Dict=0     ):

      """simple docstring"""
      if torch_device == "mps":
         return torch.manual_seed(lowerCAmelCase_     )
      return torch.Generator(device=lowerCAmelCase_     ).manual_seed(lowerCAmelCase_     )


   @parameterized.expand(
       [
           # fmt: off
           [3_3, [-0.1603, 0.9878, -0.0495, -0.0790, -0.2709, 0.8375, -0.2060, -0.0824], [-0.2395, 0.0098, 0.0102, -0.0709, -0.2840, -0.0274, -0.0718, -0.1824]],
           [4_7, [-0.2376, 0.1168, 0.1332, -0.4840, -0.2508, -0.0791, -0.0493, -0.4089], [0.0350, 0.0847, 0.0467, 0.0344, -0.0842, -0.0547, -0.0633, -0.1131]],
           # fmt: on
       ]     )
   def  __magic_name__				(					self     :							Tuple			,			lowerCAmelCase_     :							List[Any]			,			lowerCAmelCase_     :							Union[str, Any]			,			lowerCAmelCase_     :							List[str]     ):

      """simple docstring"""
      _A:  List[Any]					=       self.get_sd_vae_model()
      _A:  Tuple					=       self.get_sd_image(lowerCAmelCase_     )
      _A:  Union[str, Any]					=       self.get_generator(lowerCAmelCase_     )

      with torch.no_grad():
         _A:  List[str]					=       model(lowerCAmelCase_			,			generator=lowerCAmelCase_			,			sample_posterior=lowerCAmelCase_     ).sample

      assert sample.shape == image.shape

      _A:  Union[str, Any]					=       sample[-1, -2:, -2:, :2].flatten().float().cpu()
      _A:  Union[str, Any]					=       torch.tensor(expected_slice_mps if torch_device == '''mps''' else expected_slice     )

      assert torch_all_close(lowerCAmelCase_			,			lowerCAmelCase_			,			atol=3e-3     )


   @parameterized.expand(
       [
           # fmt: off
           [3_3, [-0.0513, 0.0289, 1.3799, 0.2166, -0.2573, -0.0871, 0.5103, -0.0999]],
           [4_7, [-0.4128, -0.1320, -0.3704, 0.1965, -0.4116, -0.2332, -0.3340, 0.2247]],
           # fmt: on
       ]     )
   @require_torch_gpu
   def  __magic_name__				(					self     :							int			,			lowerCAmelCase_     :							Any			,			lowerCAmelCase_     :							Optional[Any]     ):

      """simple docstring"""
      _A:  Optional[int]					=       self.get_sd_vae_model(fpaa=lowerCAmelCase_     )
      _A:  Optional[Any]					=       self.get_sd_image(lowerCAmelCase_			,			fpaa=lowerCAmelCase_     )
      _A:  Optional[int]					=       self.get_generator(lowerCAmelCase_     )

      with torch.no_grad():
         _A:  Tuple					=       model(lowerCAmelCase_			,			generator=lowerCAmelCase_			,			sample_posterior=lowerCAmelCase_     ).sample

      assert sample.shape == image.shape

      _A:  Optional[Any]					=       sample[-1, -2:, :2, -2:].flatten().float().cpu()
      _A:  Dict					=       torch.tensor(lowerCAmelCase_     )

      assert torch_all_close(lowerCAmelCase_			,			lowerCAmelCase_			,			atol=1e-2     )


   @parameterized.expand(
       [
           # fmt: off
           [3_3, [-0.1609, 0.9866, -0.0487, -0.0777, -0.2716, 0.8368, -0.2055, -0.0814], [-0.2395, 0.0098, 0.0102, -0.0709, -0.2840, -0.0274, -0.0718, -0.1824]],
           [4_7, [-0.2377, 0.1147, 0.1333, -0.4841, -0.2506, -0.0805, -0.0491, -0.4085], [0.0350, 0.0847, 0.0467, 0.0344, -0.0842, -0.0547, -0.0633, -0.1131]],
           # fmt: on
       ]     )
   def  __magic_name__				(					self     :							List[Any]			,			lowerCAmelCase_     :							Any			,			lowerCAmelCase_     :							int			,			lowerCAmelCase_     :							int     ):

      """simple docstring"""
      _A:  List[Any]					=       self.get_sd_vae_model()
      _A:  Tuple					=       self.get_sd_image(lowerCAmelCase_     )

      with torch.no_grad():
         _A:  Optional[int]					=       model(lowerCAmelCase_     ).sample

      assert sample.shape == image.shape

      _A:  Union[str, Any]					=       sample[-1, -2:, -2:, :2].flatten().float().cpu()
      _A:  Optional[Any]					=       torch.tensor(expected_slice_mps if torch_device == '''mps''' else expected_slice     )

      assert torch_all_close(lowerCAmelCase_			,			lowerCAmelCase_			,			atol=3e-3     )


   @parameterized.expand(
       [
           # fmt: off
           [1_3, [-0.2051, -0.1803, -0.2311, -0.2114, -0.3292, -0.3574, -0.2953, -0.3323]],
           [3_7, [-0.2632, -0.2625, -0.2199, -0.2741, -0.4539, -0.4990, -0.3720, -0.4925]],
           # fmt: on
       ]     )
   @require_torch_gpu
   def  __magic_name__				(					self     :							Dict			,			lowerCAmelCase_     :							Optional[Any]			,			lowerCAmelCase_     :							str     ):

      """simple docstring"""
      _A:  Union[str, Any]					=       self.get_sd_vae_model()
      _A:  Optional[Any]					=       self.get_sd_image(lowerCAmelCase_			,			shape=(3, 4, 6_4, 6_4)     )

      with torch.no_grad():
         _A:  Any					=       model.decode(lowerCAmelCase_     ).sample

      assert list(sample.shape     ) == [3, 3, 5_1_2, 5_1_2]

      _A:  str					=       sample[-1, -2:, :2, -2:].flatten().cpu()
      _A:  Union[str, Any]					=       torch.tensor(lowerCAmelCase_     )

      assert torch_all_close(lowerCAmelCase_			,			lowerCAmelCase_			,			atol=1e-3     )


   @parameterized.expand(
       [
           # fmt: off
           [2_7, [-0.0369, 0.0207, -0.0776, -0.0682, -0.1747, -0.1930, -0.1465, -0.2039]],
           [1_6, [-0.1628, -0.2134, -0.2747, -0.2642, -0.3774, -0.4404, -0.3687, -0.4277]],
           # fmt: on
       ]     )
   @require_torch_gpu
   def  __magic_name__				(					self     :							Optional[int]			,			lowerCAmelCase_     :							Optional[int]			,			lowerCAmelCase_     :							Dict     ):

      """simple docstring"""
      _A:  List[Any]					=       self.get_sd_vae_model(fpaa=lowerCAmelCase_     )
      _A:  str					=       self.get_sd_image(lowerCAmelCase_			,			shape=(3, 4, 6_4, 6_4)			,			fpaa=lowerCAmelCase_     )

      with torch.no_grad():
         _A:  int					=       model.decode(lowerCAmelCase_     ).sample

      assert list(sample.shape     ) == [3, 3, 5_1_2, 5_1_2]

      _A:  Tuple					=       sample[-1, -2:, :2, -2:].flatten().float().cpu()
      _A:  Any					=       torch.tensor(lowerCAmelCase_     )

      assert torch_all_close(lowerCAmelCase_			,			lowerCAmelCase_			,			atol=5e-3     )


   @parameterized.expand([(1_3,), (1_6,), (2_7,)]     )
   @require_torch_gpu
   @unittest.skipIf(not is_xformers_available()			,			reason='''xformers is not required when using PyTorch 2.0.'''     )
   def  __magic_name__				(					self     :							Tuple			,			lowerCAmelCase_     :							Union[str, Any]     ):

      """simple docstring"""
      _A:  Union[str, Any]					=       self.get_sd_vae_model(fpaa=lowerCAmelCase_     )
      _A:  List[Any]					=       self.get_sd_image(lowerCAmelCase_			,			shape=(3, 4, 6_4, 6_4)			,			fpaa=lowerCAmelCase_     )

      with torch.no_grad():
         _A:  List[str]					=       model.decode(lowerCAmelCase_     ).sample

      model.enable_xformers_memory_efficient_attention()
      with torch.no_grad():
         _A:  Union[str, Any]					=       model.decode(lowerCAmelCase_     ).sample

      assert list(sample.shape     ) == [3, 3, 5_1_2, 5_1_2]

      assert torch_all_close(lowerCAmelCase_			,			lowerCAmelCase_			,			atol=1e-1     )


   @parameterized.expand([(1_3,), (1_6,), (3_7,)]     )
   @require_torch_gpu
   @unittest.skipIf(not is_xformers_available()			,			reason='''xformers is not required when using PyTorch 2.0.'''     )
   def  __magic_name__				(					self     :							str			,			lowerCAmelCase_     :							str     ):

      """simple docstring"""
      _A:  Tuple					=       self.get_sd_vae_model()
      _A:  List[str]					=       self.get_sd_image(lowerCAmelCase_			,			shape=(3, 4, 6_4, 6_4)     )

      with torch.no_grad():
         _A:  List[Any]					=       model.decode(lowerCAmelCase_     ).sample

      model.enable_xformers_memory_efficient_attention()
      with torch.no_grad():
         _A:  Optional[int]					=       model.decode(lowerCAmelCase_     ).sample

      assert list(sample.shape     ) == [3, 3, 5_1_2, 5_1_2]

      assert torch_all_close(lowerCAmelCase_			,			lowerCAmelCase_			,			atol=1e-2     )


   @parameterized.expand(
       [
           # fmt: off
           [3_3, [-0.3001, 0.0918, -2.6984, -3.9720, -3.2099, -5.0353, 1.7338, -0.2065, 3.4267]],
           [4_7, [-1.5030, -4.3871, -6.0355, -9.1157, -1.6661, -2.7853, 2.1607, -5.0823, 2.5633]],
           # fmt: on
       ]     )
   def  __magic_name__				(					self     :							Union[str, Any]			,			lowerCAmelCase_     :							str			,			lowerCAmelCase_     :							int     ):

      """simple docstring"""
      _A:  List[str]					=       self.get_sd_vae_model()
      _A:  Tuple					=       self.get_sd_image(lowerCAmelCase_     )
      _A:  Any					=       self.get_generator(lowerCAmelCase_     )

      with torch.no_grad():
         _A:  Tuple					=       model.encode(lowerCAmelCase_     ).latent_dist
         _A:  Union[str, Any]					=       dist.sample(generator=lowerCAmelCase_     )

      assert list(sample.shape     ) == [image.shape[0], 4] + [i // 8 for i in image.shape[2:]]

      _A:  Tuple					=       sample[0, -1, -3:, -3:].flatten().cpu()
      _A:  Any					=       torch.tensor(lowerCAmelCase_     )

      _A:  int					=       3e-3 if torch_device != '''mps''' else 1e-2
      assert torch_all_close(lowerCAmelCase_			,			lowerCAmelCase_			,			atol=lowerCAmelCase_     )





# Copyright 2021 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import argparse

from .config import config_command_parser
from .config_args import default_config_file, load_config_from_file  # noqa: F401
from .default import default_command_parser
from .update import update_command_parser






def   lowerCamelCase__							(					a=None      )      ->   int:
   _A:  Union[str, Any]					=       argparse.ArgumentParser(add_help=a		,		allow_abbrev=a      )
   # The main config parser
   _A:  str					=       config_command_parser(a      )
   # The subparser to add commands to
   _A:  str					=       config_parser.add_subparsers(title='''subcommands'''		,		dest='''subcommand'''      )

   # Then add other parsers with the parent parser
   default_command_parser(a		,		parents=[parent_parser]      )
   update_command_parser(a		,		parents=[parent_parser]      )

   return config_parser






def   lowerCamelCase__							(					)      ->   Union[str, Any]:
   _A:  Any					=       get_config_parser()
   _A:  Tuple					=       config_parser.parse_args()

   if not hasattr(a		,		'''func'''      ):
      config_parser.print_help()
      exit(1      )

   # Run
   args.func(a      )


if __name__ == "__main__":
   main()



