




'''simple docstring'''







import gc
import unittest

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

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    StableDiffusionSAGPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()


class     _a						(			lowercase__							,							lowercase__							,							unittest.TestCase				):
       __a       :  int            =      StableDiffusionSAGPipeline
       __a       :  Dict            =      TEXT_TO_IMAGE_PARAMS
       __a       :  Dict            =      TEXT_TO_IMAGE_BATCH_PARAMS
       __a       :  Dict            =      TEXT_TO_IMAGE_IMAGE_PARAMS
       __a       :  List[Any]            =      TEXT_TO_IMAGE_IMAGE_PARAMS
       __a       :  Tuple            =      False
       def 					A   (			self		:			int       ):



           '''simple docstring'''

           torch.manual_seed(0       )
           UpperCAmelCase     =	UNetaDConditionModel(
               block_out_channels=(32, 64)     ,       layers_per_block=2     ,       sample_size=32     ,       in_channels=4     ,       out_channels=4     ,       down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''')     ,       up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''')     ,       cross_attention_dim=32     ,       )
           UpperCAmelCase     =	DDIMScheduler(
               beta_start=0.0_0085     ,       beta_end=0.012     ,       beta_schedule='''scaled_linear'''     ,       clip_sample=UpperCAmelCase__     ,       set_alpha_to_one=UpperCAmelCase__     ,       )
           torch.manual_seed(0       )
           UpperCAmelCase     =	AutoencoderKL(
               block_out_channels=[32, 64]     ,       in_channels=3     ,       out_channels=3     ,       down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D''']     ,       up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D''']     ,       latent_channels=4     ,       )
           torch.manual_seed(0       )
           UpperCAmelCase     =	CLIPTextConfig(
               bos_token_id=0     ,       eos_token_id=2     ,       hidden_size=32     ,       intermediate_size=37     ,       layer_norm_eps=1E-05     ,       num_attention_heads=4     ,       num_hidden_layers=5     ,       pad_token_id=1     ,       vocab_size=1_000     ,       )
           UpperCAmelCase     =	CLIPTextModel(UpperCAmelCase__       )
           UpperCAmelCase     =	CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''       )

           UpperCAmelCase     =	{
               '''unet''': unet,
               '''scheduler''': scheduler,
               '''vae''': vae,
               '''text_encoder''': text_encoder,
               '''tokenizer''': tokenizer,
               '''safety_checker''': None,
               '''feature_extractor''': None,
           }
           return components
       def 					A   (			self		:			Any     ,       lowercase		:			Any     ,       lowercase		:			List[str]=0       ):



           '''simple docstring'''

           if str(UpperCAmelCase__       ).startswith('''mps'''       ):
               UpperCAmelCase     =	torch.manual_seed(UpperCAmelCase__       )
           else:
               UpperCAmelCase     =	torch.Generator(device=UpperCAmelCase__       ).manual_seed(UpperCAmelCase__       )
           UpperCAmelCase     =	{
               '''prompt''': '''.''',
               '''generator''': generator,
               '''num_inference_steps''': 2,
               '''guidance_scale''': 1.0,
               '''sag_scale''': 1.0,
               '''output_type''': '''numpy''',
           }
           return inputs







       def 					A   (			self		:			Optional[Any]       ):



           '''simple docstring'''

           super().test_inference_batch_single_identical(expected_max_diff=3E-3       )






