
import argparse
from pathlib import Path

import fairseq
import torch
from fairseq.models.xmod import XMODModel as FairseqXmodModel
from packaging import version

from transformers import XmodConfig, XmodForMaskedLM, XmodForSequenceClassification
from transformers.utils import logging


if version.parse(fairseq.__version__) < version.parse('0.12.2'):
					raise Exception('requires fairseq >= 0.12.2')
if version.parse(fairseq.__version__) > version.parse('2'):
					raise Exception('requires fairseq < v2')

logging.set_verbosity_info()
SCREAMING_SNAKE_CASE				:str									=							logging.get_logger(__name__)

SCREAMING_SNAKE_CASE				:Optional[int]									=							'Hello, World!'
SCREAMING_SNAKE_CASE				:Optional[Any]									=							'en_XX'


def 		UpperCAmelCase     (      a_						,  a_						,  a_		)						->      Optional[int]:







				"""simple docstring"""



				__A       =					Path("data_bin"		)
				__A       =					FairseqXmodModel.from_pretrained(
				    model_name_or_path=str(Path(a_		).parent		)						,  checkpoint_file=Path(a_		).name						,  _name="xmod_base"						,  arch="xmod_base"						,  task="multilingual_masked_lm"						,  data_name_or_path=str(a_		)						,  bpe="sentencepiece"						,  sentencepiece_model=str(Path(a_		).parent / "sentencepiece.bpe.model"		)						,  src_dict=str(data_dir / "dict.txt"		)						,  )
				xmod.eval()  # disable dropout
				print(a_		)

				__A       =					xmod.model.encoder.sentence_encoder
				__A       =					XmodConfig(
				    vocab_size=xmod_sent_encoder.embed_tokens.num_embeddings						,  hidden_size=xmod.cfg.model.encoder_embed_dim						,  num_hidden_layers=xmod.cfg.model.encoder_layers						,  num_attention_heads=xmod.cfg.model.encoder_attention_heads						,  intermediate_size=xmod.cfg.model.encoder_ffn_embed_dim						,  max_position_embeddings=5_1_4						,  type_vocab_size=1						,  layer_norm_eps=1E-5						,  pre_norm=xmod.cfg.model.encoder_normalize_before						,  adapter_reduction_factor=getattr(xmod.cfg.model						,  "bottleneck"						,  2		)						,  adapter_layer_norm=xmod.cfg.model.adapter_layer_norm						,  adapter_reuse_layer_norm=xmod.cfg.model.adapter_reuse_layer_norm						,  ln_before_adapter=xmod.cfg.model.ln_before_adapter						,  languages=xmod.cfg.model.languages						,  )
				if classification_head:
								__A       =					xmod.model.classification_heads["mnli"].out_proj.weight.shape[0]

				print("Our X-MOD config:"						,  a_		)

				__A       =					XmodForSequenceClassification(a_		) if classification_head else XmodForMaskedLM(a_		)
				model.eval()

				# Now let's copy all the weights.
				# Embeddings
				__A       =					xmod_sent_encoder.embed_tokens.weight
				__A       =					xmod_sent_encoder.embed_positions.weight
				__A       =					torch.zeros_like(
				    model.roberta.embeddings.token_type_embeddings.weight		)  # just zero them out b/c xmod doesn't use them.

				__A       =					xmod_sent_encoder.layernorm_embedding.weight
				__A       =					xmod_sent_encoder.layernorm_embedding.bias

				for i in range(config.num_hidden_layers		):
								# Encoder: start of layer
								__A       =					model.roberta.encoder.layer[i]
								__A       =					xmod_sent_encoder.layers[i]

								# self attention
								__A       =					layer.attention.self
								if not (
								    xmod_layer.self_attn.k_proj.weight.data.shape
								    == xmod_layer.self_attn.q_proj.weight.data.shape
								    == xmod_layer.self_attn.v_proj.weight.data.shape
								    == torch.Size((config.hidden_size, config.hidden_size)		)
								):
												raise AssertionError("Dimensions of self-attention weights do not match."		)

								__A       =					xmod_layer.self_attn.q_proj.weight
								__A       =					xmod_layer.self_attn.q_proj.bias
								__A       =					xmod_layer.self_attn.k_proj.weight
								__A       =					xmod_layer.self_attn.k_proj.bias
								__A       =					xmod_layer.self_attn.v_proj.weight
								__A       =					xmod_layer.self_attn.v_proj.bias

								# self-attention output
								__A       =					layer.attention.output
								if self_output.dense.weight.shape != xmod_layer.self_attn.out_proj.weight.shape:
												raise AssertionError("Dimensions of self-attention output weights do not match."		)
								__A       =					xmod_layer.self_attn.out_proj.weight
								__A       =					xmod_layer.self_attn.out_proj.bias
								__A       =					xmod_layer.self_attn_layer_norm.weight
								__A       =					xmod_layer.self_attn_layer_norm.bias

								# intermediate
								__A       =					layer.intermediate
								if intermediate.dense.weight.shape != xmod_layer.fca.weight.shape:
												raise AssertionError("Dimensions of intermediate weights do not match."		)
								__A       =					xmod_layer.fca.weight
								__A       =					xmod_layer.fca.bias

								# output
								__A       =					layer.output
								if bert_output.dense.weight.shape != xmod_layer.fca.weight.shape:
												raise AssertionError("Dimensions of feed-forward weights do not match."		)
								__A       =					xmod_layer.fca.weight
								__A       =					xmod_layer.fca.bias
								__A       =					xmod_layer.final_layer_norm.weight
								__A       =					xmod_layer.final_layer_norm.bias
								if bert_output.adapter_layer_norm is not None:
												__A       =					xmod_layer.adapter_layer_norm.weight
												__A       =					xmod_layer.adapter_layer_norm.bias

								if sorted(bert_output.adapter_modules.keys()		) != sorted(xmod_layer.adapter_modules.keys()		):
												raise AssertionError("Lists of language adapters do not match."		)
								for lang_code, adapter in xmod_layer.adapter_modules.items():
												__A       =					bert_output.adapter_modules[lang_code]
												__A       =					xmod_layer.adapter_modules[lang_code]
												__A       =					from_adapter.fca.weight
												__A       =					from_adapter.fca.bias
												__A       =					from_adapter.fca.weight
												__A       =					from_adapter.fca.bias

								# end of layer

				if xmod_sent_encoder.layer_norm is not None:
								__A       =					xmod_sent_encoder.layer_norm.weight
								__A       =					xmod_sent_encoder.layer_norm.bias

				if classification_head:
								__A       =					xmod.model.classification_heads["mnli"].dense.weight
								__A       =					xmod.model.classification_heads["mnli"].dense.bias
								__A       =					xmod.model.classification_heads["mnli"].out_proj.weight
								__A       =					xmod.model.classification_heads["mnli"].out_proj.bias
				else:
								# LM Head
								__A       =					xmod.model.encoder.lm_head.dense.weight
								__A       =					xmod.model.encoder.lm_head.dense.bias
								__A       =					xmod.model.encoder.lm_head.layer_norm.weight
								__A       =					xmod.model.encoder.lm_head.layer_norm.bias
								__A       =					xmod.model.encoder.lm_head.weight
								__A       =					xmod.model.encoder.lm_head.bias

				# Let's check that we get the same results.
				__A       =					xmod.encode(a_		).unsqueeze(0		)  # batch of size 1
				model.roberta.set_default_language(a_		)

				__A       =					model(a_		)[0]
				if classification_head:
								__A       =					xmod.model.classification_heads["mnli"](xmod.extract_features(a_		)		)
				else:
								__A       =					xmod.model(a_						,  lang_id=[SAMPLE_LANGUAGE]		)[0]
				print(our_output.shape						,  their_output.shape		)
				__A       =					torch.max(torch.abs(our_output - their_output		)		).item()
				print(F'''max_absolute_diff = {max_absolute_diff}'''		)  # ~ 1e-7
				__A       =					torch.allclose(a_						,  a_						,  atol=1E-3		)
				print("Do both models output the same tensors?"						,  "🔥" if success else "💩"		)
				if not success:
								raise Exception("Something went wRoNg"		)

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


