



import inspect
import unittest

import numpy as np

from tests.test_modeling_common import floats_tensor
from transformers import MaskaFormerConfig, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import cached_property

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
  import torch

  from transformers import MaskaFormerForUniversalSegmentation, MaskaFormerModel

  if is_vision_available():
    from transformers import MaskaFormerImageProcessor

if is_vision_available():
  from PIL import Image



class 			__lowerCAmelCase  :




 def __init__(    self						,					__UpperCAmelCase						,					__UpperCAmelCase=2						,					__UpperCAmelCase=True						,					__UpperCAmelCase=False						,					__UpperCAmelCase=10						,					__UpperCAmelCase=3						,					__UpperCAmelCase=32 * 8						,					__UpperCAmelCase=32 * 8						,					__UpperCAmelCase=4						,					__UpperCAmelCase=64						,					):



    '''simple docstring'''
    __lowerCamelCase    				=     parent
    __lowerCamelCase    				=     batch_size
    __lowerCamelCase    				=     is_training
    __lowerCamelCase    				=     use_auxiliary_loss
    __lowerCamelCase    				=     num_queries
    __lowerCamelCase    				=     num_channels
    __lowerCamelCase    				=     min_size
    __lowerCamelCase    				=     max_size
    __lowerCamelCase    				=     num_labels
    __lowerCamelCase    				=     hidden_dim
    __lowerCamelCase    				=     hidden_dim




 def 							lowerCamelCase   (    self					):



    '''simple docstring'''
    __lowerCamelCase    				=     floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size]					).to(
        __UpperCAmelCase					)

    __lowerCamelCase    				=     torch.ones([self.batch_size, self.min_size, self.max_size]						,					device=__UpperCAmelCase					)

    __lowerCamelCase    				=     (
        torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size]						,					device=__UpperCAmelCase					) > 0.5
    ).float()
    __lowerCamelCase    				=     (torch.rand((self.batch_size, self.num_labels)						,					device=__UpperCAmelCase					) > 0.5).long()

    __lowerCamelCase    				=     self.get_config()
    return config, pixel_values, pixel_mask, mask_labels, class_labels




 def 							lowerCamelCase   (    self					):



    '''simple docstring'''
    __lowerCamelCase    				=     MaskaFormerConfig(
        hidden_size=self.hidden_dim						,					)
    __lowerCamelCase    				=     self.num_queries
    __lowerCamelCase    				=     self.num_labels

    __lowerCamelCase    				=     [1, 1, 1, 1]
    __lowerCamelCase    				=     self.num_channels

    __lowerCamelCase    				=     64
    __lowerCamelCase    				=     128
    __lowerCamelCase    				=     self.hidden_dim
    __lowerCamelCase    				=     self.hidden_dim
    __lowerCamelCase    				=     self.hidden_dim
    return config




 def 							lowerCamelCase   (    self					):



    '''simple docstring'''
    __lowerCamelCase				,__lowerCamelCase				,__lowerCamelCase				,__lowerCamelCase				,__lowerCamelCase    				=     self.prepare_config_and_inputs()
    __lowerCamelCase    				=     {'''pixel_values''': pixel_values, '''pixel_mask''': pixel_mask}
    return config, inputs_dict




 def 							lowerCamelCase   (    self						,					__UpperCAmelCase						,					__UpperCAmelCase					):



    '''simple docstring'''
    __lowerCamelCase    				=     output.encoder_hidden_states
    __lowerCamelCase    				=     output.pixel_decoder_hidden_states
    __lowerCamelCase    				=     output.transformer_decoder_hidden_states

    self.parent.assertTrue(len(__UpperCAmelCase					)						,					len(config.backbone_config.depths					)					)
    self.parent.assertTrue(len(__UpperCAmelCase					)						,					len(config.backbone_config.depths					)					)
    self.parent.assertTrue(len(__UpperCAmelCase					)						,					config.decoder_layers					)




 def 							lowerCamelCase   (    self						,					__UpperCAmelCase						,					__UpperCAmelCase						,					__UpperCAmelCase						,					__UpperCAmelCase=False					):



    '''simple docstring'''
    with torch.no_grad():
       __lowerCamelCase    				=     MaskaFormerModel(config=__UpperCAmelCase					)
       model.to(__UpperCAmelCase					)
       model.eval()

       __lowerCamelCase    				=     model(pixel_values=__UpperCAmelCase						,					pixel_mask=__UpperCAmelCase					)
       __lowerCamelCase    				=     model(__UpperCAmelCase						,					output_hidden_states=__UpperCAmelCase					)

    self.parent.assertEqual(
        output.transformer_decoder_last_hidden_state.shape						,					(self.batch_size, self.num_queries, self.hidden_dim)						,					)
    # let's ensure the other two hidden state exists
    self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None					)
    self.parent.assertTrue(output.encoder_last_hidden_state is not None					)

    if output_hidden_states:
       self.check_output_hidden_state(__UpperCAmelCase						,					__UpperCAmelCase					)




 def 							lowerCamelCase   (    self						,					__UpperCAmelCase						,					__UpperCAmelCase						,					__UpperCAmelCase						,					__UpperCAmelCase						,					__UpperCAmelCase					):



    '''simple docstring'''
    __lowerCamelCase    				=     MaskaFormerForUniversalSegmentation(config=__UpperCAmelCase					)
    model.to(__UpperCAmelCase					)
    model.eval()

    def comm_check_on_output(__UpperCAmelCase					):
       # let's still check that all the required stuff is there
       self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None					)
       self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None					)
       self.parent.assertTrue(result.encoder_last_hidden_state is not None					)
       # okay, now we need to check the logits shape
       # due to the encoder compression, masks have a //4 spatial size
       self.parent.assertEqual(
           result.masks_queries_logits.shape						,					(self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4)						,					)
       # + 1 for null class
       self.parent.assertEqual(
           result.class_queries_logits.shape						,					(self.batch_size, self.num_queries, self.num_labels + 1)					)

    with torch.no_grad():
       __lowerCamelCase    				=     model(pixel_values=__UpperCAmelCase						,					pixel_mask=__UpperCAmelCase					)
       __lowerCamelCase    				=     model(__UpperCAmelCase					)

       comm_check_on_output(__UpperCAmelCase					)

       __lowerCamelCase    				=     model(
           pixel_values=__UpperCAmelCase						,					pixel_mask=__UpperCAmelCase						,					mask_labels=__UpperCAmelCase						,					class_labels=__UpperCAmelCase					)

    comm_check_on_output(__UpperCAmelCase					)

    self.parent.assertTrue(result.loss is not None					)
    self.parent.assertEqual(result.loss.shape						,					torch.Size([1]					)					)