@slow
@require_torch_gpu
class     _a						(			unittest.TestCase				):
       def 					A   (			self		:			List[Any]       ):



           '''simple docstring'''

           super().tearDown()
           gc.collect()
           torch.cuda.empty_cache()
       def 					A   (			self		:			Dict       ):



           '''simple docstring'''

           UpperCAmelCase     =	StableDiffusionSAGPipeline.from_pretrained('''CompVis/stable-diffusion-v1-4'''       )
           UpperCAmelCase     =	sag_pipe.to(UpperCAmelCase__       )
           sag_pipe.set_progress_bar_config(disable=UpperCAmelCase__       )

           UpperCAmelCase     =	'''.'''
           UpperCAmelCase     =	torch.manual_seed(0       )
           UpperCAmelCase     =	sag_pipe(
               [prompt]     ,       generator=UpperCAmelCase__     ,       guidance_scale=7.5     ,       sag_scale=1.0     ,       num_inference_steps=20     ,       output_type='''np'''       )

           UpperCAmelCase     =	output.images

           UpperCAmelCase     =	image[0, -3:, -3:, -1]

           assert image.shape == (1, 512, 512, 3)
           UpperCAmelCase     =	np.array([0.1568, 0.1738, 0.1695, 0.1693, 0.1507, 0.1705, 0.1547, 0.1751, 0.1949]       )

           assert np.abs(image_slice.flatten() - expected_slice       ).max() < 5E-2
       def 					A   (			self		:			str       ):



           '''simple docstring'''

           UpperCAmelCase     =	StableDiffusionSAGPipeline.from_pretrained('''stabilityai/stable-diffusion-2-1-base'''       )
           UpperCAmelCase     =	sag_pipe.to(UpperCAmelCase__       )
           sag_pipe.set_progress_bar_config(disable=UpperCAmelCase__       )

           UpperCAmelCase     =	'''.'''
           UpperCAmelCase     =	torch.manual_seed(0       )
           UpperCAmelCase     =	sag_pipe(
               [prompt]     ,       generator=UpperCAmelCase__     ,       guidance_scale=7.5     ,       sag_scale=1.0     ,       num_inference_steps=20     ,       output_type='''np'''       )

           UpperCAmelCase     =	output.images

           UpperCAmelCase     =	image[0, -3:, -3:, -1]

           assert image.shape == (1, 512, 512, 3)
           UpperCAmelCase     =	np.array([0.3459, 0.2876, 0.2537, 0.3002, 0.2671, 0.2160, 0.3026, 0.2262, 0.2371]       )

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







       def 					A   (			self		:			Optional[int]       ):



           '''simple docstring'''

           UpperCAmelCase     =	StableDiffusionSAGPipeline.from_pretrained('''stabilityai/stable-diffusion-2-1-base'''       )
           UpperCAmelCase     =	sag_pipe.to(UpperCAmelCase__       )
           sag_pipe.set_progress_bar_config(disable=UpperCAmelCase__       )

           UpperCAmelCase     =	'''.'''
           UpperCAmelCase     =	torch.manual_seed(0       )
           UpperCAmelCase     =	sag_pipe(
               [prompt]     ,       width=768     ,       height=512     ,       generator=UpperCAmelCase__     ,       guidance_scale=7.5     ,       sag_scale=1.0     ,       num_inference_steps=20     ,       output_type='''np'''     ,       )

           UpperCAmelCase     =	output.images

           assert image.shape == (1, 512, 768, 3)







'''simple docstring'''







import argparse
import json
from pathlib import Path

import requests
import torch
from huggingface_hub import hf_hub_download
from PIL import Image

from transformers import BeitConfig, BeitForImageClassification, BeitForMaskedImageModeling, BeitImageProcessor
from transformers.image_utils import PILImageResampling
from transformers.utils import logging


logging.set_verbosity_info()
A									=logging.get_logger(__name__)