if __name__ == "__main__":
					SCREAMING_SNAKE_CASE				:Union[str, Any]									=							argparse.ArgumentParser()
					# Required parameters
					parser.add_argument(
					    '--xmod_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.'
					)
					SCREAMING_SNAKE_CASE				:str									=							parser.parse_args()
					convert_xmod_checkpoint_to_pytorch(
					    args.xmod_checkpoint_path, args.pytorch_dump_folder_path, args.classification_head
					)





from __future__ import annotations

import collections
import tempfile
import unittest

import numpy as np

from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import is_tf_available, is_vision_available

from ...test_modeling_tf_common import floats_tensor, ids_tensor, random_attention_mask
from ..bert.test_modeling_tf_bert import TFBertModelTester
from ..clip.test_modeling_tf_clip import TFCLIPVisionModelTester
from ..deit.test_modeling_tf_deit import TFDeiTModelTester
from ..roberta.test_modeling_tf_roberta import TFRobertaModelTester
from ..vit.test_modeling_tf_vit import TFViTModelTester


if is_tf_available():
   from transformers import (
       TFBertModel,
       TFCLIPVisionModel,
       TFDeiTModel,
       TFRobertaModel,
       TFVisionTextDualEncoderModel,
       TFViTModel,
       VisionTextDualEncoderConfig,
   )

