import argparse
import json
import os
import re
from collections import OrderedDict
from os.path import basename, dirname

import fairseq
import torch
from fairseq import hub_utils
from fairseq.data.dictionary import Dictionary

from transformers import FSMTConfig, FSMTForConditionalGeneration
from transformers.models.fsmt.tokenization_fsmt import VOCAB_FILES_NAMES
from transformers.tokenization_utils_base import TOKENIZER_CONFIG_FILE
from transformers.utils import WEIGHTS_NAME, logging


logging.set_verbosity_warning()

lowercase_  : Optional[Any]								=					2

# based on the results of a search on a range of `num_beams`, `length_penalty` and `early_stopping`
# values against wmt19 test data to obtain the best BLEU scores, we will use the following defaults:
#
# * `num_beams`: 5 (higher scores better, but requires more memory/is slower, can be adjusted by users)
# * `early_stopping`: `False` consistently scored better
# * `length_penalty` varied, so will assign the best one depending on the model
lowercase_  : str								=					{
    # fairseq:
    'wmt19-ru-en': {'length_penalty': 1.1},
    'wmt19-en-ru': {'length_penalty': 1.15},
    'wmt19-en-de': {'length_penalty': 1.0},
    'wmt19-de-en': {'length_penalty': 1.1},
    # allenai:
    'wmt16-en-de-dist-12-1': {'length_penalty': 0.6},
    'wmt16-en-de-dist-6-1': {'length_penalty': 0.6},
    'wmt16-en-de-12-1': {'length_penalty': 0.8},
    'wmt19-de-en-6-6-base': {'length_penalty': 0.6},
    'wmt19-de-en-6-6-big': {'length_penalty': 0.6},
}

# this remaps the different models to their organization names
lowercase_  : Tuple								=					{}
for m in ["wmt19-ru-en", "wmt19-en-ru", "wmt19-en-de", "wmt19-de-en"]:
      lowercase_  : Tuple								=					'facebook'
for m in [
    "wmt16-en-de-dist-12-1",
    "wmt16-en-de-dist-6-1",
    "wmt16-en-de-12-1",
    "wmt19-de-en-6-6-base",
    "wmt19-de-en-6-6-big",
]:
      lowercase_  : Tuple								=					'allenai'







def       A__   (						snake_case_			:		int   ):
 SCREAMING_SNAKE_CASE__: int=   dict((re.sub(r'''@@$'''							,					''''''							,					_A   ), v) if k.endswith('''@@'''   ) else (re.sub(r'''$'''							,					'''</w>'''							,					_A   ), v) for k, v in d.items()   )
 SCREAMING_SNAKE_CASE__: List[str]=   '''<s> <pad> </s> <unk>'''.split()
 # restore the special tokens
 for k in keep_keys:
  del da[F'{k}</w>']
  SCREAMING_SNAKE_CASE__: Optional[Any]=   d[k]  # restore
 return da