def 		snake_case_							(_a			:							Tuple					,     _a			:							Any=False					,     _a			:							str=False  ):
    UpperCAmelCase     =	'''backbone.''' if is_semantic else ''''''

    UpperCAmelCase     =	[]
    for i in range(config.num_hidden_layers  ):
        # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms
        rename_keys.append((F"{prefix}blocks.{i}.norm1.weight", F"beit.encoder.layer.{i}.layernorm_before.weight")  )
        rename_keys.append((F"{prefix}blocks.{i}.norm1.bias", F"beit.encoder.layer.{i}.layernorm_before.bias")  )
        rename_keys.append(
            (F"{prefix}blocks.{i}.attn.proj.weight", F"beit.encoder.layer.{i}.attention.output.dense.weight")  )
        rename_keys.append(
            (F"{prefix}blocks.{i}.attn.proj.bias", F"beit.encoder.layer.{i}.attention.output.dense.bias")  )
        rename_keys.append((F"{prefix}blocks.{i}.norm2.weight", F"beit.encoder.layer.{i}.layernorm_after.weight")  )
        rename_keys.append((F"{prefix}blocks.{i}.norm2.bias", F"beit.encoder.layer.{i}.layernorm_after.bias")  )
        rename_keys.append((F"{prefix}blocks.{i}.mlp.fc1.weight", F"beit.encoder.layer.{i}.intermediate.dense.weight")  )
        rename_keys.append((F"{prefix}blocks.{i}.mlp.fc1.bias", F"beit.encoder.layer.{i}.intermediate.dense.bias")  )
        rename_keys.append((F"{prefix}blocks.{i}.mlp.fc2.weight", F"beit.encoder.layer.{i}.output.dense.weight")  )
        rename_keys.append((F"{prefix}blocks.{i}.mlp.fc2.bias", F"beit.encoder.layer.{i}.output.dense.bias")  )

    # projection layer + position embeddings
    rename_keys.extend(
        [
            (F"{prefix}cls_token", '''beit.embeddings.cls_token'''),
            (F"{prefix}patch_embed.proj.weight", '''beit.embeddings.patch_embeddings.projection.weight'''),
            (F"{prefix}patch_embed.proj.bias", '''beit.embeddings.patch_embeddings.projection.bias'''),
            (F"{prefix}pos_embed", '''beit.embeddings.position_embeddings'''),
        ]  )

    if has_lm_head:
        # mask token + layernorm
        rename_keys.extend(
            [
                ('''mask_token''', '''beit.embeddings.mask_token'''),
                ('''norm.weight''', '''layernorm.weight'''),
                ('''norm.bias''', '''layernorm.bias'''),
            ]  )
    else:
        # layernorm + classification head
        rename_keys.extend(
            [
                ('''fc_norm.weight''', '''beit.pooler.layernorm.weight'''),
                ('''fc_norm.bias''', '''beit.pooler.layernorm.bias'''),
                ('''head.weight''', '''classifier.weight'''),
                ('''head.bias''', '''classifier.bias'''),
            ]  )

    return rename_keys





def 		snake_case_							(_a			:							str					,     _a			:							List[Any]					,     _a			:							List[Any]=False					,     _a			:							Union[str, Any]=False  ):
    for i in range(config.num_hidden_layers  ):
        UpperCAmelCase     =	'''backbone.''' if is_semantic else ''''''
        # queries, keys and values
        UpperCAmelCase     =	state_dict.pop(F"{prefix}blocks.{i}.attn.qkv.weight"  )
        UpperCAmelCase     =	state_dict.pop(F"{prefix}blocks.{i}.attn.q_bias"  )
        UpperCAmelCase     =	state_dict.pop(F"{prefix}blocks.{i}.attn.v_bias"  )

        UpperCAmelCase     =	in_proj_weight[
            : config.hidden_size, :
        ]
        UpperCAmelCase     =	q_bias
        UpperCAmelCase     =	in_proj_weight[
            config.hidden_size : config.hidden_size * 2, :
        ]
        UpperCAmelCase     =	in_proj_weight[
            -config.hidden_size :, :
        ]
        UpperCAmelCase     =	v_bias

        # gamma_1 and gamma_2
        # we call them lambda because otherwise they are renamed when using .from_pretrained
        UpperCAmelCase     =	state_dict.pop(F"{prefix}blocks.{i}.gamma_1"  )
        UpperCAmelCase     =	state_dict.pop(F"{prefix}blocks.{i}.gamma_2"  )

        UpperCAmelCase     =	gamma_a
        UpperCAmelCase     =	gamma_a





def 		snake_case_							(_a			:							Union[str, Any]					,     _a			:							str					,     _a			:							Optional[int]  ):
    UpperCAmelCase     =	dct.pop(_a  )
    UpperCAmelCase     =	val





def 		snake_case_							():
    UpperCAmelCase     =	'''http://images.cocodataset.org/val2017/000000039769.jpg'''
    UpperCAmelCase     =	Image.open(requests.get(_a					,     stream=_a  ).raw  )
    return im