if is_vision_available():
   from PIL import Image

   from transformers import VisionTextDualEncoderProcessor



def 		lowerCAmelCase__     (       UpperCamelCase_					:							List[Any]						)->	Dict:
    if isinstance(UpperCamelCase_			,							collections.abc.Iterable						):
        return x
    return (x, x)



@require_tf
class      _UpperCAmelCase      :




     def 		snake_case_		(					self			,    a__			,    a__):
         pass




     def 		snake_case_		(					self):
         pass




     def 		snake_case_		(					self):
         pass




     def 		snake_case_		(					self			,    a__			,    a__			,    a__			,    a__			,    a__=None			,    **a__):
         A__					=       VisionTextDualEncoderConfig.from_vision_text_configs(a__			,    a__)

         A__					=       TFVisionTextDualEncoderModel(a__)

         A__					=       model(input_ids=a__			,    pixel_values=a__			,    attention_mask=a__)

         self.assertEqual(output['''text_embeds'''].shape			,    (input_ids.shape[0], config.projection_dim))
         self.assertEqual(output['''image_embeds'''].shape			,    (pixel_values.shape[0], config.projection_dim))




     def 		snake_case_		(					self			,    a__			,    a__			,    a__			,    a__			,    a__=None			,    **a__):
         A__			,						A__					=       self.get_vision_text_model(a__			,    a__)
         A__					=       TFVisionTextDualEncoderModel(vision_model=a__			,    text_model=a__)

         A__					=       model(input_ids=a__			,    pixel_values=a__			,    attention_mask=a__)

         self.assertEqual(output['''text_embeds'''].shape			,    (input_ids.shape[0], model.config.projection_dim))
         self.assertEqual(output['''image_embeds'''].shape			,    (pixel_values.shape[0], model.config.projection_dim))




     def 		snake_case_		(					self			,    a__			,    a__			,    a__			,    a__			,    a__=None			,    **a__):
         A__			,						A__					=       self.get_vision_text_model(a__			,    a__)
         A__					=       {'''vision_model''': vision_model, '''text_model''': text_model}
         A__					=       TFVisionTextDualEncoderModel.from_vision_text_pretrained(**a__)

         A__					=       model(input_ids=a__			,    pixel_values=a__			,    attention_mask=a__)

         self.assertEqual(output['''text_embeds'''].shape			,    (input_ids.shape[0], model.config.projection_dim))
         self.assertEqual(output['''image_embeds'''].shape			,    (pixel_values.shape[0], model.config.projection_dim))




     def 		snake_case_		(					self			,    a__			,    a__			,    a__			,    a__			,    a__=None			,    **a__):
         A__			,						A__					=       self.get_vision_text_model(a__			,    a__)
         A__					=       TFVisionTextDualEncoderModel(vision_model=a__			,    text_model=a__)

         A__					=       model(input_ids=a__			,    pixel_values=a__			,    attention_mask=a__)
         A__					=       output[0].numpy()

         with tempfile.TemporaryDirectory() as tmpdirname:
             model.save_pretrained(a__)
             A__					=       TFVisionTextDualEncoderModel.from_pretrained(a__)

             A__					=       model(input_ids=a__			,    pixel_values=a__			,    attention_mask=a__)
             A__					=       after_output[0].numpy()
             A__					=       np.amax(np.abs(out_a - out_a))
             self.assertLessEqual(a__			,    1e-5)




     def 		snake_case_		(					self			,    a__			,    a__			,    a__			,    a__			,    a__=None			,    **a__):
         A__			,						A__					=       self.get_vision_text_model(a__			,    a__)
         A__					=       TFVisionTextDualEncoderModel(vision_model=a__			,    text_model=a__)

         A__					=       model(
             input_ids=a__			,    pixel_values=a__			,    attention_mask=a__			,    output_attentions=a__)

         A__					=       output.vision_model_output.attentions
         self.assertEqual(len(a__)			,    vision_config.num_hidden_layers)

         # in ViT, the seq_len equals the number of patches + 1 (we add 1 for the [CLS] token)
         A__					=       to_atuple(vision_model.config.image_size)
         A__					=       to_atuple(vision_model.config.patch_size)
         A__					=       (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
         A__					=       num_patches + 1
         self.assertEqual(vision_attentions[0].shape[-3:]			,    (vision_config.num_attention_heads, seq_len, seq_len))

         A__					=       output.text_model_output.attentions
         self.assertEqual(len(a__)			,    text_config.num_hidden_layers)

         self.assertEqual(
             text_attentions[0].shape[-3:]			,    (text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1])			,    )




     def 		snake_case_		(					self			,    a__			,    a__			,    a__):
         A__					=       np.abs((a - b)).max()
         self.assertLessEqual(a__			,    a__			,    F"Difference between torch and flax is {diff} (>= {tol}).")




     def 		snake_case_		(					self):
         A__					=       self.prepare_config_and_inputs()
         self.check_vision_text_dual_encoder_model(**a__)




     def 		snake_case_		(					self):
         A__					=       self.prepare_config_and_inputs()
         self.check_model_from_pretrained_configs(**a__)




     def 		snake_case_		(					self):
         A__					=       self.prepare_config_and_inputs()
         self.check_vision_text_dual_encoder_from_pretrained(**a__)




     def 		snake_case_		(					self):
         A__					=       self.prepare_config_and_inputs()
         self.check_save_load(**a__)




     def 		snake_case_		(					self):
         A__					=       self.prepare_config_and_inputs()
         self.check_vision_text_output_attention(**a__)




     @slow
     def 		snake_case_		(					self):
         A__			,						A__					=       self.get_pretrained_model_and_inputs()

         A__					=       model_a(**a__)
         A__					=       outputs[0].numpy()

         with tempfile.TemporaryDirectory() as tmp_dirname:
             model_a.save_pretrained(a__)
             A__					=       TFVisionTextDualEncoderModel.from_pretrained(a__)

             A__					=       model_a(**a__)
             A__					=       after_outputs[0].numpy()
             A__					=       np.amax(np.abs(out_a - out_a))
             self.assertLessEqual(a__			,    1e-5)