@require_torch
class 			__lowerCAmelCase  (						lowerCAmelCase__	,						lowerCAmelCase__	,						unittest.TestCase ):
 lowerCAmelCase__							       =	(MaskaFormerModel, MaskaFormerForUniversalSegmentation) if is_torch_available() else ()
 lowerCAmelCase__							       =	{"""feature-extraction""": MaskaFormerModel} if is_torch_available() else {}

 lowerCAmelCase__							       =	False
 lowerCAmelCase__							       =	False
 lowerCAmelCase__							       =	False
 lowerCAmelCase__							       =	False




 def 							lowerCamelCase   (    self					):



    '''simple docstring'''
    __lowerCamelCase    				=     MaskaFormerModelTester(self					)
    __lowerCamelCase    				=     ConfigTester(self						,					config_class=__UpperCAmelCase						,					has_text_modality=__UpperCAmelCase					)




 def 							lowerCamelCase   (    self					):



    '''simple docstring'''
    self.config_tester.run_common_tests()




 def 							lowerCamelCase   (    self					):



    '''simple docstring'''
    __lowerCamelCase				,__lowerCamelCase    				=     self.model_tester.prepare_config_and_inputs_for_common()
    self.model_tester.create_and_check_maskaformer_model(__UpperCAmelCase						,					**__UpperCAmelCase						,					output_hidden_states=__UpperCAmelCase					)




 def 							lowerCamelCase   (    self					):



    '''simple docstring'''
    __lowerCamelCase    				=     self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_maskaformer_instance_segmentation_head_model(*__UpperCAmelCase					)




 @unittest.skip(reason='''Mask2Former does not use inputs_embeds'''					)
 def 							lowerCamelCase   (    self					):



    '''simple docstring'''
    pass




 @unittest.skip(reason='''Mask2Former does not have a get_input_embeddings method'''					)
 def 							lowerCamelCase   (    self					):



    '''simple docstring'''
    pass




 @unittest.skip(reason='''Mask2Former is not a generative model'''					)
 def 							lowerCamelCase   (    self					):



    '''simple docstring'''
    pass




 @unittest.skip(reason='''Mask2Former does not use token embeddings'''					)
 def 							lowerCamelCase   (    self					):



    '''simple docstring'''
    pass




 @require_torch_multi_gpu
 @unittest.skip(
     reason='''Mask2Former has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`'''					)
 def 							lowerCamelCase   (    self					):



    '''simple docstring'''
    pass




 @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.'''					)
 def 							lowerCamelCase   (    self					):



    '''simple docstring'''
    pass




 def 							lowerCamelCase   (    self					):



    '''simple docstring'''
    __lowerCamelCase				,__lowerCamelCase    				=     self.model_tester.prepare_config_and_inputs_for_common()

    for model_class in self.all_model_classes:
       __lowerCamelCase    				=     model_class(__UpperCAmelCase					)
       __lowerCamelCase    				=     inspect.signature(model.forward					)
       # signature.parameters is an OrderedDict => so arg_names order is deterministic
       __lowerCamelCase    				=     [*signature.parameters.keys()]

       __lowerCamelCase    				=     ['''pixel_values''']
       self.assertListEqual(arg_names[:1]						,					__UpperCAmelCase					)




 @slow
 def 							lowerCamelCase   (    self					):



    '''simple docstring'''
    for model_name in ["facebook/mask2former-swin-small-coco-instance"]:
       __lowerCamelCase    				=     MaskaFormerModel.from_pretrained(__UpperCAmelCase					)
       self.assertIsNotNone(__UpperCAmelCase					)




 def 							lowerCamelCase   (    self					):



    '''simple docstring'''
    __lowerCamelCase    				=     (self.model_tester.min_size,) * 2
    __lowerCamelCase    				=     {
        '''pixel_values''': torch.randn((2, 3, *size)						,					device=__UpperCAmelCase					),
        '''mask_labels''': torch.randn((2, 10, *size)						,					device=__UpperCAmelCase					),
        '''class_labels''': torch.zeros(2						,					10						,					device=__UpperCAmelCase					).long(),
    }
    __lowerCamelCase    				=     self.model_tester.get_config()

    __lowerCamelCase    				=     MaskaFormerForUniversalSegmentation(__UpperCAmelCase					).to(__UpperCAmelCase					)
    __lowerCamelCase    				=     model(**__UpperCAmelCase					)
    self.assertTrue(outputs.loss is not None					)




 def 							lowerCamelCase   (    self					):



    '''simple docstring'''
    __lowerCamelCase				,__lowerCamelCase    				=     self.model_tester.prepare_config_and_inputs_for_common()
    self.model_tester.create_and_check_maskaformer_model(__UpperCAmelCase						,					**__UpperCAmelCase						,					output_hidden_states=__UpperCAmelCase					)




 def 							lowerCamelCase   (    self					):



    '''simple docstring'''
    __lowerCamelCase				,__lowerCamelCase    				=     self.model_tester.prepare_config_and_inputs_for_common()

    for model_class in self.all_model_classes:
       __lowerCamelCase    				=     model_class(__UpperCAmelCase					).to(__UpperCAmelCase					)
       __lowerCamelCase    				=     model(**__UpperCAmelCase						,					output_attentions=__UpperCAmelCase					)
       self.assertTrue(outputs.attentions is not None					)




 def 							lowerCamelCase   (    self					):



    '''simple docstring'''
    if not self.model_tester.is_training:
       return

    __lowerCamelCase    				=     self.all_model_classes[1]
    __lowerCamelCase				,__lowerCamelCase				,__lowerCamelCase				,__lowerCamelCase				,__lowerCamelCase    				=     self.model_tester.prepare_config_and_inputs()

    __lowerCamelCase    				=     model_class(__UpperCAmelCase					)
    model.to(__UpperCAmelCase					)
    model.train()

    __lowerCamelCase    				=     model(__UpperCAmelCase						,					mask_labels=__UpperCAmelCase						,					class_labels=__UpperCAmelCase					).loss
    loss.backward()




 def 							lowerCamelCase   (    self					):



    '''simple docstring'''
    __lowerCamelCase    				=     self.all_model_classes[1]
    __lowerCamelCase				,__lowerCamelCase				,__lowerCamelCase				,__lowerCamelCase				,__lowerCamelCase    				=     self.model_tester.prepare_config_and_inputs()
    __lowerCamelCase    				=     True
    __lowerCamelCase    				=     True

    __lowerCamelCase    				=     model_class(__UpperCAmelCase					).to(__UpperCAmelCase					)
    model.train()

    __lowerCamelCase    				=     model(__UpperCAmelCase						,					mask_labels=__UpperCAmelCase						,					class_labels=__UpperCAmelCase					)

    __lowerCamelCase    				=     outputs.encoder_hidden_states[0]
    encoder_hidden_states.retain_grad()

    __lowerCamelCase    				=     outputs.pixel_decoder_hidden_states[0]
    pixel_decoder_hidden_states.retain_grad()

    __lowerCamelCase    				=     outputs.transformer_decoder_hidden_states[0]
    transformer_decoder_hidden_states.retain_grad()

    __lowerCamelCase    				=     outputs.attentions[0]
    attentions.retain_grad()

    outputs.loss.backward(retain_graph=__UpperCAmelCase					)

    self.assertIsNotNone(encoder_hidden_states.grad					)
    self.assertIsNotNone(pixel_decoder_hidden_states.grad					)
    self.assertIsNotNone(transformer_decoder_hidden_states.grad					)
    self.assertIsNotNone(attentions.grad					)



a_								=       1E-4





def 		a__      (		):
   __lowerCamelCase    				=     Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''				)
   return image





@require_vision
@slow
class 			__lowerCAmelCase  (						unittest.TestCase ):




 @cached_property
 def 							lowerCamelCase   (    self					):



    '''simple docstring'''
    return "facebook/mask2former-swin-small-coco-instance"




 @cached_property
 def 							lowerCamelCase   (    self					):



    '''simple docstring'''
    return MaskaFormerImageProcessor.from_pretrained(self.model_checkpoints					) if is_vision_available() else None




 def 							lowerCamelCase   (    self					):



    '''simple docstring'''
    __lowerCamelCase    				=     MaskaFormerModel.from_pretrained(self.model_checkpoints					).to(__UpperCAmelCase					)
    __lowerCamelCase    				=     self.default_image_processor
    __lowerCamelCase    				=     prepare_img()
    __lowerCamelCase    				=     image_processor(__UpperCAmelCase						,					return_tensors='''pt'''					).to(__UpperCAmelCase					)
    __lowerCamelCase    				=     inputs['''pixel_values'''].shape
    # check size is divisible by 32
    self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0					)
    # check size
    self.assertEqual(__UpperCAmelCase						,					(1, 3, 384, 384)					)

    with torch.no_grad():
       __lowerCamelCase    				=     model(**__UpperCAmelCase					)

    __lowerCamelCase    				=     torch.tensor(
        [[-0.2_790, -1.0_717, -1.1_668], [-0.5_128, -0.3_128, -0.4_987], [-0.5_832, 0.1_971, -0.0_197]]					).to(__UpperCAmelCase					)
    self.assertTrue(
        torch.allclose(
            outputs.encoder_last_hidden_state[0, 0, :3, :3]						,					__UpperCAmelCase						,					atol=__UpperCAmelCase					)					)

    __lowerCamelCase    				=     torch.tensor(
        [[0.8_973, 1.1_847, 1.1_776], [1.1_934, 1.5_040, 1.5_128], [1.1_153, 1.4_486, 1.4_951]]					).to(__UpperCAmelCase					)
    self.assertTrue(
        torch.allclose(
            outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3]						,					__UpperCAmelCase						,					atol=__UpperCAmelCase					)					)

    __lowerCamelCase    				=     torch.tensor(
        [[2.1_152, 1.7_000, -0.8_603], [1.5_808, 1.8_004, -0.9_353], [1.6_043, 1.7_495, -0.5_999]]					).to(__UpperCAmelCase					)
    self.assertTrue(
        torch.allclose(
            outputs.transformer_decoder_last_hidden_state[0, :3, :3]						,					__UpperCAmelCase						,					atol=__UpperCAmelCase					)					)




 def 							lowerCamelCase   (    self					):



    '''simple docstring'''
    __lowerCamelCase    				=     MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints					).to(__UpperCAmelCase					).eval()
    __lowerCamelCase    				=     self.default_image_processor
    __lowerCamelCase    				=     prepare_img()
    __lowerCamelCase    				=     image_processor(__UpperCAmelCase						,					return_tensors='''pt'''					).to(__UpperCAmelCase					)
    __lowerCamelCase    				=     inputs['''pixel_values'''].shape
    # check size is divisible by 32
    self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0					)
    # check size
    self.assertEqual(__UpperCAmelCase						,					(1, 3, 384, 384)					)

    with torch.no_grad():
       __lowerCamelCase    				=     model(**__UpperCAmelCase					)
    # masks_queries_logits
    __lowerCamelCase    				=     outputs.masks_queries_logits
    self.assertEqual(
        masks_queries_logits.shape						,					(1, model.config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4)					)
    __lowerCamelCase    				=     [
        [-8.7_839, -9.0_056, -8.8_121],
        [-7.4_104, -7.0_313, -6.5_401],
        [-6.6_105, -6.3_427, -6.4_675],
    ]
    __lowerCamelCase    				=     torch.tensor(__UpperCAmelCase					).to(__UpperCAmelCase					)
    self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3]						,					__UpperCAmelCase						,					atol=__UpperCAmelCase					)					)
    # class_queries_logits
    __lowerCamelCase    				=     outputs.class_queries_logits
    self.assertEqual(class_queries_logits.shape						,					(1, model.config.num_queries, model.config.num_labels + 1)					)
    __lowerCamelCase    				=     torch.tensor(
        [
            [1.8_324, -8.0_835, -4.1_922],
            [0.8_450, -9.0_050, -3.6_053],
            [0.3_045, -7.7_293, -3.0_275],
        ]					).to(__UpperCAmelCase					)
    self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3]						,					__UpperCAmelCase						,					atol=__UpperCAmelCase					)					)




 def 							lowerCamelCase   (    self					):



    '''simple docstring'''
    __lowerCamelCase    				=     MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints					).to(__UpperCAmelCase					).eval()
    __lowerCamelCase    				=     self.default_image_processor

    __lowerCamelCase    				=     image_processor(
        [np.zeros((3, 800, 1333)					), np.zeros((3, 800, 1333)					)]						,					segmentation_maps=[np.zeros((384, 384)					).astype(np.floataa					), np.zeros((384, 384)					).astype(np.floataa					)]						,					return_tensors='''pt'''						,					)

    __lowerCamelCase    				=     inputs['''pixel_values'''].to(__UpperCAmelCase					)
    __lowerCamelCase    				=     [el.to(__UpperCAmelCase					) for el in inputs['''mask_labels''']]
    __lowerCamelCase    				=     [el.to(__UpperCAmelCase					) for el in inputs['''class_labels''']]

    with torch.no_grad():
       __lowerCamelCase    				=     model(**__UpperCAmelCase					)

    self.assertTrue(outputs.loss is not None					)











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()
a_								=       logging.get_logger(__name__)

a_								=       """Hello, World!"""
a_								=       """en_XX"""





def 		a__      (		_UpperCamelCase      :			str			,_UpperCamelCase      :			str			,_UpperCamelCase      :			bool				):
   __lowerCamelCase    				=     Path('''data_bin'''				)
   __lowerCamelCase    				=     FairseqXmodModel.from_pretrained(
       model_name_or_path=str(Path(_UpperCamelCase				).parent				)			,checkpoint_file=Path(_UpperCamelCase				).name			,_name='''xmod_base'''			,arch='''xmod_base'''			,task='''multilingual_masked_lm'''			,data_name_or_path=str(_UpperCamelCase				)			,bpe='''sentencepiece'''			,sentencepiece_model=str(Path(_UpperCamelCase				).parent / '''sentencepiece.bpe.model'''				)			,src_dict=str(data_dir / '''dict.txt'''				)			,)
   xmod.eval()  # disable dropout
   print(_UpperCamelCase				)

   __lowerCamelCase    				=     xmod.model.encoder.sentence_encoder
   __lowerCamelCase    				=     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_14			,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:
      __lowerCamelCase    				=     xmod.model.classification_heads['''mnli'''].out_proj.weight.shape[0]

   print('''Our X-MOD config:'''			,_UpperCamelCase				)

   __lowerCamelCase    				=     XmodForSequenceClassification(_UpperCamelCase				) if classification_head else XmodForMaskedLM(_UpperCamelCase				)
   model.eval()

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

   __lowerCamelCase    				=     xmod_sent_encoder.layernorm_embedding.weight
   __lowerCamelCase    				=     xmod_sent_encoder.layernorm_embedding.bias

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

      # self attention
      __lowerCamelCase    				=     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.'''				)

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

      # self-attention output
      __lowerCamelCase    				=     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.'''				)
      __lowerCamelCase    				=     xmod_layer.self_attn.out_proj.weight
      __lowerCamelCase    				=     xmod_layer.self_attn.out_proj.bias
      __lowerCamelCase    				=     xmod_layer.self_attn_layer_norm.weight
      __lowerCamelCase    				=     xmod_layer.self_attn_layer_norm.bias

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

      # output
      __lowerCamelCase    				=     layer.output
      if bert_output.dense.weight.shape != xmod_layer.fca.weight.shape:
         raise AssertionError('''Dimensions of feed-forward weights do not match.'''				)
      __lowerCamelCase    				=     xmod_layer.fca.weight
      __lowerCamelCase    				=     xmod_layer.fca.bias
      __lowerCamelCase    				=     xmod_layer.final_layer_norm.weight
      __lowerCamelCase    				=     xmod_layer.final_layer_norm.bias
      if bert_output.adapter_layer_norm is not None:
         __lowerCamelCase    				=     xmod_layer.adapter_layer_norm.weight
         __lowerCamelCase    				=     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():
         __lowerCamelCase    				=     bert_output.adapter_modules[lang_code]
         __lowerCamelCase    				=     xmod_layer.adapter_modules[lang_code]
         __lowerCamelCase    				=     from_adapter.fca.weight
         __lowerCamelCase    				=     from_adapter.fca.bias
         __lowerCamelCase    				=     from_adapter.fca.weight
         __lowerCamelCase    				=     from_adapter.fca.bias

      # end of layer

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

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

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

   __lowerCamelCase    				=     model(_UpperCamelCase				)[0]
   if classification_head:
      __lowerCamelCase    				=     xmod.model.classification_heads['''mnli'''](xmod.extract_features(_UpperCamelCase				)				)
   else:
      __lowerCamelCase    				=     xmod.model(_UpperCamelCase			,lang_id=[SAMPLE_LANGUAGE]				)[0]
   print(our_output.shape			,their_output.shape				)
   __lowerCamelCase    				=     torch.max(torch.abs(our_output - their_output				)				).item()
   print(F"""max_absolute_diff = {max_absolute_diff}"""				)  # ~ 1e-7
   __lowerCamelCase    				=     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'''				)

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


if __name__ == "__main__":
  a_								=       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."""
  )
  a_								=       parser.parse_args()
  convert_xmod_checkpoint_to_pytorch(
      args.xmod_checkpoint_path, args.pytorch_dump_folder_path, args.classification_head
  )






