


from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available


SCREAMING_SNAKE_CASE__       			=				{
    """configuration_markuplm""": ["""MARKUPLM_PRETRAINED_CONFIG_ARCHIVE_MAP""", """MarkupLMConfig"""],
    """feature_extraction_markuplm""": ["""MarkupLMFeatureExtractor"""],
    """processing_markuplm""": ["""MarkupLMProcessor"""],
    """tokenization_markuplm""": ["""MarkupLMTokenizer"""],
}

try:
							if not is_tokenizers_available():
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							pass
else:
							SCREAMING_SNAKE_CASE__       			=				["""MarkupLMTokenizerFast"""]

try:
							if not is_torch_available():
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							pass
else:
							SCREAMING_SNAKE_CASE__       			=				[
							    """MARKUPLM_PRETRAINED_MODEL_ARCHIVE_LIST""",
							    """MarkupLMForQuestionAnswering""",
							    """MarkupLMForSequenceClassification""",
							    """MarkupLMForTokenClassification""",
							    """MarkupLMModel""",
							    """MarkupLMPreTrainedModel""",
							]


if TYPE_CHECKING:
							from .configuration_markuplm import MARKUPLM_PRETRAINED_CONFIG_ARCHIVE_MAP, MarkupLMConfig
							from .feature_extraction_markuplm import MarkupLMFeatureExtractor
							from .processing_markuplm import MarkupLMProcessor
							from .tokenization_markuplm import MarkupLMTokenizer

							try:
														if not is_tokenizers_available():
																					raise OptionalDependencyNotAvailable()
							except OptionalDependencyNotAvailable:
														pass
							else:
														from .tokenization_markuplm_fast import MarkupLMTokenizerFast

							try:
														if not is_torch_available():
																					raise OptionalDependencyNotAvailable()
							except OptionalDependencyNotAvailable:
														pass
							else:
														from .modeling_markuplm import (
														    MARKUPLM_PRETRAINED_MODEL_ARCHIVE_LIST,
														    MarkupLMForQuestionAnswering,
														    MarkupLMForSequenceClassification,
														    MarkupLMForTokenClassification,
														    MarkupLMModel,
														    MarkupLMPreTrainedModel,
														)


else:
							import sys

							SCREAMING_SNAKE_CASE__       			=				_LazyModule(__name__, globals()["""__file__"""], _import_structure)





import argparse

import torch
from clip import load

from transformers import CLIPConfig, CLIPModel




def SCREAMING_SNAKE_CASE_  (				__lowerCamelCase:		Optional[int]  ,			__lowerCamelCase:		Optional[int]  ):







	'''simple docstring'''



	lowercase_ ,	lowercase_ ,	lowercase_			 = pt_attn_layer.in_proj_weight.chunk(3  ,			dim=0  )
	lowercase_ ,	lowercase_ ,	lowercase_			 = pt_attn_layer.in_proj_bias.chunk(3  ,			dim=0  )

	lowercase_			 = pt_attn_layer.out_proj.weight
	lowercase_			 = pt_attn_layer.out_proj.bias

	lowercase_			 = q_proj
	lowercase_			 = q_proj_bias

	lowercase_			 = k_proj
	lowercase_			 = k_proj_bias

	lowercase_			 = v_proj
	lowercase_			 = v_proj_bias

	lowercase_			 = out_proj_weights
	lowercase_			 = out_proj_bias




def SCREAMING_SNAKE_CASE_  (				__lowerCamelCase:		int  ,			__lowerCamelCase:		List[str]  ):







	'''simple docstring'''



	copy_linear(hf_mlp.fca  ,			pt_mlp.c_fc  )
	copy_linear(hf_mlp.fca  ,			pt_mlp.c_proj  )




def SCREAMING_SNAKE_CASE_  (				__lowerCamelCase:		List[str]  ,			__lowerCamelCase:		Dict  ):







	'''simple docstring'''



	lowercase_			 = pt_linear.weight
	lowercase_			 = pt_linear.bias




def SCREAMING_SNAKE_CASE_  (				__lowerCamelCase:		int  ,			__lowerCamelCase:		Any  ):







	'''simple docstring'''



	copy_linear(hf_layer.layer_norma  ,			pt_layer.ln_a  )
	copy_linear(hf_layer.layer_norma  ,			pt_layer.ln_a  )

	# copy MLP
	copy_mlp(hf_layer.mlp  ,			pt_layer.mlp  )

	# copy attn
	copy_attn_layer(hf_layer.self_attn  ,			pt_layer.attn  )