@require_tf
class      _UpperCAmelCase      (							A__      ,   unittest.TestCase  ):




     def 		snake_case_		(					self):
         A__					=       TFVisionTextDualEncoderModel.from_vision_text_pretrained(
             '''hf-internal-testing/tiny-random-vit'''			,    '''hf-internal-testing/tiny-random-bert''')
         A__					=       1_3
         A__					=       floats_tensor(
             [
                 batch_size,
                 model.vision_model.config.num_channels,
                 model.vision_model.config.image_size,
                 model.vision_model.config.image_size,
             ])
         A__					=       ids_tensor([batch_size, 4]			,    model.text_model.config.vocab_size)
         A__					=       random_attention_mask([batch_size, 4])
         A__					=       {'''pixel_values''': pixel_values, '''input_ids''': input_ids, '''attention_mask''': attention_mask}

         return model, inputs




     def 		snake_case_		(					self			,    a__			,    a__):
         A__					=       TFViTModel(a__			,    name='''vision_model''')
         A__					=       TFBertModel(a__			,    name='''text_model''')
         return vision_model, text_model




     def 		snake_case_		(					self):
         A__					=       TFViTModelTester(self)
         A__					=       TFBertModelTester(self)
         A__					=       vit_model_tester.prepare_config_and_inputs()
         A__					=       bert_model_tester.prepare_config_and_inputs()

         A__			,						A__			,						A__					=       vision_config_and_inputs

         (
             (
             A__
         )			,						(
             A__
         )			,						(
             A__
         )			,						(
             A__
         )			,						(
             A__
         )			,						(
             A__
         )			,						(
             A__
         )			,						
         )					=       text_config_and_inputs

         return {
             "text_config": text_config,
             "vision_config": vision_config,
             "pixel_values": pixel_values,
             "attention_mask": input_mask,
             "input_ids": input_ids,
             "text_token_type_ids": token_type_ids,
             "text_sequence_labels": sequence_labels,
             "text_token_labels": token_labels,
             "text_choice_labels": choice_labels,
         }







