






"""simple docstring"""



import argparse
import os

import align
import numpy as np
import requests
import tensorflow as tf
import torch
from PIL import Image
from tokenizer import Tokenizer

from transformers import (
    AlignConfig,
    AlignModel,
    AlignProcessor,
    BertConfig,
    BertTokenizer,
    EfficientNetConfig,
    EfficientNetImageProcessor,
)
from transformers.utils import logging


logging.set_verbosity_info()
_snake_case							:   int	  =       logging.get_logger(__name__)




def     lowerCamelCase_					(	__A	:		Optional[Any]      ):
					lowerCamelCase__					=tf.image.resize(__A      ,						(346, 346)      )
					lowerCamelCase__					=tf.image.crop_to_bounding_box(__A      ,						(346 - 289) // 2      ,						(346 - 289) // 2      ,						289      ,						289      )
					return image




def     lowerCamelCase_					(	):
					lowerCamelCase__					=EfficientNetConfig.from_pretrained('google/efficientnet-b7'      )
					lowerCamelCase__					=289
					lowerCamelCase__					=640
					lowerCamelCase__					={'0': 'LABEL_0', '1': 'LABEL_1'}
					lowerCamelCase__					={'LABEL_0': 0, 'LABEL_1': 1}
					lowerCamelCase__					=[]

					lowerCamelCase__					=BertConfig()
					lowerCamelCase__					=AlignConfig.from_text_vision_configs(
					    text_config=__A      ,						vision_config=__A      ,						projection_dim=640      )
					return config




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




def     lowerCamelCase_					(	):
					lowerCamelCase__					=EfficientNetImageProcessor(
					    do_center_crop=__A      ,						rescale_factor=1 / 1_2_7.5      ,						rescale_offset=__A      ,						do_normalize=__A      ,						include_top=__A      ,						resample=Image.BILINEAR      ,						)
					lowerCamelCase__					=BertTokenizer.from_pretrained('bert-base-uncased'      )
					lowerCamelCase__					=64
					lowerCamelCase__					=AlignProcessor(image_processor=__A      ,						tokenizer=__A      )
					return processor




def     lowerCamelCase_					(	__A	:		str      ):
					# EfficientNet image encoder
					lowerCamelCase__					=[v.split('_'      )[0].split('block'      )[1] for v in original_param_names if v.startswith('block'      )]
					lowerCamelCase__					=list(set(__A      )      )
					lowerCamelCase__					=sorted(__A      )
					lowerCamelCase__					=len(__A      )
					lowerCamelCase__					={b: str(__A      ) for b, i in zip(__A      ,						range(__A      )      )}

					lowerCamelCase__					=[]
					rename_keys.append(('stem_conv/kernel:0', 'embeddings.convolution.weight')      )
					rename_keys.append(('stem_bn/gamma:0', 'embeddings.batchnorm.weight')      )
					rename_keys.append(('stem_bn/beta:0', 'embeddings.batchnorm.bias')      )
					rename_keys.append(('stem_bn/moving_mean:0', 'embeddings.batchnorm.running_mean')      )
					rename_keys.append(('stem_bn/moving_variance:0', 'embeddings.batchnorm.running_var')      )

					for b in block_names:
										lowerCamelCase__					=block_name_mapping[b]
										rename_keys.append((f"block{b}_expand_conv/kernel:0", f"encoder.blocks.{hf_b}.expansion.expand_conv.weight")      )
										rename_keys.append((f"block{b}_expand_bn/gamma:0", f"encoder.blocks.{hf_b}.expansion.expand_bn.weight")      )
										rename_keys.append((f"block{b}_expand_bn/beta:0", f"encoder.blocks.{hf_b}.expansion.expand_bn.bias")      )
										rename_keys.append(
										    (f"block{b}_expand_bn/moving_mean:0", f"encoder.blocks.{hf_b}.expansion.expand_bn.running_mean")      )
										rename_keys.append(
										    (f"block{b}_expand_bn/moving_variance:0", f"encoder.blocks.{hf_b}.expansion.expand_bn.running_var")      )
										rename_keys.append(
										    (f"block{b}_dwconv/depthwise_kernel:0", f"encoder.blocks.{hf_b}.depthwise_conv.depthwise_conv.weight")      )
										rename_keys.append((f"block{b}_bn/gamma:0", f"encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.weight")      )
										rename_keys.append((f"block{b}_bn/beta:0", f"encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.bias")      )
										rename_keys.append(
										    (f"block{b}_bn/moving_mean:0", f"encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.running_mean")      )
										rename_keys.append(
										    (f"block{b}_bn/moving_variance:0", f"encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.running_var")      )

										rename_keys.append((f"block{b}_se_reduce/kernel:0", f"encoder.blocks.{hf_b}.squeeze_excite.reduce.weight")      )
										rename_keys.append((f"block{b}_se_reduce/bias:0", f"encoder.blocks.{hf_b}.squeeze_excite.reduce.bias")      )
										rename_keys.append((f"block{b}_se_expand/kernel:0", f"encoder.blocks.{hf_b}.squeeze_excite.expand.weight")      )
										rename_keys.append((f"block{b}_se_expand/bias:0", f"encoder.blocks.{hf_b}.squeeze_excite.expand.bias")      )
										rename_keys.append(
										    (f"block{b}_project_conv/kernel:0", f"encoder.blocks.{hf_b}.projection.project_conv.weight")      )
										rename_keys.append((f"block{b}_project_bn/gamma:0", f"encoder.blocks.{hf_b}.projection.project_bn.weight")      )
										rename_keys.append((f"block{b}_project_bn/beta:0", f"encoder.blocks.{hf_b}.projection.project_bn.bias")      )
										rename_keys.append(
										    (f"block{b}_project_bn/moving_mean:0", f"encoder.blocks.{hf_b}.projection.project_bn.running_mean")      )
										rename_keys.append(
										    (f"block{b}_project_bn/moving_variance:0", f"encoder.blocks.{hf_b}.projection.project_bn.running_var")      )

					lowerCamelCase__					={}
					for item in rename_keys:
										if item[0] in original_param_names:
															lowerCamelCase__					='vision_model.' + item[1]

    # BERT text encoder
					lowerCamelCase__					=[]
					lowerCamelCase__					='tf_bert_model/bert'
					lowerCamelCase__					='text_model'
					for i in range(12      ):
										rename_keys.append(
										    (
										        f"{old}/encoder/layer_._{i}/attention/self/query/kernel:0",
										        f"{new}.encoder.layer.{i}.attention.self.query.weight",
										    )      )
										rename_keys.append(
										    (
										        f"{old}/encoder/layer_._{i}/attention/self/query/bias:0",
										        f"{new}.encoder.layer.{i}.attention.self.query.bias",
										    )      )
										rename_keys.append(
										    (
										        f"{old}/encoder/layer_._{i}/attention/self/key/kernel:0",
										        f"{new}.encoder.layer.{i}.attention.self.key.weight",
										    )      )
										rename_keys.append(
										    (
										        f"{old}/encoder/layer_._{i}/attention/self/key/bias:0",
										        f"{new}.encoder.layer.{i}.attention.self.key.bias",
										    )      )
										rename_keys.append(
										    (
										        f"{old}/encoder/layer_._{i}/attention/self/value/kernel:0",
										        f"{new}.encoder.layer.{i}.attention.self.value.weight",
										    )      )
										rename_keys.append(
										    (
										        f"{old}/encoder/layer_._{i}/attention/self/value/bias:0",
										        f"{new}.encoder.layer.{i}.attention.self.value.bias",
										    )      )
										rename_keys.append(
										    (
										        f"{old}/encoder/layer_._{i}/attention/output/dense/kernel:0",
										        f"{new}.encoder.layer.{i}.attention.output.dense.weight",
										    )      )
										rename_keys.append(
										    (
										        f"{old}/encoder/layer_._{i}/attention/output/dense/bias:0",
										        f"{new}.encoder.layer.{i}.attention.output.dense.bias",
										    )      )
										rename_keys.append(
										    (
										        f"{old}/encoder/layer_._{i}/attention/output/LayerNorm/gamma:0",
										        f"{new}.encoder.layer.{i}.attention.output.LayerNorm.weight",
										    )      )
										rename_keys.append(
										    (
										        f"{old}/encoder/layer_._{i}/attention/output/LayerNorm/beta:0",
										        f"{new}.encoder.layer.{i}.attention.output.LayerNorm.bias",
										    )      )
										rename_keys.append(
										    (
										        f"{old}/encoder/layer_._{i}/intermediate/dense/kernel:0",
										        f"{new}.encoder.layer.{i}.intermediate.dense.weight",
										    )      )
										rename_keys.append(
										    (
										        f"{old}/encoder/layer_._{i}/intermediate/dense/bias:0",
										        f"{new}.encoder.layer.{i}.intermediate.dense.bias",
										    )      )
										rename_keys.append(
										    (f"{old}/encoder/layer_._{i}/output/dense/kernel:0", f"{new}.encoder.layer.{i}.output.dense.weight")      )
										rename_keys.append(
										    (f"{old}/encoder/layer_._{i}/output/dense/bias:0", f"{new}.encoder.layer.{i}.output.dense.bias")      )
										rename_keys.append(
										    (f"{old}/encoder/layer_._{i}/output/LayerNorm/gamma:0", f"{new}.encoder.layer.{i}.output.LayerNorm.weight")      )
										rename_keys.append(
										    (f"{old}/encoder/layer_._{i}/output/LayerNorm/beta:0", f"{new}.encoder.layer.{i}.output.LayerNorm.bias")      )

					rename_keys.append((f"{old}/embeddings/word_embeddings/weight:0", f"{new}.embeddings.word_embeddings.weight")      )
					rename_keys.append(
					    (f"{old}/embeddings/position_embeddings/embeddings:0", f"{new}.embeddings.position_embeddings.weight")      )
					rename_keys.append(
					    (f"{old}/embeddings/token_type_embeddings/embeddings:0", f"{new}.embeddings.token_type_embeddings.weight")      )
					rename_keys.append((f"{old}/embeddings/LayerNorm/gamma:0", f"{new}.embeddings.LayerNorm.weight")      )
					rename_keys.append((f"{old}/embeddings/LayerNorm/beta:0", f"{new}.embeddings.LayerNorm.bias")      )

					rename_keys.append((f"{old}/pooler/dense/kernel:0", f"{new}.pooler.dense.weight")      )
					rename_keys.append((f"{old}/pooler/dense/bias:0", f"{new}.pooler.dense.bias")      )
					rename_keys.append(('dense/kernel:0', 'text_projection.weight')      )
					rename_keys.append(('dense/bias:0', 'text_projection.bias')      )
					rename_keys.append(('dense/bias:0', 'text_projection.bias')      )
					rename_keys.append(('temperature:0', 'temperature')      )

					for item in rename_keys:
										if item[0] in original_param_names:
															lowerCamelCase__					=item[1]
					return key_mapping




def     lowerCamelCase_					(	__A	:		Optional[Any]      ,						__A	:		Tuple      ,						__A	:		Union[str, Any]      ):
					list(hf_params.keys()      )

					for key, value in tf_params.items():
										if key not in key_mapping:
															continue

										lowerCamelCase__					=key_mapping[key]
										if "_conv" in key and "kernel" in key:
															lowerCamelCase__					=torch.from_numpy(__A      ).permute(3      ,						2      ,						0      ,						1      )
										elif "embeddings" in key:
															lowerCamelCase__					=torch.from_numpy(__A      )
										elif "depthwise_kernel" in key:
															lowerCamelCase__					=torch.from_numpy(__A      ).permute(2      ,						3      ,						0      ,						1      )
										elif "kernel" in key:
															lowerCamelCase__					=torch.from_numpy(np.transpose(__A      )      )
										elif "temperature" in key:
															lowerCamelCase__					=value
										elif "bn/gamma" or "bn/beta" in key:
															lowerCamelCase__					=torch.from_numpy(np.transpose(__A      )      ).squeeze()
										else:
															lowerCamelCase__					=torch.from_numpy(__A      )

										# Replace HF parameters with original TF model parameters
										hf_params[hf_key].copy_(__A      )




@torch.no_grad()
def     lowerCamelCase_					(	__A	:		List[Any]      ,						__A	:		Any      ,						__A	:		List[str]      ,						__A	:		List[str]      ):
					lowerCamelCase__					=64
					lowerCamelCase__					=Tokenizer(__A      )
					lowerCamelCase__					=align.Align('efficientnet-b7'      ,						'bert-base'      ,						640      ,						__A      ,						tok.get_vocab_size()      )
					original_model.compile()
					original_model.load_weights(__A      )

					lowerCamelCase__					=original_model.trainable_variables
					lowerCamelCase__					=original_model.non_trainable_variables
					lowerCamelCase__					={param.name: param.numpy() for param in tf_params}
					for param in tf_non_train_params:
										lowerCamelCase__					=param.numpy()
					lowerCamelCase__					=list(tf_params.keys()      )

					# Load HuggingFace model
					lowerCamelCase__					=get_align_config()
					lowerCamelCase__					=AlignModel(__A      ).eval()
					lowerCamelCase__					=hf_model.state_dict()

					# Create src-to-dst parameter name mapping dictionary
					print('Converting parameters...'      )
					lowerCamelCase__					=rename_keys(__A      )
					replace_params(__A      ,						__A      ,						__A      )

					# Initialize processor
					lowerCamelCase__					=get_processor()
					lowerCamelCase__					=processor(
					    images=prepare_img()      ,						text='A picture of a cat'      ,						padding='max_length'      ,						max_length=64      ,						return_tensors='pt'      )

					# HF model inference
					hf_model.eval()
					with torch.no_grad():
										lowerCamelCase__					=hf_model(**__A      )

					lowerCamelCase__					=outputs.image_embeds.detach().numpy()
					lowerCamelCase__					=outputs.text_embeds.detach().numpy()

					# Original model inference
					lowerCamelCase__					=False
					lowerCamelCase__					=EfficientNetImageProcessor(
					    do_center_crop=__A      ,						do_rescale=__A      ,						do_normalize=__A      ,						include_top=__A      ,						resample=Image.BILINEAR      ,						)
					lowerCamelCase__					=tf_image_processor(images=prepare_img()      ,						return_tensors='tf'      ,						data_format='channels_last'      )['pixel_values']
					lowerCamelCase__					=tok(tf.constant(['A picture of a cat']      )      )

					lowerCamelCase__					=original_model.image_encoder(__A      ,						training=__A      )
					lowerCamelCase__					=original_model.text_encoder(__A      ,						training=__A      )

					lowerCamelCase__					=tf.nn.la_normalize(__A      ,						axis=-1      )
					lowerCamelCase__					=tf.nn.la_normalize(__A      ,						axis=-1      )

					# Check whether original and HF model outputs match  -> np.allclose
					if not np.allclose(__A      ,						__A      ,						atol=1E-3      ):
										raise ValueError('The predicted image features are not the same.'      )
					if not np.allclose(__A      ,						__A      ,						atol=1E-3      ):
										raise ValueError('The predicted text features are not the same.'      )
					print('Model outputs match!'      )

					if save_model:
										# Create folder to save model
										if not os.path.isdir(__A      ):
															os.mkdir(__A      )
										# Save converted model and image processor
										hf_model.save_pretrained(__A      )
										processor.save_pretrained(__A      )

					if push_to_hub:
										# Push model and image processor to hub
										print('Pushing converted ALIGN to the hub...'      )
										processor.push_to_hub('align-base'      )
										hf_model.push_to_hub('align-base'      )


if __name__ == "__main__":
						_snake_case							:   str	  =       argparse.ArgumentParser()
						# Required parameters
						parser.add_argument(
						    "--checkpoint_path",
						    default="./weights/model-weights",
						    type=str,
						    help="Path to the pretrained TF ALIGN checkpoint.",
						)
						parser.add_argument(
						    "--pytorch_dump_folder_path",
						    default="hf_model",
						    type=str,
						    help="Path to the output PyTorch model directory.",
						)
						parser.add_argument("--save_model", action="store_true", help="Save model to local")
						parser.add_argument("--push_to_hub", action="store_true", help="Push model and image processor to the hub")

						_snake_case							:   Union[str, Any]	  =       parser.parse_args()
						convert_align_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.save_model, args.push_to_hub)







