


import argparse
import json

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

from transformers import BitImageProcessor, FocalNetConfig, FocalNetForImageClassification
from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, PILImageResampling






def 						a__			(				A__				):
			SCREAMING_SNAKE_CASE_		:     Dict					=					[2, 2, 6, 2] if 'tiny' in model_name else [2, 2, 1_8, 2]
			SCREAMING_SNAKE_CASE_		:     Union[str, Any]					=					True if 'large' in model_name or 'huge' in model_name else False
			SCREAMING_SNAKE_CASE_		:     List[str]					=					True if 'large' in model_name or 'huge' in model_name else False
			SCREAMING_SNAKE_CASE_		:     Tuple					=					True if 'large' in model_name or 'huge' in model_name else False

			if "large" in model_name or "xlarge" in model_name or "huge" in model_name:
						if "fl3" in model_name:
									SCREAMING_SNAKE_CASE_		:     Optional[int]					=					[3, 3, 3, 3]
									SCREAMING_SNAKE_CASE_		:     Optional[int]					=					[5, 5, 5, 5]
						elif "fl4" in model_name:
									SCREAMING_SNAKE_CASE_		:     Union[str, Any]					=					[4, 4, 4, 4]
									SCREAMING_SNAKE_CASE_		:     Tuple					=					[3, 3, 3, 3]

			if "tiny" in model_name or "small" in model_name or "base" in model_name:
						SCREAMING_SNAKE_CASE_		:     str					=					[3, 3, 3, 3]
						if "lrf" in model_name:
									SCREAMING_SNAKE_CASE_		:     Any					=					[3, 3, 3, 3]
						else:
									SCREAMING_SNAKE_CASE_		:     Optional[int]					=					[2, 2, 2, 2]

			if "tiny" in model_name:
						SCREAMING_SNAKE_CASE_		:     Any					=					9_6
			elif "small" in model_name:
						SCREAMING_SNAKE_CASE_		:     str					=					9_6
			elif "base" in model_name:
						SCREAMING_SNAKE_CASE_		:     Any					=					1_2_8
			elif "large" in model_name:
						SCREAMING_SNAKE_CASE_		:     List[Any]					=					1_9_2
			elif "xlarge" in model_name:
						SCREAMING_SNAKE_CASE_		:     Optional[int]					=					2_5_6
			elif "huge" in model_name:
						SCREAMING_SNAKE_CASE_		:     Union[str, Any]					=					3_5_2

			# set label information
			SCREAMING_SNAKE_CASE_		:     Union[str, Any]					=					'huggingface/label-files'
			if "large" in model_name or "huge" in model_name:
						SCREAMING_SNAKE_CASE_		:     Optional[Any]					=					'imagenet-22k-id2label.json'
			else:
						SCREAMING_SNAKE_CASE_		:     Optional[int]					=					'imagenet-1k-id2label.json'

			SCREAMING_SNAKE_CASE_		:     Any					=					json.load(open(hf_hub_download(A__,      A__,      repo_type='dataset'				),      'r'				)				)
			SCREAMING_SNAKE_CASE_		:     str					=					{int(A__				): v for k, v in idalabel.items()}
			SCREAMING_SNAKE_CASE_		:     Optional[int]					=					{v: k for k, v in idalabel.items()}

			SCREAMING_SNAKE_CASE_		:     int					=					FocalNetConfig(
			    embed_dim=A__,      depths=A__,      focal_levels=A__,      focal_windows=A__,      use_conv_embed=A__,      idalabel=A__,      labelaid=A__,      use_post_layernorm=A__,      use_layerscale=A__,      )

			return config






