

import argparse
import os

import torch

from transformers import FlavaConfig, FlavaForPreTraining
from transformers.models.flava.convert_dalle_to_flava_codebook import convert_dalle_checkpoint







def 	_snake_case		(    SCREAMING_SNAKE_CASE				)       ->      Optional[int]:

     """simple docstring"""







     return sum(param.float().sum() if "encoder.embeddings" not in key else 0 for key, param in state_dict.items()				)







def 	_snake_case		(    SCREAMING_SNAKE_CASE		,							SCREAMING_SNAKE_CASE				)       ->      Tuple:

     """simple docstring"""







     _lowerCAmelCase   :					str        =    {}

     for key, value in state_dict.items():
          if "text_encoder.embeddings" in key or "image_encoder.embeddings" in key:
               continue

          _lowerCAmelCase   :					Union[str, Any]        =    key.replace("heads.cmd.mim_head.cls.predictions"		,							"mmm_image_head"				)
          _lowerCAmelCase   :					int        =    key.replace("heads.cmd.mlm_head.cls.predictions"		,							"mmm_text_head"				)
          _lowerCAmelCase   :					Any        =    key.replace("heads.cmd.itm_head.cls"		,							"itm_head"				)
          _lowerCAmelCase   :					Optional[Any]        =    key.replace("heads.cmd.itm_head.pooler"		,							"itm_head.pooler"				)
          _lowerCAmelCase   :					Any        =    key.replace("heads.cmd.clip_head.logit_scale"		,							"flava.logit_scale"				)
          _lowerCAmelCase   :					List[Any]        =    key.replace("heads.fairseq_mlm.cls.predictions"		,							"mlm_head"				)
          _lowerCAmelCase   :					Union[str, Any]        =    key.replace("heads.imagenet.mim_head.cls.predictions"		,							"mim_head"				)
          _lowerCAmelCase   :					Optional[int]        =    key.replace("mm_text_projection"		,							"flava.text_to_mm_projection"				)
          _lowerCAmelCase   :					int        =    key.replace("mm_image_projection"		,							"flava.image_to_mm_projection"				)
          _lowerCAmelCase   :					List[str]        =    key.replace("image_encoder.module"		,							"flava.image_model"				)
          _lowerCAmelCase   :					Optional[int]        =    key.replace("text_encoder.module"		,							"flava.text_model"				)
          _lowerCAmelCase   :					List[str]        =    key.replace("mm_encoder.module.encoder.cls_token"		,							"flava.multimodal_model.cls_token"				)
          _lowerCAmelCase   :					Dict        =    key.replace("mm_encoder.module"		,							"flava.multimodal_model"				)
          _lowerCAmelCase   :					Dict        =    key.replace("text_projection"		,							"flava.text_projection"				)
          _lowerCAmelCase   :					Optional[Any]        =    key.replace("image_projection"		,							"flava.image_projection"				)

          _lowerCAmelCase   :					List[Any]        =    value.float()

     for key, value in codebook_state_dict.items():
          _lowerCAmelCase   :					int        =    value

     return upgrade