def SCREAMING_SNAKE_CASE_  (				__lowerCamelCase:		str  ,			__lowerCamelCase:		Optional[int]  ):







	'''simple docstring'''



	for hf_layer, pt_layer in zip(__lowerCamelCase  ,			__lowerCamelCase  ):
		copy_layer(__lowerCamelCase  ,			__lowerCamelCase  )




def SCREAMING_SNAKE_CASE_  (				__lowerCamelCase:		Optional[Any]  ,			__lowerCamelCase:		str  ):







	'''simple docstring'''



	lowercase_			 = pt_model.token_embedding.weight
	lowercase_			 = pt_model.positional_embedding

	# copy layer norm
	copy_linear(hf_encoder.final_layer_norm  ,			pt_model.ln_final  )

	# copy hidden layers
	copy_layers(hf_encoder.encoder.layers  ,			pt_model.transformer.resblocks  )




def SCREAMING_SNAKE_CASE_  (				__lowerCamelCase:		Optional[Any]  ,			__lowerCamelCase:		Any  ):







	'''simple docstring'''



	lowercase_			 = pt_model.text_projection.data.T

	# copy text encoder
	copy_encoder(hf_model.text_model  ,			__lowerCamelCase  )




def SCREAMING_SNAKE_CASE_  (				__lowerCamelCase:		List[Any]  ,			__lowerCamelCase:		List[Any]  ):







	'''simple docstring'''



	lowercase_			 = pt_model.visual.proj.data.T

	# copy layer norms
	copy_linear(hf_model.vision_model.pre_layrnorm  ,			pt_model.visual.ln_pre  )
	copy_linear(hf_model.vision_model.post_layernorm  ,			pt_model.visual.ln_post  )

	# copy embeds
	lowercase_			 = pt_model.visual.conva.weight.data
	lowercase_			 = pt_model.visual.class_embedding
	lowercase_			 = pt_model.visual.positional_embedding.data

	# copy encoder
	copy_layers(hf_model.vision_model.encoder.layers  ,			pt_model.visual.transformer.resblocks  )




@torch.no_grad()
def SCREAMING_SNAKE_CASE_  (				__lowerCamelCase:		int  ,			__lowerCamelCase:		Dict  ,			__lowerCamelCase:		Dict=None  ):







	'''simple docstring'''



	if config_path is not None:
		lowercase_			 = CLIPConfig.from_pretrained(__lowerCamelCase  )
	else:
		lowercase_			 = CLIPConfig(projection_dim=512  ,			text_config={}  ,			vision_config={}  )

	lowercase_			 = CLIPModel(__lowerCamelCase  ).eval()

	lowercase_ ,	lowercase_			 = load(__lowerCamelCase  ,			device="cpu"  ,			jit=__lowerCamelCase  )
	lowercase_			 = pt_model.eval()

	copy_text_model_and_projection(__lowerCamelCase  ,			__lowerCamelCase  )
	copy_vison_model_and_projection(__lowerCamelCase  ,			__lowerCamelCase  )
	lowercase_			 = pt_model.logit_scale

	lowercase_			 = torch.arange(0  ,			77  ).unsqueeze(0  )
	lowercase_			 = torch.randn(1  ,			3  ,			224  ,			224  )

	lowercase_			 = hf_model(input_ids=__lowerCamelCase  ,			pixel_values=__lowerCamelCase  ,			return_dict=__lowerCamelCase  )
	lowercase_			 = hf_outputs.logits_per_image
	lowercase_			 = hf_outputs.logits_per_text
	lowercase_ ,	lowercase_			 = pt_model(__lowerCamelCase  ,			__lowerCamelCase  )

	assert torch.allclose(__lowerCamelCase  ,			__lowerCamelCase  ,			atol=1E-3  )
	assert torch.allclose(__lowerCamelCase  ,			__lowerCamelCase  ,			atol=1E-3  )

	hf_model.save_pretrained(__lowerCamelCase  )


if __name__ == "__main__":
							SCREAMING_SNAKE_CASE__       			=				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 fairseq checkpoint""")
							parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""")
							SCREAMING_SNAKE_CASE__       			=				parser.parse_args()

							convert_clip_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)