@require_tf
class      _UpperCAmelCase      (							A__      ,   unittest.TestCase  ):




     def 		snake_case_		(					self):
         # DeiT repo doesn't have TF weights, but we don't actually use the weights at all so let's
         # just reinitialize it.
         A__					=       TFVisionTextDualEncoderModel.from_vision_text_pretrained(
             '''Rocketknight1/tiny-random-deit-tf'''			,    '''hf-internal-testing/tiny-random-roberta''')
         A__					=       1_3
         A__					=       floats_tensor(
             [
                 batch_size,
                 model.vision_model.config.num_channels,
                 model.vision_model.config.image_size,
                 model.vision_model.config.image_size,
             ])
         A__					=       ids_tensor([batch_size, 4]			,    model.text_model.config.vocab_size)
         A__					=       random_attention_mask([batch_size, 4])
         A__					=       {'''pixel_values''': pixel_values, '''input_ids''': input_ids, '''attention_mask''': attention_mask}

         return model, inputs




     def 		snake_case_		(					self			,    a__			,    a__			,    a__			,    a__			,    a__=None			,    **a__):
         A__			,						A__					=       self.get_vision_text_model(a__			,    a__)
         A__					=       TFVisionTextDualEncoderModel(vision_model=a__			,    text_model=a__)

         A__					=       model(
             input_ids=a__			,    pixel_values=a__			,    attention_mask=a__			,    output_attentions=a__)

         A__					=       output.vision_model_output.attentions
         self.assertEqual(len(a__)			,    vision_config.num_hidden_layers)

         # in DEiT, the seq_len equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens)
         A__					=       to_atuple(vision_model.config.image_size)
         A__					=       to_atuple(vision_model.config.patch_size)
         A__					=       (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
         A__					=       num_patches + 2
         self.assertEqual(vision_attentions[0].shape[-3:]			,    (vision_config.num_attention_heads, seq_len, seq_len))

         A__					=       output.text_model_output.attentions
         self.assertEqual(len(a__)			,    text_config.num_hidden_layers)

         self.assertEqual(
             text_attentions[0].shape[-3:]			,    (text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1])			,    )




     def 		snake_case_		(					self			,    a__			,    a__):
         A__					=       TFDeiTModel(a__			,    name='''vision_model''')
         A__					=       TFRobertaModel(a__			,    name='''text_model''')
         return vision_model, text_model




     def 		snake_case_		(					self):
         A__					=       TFDeiTModelTester(self)
         A__					=       TFRobertaModelTester(self)
         A__					=       vit_model_tester.prepare_config_and_inputs()
         A__					=       bert_model_tester.prepare_config_and_inputs()

         A__			,						A__			,						A__					=       vision_config_and_inputs

         (
             (
             A__
         )			,						(
             A__
         )			,						(
             A__
         )			,						(
             A__
         )			,						(
             A__
         )			,						(
             A__
         )			,						(
             A__
         )			,						
         )					=       text_config_and_inputs

         return {
             "text_config": text_config,
             "vision_config": vision_config,
             "pixel_values": pixel_values,
             "attention_mask": input_mask,
             "input_ids": input_ids,
             "text_token_type_ids": token_type_ids,
             "text_sequence_labels": sequence_labels,
             "text_token_labels": token_labels,
             "text_choice_labels": choice_labels,
         }