def 						a__			(				A__				):
			if "patch_embed.proj" in name:
						SCREAMING_SNAKE_CASE_		:     str					=					name.replace('patch_embed.proj',      'embeddings.patch_embeddings.projection'				)
			if "patch_embed.norm" in name:
						SCREAMING_SNAKE_CASE_		:     int					=					name.replace('patch_embed.norm',      'embeddings.norm'				)
			if "layers" in name:
						SCREAMING_SNAKE_CASE_		:     Any					=					'encoder.' + name
			if "encoder.layers" in name:
						SCREAMING_SNAKE_CASE_		:     Optional[int]					=					name.replace('encoder.layers',      'encoder.stages'				)
			if "downsample.proj" in name:
						SCREAMING_SNAKE_CASE_		:     str					=					name.replace('downsample.proj',      'downsample.projection'				)
			if "blocks" in name:
						SCREAMING_SNAKE_CASE_		:     Any					=					name.replace('blocks',      'layers'				)
			if "modulation.f.weight" in name or "modulation.f.bias" in name:
						SCREAMING_SNAKE_CASE_		:     Optional[int]					=					name.replace('modulation.f',      'modulation.projection_in'				)
			if "modulation.h.weight" in name or "modulation.h.bias" in name:
						SCREAMING_SNAKE_CASE_		:     Dict					=					name.replace('modulation.h',      'modulation.projection_context'				)
			if "modulation.proj.weight" in name or "modulation.proj.bias" in name:
						SCREAMING_SNAKE_CASE_		:     Optional[Any]					=					name.replace('modulation.proj',      'modulation.projection_out'				)

			if name == "norm.weight":
						SCREAMING_SNAKE_CASE_		:     int					=					'layernorm.weight'
			if name == "norm.bias":
						SCREAMING_SNAKE_CASE_		:     List[Any]					=					'layernorm.bias'

			if "head" in name:
						SCREAMING_SNAKE_CASE_		:     List[Any]					=					name.replace('head',      'classifier'				)
			else:
						SCREAMING_SNAKE_CASE_		:     List[str]					=					'focalnet.' + name

			return name






