



'''simple docstring'''



import gc
import unittest

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

from diffusers import AltDiffusionPipeline, AutoencoderKL, DDIMScheduler, PNDMScheduler, UNetaDConditionModel
from diffusers.pipelines.alt_diffusion.modeling_roberta_series import (
    RobertaSeriesConfig,
    RobertaSeriesModelWithTransformation,
)
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 PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()






class 					UpperCAmelCase__	(		UpperCamelCase__							,       UpperCamelCase__							,       UpperCamelCase__							,       unittest.TestCase ):
					a      :     Optional[Any]        =							AltDiffusionPipeline
					a      :     Optional[int]        =							TEXT_TO_IMAGE_PARAMS
					a      :     Union[str, Any]        =							TEXT_TO_IMAGE_BATCH_PARAMS
					a      :     Dict        =							TEXT_TO_IMAGE_IMAGE_PARAMS
					a      :     Optional[int]        =							TEXT_TO_IMAGE_IMAGE_PARAMS



					def        UpperCAmelCase_ (    self     )     ->			Union[str, Any]:
						torch.manual_seed(0     )
						__lowerCAmelCase												=  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			,				)
						__lowerCAmelCase												=  DDIMScheduler(
						    beta_start=0.0_00_85			,				beta_end=0.0_12			,				beta_schedule="scaled_linear"			,				clip_sample=UpperCamelCase			,				set_alpha_to_one=UpperCamelCase			,				)
						torch.manual_seed(0     )
						__lowerCAmelCase												=  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			,				)

						# TODO: address the non-deterministic text encoder (fails for save-load tests)
						# torch.manual_seed(0)
						# text_encoder_config = RobertaSeriesConfig(
						#     hidden_size=32,
						#     project_dim=32,
						#     intermediate_size=37,
						#     layer_norm_eps=1e-05,
						#     num_attention_heads=4,
						#     num_hidden_layers=5,
						#     vocab_size=5002,
						# )
						# text_encoder = RobertaSeriesModelWithTransformation(text_encoder_config)

						torch.manual_seed(0     )
						__lowerCAmelCase												=  CLIPTextConfig(
						    bos_token_id=0			,				eos_token_id=2			,				hidden_size=32			,				projection_dim=32			,				intermediate_size=37			,				layer_norm_eps=1E-05			,				num_attention_heads=4			,				num_hidden_layers=5			,				pad_token_id=1			,				vocab_size=5002			,				)
						__lowerCAmelCase												=  CLIPTextModel(UpperCamelCase     )

						__lowerCAmelCase												=  XLMRobertaTokenizer.from_pretrained("hf-internal-testing/tiny-xlm-roberta"     )
						__lowerCAmelCase												=  77

						__lowerCAmelCase												=  {
						    "unet": unet,
						    "scheduler": scheduler,
						    "vae": vae,
						    "text_encoder": text_encoder,
						    "tokenizer": tokenizer,
						    "safety_checker": None,
						    "feature_extractor": None,
						}
						return components



					def        UpperCAmelCase_ (    self			,				UpperCamelCase			,				UpperCamelCase=0     )     ->			Dict:
						if str(UpperCamelCase     ).startswith("mps"     ):
							__lowerCAmelCase												=  torch.manual_seed(UpperCamelCase     )
						else:
							__lowerCAmelCase												=  torch.Generator(device=UpperCamelCase     ).manual_seed(UpperCamelCase     )
						__lowerCAmelCase												=  {
						    "prompt": "A painting of a squirrel eating a burger",
						    "generator": generator,
						    "num_inference_steps": 2,
						    "guidance_scale": 6.0,
						    "output_type": "numpy",
						}
						return inputs



					def        UpperCAmelCase_ (    self     )     ->			Union[str, Any]:
						super().test_attention_slicing_forward_pass(expected_max_diff=3E-3     )



					def        UpperCAmelCase_ (    self     )     ->			int:
						super().test_inference_batch_single_identical(expected_max_diff=3E-3     )



					def        UpperCAmelCase_ (    self     )     ->			Union[str, Any]:
						__lowerCAmelCase												=  "cpu"  # ensure determinism for the device-dependent torch.Generator

						__lowerCAmelCase												=  self.get_dummy_components()
						torch.manual_seed(0     )
						__lowerCAmelCase												=  RobertaSeriesConfig(
						    hidden_size=32			,				project_dim=32			,				intermediate_size=37			,				layer_norm_eps=1E-05			,				num_attention_heads=4			,				num_hidden_layers=5			,				vocab_size=5002			,				)
						# TODO: remove after fixing the non-deterministic text encoder
						__lowerCAmelCase												=  RobertaSeriesModelWithTransformation(UpperCamelCase     )
						__lowerCAmelCase												=  text_encoder

						__lowerCAmelCase												=  AltDiffusionPipeline(**UpperCamelCase     )
						__lowerCAmelCase												=  alt_pipe.to(UpperCamelCase     )
						alt_pipe.set_progress_bar_config(disable=UpperCamelCase     )

						__lowerCAmelCase												=  self.get_dummy_inputs(UpperCamelCase     )
						__lowerCAmelCase												=  "A photo of an astronaut"
						__lowerCAmelCase												=  alt_pipe(**UpperCamelCase     )
						__lowerCAmelCase												=  output.images
						__lowerCAmelCase												=  image[0, -3:, -3:, -1]

						assert image.shape == (1, 64, 64, 3)
						__lowerCAmelCase												=  np.array(
						    [0.5_74_81_62, 0.60_44_71_45, 0.48_82_12_17, 0.50_10_06_36, 0.5_43_11_85, 0.45_76_36_83, 0.49_65_76_96, 0.48_13_27_33, 0.47_57_30_93]     )

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



					def        UpperCAmelCase_ (    self     )     ->			Optional[int]:
						__lowerCAmelCase												=  "cpu"  # ensure determinism for the device-dependent torch.Generator

						__lowerCAmelCase												=  self.get_dummy_components()
						__lowerCAmelCase												=  PNDMScheduler(skip_prk_steps=UpperCamelCase     )
						torch.manual_seed(0     )
						__lowerCAmelCase												=  RobertaSeriesConfig(
						    hidden_size=32			,				project_dim=32			,				intermediate_size=37			,				layer_norm_eps=1E-05			,				num_attention_heads=4			,				num_hidden_layers=5			,				vocab_size=5002			,				)
						# TODO: remove after fixing the non-deterministic text encoder
						__lowerCAmelCase												=  RobertaSeriesModelWithTransformation(UpperCamelCase     )
						__lowerCAmelCase												=  text_encoder
						__lowerCAmelCase												=  AltDiffusionPipeline(**UpperCamelCase     )
						__lowerCAmelCase												=  alt_pipe.to(UpperCamelCase     )
						alt_pipe.set_progress_bar_config(disable=UpperCamelCase     )

						__lowerCAmelCase												=  self.get_dummy_inputs(UpperCamelCase     )
						__lowerCAmelCase												=  alt_pipe(**UpperCamelCase     )
						__lowerCAmelCase												=  output.images
						__lowerCAmelCase												=  image[0, -3:, -3:, -1]

						assert image.shape == (1, 64, 64, 3)
						__lowerCAmelCase												=  np.array(
						    [0.51_60_50_93, 0.5_70_72_41, 0.47_36_55_07, 0.50_57_88_86, 0.5_63_38_77, 0.4_64_25_03, 0.5_18_20_81, 0.48_76_34_84, 0.49_08_42_37]     )

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






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



					def        UpperCAmelCase_ (    self     )     ->			str:
						# clean up the VRAM after each test
						super().tearDown()
						gc.collect()
						torch.cuda.empty_cache()



					def        UpperCAmelCase_ (    self     )     ->			str:
						# make sure here that pndm scheduler skips prk
						__lowerCAmelCase												=  AltDiffusionPipeline.from_pretrained("BAAI/AltDiffusion"			,				safety_checker=UpperCamelCase     )
						__lowerCAmelCase												=  alt_pipe.to(UpperCamelCase     )
						alt_pipe.set_progress_bar_config(disable=UpperCamelCase     )

						__lowerCAmelCase												=  "A painting of a squirrel eating a burger"
						__lowerCAmelCase												=  torch.manual_seed(0     )
						__lowerCAmelCase												=  alt_pipe([prompt]			,				generator=UpperCamelCase			,				guidance_scale=6.0			,				num_inference_steps=20			,				output_type="np"     )

						__lowerCAmelCase												=  output.images

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

						assert image.shape == (1, 512, 512, 3)
						__lowerCAmelCase												=  np.array([0.10_10, 0.08_00, 0.07_94, 0.08_85, 0.08_43, 0.07_62, 0.07_69, 0.07_29, 0.05_86]     )

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



					def        UpperCAmelCase_ (    self     )     ->			List[Any]:
						__lowerCAmelCase												=  DDIMScheduler.from_pretrained("BAAI/AltDiffusion"			,				subfolder="scheduler"     )

						__lowerCAmelCase												=  AltDiffusionPipeline.from_pretrained("BAAI/AltDiffusion"			,				scheduler=UpperCamelCase			,				safety_checker=UpperCamelCase     )
						__lowerCAmelCase												=  alt_pipe.to(UpperCamelCase     )
						alt_pipe.set_progress_bar_config(disable=UpperCamelCase     )

						__lowerCAmelCase												=  "A painting of a squirrel eating a burger"
						__lowerCAmelCase												=  torch.manual_seed(0     )

						__lowerCAmelCase												=  alt_pipe([prompt]			,				generator=UpperCamelCase			,				num_inference_steps=2			,				output_type="numpy"     )
						__lowerCAmelCase												=  output.images

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

						assert image.shape == (1, 512, 512, 3)
						__lowerCAmelCase												=  np.array([0.40_19, 0.40_52, 0.38_10, 0.41_19, 0.39_16, 0.39_82, 0.46_51, 0.41_95, 0.53_23]     )

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