@require_tf
class      _UpperCAmelCase      (							A__      ,   unittest.TestCase  ):




     def 		snake_case_		(					self):
         A__					=       TFVisionTextDualEncoderModel.from_vision_text_pretrained(
             '''Rocketknight1/tiny-random-clip-tf'''			,    '''hf-internal-testing/tiny-random-bert''')
         A__					=       1_3
         A__					=       floats_tensor(
             [
                 batch_size,
                 model.vision_model.config.num_channels,
                 model.vision_model.config.image_size,
                 model.vision_model.config.image_size,
             ])
         A__					=       ids_tensor([batch_size, 4]			,    model.text_model.config.vocab_size)
         A__					=       random_attention_mask([batch_size, 4])
         A__					=       {'''pixel_values''': pixel_values, '''input_ids''': input_ids, '''attention_mask''': attention_mask}

         return model, inputs




     def 		snake_case_		(					self			,    a__			,    a__):
         A__					=       TFCLIPVisionModel(a__			,    name='''vision_model''')
         A__					=       TFBertModel(a__			,    name='''text_model''')
         return vision_model, text_model




     def 		snake_case_		(					self):
         A__					=       TFCLIPVisionModelTester(self)
         A__					=       TFBertModelTester(self)
         A__					=       clip_model_tester.prepare_config_and_inputs()
         A__					=       bert_model_tester.prepare_config_and_inputs()

         A__			,						A__					=       vision_config_and_inputs

         (
             (
             A__
         )			,						(
             A__
         )			,						(
             A__
         )			,						(
             A__
         )			,						(
             A__
         )			,						(
             A__
         )			,						(
             A__
         )			,						
         )					=       text_config_and_inputs

         return {
             "text_config": text_config,
             "vision_config": vision_config,
             "pixel_values": pixel_values,
             "attention_mask": input_mask,
             "input_ids": input_ids,
             "text_token_type_ids": token_type_ids,
             "text_sequence_labels": sequence_labels,
             "text_token_labels": token_labels,
             "text_choice_labels": choice_labels,
         }







@require_vision
@require_tf
class      _UpperCAmelCase      (							unittest.TestCase  ):




     @slow
     def 		snake_case_		(					self):
         A__					=       TFVisionTextDualEncoderModel.from_pretrained(
             '''clip-italian/clip-italian'''			,    logit_scale_init_value=1.0			,    from_pt=a__)
         A__					=       VisionTextDualEncoderProcessor.from_pretrained('''clip-italian/clip-italian''')

         A__					=       Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''')
         A__					=       processor(
             text=['''una foto di un gatto''', '''una foto di un cane''']			,    images=a__			,    padding=a__			,    return_tensors='''np''')

         A__					=       model(**a__)

         # verify the logits
         self.assertEqual(outputs.logits_per_image.shape			,    (inputs.pixel_values.shape[0], inputs.input_ids.shape[0]))
         self.assertEqual(
             outputs.logits_per_text.shape			,    (inputs.input_ids.shape[0], inputs.pixel_values.shape[0])			,    )

         A__					=       np.array([[1.2_2_8_4_7_2_7, 0.3_1_0_4_1_2_2]])

         self.assertTrue(np.allclose(outputs.logits_per_image.numpy()			,    a__			,    atol=1e-3))