def 						a__			(				A__,      A__,      A__=False				):
			# fmt: off
			SCREAMING_SNAKE_CASE_		:     List[Any]					=					{
			    'focalnet-tiny': 'https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_tiny_srf.pth',
			    'focalnet-tiny-lrf': 'https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_tiny_lrf.pth',
			    'focalnet-small': 'https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_small_srf.pth',
			    'focalnet-small-lrf': 'https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_small_lrf.pth',
			    'focalnet-base': 'https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_base_srf.pth',
			    'focalnet-base-lrf': 'https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_base_lrf.pth',
			    'focalnet-large-lrf-fl3': 'https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_large_lrf_384.pth',
			    'focalnet-large-lrf-fl4': 'https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_large_lrf_384_fl4.pth',
			    'focalnet-xlarge-lrf-fl3': 'https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_xlarge_lrf_384.pth',
			    'focalnet-xlarge-lrf-fl4': 'https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_xlarge_lrf_384_fl4.pth',
			}
			# fmt: on

			SCREAMING_SNAKE_CASE_		:     Optional[int]					=					model_name_to_url[model_name]
			print('Checkpoint URL: ',      A__				)
			SCREAMING_SNAKE_CASE_		:     str					=					torch.hub.load_state_dict_from_url(A__,      map_location='cpu'				)['model']

			# rename keys
			for key in state_dict.copy().keys():
						SCREAMING_SNAKE_CASE_		:     Dict					=					state_dict.pop(A__				)
						SCREAMING_SNAKE_CASE_		:     Dict					=					val

			SCREAMING_SNAKE_CASE_		:     List[Any]					=					get_focalnet_config(A__				)
			SCREAMING_SNAKE_CASE_		:     int					=					FocalNetForImageClassification(A__				)
			model.eval()

			# load state dict
			model.load_state_dict(A__				)

			# verify conversion
			SCREAMING_SNAKE_CASE_		:     Optional[int]					=					'http://images.cocodataset.org/val2017/000000039769.jpg'

			SCREAMING_SNAKE_CASE_		:     List[Any]					=					BitImageProcessor(
			    do_resize=A__,      size={'shortest_edge': 2_5_6},      resample=PILImageResampling.BILINEAR,      do_center_crop=A__,      crop_size=2_2_4,      do_normalize=A__,      image_mean=A__,      image_std=A__,      )
			SCREAMING_SNAKE_CASE_		:     List[Any]					=					Image.open(requests.get(A__,      stream=A__				).raw				)
			SCREAMING_SNAKE_CASE_		:     str					=					processor(images=A__,      return_tensors='pt'				)

			SCREAMING_SNAKE_CASE_		:     int					=					transforms.Compose(
			    [
			        transforms.Resize(2_5_6				),
			        transforms.CenterCrop(2_2_4				),
			        transforms.ToTensor(),
			        transforms.Normalize(mean=[0.4_85, 0.4_56, 0.4_06],      std=[0.2_29, 0.2_24, 0.2_25]				),
			    ]				)

			SCREAMING_SNAKE_CASE_		:     Optional[Any]					=					image_transforms(A__				).unsqueeze(0				)

			# verify pixel_values
			assert torch.allclose(inputs.pixel_values,      A__,      atol=1E-4				)

			SCREAMING_SNAKE_CASE_		:     Union[str, Any]					=					model(**A__				)

			SCREAMING_SNAKE_CASE_		:     Optional[Any]					=					outputs.logits.argmax(-1				).item()
			print('Predicted class:',      model.config.idalabel[predicted_class_idx]				)

			print('First values of logits:',      outputs.logits[0, :3]				)

			if model_name == "focalnet-tiny":
						SCREAMING_SNAKE_CASE_		:     Dict					=					torch.tensor([0.21_66, -0.43_68, 0.21_91]				)
			elif model_name == "focalnet-tiny-lrf":
						SCREAMING_SNAKE_CASE_		:     Any					=					torch.tensor([1.16_69, 0.01_25, -0.16_95]				)
			elif model_name == "focalnet-small":
						SCREAMING_SNAKE_CASE_		:     List[Any]					=					torch.tensor([0.49_17, -0.04_30, 0.13_41]				)
			elif model_name == "focalnet-small-lrf":
						SCREAMING_SNAKE_CASE_		:     Optional[int]					=					torch.tensor([-0.25_88, -0.53_42, -0.23_31]				)
			elif model_name == "focalnet-base":
						SCREAMING_SNAKE_CASE_		:     Optional[int]					=					torch.tensor([-0.16_55, -0.40_90, -0.17_30]				)
			elif model_name == "focalnet-base-lrf":
						SCREAMING_SNAKE_CASE_		:     Union[str, Any]					=					torch.tensor([0.53_06, -0.04_83, -0.39_28]				)
			assert torch.allclose(outputs.logits[0, :3],      A__,      atol=1E-4				)
			print('Looks ok!'				)

			if pytorch_dump_folder_path is not None:
						print(F'''Saving model and processor of {model_name} to {pytorch_dump_folder_path}'''				)
						model.save_pretrained(A__				)
						processor.save_pretrained(A__				)

			if push_to_hub:
						print(F'''Pushing model and processor of {model_name} to the hub...'''				)
						model.push_to_hub(F'''{model_name}'''				)
						processor.push_to_hub(F'''{model_name}'''				)


if __name__ == "__main__":
				lowerCAmelCase__			:      List[Any]								=argparse.ArgumentParser()
				# Required parameters
				parser.add_argument(
				    '--model_name',
				    default='focalnet-tiny',
				    type=str,
				    help='Name of the FocalNet model you\'d like to convert.',
				)
				parser.add_argument(
				    '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.'
				)
				parser.add_argument(
				    '--push_to_hub',
				    action='store_true',
				    help='Whether to push the model and processor to the hub.',
				)

				lowerCAmelCase__			:      Optional[int]								=parser.parse_args()
				convert_focalnet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)









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)


