


import argparse
import json

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

from transformers import ViTImageProcessor, ViTMSNConfig, ViTMSNModel
from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD


torch.set_grad_enabled(False)



def 							UpperCamelCase_( lowerCamelCase_				,					lowerCamelCase_=False					)       ->		str:
    _lowercase			:				List[str] 						=						[]
    for i in range(config.num_hidden_layers					):
        # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms
        rename_keys.append((F'''module.blocks.{i}.norm1.weight''', F'''vit.encoder.layer.{i}.layernorm_before.weight''')					)
        rename_keys.append((F'''module.blocks.{i}.norm1.bias''', F'''vit.encoder.layer.{i}.layernorm_before.bias''')					)
        rename_keys.append(
            (F'''module.blocks.{i}.attn.proj.weight''', F'''vit.encoder.layer.{i}.attention.output.dense.weight''')					)
        rename_keys.append((F'''module.blocks.{i}.attn.proj.bias''', F'''vit.encoder.layer.{i}.attention.output.dense.bias''')					)
        rename_keys.append((F'''module.blocks.{i}.norm2.weight''', F'''vit.encoder.layer.{i}.layernorm_after.weight''')					)
        rename_keys.append((F'''module.blocks.{i}.norm2.bias''', F'''vit.encoder.layer.{i}.layernorm_after.bias''')					)
        rename_keys.append((F'''module.blocks.{i}.mlp.fc1.weight''', F'''vit.encoder.layer.{i}.intermediate.dense.weight''')					)
        rename_keys.append((F'''module.blocks.{i}.mlp.fc1.bias''', F'''vit.encoder.layer.{i}.intermediate.dense.bias''')					)
        rename_keys.append((F'''module.blocks.{i}.mlp.fc2.weight''', F'''vit.encoder.layer.{i}.output.dense.weight''')					)
        rename_keys.append((F'''module.blocks.{i}.mlp.fc2.bias''', F'''vit.encoder.layer.{i}.output.dense.bias''')					)

    # projection layer + position embeddings
    rename_keys.extend(
        [
            ('module.cls_token', 'vit.embeddings.cls_token'),
            ('module.patch_embed.proj.weight', 'vit.embeddings.patch_embeddings.projection.weight'),
            ('module.patch_embed.proj.bias', 'vit.embeddings.patch_embeddings.projection.bias'),
            ('module.pos_embed', 'vit.embeddings.position_embeddings'),
        ]					)

    if base_model:
        # layernorm + pooler
        rename_keys.extend(
            [
                ('module.norm.weight', 'layernorm.weight'),
                ('module.norm.bias', 'layernorm.bias'),
            ]					)

        # if just the base model, we should remove "vit" from all keys that start with "vit"
        _lowercase			:				str 						=						[(pair[0], pair[1][4:]) if pair[1].startswith('vit'					) else pair for pair in rename_keys]
    else:
        # layernorm + classification head
        rename_keys.extend(
            [
                ('norm.weight', 'vit.layernorm.weight'),
                ('norm.bias', 'vit.layernorm.bias'),
                ('head.weight', 'classifier.weight'),
                ('head.bias', 'classifier.bias'),
            ]					)

    return rename_keys



def 							UpperCamelCase_( lowerCamelCase_				,					lowerCamelCase_				,					lowerCamelCase_=False					)       ->		str:
    for i in range(config.num_hidden_layers					):
        if base_model:
            _lowercase			:				List[Any] 						=						''
        else:
            _lowercase			:				Dict 						=						'vit.'
        # read in weights + bias of input projection layer (in timm, this is a single matrix + bias)
        _lowercase			:				Any 						=						state_dict.pop(F'''module.blocks.{i}.attn.qkv.weight'''					)
        _lowercase			:				str 						=						state_dict.pop(F'''module.blocks.{i}.attn.qkv.bias'''					)
        # next, add query, keys and values (in that order) to the state dict
        _lowercase			:				int 						=						in_proj_weight[
            : config.hidden_size, :
        ]
        _lowercase			:				str 						=						in_proj_bias[: config.hidden_size]
        _lowercase			:				Optional[int] 						=						in_proj_weight[
            config.hidden_size : config.hidden_size * 2, :
        ]
        _lowercase			:				Optional[Any] 						=						in_proj_bias[
            config.hidden_size : config.hidden_size * 2
        ]
        _lowercase			:				List[str] 						=						in_proj_weight[
            -config.hidden_size :, :
        ]
        _lowercase			:				Tuple 						=						in_proj_bias[-config.hidden_size :]