@torch.no_grad()
def 	_snake_case		(    SCREAMING_SNAKE_CASE		,							SCREAMING_SNAKE_CASE		,							SCREAMING_SNAKE_CASE		,							SCREAMING_SNAKE_CASE=None				)       ->      Tuple:

     """simple docstring"""







     if config_path is not None:
          _lowerCAmelCase   :					Dict        =    FlavaConfig.from_pretrained(SCREAMING_SNAKE_CASE				)
     else:
          _lowerCAmelCase   :					Dict        =    FlavaConfig()

     _lowerCAmelCase   :					List[Any]        =    FlavaForPreTraining(SCREAMING_SNAKE_CASE				).eval()

     _lowerCAmelCase   :					Optional[int]        =    convert_dalle_checkpoint(SCREAMING_SNAKE_CASE		,							SCREAMING_SNAKE_CASE		,							save_checkpoint=SCREAMING_SNAKE_CASE				)

     if os.path.exists(SCREAMING_SNAKE_CASE				):
          _lowerCAmelCase   :					Dict        =    torch.load(SCREAMING_SNAKE_CASE		,							map_location="cpu"				)
     else:
          _lowerCAmelCase   :					Tuple        =    torch.hub.load_state_dict_from_url(SCREAMING_SNAKE_CASE		,							map_location="cpu"				)

     _lowerCAmelCase   :					Optional[int]        =    upgrade_state_dict(SCREAMING_SNAKE_CASE		,							SCREAMING_SNAKE_CASE				)
     hf_model.load_state_dict(SCREAMING_SNAKE_CASE				)
     _lowerCAmelCase   :					Optional[Any]        =    hf_model.state_dict()
     _lowerCAmelCase   :					Optional[Any]        =    count_parameters(SCREAMING_SNAKE_CASE				)
     _lowerCAmelCase   :					Optional[Any]        =    count_parameters(SCREAMING_SNAKE_CASE				) + count_parameters(SCREAMING_SNAKE_CASE				)

     assert torch.allclose(SCREAMING_SNAKE_CASE		,							SCREAMING_SNAKE_CASE		,							atol=1e-3				)

     hf_model.save_pretrained(SCREAMING_SNAKE_CASE				)


if __name__ == "__main__":
  __UpperCAmelCase    				=     argparse.ArgumentParser()
  parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.')
  parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to flava checkpoint')
  parser.add_argument('--codebook_path', default=None, type=str, help='Path to flava codebook checkpoint')
  parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert')
  __UpperCAmelCase    				=     parser.parse_args()

  convert_flava_checkpoint(args.checkpoint_path, args.codebook_path, args.pytorch_dump_folder_path, args.config_path)









import gc
import random
import unittest

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

from diffusers import AutoencoderKL, DDIMScheduler, DDPMScheduler, StableDiffusionUpscalePipeline, UNetaDConditionModel
from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu


enable_full_determinism()