"""simple docstring"""



import torch

from diffusers import EulerAncestralDiscreteScheduler
from diffusers.utils import torch_device

from .test_schedulers import SchedulerCommonTest




class 							__lowercase(							_UpperCamelCase	):
						lowerCAmelCase_		:				Dict=							(EulerAncestralDiscreteScheduler,)
						lowerCAmelCase_		:				int=							10






						def 		lowerCAmelCase (       self     ,    **_SCREAMING_SNAKE_CASE)      ->	List[str]:




											"""simple docstring"""





											lowerCamelCase__					={
											    'num_train_timesteps': 11_00,
											    'beta_start': 0.0001,
											    'beta_end': 0.02,
											    'beta_schedule': 'linear',
											}

											config.update(**_SCREAMING_SNAKE_CASE)
											return config






						def 		lowerCAmelCase (       self)      ->	List[Any]:




											"""simple docstring"""





											for timesteps in [10, 50, 1_00, 10_00]:
																self.check_over_configs(num_train_timesteps=_SCREAMING_SNAKE_CASE)






						def 		lowerCAmelCase (       self)      ->	Tuple:




											"""simple docstring"""





											for beta_start, beta_end in zip([0.00001, 0.0001, 0.001]     ,    [0.0002, 0.002, 0.02]):
																self.check_over_configs(beta_start=_SCREAMING_SNAKE_CASE     ,    beta_end=_SCREAMING_SNAKE_CASE)






						def 		lowerCAmelCase (       self)      ->	List[Any]:




											"""simple docstring"""





											for schedule in ["linear", "scaled_linear"]:
																self.check_over_configs(beta_schedule=_SCREAMING_SNAKE_CASE)






						def 		lowerCAmelCase (       self)      ->	Dict:




											"""simple docstring"""





											for prediction_type in ["epsilon", "v_prediction"]:
																self.check_over_configs(prediction_type=_SCREAMING_SNAKE_CASE)






						def 		lowerCAmelCase (       self)      ->	List[str]:




											"""simple docstring"""





											lowerCamelCase__					=self.scheduler_classes[0]
											lowerCamelCase__					=self.get_scheduler_config()
											lowerCamelCase__					=scheduler_class(**_SCREAMING_SNAKE_CASE)

											scheduler.set_timesteps(self.num_inference_steps)

											lowerCamelCase__					=torch.manual_seed(0)

											lowerCamelCase__					=self.dummy_model()
											lowerCamelCase__					=self.dummy_sample_deter * scheduler.init_noise_sigma.cpu()
											lowerCamelCase__					=sample.to(_SCREAMING_SNAKE_CASE)

											for i, t in enumerate(scheduler.timesteps):
																lowerCamelCase__					=scheduler.scale_model_input(_SCREAMING_SNAKE_CASE     ,    _SCREAMING_SNAKE_CASE)

																lowerCamelCase__					=model(_SCREAMING_SNAKE_CASE     ,    _SCREAMING_SNAKE_CASE)

																lowerCamelCase__					=scheduler.step(_SCREAMING_SNAKE_CASE     ,    _SCREAMING_SNAKE_CASE     ,    _SCREAMING_SNAKE_CASE     ,    generator=_SCREAMING_SNAKE_CASE)
																lowerCamelCase__					=output.prev_sample

											lowerCamelCase__					=torch.sum(torch.abs(_SCREAMING_SNAKE_CASE))
											lowerCamelCase__					=torch.mean(torch.abs(_SCREAMING_SNAKE_CASE))

											assert abs(result_sum.item() - 152.3192) < 1E-2
											assert abs(result_mean.item() - 0.1983) < 1E-3






						def 		lowerCAmelCase (       self)      ->	str:




											"""simple docstring"""





											lowerCamelCase__					=self.scheduler_classes[0]
											lowerCamelCase__					=self.get_scheduler_config(prediction_type='v_prediction')
											lowerCamelCase__					=scheduler_class(**_SCREAMING_SNAKE_CASE)

											scheduler.set_timesteps(self.num_inference_steps)

											lowerCamelCase__					=torch.manual_seed(0)

											lowerCamelCase__					=self.dummy_model()
											lowerCamelCase__					=self.dummy_sample_deter * scheduler.init_noise_sigma
											lowerCamelCase__					=sample.to(_SCREAMING_SNAKE_CASE)

											for i, t in enumerate(scheduler.timesteps):
																lowerCamelCase__					=scheduler.scale_model_input(_SCREAMING_SNAKE_CASE     ,    _SCREAMING_SNAKE_CASE)

																lowerCamelCase__					=model(_SCREAMING_SNAKE_CASE     ,    _SCREAMING_SNAKE_CASE)

																lowerCamelCase__					=scheduler.step(_SCREAMING_SNAKE_CASE     ,    _SCREAMING_SNAKE_CASE     ,    _SCREAMING_SNAKE_CASE     ,    generator=_SCREAMING_SNAKE_CASE)
																lowerCamelCase__					=output.prev_sample

											lowerCamelCase__					=torch.sum(torch.abs(_SCREAMING_SNAKE_CASE))
											lowerCamelCase__					=torch.mean(torch.abs(_SCREAMING_SNAKE_CASE))

											assert abs(result_sum.item() - 108.4439) < 1E-2
											assert abs(result_mean.item() - 0.1412) < 1E-3






						def 		lowerCAmelCase (       self)      ->	Any:




											"""simple docstring"""





											lowerCamelCase__					=self.scheduler_classes[0]
											lowerCamelCase__					=self.get_scheduler_config()
											lowerCamelCase__					=scheduler_class(**_SCREAMING_SNAKE_CASE)

											scheduler.set_timesteps(self.num_inference_steps     ,    device=_SCREAMING_SNAKE_CASE)
											lowerCamelCase__					=torch.manual_seed(0)

											lowerCamelCase__					=self.dummy_model()
											lowerCamelCase__					=self.dummy_sample_deter * scheduler.init_noise_sigma.cpu()
											lowerCamelCase__					=sample.to(_SCREAMING_SNAKE_CASE)

											for t in scheduler.timesteps:
																lowerCamelCase__					=scheduler.scale_model_input(_SCREAMING_SNAKE_CASE     ,    _SCREAMING_SNAKE_CASE)

																lowerCamelCase__					=model(_SCREAMING_SNAKE_CASE     ,    _SCREAMING_SNAKE_CASE)

																lowerCamelCase__					=scheduler.step(_SCREAMING_SNAKE_CASE     ,    _SCREAMING_SNAKE_CASE     ,    _SCREAMING_SNAKE_CASE     ,    generator=_SCREAMING_SNAKE_CASE)
																lowerCamelCase__					=output.prev_sample

											lowerCamelCase__					=torch.sum(torch.abs(_SCREAMING_SNAKE_CASE))
											lowerCamelCase__					=torch.mean(torch.abs(_SCREAMING_SNAKE_CASE))

											assert abs(result_sum.item() - 152.3192) < 1E-2
											assert abs(result_mean.item() - 0.1983) < 1E-3