def 							UpperCamelCase_( lowerCamelCase_					)       ->		str:
    _lowercase			:				Dict 						=						['head.weight', 'head.bias']
    for k in ignore_keys:
        state_dict.pop(lowerCamelCase_				,					lowerCamelCase_					)



def 							UpperCamelCase_( lowerCamelCase_					)       ->		Optional[int]:
    # projection head is used in the self-supervised pre-training in MSN,
    # for downstream task it's not needed.
    _lowercase			:				List[str] 						=						[
        'module.fc.fc1.weight',
        'module.fc.fc1.bias',
        'module.fc.bn1.weight',
        'module.fc.bn1.bias',
        'module.fc.bn1.running_mean',
        'module.fc.bn1.running_var',
        'module.fc.bn1.num_batches_tracked',
        'module.fc.fc2.weight',
        'module.fc.fc2.bias',
        'module.fc.bn2.weight',
        'module.fc.bn2.bias',
        'module.fc.bn2.running_mean',
        'module.fc.bn2.running_var',
        'module.fc.bn2.num_batches_tracked',
        'module.fc.fc3.weight',
        'module.fc.fc3.bias',
    ]
    for k in ignore_keys:
        state_dict.pop(lowerCamelCase_				,					lowerCamelCase_					)



def 							UpperCamelCase_( lowerCamelCase_				,					lowerCamelCase_				,					lowerCamelCase_					)       ->		Optional[int]:
    _lowercase			:				Union[str, Any] 						=						dct.pop(lowerCamelCase_					)
    _lowercase			:				str 						=						val



def 							UpperCamelCase_( lowerCamelCase_				,					lowerCamelCase_					)       ->		int:
    _lowercase			:				Any 						=						ViTMSNConfig()
    _lowercase			:				List[str] 						=						1000

    _lowercase			:				List[Any] 						=						'datasets/huggingface/label-files'
    _lowercase			:				Dict 						=						'imagenet-1k-id2label.json'
    _lowercase			:				Optional[Any] 						=						json.load(open(hf_hub_download(lowerCamelCase_				,					lowerCamelCase_					)				,					'r'					)					)
    _lowercase			:				Tuple 						=						{int(lowerCamelCase_					): v for k, v in idalabel.items()}
    _lowercase			:				Optional[Any] 						=						idalabel
    _lowercase			:				Tuple 						=						{v: k for k, v in idalabel.items()}

    if "s16" in checkpoint_url:
        _lowercase			:				Any 						=						384
        _lowercase			:				List[Any] 						=						1536
        _lowercase			:				Dict 						=						6
    elif "l16" in checkpoint_url:
        _lowercase			:				List[str] 						=						1024
        _lowercase			:				Optional[int] 						=						4096
        _lowercase			:				Any 						=						24
        _lowercase			:				List[str] 						=						16
        _lowercase			:				Optional[int] 						=						0.1
    elif "b4" in checkpoint_url:
        _lowercase			:				int 						=						4
    elif "l7" in checkpoint_url:
        _lowercase			:				List[Any] 						=						7
        _lowercase			:				Union[str, Any] 						=						1024
        _lowercase			:				Union[str, Any] 						=						4096
        _lowercase			:				str 						=						24
        _lowercase			:				Any 						=						16
        _lowercase			:				Any 						=						0.1

    _lowercase			:				Any 						=						ViTMSNModel(lowerCamelCase_					)

    _lowercase			:				Any 						=						torch.hub.load_state_dict_from_url(lowerCamelCase_				,					map_location='cpu'					)['target_encoder']

    _lowercase			:				Any 						=						ViTImageProcessor(size=config.image_size					)

    remove_projection_head(lowerCamelCase_					)
    _lowercase			:				Dict 						=						create_rename_keys(lowerCamelCase_				,					base_model=lowerCamelCase_					)

    for src, dest in rename_keys:
        rename_key(lowerCamelCase_				,					lowerCamelCase_				,					lowerCamelCase_					)
    read_in_q_k_v(lowerCamelCase_				,					lowerCamelCase_				,					base_model=lowerCamelCase_					)

    model.load_state_dict(lowerCamelCase_					)
    model.eval()

    _lowercase			:				List[str] 						=						'http://images.cocodataset.org/val2017/000000039769.jpg'

    _lowercase			:				Tuple 						=						Image.open(requests.get(lowerCamelCase_				,					stream=lowerCamelCase_					).raw					)
    _lowercase			:				List[Any] 						=						ViTImageProcessor(
        size=config.image_size				,					image_mean=lowerCamelCase_				,					image_std=lowerCamelCase_					)
    _lowercase			:				Dict 						=						image_processor(images=lowerCamelCase_				,					return_tensors='pt'					)

    # forward pass
    torch.manual_seed(2					)
    _lowercase			:				Tuple 						=						model(**lowerCamelCase_					)
    _lowercase			:				Optional[int] 						=						outputs.last_hidden_state

    # The following Colab Notebook was used to generate these outputs:
    # https://colab.research.google.com/gist/sayakpaul/3672419a04f5997827503fd84079bdd1/scratchpad.ipynb
    if "s16" in checkpoint_url:
        _lowercase			:				int 						=						torch.tensor([[-1.09_15, -1.48_76, -1.18_09]]					)
    elif "b16" in checkpoint_url:
        _lowercase			:				Optional[Any] 						=						torch.tensor([[14.28_89, -18.90_45, 11.72_81]]					)
    elif "l16" in checkpoint_url:
        _lowercase			:				Union[str, Any] 						=						torch.tensor([[41.50_28, -22.86_81, 45.64_75]]					)
    elif "b4" in checkpoint_url:
        _lowercase			:				List[Any] 						=						torch.tensor([[-4.38_68, 5.29_32, -0.41_37]]					)
    else:
        _lowercase			:				Optional[Any] 						=						torch.tensor([[-0.17_92, -0.64_65, 2.42_63]]					)

    # verify logits
    assert torch.allclose(last_hidden_state[:, 0, :3]				,					lowerCamelCase_				,					atol=1e-4					)

    print(F'''Saving model to {pytorch_dump_folder_path}'''					)
    model.save_pretrained(lowerCamelCase_					)

    print(F'''Saving image processor to {pytorch_dump_folder_path}'''					)
    image_processor.save_pretrained(lowerCamelCase_					)


