



'''simple docstring'''



import gc
import unittest

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

from diffusers import (
    AutoencoderKL,
    DiffusionPipeline,
    EulerDiscreteScheduler,
    StableDiffusionXLPipeline,
    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 			_SCREAMING_SNAKE_CASE				(lowercase__,	lowercase__,	unittest.TestCase      ):
			A__								=  StableDiffusionXLPipeline
			A__								=  TEXT_TO_IMAGE_PARAMS
			A__								=  TEXT_TO_IMAGE_BATCH_PARAMS
			A__								=  TEXT_TO_IMAGE_IMAGE_PARAMS
			A__								=  TEXT_TO_IMAGE_IMAGE_PARAMS



			def 				lowerCAmelCase (     self		:						List[str]			)      ->      Tuple:
							"""simple docstring"""





							torch.manual_seed(0			)
							snake_case__      :   Any      =    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''')    ,			attention_head_dim=(2, 4)    ,			use_linear_projection=__UpperCamelCase    ,			addition_embed_type='''text_time'''    ,			addition_time_embed_dim=8    ,			transformer_layers_per_block=(1, 2)    ,			projection_class_embeddings_input_dim=80    ,			cross_attention_dim=64    ,			)
							snake_case__      :   Tuple      =    EulerDiscreteScheduler(
							    beta_start=0.00085    ,			beta_end=0.012    ,			steps_offset=1    ,			beta_schedule='''scaled_linear'''    ,			timestep_spacing='''leading'''    ,			)
							torch.manual_seed(0			)
							snake_case__      :   Union[str, Any]      =    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    ,			sample_size=128    ,			)
							torch.manual_seed(0			)
							snake_case__      :   List[Any]      =    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=1000    ,			hidden_act='''gelu'''    ,			projection_dim=32    ,			)
							snake_case__      :   List[str]      =    CLIPTextModel(__UpperCamelCase			)
							snake_case__      :   Dict      =    CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''    ,			local_files_only=__UpperCamelCase			)

							snake_case__      :   Optional[int]      =    CLIPTextModelWithProjection(__UpperCamelCase			)
							snake_case__      :   Optional[int]      =    CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''    ,			local_files_only=__UpperCamelCase			)

							snake_case__      :   List[str]      =    {
							    '''unet''': unet,
							    '''scheduler''': scheduler,
							    '''vae''': vae,
							    '''text_encoder''': text_encoder,
							    '''tokenizer''': tokenizer,
							    '''text_encoder_2''': text_encoder_a,
							    '''tokenizer_2''': tokenizer_a,
							    # "safety_checker": None,
							    # "feature_extractor": None,
							}
							return components



			def 				lowerCAmelCase (     self		:						Union[str, Any]    ,			__UpperCamelCase		:						int    ,			__UpperCamelCase		:						Union[str, Any]=0			)      ->      Optional[Any]:
							"""simple docstring"""





							if str(__UpperCamelCase			).startswith('''mps'''			):
											snake_case__      :   List[Any]      =    torch.manual_seed(__UpperCamelCase			)
							else:
											snake_case__      :   List[Any]      =    torch.Generator(device=__UpperCamelCase			).manual_seed(__UpperCamelCase			)
							snake_case__      :   Dict      =    {
							    '''prompt''': '''A painting of a squirrel eating a burger''',
							    '''generator''': generator,
							    '''num_inference_steps''': 2,
							    '''guidance_scale''': 5.0,
							    '''output_type''': '''numpy''',
							}
							return inputs



			def 				lowerCAmelCase (     self		:						List[Any]			)      ->      Tuple:
							"""simple docstring"""





							snake_case__      :   Any      =    '''cpu'''  # ensure determinism for the device-dependent torch.Generator
							snake_case__      :   Union[str, Any]      =    self.get_dummy_components()
							snake_case__      :   List[Any]      =    StableDiffusionXLPipeline(**__UpperCamelCase			)
							snake_case__      :   Optional[int]      =    sd_pipe.to(__UpperCamelCase			)
							sd_pipe.set_progress_bar_config(disable=__UpperCamelCase			)

							snake_case__      :   Dict      =    self.get_dummy_inputs(__UpperCamelCase			)
							snake_case__      :   Union[str, Any]      =    sd_pipe(**__UpperCamelCase			).images
							snake_case__      :   List[Any]      =    image[0, -3:, -3:, -1]

							assert image.shape == (1, 64, 64, 3)
							snake_case__      :   Union[str, Any]      =    np.array([0.5873, 0.6128, 0.4797, 0.5122, 0.5674, 0.4639, 0.5227, 0.5149, 0.4747]			)

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



			def 				lowerCAmelCase (     self		:						Optional[Any]			)      ->      Optional[int]:
							"""simple docstring"""





							snake_case__      :   List[str]      =    self.get_dummy_components()
							snake_case__      :   Optional[Any]      =    StableDiffusionXLPipeline(**__UpperCamelCase			)
							snake_case__      :   str      =    sd_pipe.to(__UpperCamelCase			)
							snake_case__      :   Tuple      =    sd_pipe.to(__UpperCamelCase			)
							sd_pipe.set_progress_bar_config(disable=__UpperCamelCase			)

							# forward without prompt embeds
							snake_case__      :   str      =    self.get_dummy_inputs(__UpperCamelCase			)
							snake_case__      :   Any      =    3 * ['''this is a negative prompt''']
							snake_case__      :   Optional[int]      =    negative_prompt
							snake_case__      :   Tuple      =    3 * [inputs['''prompt''']]

							snake_case__      :   Tuple      =    sd_pipe(**__UpperCamelCase			)
							snake_case__      :   str      =    output.images[0, -3:, -3:, -1]

							# forward with prompt embeds
							snake_case__      :   Tuple      =    self.get_dummy_inputs(__UpperCamelCase			)
							snake_case__      :   List[Any]      =    3 * ['''this is a negative prompt''']
							snake_case__      :   List[Any]      =    3 * [inputs.pop('''prompt'''			)]

							(
							    (
							    snake_case__
							)  ,      (
							    snake_case__
							)  ,      (
							    snake_case__
							)  ,      (
							    snake_case__
							)  ,      
							)      :   List[Any]      =    sd_pipe.encode_prompt(__UpperCamelCase    ,			negative_prompt=__UpperCamelCase			)

							snake_case__      :   Dict      =    sd_pipe(
							    **__UpperCamelCase    ,			prompt_embeds=__UpperCamelCase    ,			negative_prompt_embeds=__UpperCamelCase    ,			pooled_prompt_embeds=__UpperCamelCase    ,			negative_pooled_prompt_embeds=__UpperCamelCase    ,			)
							snake_case__      :   Optional[Any]      =    output.images[0, -3:, -3:, -1]

							# make sure that it's equal
							assert np.abs(image_slice_a.flatten() - image_slice_a.flatten()			).max() < 1e-4



			def 				lowerCAmelCase (     self		:						Dict			)      ->      Dict:
							"""simple docstring"""





							super().test_attention_slicing_forward_pass(expected_max_diff=3e-3			)







			def 				lowerCAmelCase (     self		:						int			)      ->      Dict:
							"""simple docstring"""





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






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



			def 				lowerCAmelCase (     self		:						Union[str, Any]			)      ->      Union[str, Any]:
							"""simple docstring"""





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



			def 				lowerCAmelCase (     self		:						Tuple    ,			__UpperCamelCase		:						Optional[int]    ,			__UpperCamelCase		:						List[str]="cpu"    ,			__UpperCamelCase		:						Tuple=torch.floataa    ,			__UpperCamelCase		:						List[str]=0			)      ->      Dict:
							"""simple docstring"""





							snake_case__      :   Dict      =    torch.Generator(device=__UpperCamelCase			).manual_seed(__UpperCamelCase			)
							snake_case__      :   int      =    np.random.RandomState(__UpperCamelCase			).standard_normal((1, 4, 64, 64)			)
							snake_case__      :   List[Any]      =    torch.from_numpy(__UpperCamelCase			).to(device=__UpperCamelCase    ,			dtype=__UpperCamelCase			)
							snake_case__      :   int      =    {
							    '''prompt''': '''a photograph of an astronaut riding a horse''',
							    '''latents''': latents,
							    '''generator''': generator,
							    '''num_inference_steps''': 3,
							    '''guidance_scale''': 7.5,
							    '''output_type''': '''numpy''',
							}
							return inputs







			def 				lowerCAmelCase (     self		:						int			)      ->      Dict:
							"""simple docstring"""





							snake_case__      :   Dict      =    DiffusionPipeline.from_pretrained('''stabilityai/stable-diffusion-2-base'''			)
							pipe.to(__UpperCamelCase			)
							pipe.set_progress_bar_config(disable=__UpperCamelCase			)

							snake_case__      :   Optional[Any]      =    self.get_inputs(__UpperCamelCase			)
							snake_case__      :   Any      =    pipe(**__UpperCamelCase			).images
							snake_case__      :   Optional[int]      =    image[0, -3:, -3:, -1].flatten()

							assert image.shape == (1, 512, 512, 3)
							snake_case__      :   Tuple      =    np.array([0.49493, 0.47896, 0.40798, 0.54214, 0.53212, 0.48202, 0.47656, 0.46329, 0.48506]			)
							assert np.abs(image_slice - expected_slice			).max() < 7e-3









'''simple docstring'''



import argparse
import os
import pathlib

import fairseq
import torch
from fairseq.modules import TransformerSentenceEncoderLayer
from packaging import version

from transformers import (
    DataaVecTextConfig,
    DataaVecTextForMaskedLM,
    DataaVecTextForSequenceClassification,
    DataaVecTextModel,
)
from transformers.models.bert.modeling_bert import (
    BertIntermediate,
    BertLayer,
    BertOutput,
    BertSelfAttention,
    BertSelfOutput,
)

# IMPORTANT: In order for this script to run, please make sure to download the dictionary: `dict.txt` from wget https://dl.fbaipublicfiles.com/fairseq/models/roberta.large.tar.gz
# File copied from https://github.com/pytorch/fairseq/blob/main/examples/data2vec/models/data2vec_text.py
from transformers.utils import logging


if version.parse(fairseq.__version__) < version.parse("0.9.0"):
				raise Exception("requires fairseq >= 0.9.0")


logging.set_verbosity_info()
_lowercase       :						Tuple						=logging.get_logger(__name__)

_lowercase       :						Optional[int]						="Hello world! cécé herlolip"


def 							__UpperCAmelCase				(				UpperCamelCase__				:str   ,				UpperCamelCase__				:str   ,				UpperCamelCase__				:bool			)		->						int:
				snake_case__  ,      snake_case__      :   int      =    os.path.split(UpperCamelCase__			)
				snake_case__      :   List[Any]      =    DataaVecTextModel.from_pretrained(
				    UpperCamelCase__   ,				checkpoint_file=UpperCamelCase__			)
				dataavec.eval()  # disable dropout
				snake_case__      :   Dict      =    dataavec.models[0]
				snake_case__      :   int      =    dataavec_model.encoder.sentence_encoder
				snake_case__      :   List[Any]      =    DataaVecTextConfig(
				    vocab_size=dataavec_sent_encoder.embed_tokens.num_embeddings   ,				hidden_size=dataavec_model.args.encoder_embed_dim   ,				num_hidden_layers=dataavec_model.args.encoder_layers   ,				num_attention_heads=dataavec_model.args.encoder_attention_heads   ,				intermediate_size=dataavec_model.args.encoder_ffn_embed_dim   ,				max_position_embeddings=514   ,				type_vocab_size=1   ,				layer_norm_eps=1e-5   ,				)
				if classification_head:
								snake_case__      :   int      =    dataavec.model.classification_heads['''mnli'''].out_proj.weight.shape[0]
				print('''Our BERT config:'''   ,				UpperCamelCase__			)

				snake_case__      :   Optional[int]      =    DataaVecTextForSequenceClassification(UpperCamelCase__			) if classification_head else DataaVecTextForMaskedLM(UpperCamelCase__			)
				model.eval()

				# Now let's copy all the weights.
				# Embeddings
				snake_case__      :   Optional[Any]      =    dataavec_sent_encoder.embed_tokens.weight
				snake_case__      :   Union[str, Any]      =    dataavec_sent_encoder.embed_positions.weight
				snake_case__      :   Any      =    torch.zeros_like(
				    model.dataavec_text.embeddings.token_type_embeddings.weight			)  # just zero them out b/c data2vec doesn't use them.
				snake_case__      :   Tuple      =    dataavec_sent_encoder.layernorm_embedding.weight
				snake_case__      :   Dict      =    dataavec_sent_encoder.layernorm_embedding.bias

				for i in range(config.num_hidden_layers			):
								# Encoder: start of layer
								snake_case__      :   BertLayer      =    model.dataavec_text.encoder.layer[i]
								snake_case__      :   TransformerSentenceEncoderLayer      =    dataavec_sent_encoder.layers[i]

								# self attention
								snake_case__      :   BertSelfAttention      =    layer.attention.self
								assert dataavec_layer.self_attn.k_proj.weight.data.shape == torch.Size(
								    (config.hidden_size, config.hidden_size)			), (
								    "Shape for data2vec_layer.self_attn.k_proj.weight.data should be"
								    F''' {torch.Size((config.hidden_size, config.hidden_size)			)}'''
								)
								assert dataavec_layer.self_attn.q_proj.weight.data.shape == torch.Size(
								    (config.hidden_size, config.hidden_size)			), (
								    "Shape for data2vec_layer.self_attn.q_proj.weight.data should be"
								    F''' {torch.Size((config.hidden_size, config.hidden_size)			)}'''
								)
								assert dataavec_layer.self_attn.v_proj.weight.data.shape == torch.Size(
								    (config.hidden_size, config.hidden_size)			), (
								    "Shape for data2vec_layer.self_attn.v_proj.weight.data should be"
								    F''' {torch.Size((config.hidden_size, config.hidden_size)			)}'''
								)

								snake_case__      :   List[Any]      =    dataavec_layer.self_attn.q_proj.weight
								snake_case__      :   List[str]      =    dataavec_layer.self_attn.q_proj.bias
								snake_case__      :   str      =    dataavec_layer.self_attn.k_proj.weight
								snake_case__      :   List[Any]      =    dataavec_layer.self_attn.k_proj.bias
								snake_case__      :   Optional[Any]      =    dataavec_layer.self_attn.v_proj.weight
								snake_case__      :   int      =    dataavec_layer.self_attn.v_proj.bias

								# self-attention output
								snake_case__      :   BertSelfOutput      =    layer.attention.output
								assert (
								    self_output.dense.weight.shape == dataavec_layer.self_attn.out_proj.weight.shape
								), F'''Shape for self_output.dense.weight should be {dataavec_layer.self_attn.out_proj.weight.shape}'''
								snake_case__      :   Optional[int]      =    dataavec_layer.self_attn.out_proj.weight
								snake_case__      :   str      =    dataavec_layer.self_attn.out_proj.bias
								snake_case__      :   int      =    dataavec_layer.self_attn_layer_norm.weight
								snake_case__      :   List[Any]      =    dataavec_layer.self_attn_layer_norm.bias

								# intermediate
								snake_case__      :   BertIntermediate      =    layer.intermediate
								assert (
								    intermediate.dense.weight.shape == dataavec_layer.fca.weight.shape
								), F'''Shape for intermediate.dense.weight should be {dataavec_layer.fca.weight.shape}'''
								snake_case__      :   List[str]      =    dataavec_layer.fca.weight
								snake_case__      :   str      =    dataavec_layer.fca.bias

								# output
								snake_case__      :   BertOutput      =    layer.output
								assert (
								    bert_output.dense.weight.shape == dataavec_layer.fca.weight.shape
								), F'''Shape for bert_output.dense.weight should be {dataavec_layer.fca.weight.shape}'''
								snake_case__      :   List[str]      =    dataavec_layer.fca.weight
								snake_case__      :   List[Any]      =    dataavec_layer.fca.bias
								snake_case__      :   str      =    dataavec_layer.final_layer_norm.weight
								snake_case__      :   List[Any]      =    dataavec_layer.final_layer_norm.bias
								# end of layer

				if classification_head:
								snake_case__      :   Any      =    dataavec.model.classification_heads['''mnli'''].dense.weight
								snake_case__      :   List[Any]      =    dataavec.model.classification_heads['''mnli'''].dense.bias
								snake_case__      :   List[Any]      =    dataavec.model.classification_heads['''mnli'''].out_proj.weight
								snake_case__      :   List[Any]      =    dataavec.model.classification_heads['''mnli'''].out_proj.bias
				else:
								# LM Head
								snake_case__      :   str      =    dataavec_model.encoder.lm_head.dense.weight
								snake_case__      :   str      =    dataavec_model.encoder.lm_head.dense.bias
								snake_case__      :   Union[str, Any]      =    dataavec_model.encoder.lm_head.layer_norm.weight
								snake_case__      :   Tuple      =    dataavec_model.encoder.lm_head.layer_norm.bias
								snake_case__      :   Tuple      =    dataavec_model.encoder.lm_head.weight
								snake_case__      :   List[str]      =    dataavec_model.encoder.lm_head.bias

				# Let's check that we get the same results.
				snake_case__      :   torch.Tensor      =    dataavec.encode(UpperCamelCase__			).unsqueeze(0			)  # batch of size 1

				snake_case__      :   str      =    model(UpperCamelCase__			)[0]
				if classification_head:
								snake_case__      :   List[str]      =    dataavec.model.classification_heads['''mnli'''](dataavec.extract_features(UpperCamelCase__			)			)
				else:
								snake_case__      :   Tuple      =    dataavec_model(UpperCamelCase__			)[0]
				print(our_output.shape   ,				their_output.shape			)
				snake_case__      :   Dict      =    torch.max(torch.abs(our_output - their_output			)			).item()
				print(F'''max_absolute_diff = {max_absolute_diff}'''			)  # ~ 1e-7
				snake_case__      :   Tuple      =    torch.allclose(UpperCamelCase__   ,				UpperCamelCase__   ,				atol=1e-3			)
				print('''Do both models output the same tensors?'''   ,				'''🔥''' if success else '''💩'''			)
				if not success:
								raise Exception('''Something went wRoNg'''			)

				pathlib.Path(UpperCamelCase__			).mkdir(parents=UpperCamelCase__   ,				exist_ok=UpperCamelCase__			)
				print(F'''Saving model to {pytorch_dump_folder_path}'''			)
				model.save_pretrained(UpperCamelCase__			)


if __name__ == "__main__":
				_lowercase       :						Any						=argparse.ArgumentParser()
				# Required parameters
				parser.add_argument(
				    "--checkpoint_path", default=None, type=str, required=True, help="Path the official PyTorch dump."
				)
				parser.add_argument(
				    "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the output PyTorch model."
				)
				parser.add_argument(
				    "--classification_head", action="store_true", help="Whether to convert a final classification head."
				)
				_lowercase       :						Tuple						=parser.parse_args()
				convert_dataavec_checkpoint_to_pytorch(
				    args.checkpoint_path, args.pytorch_dump_folder_path, args.classification_head
				)