'''simple docstring'''



import argparse
import json

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

from transformers import BitImageProcessor, FocalNetConfig, FocalNetForImageClassification
from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, PILImageResampling



def   __lowerCAmelCase					(							lowerCamelCase   :						Any					):






	'''simple docstring'''




	__lowerCAmelCase												=  [2, 2, 6, 2] if "tiny" in model_name else [2, 2, 18, 2]
	__lowerCAmelCase												=  True if "large" in model_name or "huge" in model_name else False
	__lowerCAmelCase												=  True if "large" in model_name or "huge" in model_name else False
	__lowerCAmelCase												=  True if "large" in model_name or "huge" in model_name else False

	if "large" in model_name or "xlarge" in model_name or "huge" in model_name:
		if "fl3" in model_name:
			__lowerCAmelCase												=  [3, 3, 3, 3]
			__lowerCAmelCase												=  [5, 5, 5, 5]
		elif "fl4" in model_name:
			__lowerCAmelCase												=  [4, 4, 4, 4]
			__lowerCAmelCase												=  [3, 3, 3, 3]

	if "tiny" in model_name or "small" in model_name or "base" in model_name:
		__lowerCAmelCase												=  [3, 3, 3, 3]
		if "lrf" in model_name:
			__lowerCAmelCase												=  [3, 3, 3, 3]
		else:
			__lowerCAmelCase												=  [2, 2, 2, 2]

	if "tiny" in model_name:
		__lowerCAmelCase												=  96
	elif "small" in model_name:
		__lowerCAmelCase												=  96
	elif "base" in model_name:
		__lowerCAmelCase												=  1_28
	elif "large" in model_name:
		__lowerCAmelCase												=  1_92
	elif "xlarge" in model_name:
		__lowerCAmelCase												=  2_56
	elif "huge" in model_name:
		__lowerCAmelCase												=  3_52

	# set label information
	__lowerCAmelCase												=  "huggingface/label-files"
	if "large" in model_name or "huge" in model_name:
		__lowerCAmelCase												=  "imagenet-22k-id2label.json"
	else:
		__lowerCAmelCase												=  "imagenet-1k-id2label.json"

	__lowerCAmelCase												=  json.load(open(hf_hub_download(lowerCamelCase				,		lowerCamelCase				,		repo_type="dataset"					)				,		"r"					)					)
	__lowerCAmelCase												=  {int(lowerCamelCase					): v for k, v in idalabel.items()}
	__lowerCAmelCase												=  {v: k for k, v in idalabel.items()}

	__lowerCAmelCase												=  FocalNetConfig(
	    embed_dim=lowerCamelCase				,		depths=lowerCamelCase				,		focal_levels=lowerCamelCase				,		focal_windows=lowerCamelCase				,		use_conv_embed=lowerCamelCase				,		idalabel=lowerCamelCase				,		labelaid=lowerCamelCase				,		use_post_layernorm=lowerCamelCase				,		use_layerscale=lowerCamelCase				,		)

	return config