if __name__ == "__main__":
 SCREAMING_SNAKE_CASE			: Any				   =					argparse.ArgumentParser()
 # Required parameters
 parser.add_argument(
     "--checkpoint_url",
     default="https://dl.fbaipublicfiles.com/msn/vits16_800ep.pth.tar",
     type=str,
     help="URL of the checkpoint you'd like to convert.",
 )
 parser.add_argument(
     "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory."
 )

 SCREAMING_SNAKE_CASE			: Union[str, Any]				   =					parser.parse_args()
 convert_vit_msn_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)






import unittest

from transformers import XLMConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
 import torch

 from transformers import (
     XLMForMultipleChoice,
     XLMForQuestionAnswering,
     XLMForQuestionAnsweringSimple,
     XLMForSequenceClassification,
     XLMForTokenClassification,
     XLMModel,
     XLMWithLMHeadModel,
 )
 from transformers.models.xlm.modeling_xlm import XLM_PRETRAINED_MODEL_ARCHIVE_LIST






class _lowerCamelCase:
       def __init__(   self, lowerCamelCase, lowerCamelCase=13, lowerCamelCase=7, lowerCamelCase=True, lowerCamelCase=True, lowerCamelCase=True, lowerCamelCase=True, lowerCamelCase=True, lowerCamelCase=False, lowerCamelCase=False, lowerCamelCase=False, lowerCamelCase=2, lowerCamelCase=99, lowerCamelCase=0, lowerCamelCase=32, lowerCamelCase=5, lowerCamelCase=4, lowerCamelCase=0.1, lowerCamelCase=0.1, lowerCamelCase=5_12, lowerCamelCase=2, lowerCamelCase=0.0_2, lowerCamelCase=2, lowerCamelCase=4, lowerCamelCase="last", lowerCamelCase=True, lowerCamelCase=None, lowerCamelCase=0, )			->  str:




           """simple docstring"""

           _lowercase			:				Union[str, Any] 						=						parent
           _lowercase			:				Optional[Any] 						=						batch_size
           _lowercase			:				List[str] 						=						seq_length
           _lowercase			:				int 						=						is_training
           _lowercase			:				List[str] 						=						use_input_lengths
           _lowercase			:				int 						=						use_token_type_ids
           _lowercase			:				Any 						=						use_labels
           _lowercase			:				Union[str, Any] 						=						gelu_activation
           _lowercase			:				List[str] 						=						sinusoidal_embeddings
           _lowercase			:				str 						=						causal
           _lowercase			:				Optional[int] 						=						asm
           _lowercase			:				Union[str, Any] 						=						n_langs
           _lowercase			:				List[Any] 						=						vocab_size
           _lowercase			:				Any 						=						n_special
           _lowercase			:				Any 						=						hidden_size
           _lowercase			:				str 						=						num_hidden_layers
           _lowercase			:				Union[str, Any] 						=						num_attention_heads
           _lowercase			:				Tuple 						=						hidden_dropout_prob
           _lowercase			:				Optional[int] 						=						attention_probs_dropout_prob
           _lowercase			:				Union[str, Any] 						=						max_position_embeddings
           _lowercase			:				List[str] 						=						type_sequence_label_size
           _lowercase			:				Any 						=						initializer_range
           _lowercase			:				int 						=						num_labels
           _lowercase			:				Optional[int] 						=						num_choices
           _lowercase			:				Optional[Any] 						=						summary_type
           _lowercase			:				Optional[Any] 						=						use_proj
           _lowercase			:				int 						=						scope
           _lowercase			:				List[Any] 						=						bos_token_id
       def      UpperCamelCase	(   self)			->  Optional[int]:




           """simple docstring"""

           _lowercase			:				Tuple 						=						ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
           _lowercase			:				List[str] 						=						random_attention_mask([self.batch_size, self.seq_length])

           _lowercase			:				int 						=						None
           if self.use_input_lengths:
               _lowercase			:				Dict 						=						(
                   ids_tensor([self.batch_size], vocab_size=2) + self.seq_length - 2
               )  # small variation of seq_length

           _lowercase			:				Tuple 						=						None
           if self.use_token_type_ids:
               _lowercase			:				Optional[Any] 						=						ids_tensor([self.batch_size, self.seq_length], self.n_langs)

           _lowercase			:				Tuple 						=						None
           _lowercase			:				int 						=						None
           _lowercase			:				int 						=						None
           if self.use_labels:
               _lowercase			:				str 						=						ids_tensor([self.batch_size], self.type_sequence_label_size)
               _lowercase			:				str 						=						ids_tensor([self.batch_size, self.seq_length], self.num_labels)
               _lowercase			:				Dict 						=						ids_tensor([self.batch_size], 2).float()
               _lowercase			:				Tuple 						=						ids_tensor([self.batch_size], self.num_choices)

           _lowercase			:				Dict 						=						self.get_config()

           return (
               config,
               input_ids,
               token_type_ids,
               input_lengths,
               sequence_labels,
               token_labels,
               is_impossible_labels,
               choice_labels,
               input_mask,
           )
       def      UpperCamelCase	(   self)			->  Union[str, Any]:




           """simple docstring"""

           return XLMConfig(
               vocab_size=self.vocab_size, n_special=self.n_special, emb_dim=self.hidden_size, n_layers=self.num_hidden_layers, n_heads=self.num_attention_heads, dropout=self.hidden_dropout_prob, attention_dropout=self.attention_probs_dropout_prob, gelu_activation=self.gelu_activation, sinusoidal_embeddings=self.sinusoidal_embeddings, asm=self.asm, causal=self.causal, n_langs=self.n_langs, max_position_embeddings=self.max_position_embeddings, initializer_range=self.initializer_range, summary_type=self.summary_type, use_proj=self.use_proj, num_labels=self.num_labels, bos_token_id=self.bos_token_id, )
       def      UpperCamelCase	(   self, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, )			->  Tuple:




           """simple docstring"""

           _lowercase			:				List[Any] 						=						XLMModel(config=lowerCamelCase)
           model.to(lowerCamelCase)
           model.eval()
           _lowercase			:				str 						=						model(lowerCamelCase, lengths=lowerCamelCase, langs=lowerCamelCase)
           _lowercase			:				int 						=						model(lowerCamelCase, langs=lowerCamelCase)
           _lowercase			:				Any 						=						model(lowerCamelCase)
           self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
       def      UpperCamelCase	(   self, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, )			->  List[Any]:




           """simple docstring"""

           _lowercase			:				Dict 						=						XLMWithLMHeadModel(lowerCamelCase)
           model.to(lowerCamelCase)
           model.eval()

           _lowercase			:				int 						=						model(lowerCamelCase, token_type_ids=lowerCamelCase, labels=lowerCamelCase)
           self.parent.assertEqual(result.loss.shape, ())
           self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
       def      UpperCamelCase	(   self, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, )			->  str:




           """simple docstring"""

           _lowercase			:				Tuple 						=						XLMForQuestionAnsweringSimple(lowerCamelCase)
           model.to(lowerCamelCase)
           model.eval()

           _lowercase			:				Dict 						=						model(lowerCamelCase)

           _lowercase			:				List[str] 						=						model(lowerCamelCase, start_positions=lowerCamelCase, end_positions=lowerCamelCase)
           _lowercase			:				Any 						=						outputs
           self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length))
           self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length))
       def      UpperCamelCase	(   self, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, )			->  Union[str, Any]:




           """simple docstring"""

           _lowercase			:				Tuple 						=						XLMForQuestionAnswering(lowerCamelCase)
           model.to(lowerCamelCase)
           model.eval()

           _lowercase			:				Optional[Any] 						=						model(lowerCamelCase)

           _lowercase			:				List[Any] 						=						model(
               lowerCamelCase, start_positions=lowerCamelCase, end_positions=lowerCamelCase, cls_index=lowerCamelCase, is_impossible=lowerCamelCase, p_mask=lowerCamelCase, )

           _lowercase			:				List[str] 						=						model(
               lowerCamelCase, start_positions=lowerCamelCase, end_positions=lowerCamelCase, cls_index=lowerCamelCase, is_impossible=lowerCamelCase, )

           ((_lowercase)						,							)			:				Optional[Any] 						=						result_with_labels.to_tuple()

           _lowercase			:				List[str] 						=						model(lowerCamelCase, start_positions=lowerCamelCase, end_positions=lowerCamelCase)

           ((_lowercase)						,							)			:				Any 						=						result_with_labels.to_tuple()

           self.parent.assertEqual(result_with_labels.loss.shape, ())
           self.parent.assertEqual(result.start_top_log_probs.shape, (self.batch_size, model.config.start_n_top))
           self.parent.assertEqual(result.start_top_index.shape, (self.batch_size, model.config.start_n_top))
           self.parent.assertEqual(
               result.end_top_log_probs.shape, (self.batch_size, model.config.start_n_top * model.config.end_n_top))
           self.parent.assertEqual(
               result.end_top_index.shape, (self.batch_size, model.config.start_n_top * model.config.end_n_top))
           self.parent.assertEqual(result.cls_logits.shape, (self.batch_size,))
       def      UpperCamelCase	(   self, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, )			->  int:




           """simple docstring"""

           _lowercase			:				Optional[Any] 						=						XLMForSequenceClassification(lowerCamelCase)
           model.to(lowerCamelCase)
           model.eval()

           _lowercase			:				Optional[int] 						=						model(lowerCamelCase)
           _lowercase			:				Optional[int] 						=						model(lowerCamelCase, labels=lowerCamelCase)
           self.parent.assertEqual(result.loss.shape, ())
           self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size))
       def      UpperCamelCase	(   self, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, )			->  List[str]:




           """simple docstring"""

           _lowercase			:				Any 						=						self.num_labels
           _lowercase			:				str 						=						XLMForTokenClassification(lowerCamelCase)
           model.to(lowerCamelCase)
           model.eval()

           _lowercase			:				int 						=						model(lowerCamelCase, attention_mask=lowerCamelCase, labels=lowerCamelCase)
           self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels))
       def      UpperCamelCase	(   self, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, )			->  Dict:




           """simple docstring"""

           _lowercase			:				Optional[Any] 						=						self.num_choices
           _lowercase			:				Optional[int] 						=						XLMForMultipleChoice(config=lowerCamelCase)
           model.to(lowerCamelCase)
           model.eval()
           _lowercase			:				Optional[Any] 						=						input_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
           _lowercase			:				int 						=						token_type_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
           _lowercase			:				Optional[Any] 						=						input_mask.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
           _lowercase			:				List[str] 						=						model(
               lowerCamelCase, attention_mask=lowerCamelCase, token_type_ids=lowerCamelCase, labels=lowerCamelCase, )
           self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_choices))




       def      UpperCamelCase	(   self)			->  Tuple:




           """simple docstring"""

           _lowercase			:				Dict 						=						self.prepare_config_and_inputs()
           (
               (
               _lowercase
           )						,							(
               _lowercase
           )						,							(
               _lowercase
           )						,							(
               _lowercase
           )						,							(
               _lowercase
           )						,							(
               _lowercase
           )						,							(
               _lowercase
           )						,							(
               _lowercase
           )						,							(
               _lowercase
           )						,							
           )			:				Optional[Any] 						=						config_and_inputs
           _lowercase			:				List[str] 						=						{'input_ids': input_ids, 'token_type_ids': token_type_ids, 'lengths': input_lengths}
           return config, inputs_dict