def       A__   (						snake_case_			:		Tuple							,					snake_case_			:		List[Any]   ):
 assert os.path.exists(_A   )
 os.makedirs(_A							,					exist_ok=_A   )
 print(F'Writing results to {pytorch_dump_folder_path}'   )

 # handle various types of models

 SCREAMING_SNAKE_CASE__: Dict=   basename(_A   )
 SCREAMING_SNAKE_CASE__: List[str]=   dirname(_A   )

 SCREAMING_SNAKE_CASE__: Union[str, Any]=   fairseq.model_parallel.models.transformer.ModelParallelTransformerModel
 SCREAMING_SNAKE_CASE__: Dict=   cls.hub_models()
 SCREAMING_SNAKE_CASE__: Dict=   {'''bpe''': '''fastbpe''', '''tokenizer''': '''moses'''}
 SCREAMING_SNAKE_CASE__: int=   '''.'''
 # note: since the model dump is old, fairseq has upgraded its model some
 # time later, and it does a whole lot of rewrites and splits on the saved
 # weights, therefore we can't use torch.load() directly on the model file.
 # see: upgrade_state_dict(state_dict) in fairseq_model.py
 print(F'using checkpoint {checkpoint_file}'   )
 SCREAMING_SNAKE_CASE__: Union[str, Any]=   hub_utils.from_pretrained(
     _A							,					_A							,					_A							,					archive_map=_A							,					**_A   )

 SCREAMING_SNAKE_CASE__: List[Any]=   vars(chkpt['''args''']['''model''']   )

 SCREAMING_SNAKE_CASE__: str=   args['''source_lang''']
 SCREAMING_SNAKE_CASE__: Tuple=   args['''target_lang''']

 SCREAMING_SNAKE_CASE__: Optional[int]=   dirname(_A   )
 SCREAMING_SNAKE_CASE__: int=   basename(_A   )

 # dicts
 SCREAMING_SNAKE_CASE__: List[Any]=   os.path.join(_A							,					F'dict.{src_lang}.txt'   )
 SCREAMING_SNAKE_CASE__: Tuple=   os.path.join(_A							,					F'dict.{tgt_lang}.txt'   )

 SCREAMING_SNAKE_CASE__: int=   Dictionary.load(_A   )
 SCREAMING_SNAKE_CASE__: Optional[int]=   rewrite_dict_keys(src_dict.indices   )
 SCREAMING_SNAKE_CASE__: List[Any]=   len(_A   )
 SCREAMING_SNAKE_CASE__: str=   os.path.join(_A							,					'''vocab-src.json'''   )
 print(F'Generating {src_vocab_file} of {src_vocab_size} of {src_lang} records'   )
 with open(_A							,					'''w'''							,					encoding='''utf-8'''   ) as f:
  f.write(json.dumps(_A							,					ensure_ascii=_A							,					indent=_A   )   )

 # detect whether this is a do_lower_case situation, which can be derived by checking whether we
 # have at least one uppercase letter in the source vocab
 SCREAMING_SNAKE_CASE__: Tuple=   True
 for k in src_vocab.keys():
  if not k.islower():
   SCREAMING_SNAKE_CASE__: int=   False
   break

 SCREAMING_SNAKE_CASE__: str=   Dictionary.load(_A   )
 SCREAMING_SNAKE_CASE__: Tuple=   rewrite_dict_keys(tgt_dict.indices   )
 SCREAMING_SNAKE_CASE__: List[str]=   len(_A   )
 SCREAMING_SNAKE_CASE__: Dict=   os.path.join(_A							,					'''vocab-tgt.json'''   )
 print(F'Generating {tgt_vocab_file} of {tgt_vocab_size} of {tgt_lang} records'   )
 with open(_A							,					'''w'''							,					encoding='''utf-8'''   ) as f:
  f.write(json.dumps(_A							,					ensure_ascii=_A							,					indent=_A   )   )

 # merges_file (bpecodes)
 SCREAMING_SNAKE_CASE__: Tuple=   os.path.join(_A							,					VOCAB_FILES_NAMES['''merges_file''']   )
 for fn in ["bpecodes", "code"]:  # older fairseq called the merges file "code"
  SCREAMING_SNAKE_CASE__: Dict=   os.path.join(_A							,					_A   )
  if os.path.exists(_A   ):
   break
 with open(_A							,					encoding='''utf-8'''   ) as fin:
  SCREAMING_SNAKE_CASE__: Optional[Any]=   fin.read()
 SCREAMING_SNAKE_CASE__: List[str]=   re.sub(r''' \d+$'''							,					''''''							,					_A							,					0							,					re.M   )  # remove frequency number
 print(F'Generating {merges_file}'   )
 with open(_A							,					'''w'''							,					encoding='''utf-8'''   ) as fout:
  fout.write(_A   )

 # model config
 SCREAMING_SNAKE_CASE__: Optional[int]=   os.path.join(_A							,					'''config.json'''   )

 # validate bpe/tokenizer config, as currently it's hardcoded to moses+fastbpe -
 # may have to modify the tokenizer if a different type is used by a future model
 assert args["bpe"] == "fastbpe", F'need to extend tokenizer to support bpe={args["bpe"]}'
 assert args["tokenizer"] == "moses", F'need to extend tokenizer to support bpe={args["tokenizer"]}'

 SCREAMING_SNAKE_CASE__: Optional[Any]=   {
     '''architectures''': ['''FSMTForConditionalGeneration'''],
     '''model_type''': '''fsmt''',
     '''activation_dropout''': args['''activation_dropout'''],
     '''activation_function''': '''relu''',
     '''attention_dropout''': args['''attention_dropout'''],
     '''d_model''': args['''decoder_embed_dim'''],
     '''dropout''': args['''dropout'''],
     '''init_std''': 0.02,
     '''max_position_embeddings''': args['''max_source_positions'''],
     '''num_hidden_layers''': args['''encoder_layers'''],
     '''src_vocab_size''': src_vocab_size,
     '''tgt_vocab_size''': tgt_vocab_size,
     '''langs''': [src_lang, tgt_lang],
     '''encoder_attention_heads''': args['''encoder_attention_heads'''],
     '''encoder_ffn_dim''': args['''encoder_ffn_embed_dim'''],
     '''encoder_layerdrop''': args['''encoder_layerdrop'''],
     '''encoder_layers''': args['''encoder_layers'''],
     '''decoder_attention_heads''': args['''decoder_attention_heads'''],
     '''decoder_ffn_dim''': args['''decoder_ffn_embed_dim'''],
     '''decoder_layerdrop''': args['''decoder_layerdrop'''],
     '''decoder_layers''': args['''decoder_layers'''],
     '''bos_token_id''': 0,
     '''pad_token_id''': 1,
     '''eos_token_id''': 2,
     '''is_encoder_decoder''': True,
     '''scale_embedding''': not args['''no_scale_embedding'''],
     '''tie_word_embeddings''': args['''share_all_embeddings'''],
 }

 # good hparam defaults to start with
 SCREAMING_SNAKE_CASE__: Optional[int]=   5
 SCREAMING_SNAKE_CASE__: Optional[Any]=   False
 if model_dir in best_score_hparams and "length_penalty" in best_score_hparams[model_dir]:
  SCREAMING_SNAKE_CASE__: str=   best_score_hparams[model_dir]['''length_penalty''']
 else:
  SCREAMING_SNAKE_CASE__: Dict=   1.0

 print(F'Generating {fsmt_model_config_file}'   )
 with open(_A							,					'''w'''							,					encoding='''utf-8'''   ) as f:
  f.write(json.dumps(_A							,					ensure_ascii=_A							,					indent=_A   )   )

 # tokenizer config
 SCREAMING_SNAKE_CASE__: List[str]=   os.path.join(_A							,					_A   )

 SCREAMING_SNAKE_CASE__: Any=   {
     '''langs''': [src_lang, tgt_lang],
     '''model_max_length''': 1_024,
     '''do_lower_case''': do_lower_case,
 }

 print(F'Generating {fsmt_tokenizer_config_file}'   )
 with open(_A							,					'''w'''							,					encoding='''utf-8'''   ) as f:
  f.write(json.dumps(_A							,					ensure_ascii=_A							,					indent=_A   )   )

 # model
 SCREAMING_SNAKE_CASE__: Dict=   chkpt['''models'''][0]
 SCREAMING_SNAKE_CASE__: Any=   model.state_dict()

 # rename keys to start with 'model.'
 SCREAMING_SNAKE_CASE__: Tuple=   OrderedDict(('''model.''' + k, v) for k, v in model_state_dict.items()   )

 # remove unneeded keys
 SCREAMING_SNAKE_CASE__: Union[str, Any]=   [
     '''model.model''',
     '''model.encoder.version''',
     '''model.decoder.version''',
     '''model.encoder_embed_tokens.weight''',
     '''model.decoder_embed_tokens.weight''',
     '''model.encoder.embed_positions._float_tensor''',
     '''model.decoder.embed_positions._float_tensor''',
 ]
 for k in ignore_keys:
  model_state_dict.pop(_A							,					_A   )

 SCREAMING_SNAKE_CASE__: List[str]=   FSMTConfig.from_pretrained(_A   )
 SCREAMING_SNAKE_CASE__: int=   FSMTForConditionalGeneration(_A   )

 # check that it loads ok
 model_new.load_state_dict(_A							,					strict=_A   )

 # save
 SCREAMING_SNAKE_CASE__: List[str]=   os.path.join(_A							,					_A   )
 print(F'Generating {pytorch_weights_dump_path}'   )
 torch.save(_A							,					_A   )

 print('''Conversion is done!'''   )
 print('''\nLast step is to upload the files to s3'''   )
 print(F'cd {data_root}'   )
 print(F'transformers-cli upload {model_dir}'   )