def   __lowerCAmelCase					(							lowerCamelCase   :						Union[str, Any]					):






	'''simple docstring'''




	if "patch_embed.proj" in name:
		__lowerCAmelCase												=  name.replace("patch_embed.proj"				,		"embeddings.patch_embeddings.projection"					)
	if "patch_embed.norm" in name:
		__lowerCAmelCase												=  name.replace("patch_embed.norm"				,		"embeddings.norm"					)
	if "layers" in name:
		__lowerCAmelCase												=  "encoder." + name
	if "encoder.layers" in name:
		__lowerCAmelCase												=  name.replace("encoder.layers"				,		"encoder.stages"					)
	if "downsample.proj" in name:
		__lowerCAmelCase												=  name.replace("downsample.proj"				,		"downsample.projection"					)
	if "blocks" in name:
		__lowerCAmelCase												=  name.replace("blocks"				,		"layers"					)
	if "modulation.f.weight" in name or "modulation.f.bias" in name:
		__lowerCAmelCase												=  name.replace("modulation.f"				,		"modulation.projection_in"					)
	if "modulation.h.weight" in name or "modulation.h.bias" in name:
		__lowerCAmelCase												=  name.replace("modulation.h"				,		"modulation.projection_context"					)
	if "modulation.proj.weight" in name or "modulation.proj.bias" in name:
		__lowerCAmelCase												=  name.replace("modulation.proj"				,		"modulation.projection_out"					)

	if name == "norm.weight":
		__lowerCAmelCase												=  "layernorm.weight"
	if name == "norm.bias":
		__lowerCAmelCase												=  "layernorm.bias"

	if "head" in name:
		__lowerCAmelCase												=  name.replace("head"				,		"classifier"					)
	else:
		__lowerCAmelCase												=  "focalnet." + name

	return name