@require_torch
class _lowerCamelCase(		_a,					_a,					_a,					unittest.TestCase  ):
       lowercase_					:      Any       					=     (
           (
               XLMModel,
               XLMWithLMHeadModel,
               XLMForQuestionAnswering,
               XLMForSequenceClassification,
               XLMForQuestionAnsweringSimple,
               XLMForTokenClassification,
               XLMForMultipleChoice,
           )
           if is_torch_available()
           else ()
       )
       lowercase_					:      Optional[int]       					=     (
           (XLMWithLMHeadModel,) if is_torch_available() else ()
       )  # TODO (PVP): Check other models whether language generation is also applicable
       lowercase_					:      Union[str, Any]       					=     (
           {
               """feature-extraction""": XLMModel,
               """fill-mask""": XLMWithLMHeadModel,
               """question-answering""": XLMForQuestionAnsweringSimple,
               """text-classification""": XLMForSequenceClassification,
               """text-generation""": XLMWithLMHeadModel,
               """token-classification""": XLMForTokenClassification,
               """zero-shot""": XLMForSequenceClassification,
           }
           if is_torch_available()
           else {}
       )
       def      UpperCamelCase	(   self, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase)			->  Optional[int]:




           """simple docstring"""

           if (
               pipeline_test_casse_name == "QAPipelineTests"
               and tokenizer_name is not None
               and not tokenizer_name.endswith('Fast')
           ):
               # `QAPipelineTests` fails for a few models when the slower tokenizer are used.
               # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework)
               # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer
               return True

           return False
       def      UpperCamelCase	(   self, lowerCamelCase, lowerCamelCase, lowerCamelCase=False)			->  Optional[int]:




           """simple docstring"""

           _lowercase			:				Any 						=						super()._prepare_for_class(lowerCamelCase, lowerCamelCase, return_labels=lowerCamelCase)

           if return_labels:
               if model_class.__name__ == "XLMForQuestionAnswering":
                   _lowercase			:				Any 						=						torch.zeros(
                       self.model_tester.batch_size, dtype=torch.long, device=lowerCamelCase)
                   _lowercase			:				Dict 						=						torch.zeros(
                       self.model_tester.batch_size, dtype=torch.long, device=lowerCamelCase)

           return inputs_dict
       def      UpperCamelCase	(   self)			->  int:




           """simple docstring"""

           _lowercase			:				Union[str, Any] 						=						XLMModelTester(self)
           _lowercase			:				List[str] 						=						ConfigTester(self, config_class=lowerCamelCase, emb_dim=37)
       def      UpperCamelCase	(   self)			->  Tuple:




           """simple docstring"""

           self.config_tester.run_common_tests()
       def      UpperCamelCase	(   self)			->  List[Any]:




           """simple docstring"""

           _lowercase			:				Optional[Any] 						=						self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_xlm_model(*lowerCamelCase)
       def      UpperCamelCase	(   self)			->  List[str]:




           """simple docstring"""

           _lowercase			:				str 						=						self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_xlm_lm_head(*lowerCamelCase)
       def      UpperCamelCase	(   self)			->  Optional[Any]:




           """simple docstring"""

           _lowercase			:				Optional[Any] 						=						self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_xlm_simple_qa(*lowerCamelCase)
       def      UpperCamelCase	(   self)			->  int:




           """simple docstring"""

           _lowercase			:				str 						=						self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_xlm_qa(*lowerCamelCase)
       def      UpperCamelCase	(   self)			->  List[str]:




           """simple docstring"""

           _lowercase			:				Dict 						=						self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_xlm_sequence_classif(*lowerCamelCase)
       def      UpperCamelCase	(   self)			->  Dict:




           """simple docstring"""

           _lowercase			:				Union[str, Any] 						=						self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_xlm_token_classif(*lowerCamelCase)
       def      UpperCamelCase	(   self)			->  Any:




           """simple docstring"""

           _lowercase			:				str 						=						self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_xlm_for_multiple_choice(*lowerCamelCase)
       def      UpperCamelCase	(   self, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase=False, lowerCamelCase=1)			->  int:




           """simple docstring"""

           self.assertIsInstance(lowerCamelCase, lowerCamelCase)
           self.assertListEqual(
               [isinstance(lowerCamelCase, lowerCamelCase) for iter_attentions in attentions], [True] * len(lowerCamelCase))
           self.assertEqual(len(lowerCamelCase), (max_length - min_length) * num_beam_groups)

           for idx, iter_attentions in enumerate(lowerCamelCase):
               # adds PAD dummy token
               _lowercase			:				Dict 						=						min_length + idx + 1
               _lowercase			:				int 						=						min_length + idx + 1

               _lowercase			:				Dict 						=						(
                   batch_size * num_beam_groups,
                   config.num_attention_heads,
                   tgt_len,
                   src_len,
               )
               # check attn size
               self.assertListEqual(
                   [layer_attention.shape for layer_attention in iter_attentions], [expected_shape] * len(lowerCamelCase))
       def      UpperCamelCase	(   self, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase=False, lowerCamelCase=1)			->  List[Any]:




           """simple docstring"""

           self.assertIsInstance(lowerCamelCase, lowerCamelCase)
           self.assertListEqual(
               [isinstance(lowerCamelCase, lowerCamelCase) for iter_hidden_states in hidden_states], [True] * len(lowerCamelCase), )
           self.assertEqual(len(lowerCamelCase), (max_length - min_length) * num_beam_groups)

           for idx, iter_hidden_states in enumerate(lowerCamelCase):
               # adds PAD dummy token
               _lowercase			:				int 						=						min_length + idx + 1
               _lowercase			:				int 						=						(batch_size * num_beam_groups, seq_len, config.hidden_size)
               # check hidden size
               self.assertListEqual(
                   [layer_hidden_states.shape for layer_hidden_states in iter_hidden_states], [expected_shape] * len(lowerCamelCase), )
           pass




       @slow
       def      UpperCamelCase	(   self)			->  int:




           """simple docstring"""

           for model_name in XLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               _lowercase			:				Dict 						=						XLMModel.from_pretrained(lowerCamelCase)
               self.assertIsNotNone(lowerCamelCase)






@require_torch
class _lowerCamelCase(		unittest.TestCase  ):
       @slow
       def      UpperCamelCase	(   self)			->  Union[str, Any]:




           """simple docstring"""

           _lowercase			:				Tuple 						=						XLMWithLMHeadModel.from_pretrained('xlm-mlm-en-2048')
           model.to(lowerCamelCase)
           _lowercase			:				Union[str, Any] 						=						torch.tensor([[14, 4_47]], dtype=torch.long, device=lowerCamelCase)  # the president
           _lowercase			:				Any 						=						[
               14,
               4_47,
               14,
               4_47,
               14,
               4_47,
               14,
               4_47,
               14,
               4_47,
               14,
               4_47,
               14,
               4_47,
               14,
               4_47,
               14,
               4_47,
               14,
               4_47,
           ]  # the president the president the president the president the president the president the president the president the president the president
           # TODO(PVP): this and other input_ids I tried for generation give pretty bad results. Not sure why. Model might just not be made for auto-regressive inference
           _lowercase			:				str 						=						model.generate(lowerCamelCase, do_sample=lowerCamelCase)
           self.assertListEqual(output_ids[0].cpu().numpy().tolist(), lowerCamelCase)