if __name__ == "__main__":
      lowercase_  : int								=					argparse.ArgumentParser()
      # Required parameters
      parser.add_argument(
          '--fsmt_checkpoint_path',
          default=None,
          type=str,
          required=True,
          help=(
              'Path to the official PyTorch checkpoint file which is expected to reside in the dump dir with dicts,'
              ' bpecodes, etc.'
          ),
      )
      parser.add_argument(
          '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.'
      )
      lowercase_  : List[str]								=					parser.parse_args()
      convert_fsmt_checkpoint_to_pytorch(args.fsmt_checkpoint_path, args.pytorch_dump_folder_path)


'''simple docstring'''

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 					_lowercase						(   lowerCAmelCase		,lowerCAmelCase		,unittest.TestCase ):
      '''simple docstring'''


      UpperCAmelCase_   :   int   				= AutoencoderKL
      UpperCAmelCase_   :   Any   				= '''sample'''
      UpperCAmelCase_   :   List[str]   				= 1E-2




      @property
      def 		lowerCAmelCase__       (					self				)      ->      int:



         '''simple docstring'''



         UpperCAmelCase__				:					Dict 					=	4
         UpperCAmelCase__				:					Optional[int] 					=	3
         UpperCAmelCase__				:					Tuple 					=	(32, 32)

         UpperCAmelCase__				:					Optional[int] 					=	floats_tensor((batch_size, num_channels) + sizes				).to(lowerCamelCase_				)

         return {"sample": image}




      @property
      def 		lowerCAmelCase__       (					self				)      ->      List[str]:



         '''simple docstring'''



         return (3, 32, 32)




      @property
      def 		lowerCAmelCase__       (					self				)      ->      Any:



         '''simple docstring'''



         return (3, 32, 32)




      def 		lowerCAmelCase__       (					self				)      ->      Dict:



         '''simple docstring'''



         UpperCAmelCase__				:					List[Any] 					=	{
             '''block_out_channels''': [32, 64],
             '''in_channels''': 3,
             '''out_channels''': 3,
             '''down_block_types''': ['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''],
             '''up_block_types''': ['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''],
             '''latent_channels''': 4,
         }
         UpperCAmelCase__				:					Optional[Any] 					=	self.dummy_input
         return init_dict, inputs_dict




      def 		lowerCAmelCase__       (					self				)      ->      Union[str, Any]:



         '''simple docstring'''



         pass




      def 		lowerCAmelCase__       (					self				)      ->      Union[str, Any]:



         '''simple docstring'''



         pass




      @unittest.skipIf(torch_device == '''mps'''       ,'''Gradient checkpointing skipped on MPS'''				)
      def 		lowerCAmelCase__       (					self				)      ->      Tuple:



         '''simple docstring'''



         UpperCAmelCase__					,   UpperCAmelCase__				:					Optional[Any] 					=	self.prepare_init_args_and_inputs_for_common()
         UpperCAmelCase__				:					Union[str, Any] 					=	self.model_class(**lowerCamelCase_				)
         model.to(lowerCamelCase_				)

         assert not model.is_gradient_checkpointing and model.training

         UpperCAmelCase__				:					Any 					=	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()

         UpperCAmelCase__				:					Optional[int] 					=	torch.randn_like(lowerCamelCase_				)
         UpperCAmelCase__				:					Optional[Any] 					=	(out - labels).mean()
         loss.backward()

         # re-instantiate the model now enabling gradient checkpointing
         UpperCAmelCase__				:					Optional[int] 					=	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

         UpperCAmelCase__				:					int 					=	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()
         UpperCAmelCase__				:					Union[str, Any] 					=	(out_a - labels).mean()
         loss_a.backward()

         # compare the output and parameters gradients
         self.assertTrue((loss - loss_a).abs() < 1e-5				)
         UpperCAmelCase__				:					Union[str, Any] 					=	dict(model.named_parameters()				)
         UpperCAmelCase__				:					int 					=	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 		lowerCAmelCase__       (					self				)      ->      Tuple:



         '''simple docstring'''



         UpperCAmelCase__					,   UpperCAmelCase__				:					Union[str, 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_				)
         UpperCAmelCase__				:					Optional[int] 					=	model(**self.dummy_input				)

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




      def 		lowerCAmelCase__       (					self				)      ->      str:



         '''simple docstring'''



         UpperCAmelCase__				:					Tuple 					=	AutoencoderKL.from_pretrained('''fusing/autoencoder-kl-dummy'''				)
         UpperCAmelCase__				:					Optional[Any] 					=	model.to(lowerCamelCase_				)
         model.eval()

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

         UpperCAmelCase__				:					str 					=	torch.randn(
             1       ,model.config.in_channels       ,model.config.sample_size       ,model.config.sample_size       ,generator=torch.manual_seed(0				)       ,)
         UpperCAmelCase__				:					int 					=	image.to(lowerCamelCase_				)
         with torch.no_grad():
            UpperCAmelCase__				:					str 					=	model(lowerCamelCase_       ,sample_posterior=lowerCamelCase_       ,generator=lowerCamelCase_				).sample

         UpperCAmelCase__				:					int 					=	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":
            UpperCAmelCase__				:					int 					=	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":
            UpperCAmelCase__				:					List[Any] 					=	torch.tensor(
                [-0.1352, 0.0878, 0.0419, -0.0818, -0.1069, 0.0688, -0.1458, -0.4446, -0.0026]				)
         else:
            UpperCAmelCase__				:					Optional[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 					_lowercase						(   unittest.TestCase ):
      '''simple docstring'''


      def 		lowerCAmelCase__       (					self       ,lowerCamelCase_       ,lowerCamelCase_				)      ->      int:



         '''simple docstring'''



         return f'''gaussian_noise_s={seed}_shape={'_'.join([str(lowerCamelCase_				) for s in shape]				)}.npy'''




      def 		lowerCAmelCase__       (					self				)      ->      Optional[int]:



         '''simple docstring'''



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




      def 		lowerCAmelCase__       (					self       ,lowerCamelCase_=0       ,lowerCamelCase_=(4, 3, 512, 512)       ,lowerCamelCase_=False				)      ->      int:



         '''simple docstring'''



         UpperCAmelCase__				:					Optional[Any] 					=	torch.floataa if fpaa else torch.floataa
         UpperCAmelCase__				:					Dict 					=	torch.from_numpy(load_hf_numpy(self.get_file_format(lowerCamelCase_       ,lowerCamelCase_				)				)				).to(lowerCamelCase_				).to(lowerCamelCase_				)
         return image




      def 		lowerCAmelCase__       (					self       ,lowerCamelCase_="CompVis/stable-diffusion-v1-4"       ,lowerCamelCase_=False				)      ->      Dict:



         '''simple docstring'''



         UpperCAmelCase__				:					Union[str, Any] 					=	'''fp16''' if fpaa else None
         UpperCAmelCase__				:					str 					=	torch.floataa if fpaa else torch.floataa

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

         return model




      def 		lowerCAmelCase__       (					self       ,lowerCamelCase_=0				)      ->      Optional[Any]:



         '''simple docstring'''



         if torch_device == "mps":
            return torch.manual_seed(lowerCamelCase_				)
         return torch.Generator(device=lowerCamelCase_				).manual_seed(lowerCamelCase_				)




      @parameterized.expand(
          [
              # fmt: off
              [33, [-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]],
              [47, [-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 		lowerCAmelCase__       (					self       ,lowerCamelCase_       ,lowerCamelCase_       ,lowerCamelCase_				)      ->      int:



         '''simple docstring'''



         UpperCAmelCase__				:					Optional[Any] 					=	self.get_sd_vae_model()
         UpperCAmelCase__				:					str 					=	self.get_sd_image(lowerCamelCase_				)
         UpperCAmelCase__				:					Dict 					=	self.get_generator(lowerCamelCase_				)

         with torch.no_grad():
            UpperCAmelCase__				:					Tuple 					=	model(lowerCamelCase_       ,generator=lowerCamelCase_       ,sample_posterior=lowerCamelCase_				).sample

         assert sample.shape == image.shape

         UpperCAmelCase__				:					List[Any] 					=	sample[-1, -2:, -2:, :2].flatten().float().cpu()
         UpperCAmelCase__				:					Tuple 					=	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
              [33, [-0.0513, 0.0289, 1.3799, 0.2166, -0.2573, -0.0871, 0.5103, -0.0999]],
              [47, [-0.4128, -0.1320, -0.3704, 0.1965, -0.4116, -0.2332, -0.3340, 0.2247]],
              # fmt: on
          ]				)
      @require_torch_gpu
      def 		lowerCAmelCase__       (					self       ,lowerCamelCase_       ,lowerCamelCase_				)      ->      List[Any]:



         '''simple docstring'''



         UpperCAmelCase__				:					Tuple 					=	self.get_sd_vae_model(fpaa=lowerCamelCase_				)
         UpperCAmelCase__				:					Tuple 					=	self.get_sd_image(lowerCamelCase_       ,fpaa=lowerCamelCase_				)
         UpperCAmelCase__				:					Union[str, Any] 					=	self.get_generator(lowerCamelCase_				)

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

         assert sample.shape == image.shape

         UpperCAmelCase__				:					Optional[Any] 					=	sample[-1, -2:, :2, -2:].flatten().float().cpu()
         UpperCAmelCase__				:					List[str] 					=	torch.tensor(lowerCamelCase_				)

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




      @parameterized.expand(
          [
              # fmt: off
              [33, [-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]],
              [47, [-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 		lowerCAmelCase__       (					self       ,lowerCamelCase_       ,lowerCamelCase_       ,lowerCamelCase_				)      ->      str:



         '''simple docstring'''



         UpperCAmelCase__				:					Any 					=	self.get_sd_vae_model()
         UpperCAmelCase__				:					Optional[int] 					=	self.get_sd_image(lowerCamelCase_				)

         with torch.no_grad():
            UpperCAmelCase__				:					List[str] 					=	model(lowerCamelCase_				).sample

         assert sample.shape == image.shape

         UpperCAmelCase__				:					str 					=	sample[-1, -2:, -2:, :2].flatten().float().cpu()
         UpperCAmelCase__				:					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
              [13, [-0.2051, -0.1803, -0.2311, -0.2114, -0.3292, -0.3574, -0.2953, -0.3323]],
              [37, [-0.2632, -0.2625, -0.2199, -0.2741, -0.4539, -0.4990, -0.3720, -0.4925]],
              # fmt: on
          ]				)
      @require_torch_gpu
      def 		lowerCAmelCase__       (					self       ,lowerCamelCase_       ,lowerCamelCase_				)      ->      Dict:



         '''simple docstring'''



         UpperCAmelCase__				:					Dict 					=	self.get_sd_vae_model()
         UpperCAmelCase__				:					Dict 					=	self.get_sd_image(lowerCamelCase_       ,shape=(3, 4, 64, 64)				)

         with torch.no_grad():
            UpperCAmelCase__				:					Optional[Any] 					=	model.decode(lowerCamelCase_				).sample

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

         UpperCAmelCase__				:					Optional[int] 					=	sample[-1, -2:, :2, -2:].flatten().cpu()
         UpperCAmelCase__				:					str 					=	torch.tensor(lowerCamelCase_				)

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




      @parameterized.expand(
          [
              # fmt: off
              [27, [-0.0369, 0.0207, -0.0776, -0.0682, -0.1747, -0.1930, -0.1465, -0.2039]],
              [16, [-0.1628, -0.2134, -0.2747, -0.2642, -0.3774, -0.4404, -0.3687, -0.4277]],
              # fmt: on
          ]				)
      @require_torch_gpu
      def 		lowerCAmelCase__       (					self       ,lowerCamelCase_       ,lowerCamelCase_				)      ->      Any:



         '''simple docstring'''



         UpperCAmelCase__				:					int 					=	self.get_sd_vae_model(fpaa=lowerCamelCase_				)
         UpperCAmelCase__				:					str 					=	self.get_sd_image(lowerCamelCase_       ,shape=(3, 4, 64, 64)       ,fpaa=lowerCamelCase_				)

         with torch.no_grad():
            UpperCAmelCase__				:					Dict 					=	model.decode(lowerCamelCase_				).sample

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

         UpperCAmelCase__				:					List[str] 					=	sample[-1, -2:, :2, -2:].flatten().float().cpu()
         UpperCAmelCase__				:					Any 					=	torch.tensor(lowerCamelCase_				)

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




      @parameterized.expand([(13,), (16,), (27,)]				)
      @require_torch_gpu
      @unittest.skipIf(not is_xformers_available()       ,reason='''xformers is not required when using PyTorch 2.0.'''				)
      def 		lowerCAmelCase__       (					self       ,lowerCamelCase_				)      ->      Tuple:



         '''simple docstring'''



         UpperCAmelCase__				:					Optional[Any] 					=	self.get_sd_vae_model(fpaa=lowerCamelCase_				)
         UpperCAmelCase__				:					Optional[int] 					=	self.get_sd_image(lowerCamelCase_       ,shape=(3, 4, 64, 64)       ,fpaa=lowerCamelCase_				)

         with torch.no_grad():
            UpperCAmelCase__				:					Any 					=	model.decode(lowerCamelCase_				).sample

         model.enable_xformers_memory_efficient_attention()
         with torch.no_grad():
            UpperCAmelCase__				:					int 					=	model.decode(lowerCamelCase_				).sample

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

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




      @parameterized.expand([(13,), (16,), (37,)]				)
      @require_torch_gpu
      @unittest.skipIf(not is_xformers_available()       ,reason='''xformers is not required when using PyTorch 2.0.'''				)
      def 		lowerCAmelCase__       (					self       ,lowerCamelCase_				)      ->      List[str]:



         '''simple docstring'''



         UpperCAmelCase__				:					List[Any] 					=	self.get_sd_vae_model()
         UpperCAmelCase__				:					List[Any] 					=	self.get_sd_image(lowerCamelCase_       ,shape=(3, 4, 64, 64)				)

         with torch.no_grad():
            UpperCAmelCase__				:					Tuple 					=	model.decode(lowerCamelCase_				).sample

         model.enable_xformers_memory_efficient_attention()
         with torch.no_grad():
            UpperCAmelCase__				:					List[str] 					=	model.decode(lowerCamelCase_				).sample

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

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




      @parameterized.expand(
          [
              # fmt: off
              [33, [-0.3001, 0.0918, -2.6984, -3.9720, -3.2099, -5.0353, 1.7338, -0.2065, 3.4267]],
              [47, [-1.5030, -4.3871, -6.0355, -9.1157, -1.6661, -2.7853, 2.1607, -5.0823, 2.5633]],
              # fmt: on
          ]				)
      def 		lowerCAmelCase__       (					self       ,lowerCamelCase_       ,lowerCamelCase_				)      ->      List[str]:



         '''simple docstring'''



         UpperCAmelCase__				:					Any 					=	self.get_sd_vae_model()
         UpperCAmelCase__				:					Optional[Any] 					=	self.get_sd_image(lowerCamelCase_				)
         UpperCAmelCase__				:					Optional[int] 					=	self.get_generator(lowerCamelCase_				)

         with torch.no_grad():
            UpperCAmelCase__				:					Optional[int] 					=	model.encode(lowerCamelCase_				).latent_dist
            UpperCAmelCase__				:					Tuple 					=	dist.sample(generator=lowerCamelCase_				)

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

         UpperCAmelCase__				:					List[str] 					=	sample[0, -1, -3:, -3:].flatten().cpu()
         UpperCAmelCase__				:					Optional[Any] 					=	torch.tensor(lowerCamelCase_				)

         UpperCAmelCase__				:					List[Any] 					=	3e-3 if torch_device != '''mps''' else 1e-2
         assert torch_all_close(lowerCamelCase_       ,lowerCamelCase_       ,atol=lowerCamelCase_				)