class A__    ( unittest.TestCase ):



 """simple docstring"""







 def    __magic_name__       (		self :	Any       ):






      '''simple docstring'''




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

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






      '''simple docstring'''




      _lowerCAmelCase   :					Optional[int]        =    1
      _lowerCAmelCase   :					List[str]        =    3
      _lowerCAmelCase   :					int        =    (3_2, 3_2)

      _lowerCAmelCase   :					Dict        =    floats_tensor((batch_size, num_channels) + sizes     ,						rng=random.Random(0       )       ).to(A_       )
      return image

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






      '''simple docstring'''




      torch.manual_seed(0       )
      _lowerCAmelCase   :					Dict        =    UNetaDConditionModel(
          block_out_channels=(3_2, 3_2, 6_4)     ,						layers_per_block=2     ,						sample_size=3_2     ,						in_channels=7     ,						out_channels=4     ,						down_block_types=("DownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D")     ,						up_block_types=("CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "UpBlock2D")     ,						cross_attention_dim=3_2     ,						attention_head_dim=8     ,						use_linear_projection=A_     ,						only_cross_attention=(True, True, False)     ,						num_class_embeds=1_0_0     ,						)
      return model

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






      '''simple docstring'''




      torch.manual_seed(0       )
      _lowerCAmelCase   :					Union[str, Any]        =    AutoencoderKL(
          block_out_channels=[3_2, 3_2, 6_4]     ,						in_channels=3     ,						out_channels=3     ,						down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D", "DownEncoderBlock2D"]     ,						up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D"]     ,						latent_channels=4     ,						)
      return model

 @property
 def    __magic_name__       (		self :	Tuple       ):






      '''simple docstring'''




      torch.manual_seed(0       )
      _lowerCAmelCase   :					Optional[Any]        =    CLIPTextConfig(
          bos_token_id=0     ,						eos_token_id=2     ,						hidden_size=3_2     ,						intermediate_size=3_7     ,						layer_norm_eps=1E-05     ,						num_attention_heads=4     ,						num_hidden_layers=5     ,						pad_token_id=1     ,						vocab_size=1_0_0_0     ,						hidden_act="gelu"     ,						projection_dim=5_1_2     ,						)
      return CLIPTextModel(A_       )

 def    __magic_name__       (		self :	str       ):






      '''simple docstring'''




      _lowerCAmelCase   :					List[str]        =    "cpu"  # ensure determinism for the device-dependent torch.Generator
      _lowerCAmelCase   :					Tuple        =    self.dummy_cond_unet_upscale
      _lowerCAmelCase   :					Optional[int]        =    DDPMScheduler()
      _lowerCAmelCase   :					Optional[Any]        =    DDIMScheduler(prediction_type="v_prediction"       )
      _lowerCAmelCase   :					str        =    self.dummy_vae
      _lowerCAmelCase   :					Any        =    self.dummy_text_encoder
      _lowerCAmelCase   :					Dict        =    CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"       )

      _lowerCAmelCase   :					List[Any]        =    self.dummy_image.cpu().permute(0     ,						2     ,						3     ,						1       )[0]
      _lowerCAmelCase   :					List[Any]        =    Image.fromarray(np.uinta(A_       )       ).convert("RGB"       ).resize((6_4, 6_4)       )

      # make sure here that pndm scheduler skips prk
      _lowerCAmelCase   :					List[Any]        =    StableDiffusionUpscalePipeline(
          unet=A_     ,						low_res_scheduler=A_     ,						scheduler=A_     ,						vae=A_     ,						text_encoder=A_     ,						tokenizer=A_     ,						max_noise_level=3_5_0     ,						)
      _lowerCAmelCase   :					Optional[int]        =    sd_pipe.to(A_       )
      sd_pipe.set_progress_bar_config(disable=A_       )

      _lowerCAmelCase   :					List[str]        =    "A painting of a squirrel eating a burger"
      _lowerCAmelCase   :					Tuple        =    torch.Generator(device=A_       ).manual_seed(0       )
      _lowerCAmelCase   :					Optional[int]        =    sd_pipe(
          [prompt]     ,						image=A_     ,						generator=A_     ,						guidance_scale=6.0     ,						noise_level=2_0     ,						num_inference_steps=2     ,						output_type="np"     ,						)

      _lowerCAmelCase   :					Tuple        =    output.images

      _lowerCAmelCase   :					Optional[int]        =    torch.Generator(device=A_       ).manual_seed(0       )
      _lowerCAmelCase   :					Union[str, Any]        =    sd_pipe(
          [prompt]     ,						image=A_     ,						generator=A_     ,						guidance_scale=6.0     ,						noise_level=2_0     ,						num_inference_steps=2     ,						output_type="np"     ,						return_dict=A_     ,						)[0]

      _lowerCAmelCase   :					List[Any]        =    image[0, -3:, -3:, -1]
      _lowerCAmelCase   :					List[str]        =    image_from_tuple[0, -3:, -3:, -1]

      _lowerCAmelCase   :					Optional[int]        =    low_res_image.size[0] * 4
      assert image.shape == (1, expected_height_width, expected_height_width, 3)
      _lowerCAmelCase   :					str        =    np.array([0.3113, 0.3910, 0.4272, 0.4859, 0.5061, 0.4652, 0.5362, 0.5715, 0.5661]       )

      assert np.abs(image_slice.flatten() - expected_slice       ).max() < 1E-2
      assert np.abs(image_from_tuple_slice.flatten() - expected_slice       ).max() < 1E-2

 def    __magic_name__       (		self :	int       ):






      '''simple docstring'''




      _lowerCAmelCase   :					List[str]        =    "cpu"  # ensure determinism for the device-dependent torch.Generator
      _lowerCAmelCase   :					List[str]        =    self.dummy_cond_unet_upscale
      _lowerCAmelCase   :					str        =    DDPMScheduler()
      _lowerCAmelCase   :					Union[str, Any]        =    DDIMScheduler(prediction_type="v_prediction"       )
      _lowerCAmelCase   :					Tuple        =    self.dummy_vae
      _lowerCAmelCase   :					Union[str, Any]        =    self.dummy_text_encoder
      _lowerCAmelCase   :					List[Any]        =    CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"       )

      _lowerCAmelCase   :					Dict        =    self.dummy_image.cpu().permute(0     ,						2     ,						3     ,						1       )[0]
      _lowerCAmelCase   :					Tuple        =    Image.fromarray(np.uinta(A_       )       ).convert("RGB"       ).resize((6_4, 6_4)       )

      # make sure here that pndm scheduler skips prk
      _lowerCAmelCase   :					Optional[Any]        =    StableDiffusionUpscalePipeline(
          unet=A_     ,						low_res_scheduler=A_     ,						scheduler=A_     ,						vae=A_     ,						text_encoder=A_     ,						tokenizer=A_     ,						max_noise_level=3_5_0     ,						)
      _lowerCAmelCase   :					Dict        =    sd_pipe.to(A_       )
      sd_pipe.set_progress_bar_config(disable=A_       )

      _lowerCAmelCase   :					Union[str, Any]        =    "A painting of a squirrel eating a burger"
      _lowerCAmelCase   :					Tuple        =    sd_pipe(
          2 * [prompt]     ,						image=2 * [low_res_image]     ,						guidance_scale=6.0     ,						noise_level=2_0     ,						num_inference_steps=2     ,						output_type="np"     ,						)
      _lowerCAmelCase   :					List[str]        =    output.images
      assert image.shape[0] == 2

      _lowerCAmelCase   :					str        =    torch.Generator(device=A_       ).manual_seed(0       )
      _lowerCAmelCase   :					List[Any]        =    sd_pipe(
          [prompt]     ,						image=A_     ,						generator=A_     ,						num_images_per_prompt=2     ,						guidance_scale=6.0     ,						noise_level=2_0     ,						num_inference_steps=2     ,						output_type="np"     ,						)
      _lowerCAmelCase   :					int        =    output.images
      assert image.shape[0] == 2


 @unittest.skipIf(torch_device != "cuda"     ,						"This test requires a GPU"       )
 def    __magic_name__       (		self :	Tuple       ):






      '''simple docstring'''




      _lowerCAmelCase   :					Any        =    self.dummy_cond_unet_upscale
      _lowerCAmelCase   :					List[str]        =    DDPMScheduler()
      _lowerCAmelCase   :					Optional[int]        =    DDIMScheduler(prediction_type="v_prediction"       )
      _lowerCAmelCase   :					Optional[Any]        =    self.dummy_vae
      _lowerCAmelCase   :					List[str]        =    self.dummy_text_encoder
      _lowerCAmelCase   :					Union[str, Any]        =    CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"       )

      _lowerCAmelCase   :					Any        =    self.dummy_image.cpu().permute(0     ,						2     ,						3     ,						1       )[0]
      _lowerCAmelCase   :					Any        =    Image.fromarray(np.uinta(A_       )       ).convert("RGB"       ).resize((6_4, 6_4)       )

      # put models in fp16, except vae as it overflows in fp16
      _lowerCAmelCase   :					Tuple        =    unet.half()
      _lowerCAmelCase   :					Optional[Any]        =    text_encoder.half()

      # make sure here that pndm scheduler skips prk
      _lowerCAmelCase   :					List[str]        =    StableDiffusionUpscalePipeline(
          unet=A_     ,						low_res_scheduler=A_     ,						scheduler=A_     ,						vae=A_     ,						text_encoder=A_     ,						tokenizer=A_     ,						max_noise_level=3_5_0     ,						)
      _lowerCAmelCase   :					Optional[Any]        =    sd_pipe.to(A_       )
      sd_pipe.set_progress_bar_config(disable=A_       )

      _lowerCAmelCase   :					str        =    "A painting of a squirrel eating a burger"
      _lowerCAmelCase   :					Any        =    torch.manual_seed(0       )
      _lowerCAmelCase   :					Optional[Any]        =    sd_pipe(
          [prompt]     ,						image=A_     ,						generator=A_     ,						num_inference_steps=2     ,						output_type="np"     ,						).images

      _lowerCAmelCase   :					List[str]        =    low_res_image.size[0] * 4
      assert image.shape == (1, expected_height_width, expected_height_width, 3)





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



 """simple docstring"""







 def    __magic_name__       (		self :	Any       ):






      '''simple docstring'''




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

 def    __magic_name__       (		self :	List[str]       ):






      '''simple docstring'''




      _lowerCAmelCase   :					List[Any]        =    load_image(
          "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
          "/sd2-upscale/low_res_cat.png"       )
      _lowerCAmelCase   :					Dict        =    load_numpy(
          "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-upscale"
          "/upsampled_cat.npy"       )

      _lowerCAmelCase   :					Union[str, Any]        =    "stabilityai/stable-diffusion-x4-upscaler"
      _lowerCAmelCase   :					Optional[int]        =    StableDiffusionUpscalePipeline.from_pretrained(A_       )
      pipe.to(A_       )
      pipe.set_progress_bar_config(disable=A_       )
      pipe.enable_attention_slicing()

      _lowerCAmelCase   :					str        =    "a cat sitting on a park bench"

      _lowerCAmelCase   :					str        =    torch.manual_seed(0       )
      _lowerCAmelCase   :					Optional[int]        =    pipe(
          prompt=A_     ,						image=A_     ,						generator=A_     ,						output_type="np"     ,						)
      _lowerCAmelCase   :					int        =    output.images[0]

      assert image.shape == (5_1_2, 5_1_2, 3)
      assert np.abs(expected_image - image       ).max() < 1E-3

 def    __magic_name__       (		self :	Tuple       ):






      '''simple docstring'''




      _lowerCAmelCase   :					Optional[int]        =    load_image(
          "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
          "/sd2-upscale/low_res_cat.png"       )
      _lowerCAmelCase   :					Dict        =    load_numpy(
          "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-upscale"
          "/upsampled_cat_fp16.npy"       )

      _lowerCAmelCase   :					Union[str, Any]        =    "stabilityai/stable-diffusion-x4-upscaler"
      _lowerCAmelCase   :					Any        =    StableDiffusionUpscalePipeline.from_pretrained(
          A_     ,						torch_dtype=torch.floataa     ,						)
      pipe.to(A_       )
      pipe.set_progress_bar_config(disable=A_       )
      pipe.enable_attention_slicing()

      _lowerCAmelCase   :					Optional[Any]        =    "a cat sitting on a park bench"

      _lowerCAmelCase   :					Any        =    torch.manual_seed(0       )
      _lowerCAmelCase   :					int        =    pipe(
          prompt=A_     ,						image=A_     ,						generator=A_     ,						output_type="np"     ,						)
      _lowerCAmelCase   :					Union[str, Any]        =    output.images[0]

      assert image.shape == (5_1_2, 5_1_2, 3)
      assert np.abs(expected_image - image       ).max() < 5E-1


 def    __magic_name__       (		self :	List[Any]       ):






      '''simple docstring'''




      torch.cuda.empty_cache()
      torch.cuda.reset_max_memory_allocated()
      torch.cuda.reset_peak_memory_stats()

      _lowerCAmelCase   :					int        =    load_image(
          "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
          "/sd2-upscale/low_res_cat.png"       )

      _lowerCAmelCase   :					Tuple        =    "stabilityai/stable-diffusion-x4-upscaler"
      _lowerCAmelCase   :					Any        =    StableDiffusionUpscalePipeline.from_pretrained(
          A_     ,						torch_dtype=torch.floataa     ,						)
      pipe.to(A_       )
      pipe.set_progress_bar_config(disable=A_       )
      pipe.enable_attention_slicing(1       )
      pipe.enable_sequential_cpu_offload()

      _lowerCAmelCase   :					List[Any]        =    "a cat sitting on a park bench"

      _lowerCAmelCase   :					Union[str, Any]        =    torch.manual_seed(0       )
      _lowerCAmelCase   :					List[Any]        =    pipe(
          prompt=A_     ,						image=A_     ,						generator=A_     ,						num_inference_steps=5     ,						output_type="np"     ,						)

      _lowerCAmelCase   :					Optional[Any]        =    torch.cuda.max_memory_allocated()
      # make sure that less than 2.9 GB is allocated
      assert mem_bytes < 2.9 * 1_0**9