@torch.no_grad()
def 		snake_case_							(_a			:							Optional[Any]					,     _a			:							Optional[Any]					,     _a			:							Optional[Any]=False  ):
    UpperCAmelCase     =	False if '''rvlcdip''' in checkpoint_url else True
    UpperCAmelCase     =	BeitConfig(use_absolute_position_embeddings=_a					,     use_mask_token=_a  )

    # size of the architecture
    if "large" in checkpoint_url or "dit-l" in checkpoint_url:
        UpperCAmelCase     =	1_0_2_4
        UpperCAmelCase     =	4_0_9_6
        UpperCAmelCase     =	2_4
        UpperCAmelCase     =	1_6

    # labels
    if "rvlcdip" in checkpoint_url:
        UpperCAmelCase     =	1_6
        UpperCAmelCase     =	'''huggingface/label-files'''
        UpperCAmelCase     =	'''rvlcdip-id2label.json'''
        UpperCAmelCase     =	json.load(open(hf_hub_download(_a					,     _a					,     repo_type='''dataset'''  )					,     '''r'''  )  )
        UpperCAmelCase     =	{int(_a  ): v for k, v in idalabel.items()}
        UpperCAmelCase     =	idalabel
        UpperCAmelCase     =	{v: k for k, v in idalabel.items()}

    # load state_dict of original model, remove and rename some keys
    UpperCAmelCase     =	torch.hub.load_state_dict_from_url(_a					,     map_location='''cpu'''  )['''model''']

    UpperCAmelCase     =	create_rename_keys(_a					,     has_lm_head=_a  )
    for src, dest in rename_keys:
        rename_key(_a					,     _a					,     _a  )
    read_in_q_k_v(_a					,     _a					,     has_lm_head=_a  )

    # load HuggingFace model
    UpperCAmelCase     =	BeitForMaskedImageModeling(_a  ) if has_lm_head else BeitForImageClassification(_a  )
    model.eval()
    model.load_state_dict(_a  )

    # Check outputs on an image
    UpperCAmelCase     =	BeitImageProcessor(
        size=config.image_size					,     resample=PILImageResampling.BILINEAR					,     do_center_crop=_a  )
    UpperCAmelCase     =	prepare_img()

    UpperCAmelCase     =	image_processor(images=_a					,     return_tensors='''pt'''  )
    UpperCAmelCase     =	encoding['''pixel_values''']

    UpperCAmelCase     =	model(_a  )
    UpperCAmelCase     =	outputs.logits

    # verify logits
    UpperCAmelCase     =	[1, 1_6] if '''rvlcdip''' in checkpoint_url else [1, 1_9_6, 8_1_9_2]
    assert logits.shape == torch.Size(_a  ), "Shape of logits not as expected"

    Path(_a  ).mkdir(exist_ok=_a  )
    print(F"Saving model to {pytorch_dump_folder_path}"  )
    model.save_pretrained(_a  )
    print(F"Saving image processor to {pytorch_dump_folder_path}"  )
    image_processor.save_pretrained(_a  )

    if push_to_hub:
        if has_lm_head:
            UpperCAmelCase     =	'''dit-base''' if '''base''' in checkpoint_url else '''dit-large'''
        else:
            UpperCAmelCase     =	'''dit-base-finetuned-rvlcdip''' if '''dit-b''' in checkpoint_url else '''dit-large-finetuned-rvlcdip'''
        image_processor.push_to_hub(
            repo_path_or_name=Path(_a					,     _a  )					,     organization='''nielsr'''					,     commit_message='''Add image processor'''					,     use_temp_dir=_a					,     )
        model.push_to_hub(
            repo_path_or_name=Path(_a					,     _a  )					,     organization='''nielsr'''					,     commit_message='''Add model'''					,     use_temp_dir=_a					,     )


if __name__ == "__main__":
   A									=argparse.ArgumentParser()

   parser.add_argument(
       '--checkpoint_url',
       default='https://layoutlm.blob.core.windows.net/dit/dit-pts/dit-base-224-p16-500k-62d53a.pth',
       type=str,
       help='URL to the original PyTorch checkpoint (.pth file).',
   )
   parser.add_argument(
       '--pytorch_dump_folder_path', default=None, type=str, help='Path to the folder to output PyTorch model.'
   )
   parser.add_argument(
       '--push_to_hub',
       action='store_true',
   )
   A									=parser.parse_args()
   convert_dit_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub)