def   __lowerCAmelCase					(							lowerCamelCase   :						int				,		lowerCamelCase   :						Any				,		lowerCamelCase   :						Union[str, Any]=False					):






	'''simple docstring'''




	__lowerCAmelCase												=  {
	    "focalnet-tiny": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_tiny_srf.pth",
	    "focalnet-tiny-lrf": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_tiny_lrf.pth",
	    "focalnet-small": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_small_srf.pth",
	    "focalnet-small-lrf": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_small_lrf.pth",
	    "focalnet-base": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_base_srf.pth",
	    "focalnet-base-lrf": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_base_lrf.pth",
	    "focalnet-large-lrf-fl3": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_large_lrf_384.pth",
	    "focalnet-large-lrf-fl4": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_large_lrf_384_fl4.pth",
	    "focalnet-xlarge-lrf-fl3": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_xlarge_lrf_384.pth",
	    "focalnet-xlarge-lrf-fl4": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_xlarge_lrf_384_fl4.pth",
	}
	# fmt: on

	__lowerCAmelCase												=  model_name_to_url[model_name]
	print("Checkpoint URL: "				,		lowerCamelCase					)
	__lowerCAmelCase												=  torch.hub.load_state_dict_from_url(lowerCamelCase				,		map_location="cpu"					)["model"]

	# rename keys
	for key in state_dict.copy().keys():
		__lowerCAmelCase												=  state_dict.pop(lowerCamelCase					)
		__lowerCAmelCase												=  val

	__lowerCAmelCase												=  get_focalnet_config(lowerCamelCase					)
	__lowerCAmelCase												=  FocalNetForImageClassification(lowerCamelCase					)
	model.eval()

	# load state dict
	model.load_state_dict(lowerCamelCase					)

	# verify conversion
	__lowerCAmelCase												=  "http://images.cocodataset.org/val2017/000000039769.jpg"

	__lowerCAmelCase												=  BitImageProcessor(
	    do_resize=lowerCamelCase				,		size={"shortest_edge": 2_56}				,		resample=PILImageResampling.BILINEAR				,		do_center_crop=lowerCamelCase				,		crop_size=2_24				,		do_normalize=lowerCamelCase				,		image_mean=lowerCamelCase				,		image_std=lowerCamelCase				,		)
	__lowerCAmelCase												=  Image.open(requests.get(lowerCamelCase				,		stream=lowerCamelCase					).raw					)
	__lowerCAmelCase												=  processor(images=lowerCamelCase				,		return_tensors="pt"					)

	__lowerCAmelCase												=  transforms.Compose(
	    [
	        transforms.Resize(2_56					),
	        transforms.CenterCrop(2_24					),
	        transforms.ToTensor(),
	        transforms.Normalize(mean=[0.4_8_5, 0.4_5_6, 0.4_0_6]				,		std=[0.2_2_9, 0.2_2_4, 0.2_2_5]					),
	    ]					)

	__lowerCAmelCase												=  image_transforms(lowerCamelCase					).unsqueeze(0					)

	# verify pixel_values
	assert torch.allclose(inputs.pixel_values				,		lowerCamelCase				,		atol=1e-4					)

	__lowerCAmelCase												=  model(**lowerCamelCase					)

	__lowerCAmelCase												=  outputs.logits.argmax(-1					).item()
	print("Predicted class:"				,		model.config.idalabel[predicted_class_idx]					)

	print("First values of logits:"				,		outputs.logits[0, :3]					)

	if model_name == "focalnet-tiny":
		__lowerCAmelCase												=  torch.tensor([0.2_1_6_6, -0.4_3_6_8, 0.2_1_9_1]					)
	elif model_name == "focalnet-tiny-lrf":
		__lowerCAmelCase												=  torch.tensor([1.1_6_6_9, 0.0_1_2_5, -0.1_6_9_5]					)
	elif model_name == "focalnet-small":
		__lowerCAmelCase												=  torch.tensor([0.4_9_1_7, -0.0_4_3_0, 0.1_3_4_1]					)
	elif model_name == "focalnet-small-lrf":
		__lowerCAmelCase												=  torch.tensor([-0.2_5_8_8, -0.5_3_4_2, -0.2_3_3_1]					)
	elif model_name == "focalnet-base":
		__lowerCAmelCase												=  torch.tensor([-0.1_6_5_5, -0.4_0_9_0, -0.1_7_3_0]					)
	elif model_name == "focalnet-base-lrf":
		__lowerCAmelCase												=  torch.tensor([0.5_3_0_6, -0.0_4_8_3, -0.3_9_2_8]					)
	assert torch.allclose(outputs.logits[0, :3]				,		lowerCamelCase				,		atol=1e-4					)
	print("Looks ok!"					)

	if pytorch_dump_folder_path is not None:
		print(f'''Saving model and processor of {model_name} to {pytorch_dump_folder_path}'''					)
		model.save_pretrained(lowerCamelCase					)
		processor.save_pretrained(lowerCamelCase					)

	if push_to_hub:
		print(f'''Pushing model and processor of {model_name} to the hub...'''					)
		model.push_to_hub(f'''{model_name}'''					)
		processor.push_to_hub(f'''{model_name}'''					)


if __name__ == "__main__":
	lowerCAmelCase	:		Tuple				=   argparse.ArgumentParser()
	# Required parameters
	parser.add_argument(
	    '''--model_name''',
	    default='''focalnet-tiny''',
	    type=str,
	    help='''Name of the FocalNet model you\'d like to convert.''',
	)
	parser.add_argument(
	    '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.'''
	)
	parser.add_argument(
	    '''--push_to_hub''',
	    action='''store_true''',
	    help='''Whether to push the model and processor to the hub.''',
	)

	lowerCAmelCase	:		Optional[int]				=   parser.parse_args()
	convert_focalnet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)