



import collections
import inspect
import unittest

from transformers import FocalNetConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_backbone_common import BackboneTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
				import torch
				from torch import nn

				from transformers import (
				    FocalNetBackbone,
				    FocalNetForImageClassification,
				    FocalNetForMaskedImageModeling,
				    FocalNetModel,
				)
				from transformers.models.focalnet.modeling_focalnet import FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST

if is_vision_available():
				from PIL import Image

				from transformers import AutoImageProcessor






class 						__a :



	def __init__(						self							:    Tuple				,	snake_case_							:    Any				,	snake_case_							:    Dict=13				,	snake_case_							:    Optional[Any]=32				,	snake_case_							:    int=2				,	snake_case_							:    Optional[Any]=3				,	snake_case_							:    Union[str, Any]=16				,	snake_case_							:    List[str]=[32, 64, 1_28]				,	snake_case_							:    Any=[1, 2, 1]				,	snake_case_							:    Tuple=[2, 2, 4]				,	snake_case_							:    Union[str, Any]=2				,	snake_case_							:    int=2.0				,	snake_case_							:    Optional[int]=True				,	snake_case_							:    Tuple=0.0				,	snake_case_							:    List[str]=0.0				,	snake_case_							:    Optional[int]=0.1				,	snake_case_							:    int="gelu"				,	snake_case_							:    Optional[int]=False				,	snake_case_							:    int=True				,	snake_case_							:    Any=0.0_2				,	snake_case_							:    List[Any]=1e-5				,	snake_case_							:    Optional[int]=True				,	snake_case_							:    Any=None				,	snake_case_							:    str=True				,	snake_case_							:    Dict=10				,	snake_case_							:    Dict=8				,	snake_case_							:    Any=["stage1", "stage2"]				,	snake_case_							:    Dict=[1, 2]				,	)->							str:
						__lowerCAmelCase	   =parent
						__lowerCAmelCase	   =batch_size
						__lowerCAmelCase	   =image_size
						__lowerCAmelCase	   =patch_size
						__lowerCAmelCase	   =num_channels
						__lowerCAmelCase	   =embed_dim
						__lowerCAmelCase	   =hidden_sizes
						__lowerCAmelCase	   =depths
						__lowerCAmelCase	   =num_heads
						__lowerCAmelCase	   =window_size
						__lowerCAmelCase	   =mlp_ratio
						__lowerCAmelCase	   =qkv_bias
						__lowerCAmelCase	   =hidden_dropout_prob
						__lowerCAmelCase	   =attention_probs_dropout_prob
						__lowerCAmelCase	   =drop_path_rate
						__lowerCAmelCase	   =hidden_act
						__lowerCAmelCase	   =use_absolute_embeddings
						__lowerCAmelCase	   =patch_norm
						__lowerCAmelCase	   =layer_norm_eps
						__lowerCAmelCase	   =initializer_range
						__lowerCAmelCase	   =is_training
						__lowerCAmelCase	   =scope
						__lowerCAmelCase	   =use_labels
						__lowerCAmelCase	   =type_sequence_label_size
						__lowerCAmelCase	   =encoder_stride
						__lowerCAmelCase	   =out_features
						__lowerCAmelCase	   =out_indices



	def 		UpperCamelCase							(						self							:    str)->							str:
						__lowerCAmelCase	   =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

						__lowerCAmelCase	   =None
						if self.use_labels:
											__lowerCAmelCase	   =ids_tensor([self.batch_size]				,	self.type_sequence_label_size)

						__lowerCAmelCase	   =self.get_config()

						return config, pixel_values, labels



	def 		UpperCamelCase							(						self							:    List[Any])->							List[str]:
						return FocalNetConfig(
						    image_size=self.image_size				,	patch_size=self.patch_size				,	num_channels=self.num_channels				,	embed_dim=self.embed_dim				,	hidden_sizes=self.hidden_sizes				,	depths=self.depths				,	num_heads=self.num_heads				,	window_size=self.window_size				,	mlp_ratio=self.mlp_ratio				,	qkv_bias=self.qkv_bias				,	hidden_dropout_prob=self.hidden_dropout_prob				,	attention_probs_dropout_prob=self.attention_probs_dropout_prob				,	drop_path_rate=self.drop_path_rate				,	hidden_act=self.hidden_act				,	use_absolute_embeddings=self.use_absolute_embeddings				,	path_norm=self.patch_norm				,	layer_norm_eps=self.layer_norm_eps				,	initializer_range=self.initializer_range				,	encoder_stride=self.encoder_stride				,	out_features=self.out_features				,	out_indices=self.out_indices				,	)



	def 		UpperCamelCase							(						self							:    List[str]				,	snake_case_							:    Optional[Any]				,	snake_case_							:    Any				,	snake_case_							:    int)->							Dict:
						__lowerCAmelCase	   =FocalNetModel(config=_UpperCamelCase)
						model.to(_UpperCamelCase)
						model.eval()
						__lowerCAmelCase	   =model(_UpperCamelCase)

						__lowerCAmelCase	   =((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths) - 1))
						__lowerCAmelCase	   =int(config.embed_dim * 2 ** (len(config.depths) - 1))

						self.parent.assertEqual(result.last_hidden_state.shape				,	(self.batch_size, expected_seq_len, expected_dim))



	def 		UpperCamelCase							(						self							:    Union[str, Any]				,	snake_case_							:    Union[str, Any]				,	snake_case_							:    Tuple				,	snake_case_							:    List[str])->							str:
						__lowerCAmelCase	   =FocalNetBackbone(config=_UpperCamelCase)
						model.to(_UpperCamelCase)
						model.eval()
						__lowerCAmelCase	   =model(_UpperCamelCase)

						# verify feature maps
						self.parent.assertEqual(len(result.feature_maps)				,	len(config.out_features))
						self.parent.assertListEqual(list(result.feature_maps[0].shape)				,	[self.batch_size, self.image_size, 8, 8])

						# verify channels
						self.parent.assertEqual(len(model.channels)				,	len(config.out_features))
						self.parent.assertListEqual(model.channels				,	config.hidden_sizes[:-1])

						# verify backbone works with out_features=None
						__lowerCAmelCase	   =None
						__lowerCAmelCase	   =FocalNetBackbone(config=_UpperCamelCase)
						model.to(_UpperCamelCase)
						model.eval()
						__lowerCAmelCase	   =model(_UpperCamelCase)

						# verify feature maps
						self.parent.assertEqual(len(result.feature_maps)				,	1)
						self.parent.assertListEqual(list(result.feature_maps[0].shape)				,	[self.batch_size, self.image_size * 2, 4, 4])

						# verify channels
						self.parent.assertEqual(len(model.channels)				,	1)
						self.parent.assertListEqual(model.channels				,	[config.hidden_sizes[-1]])



	def 		UpperCamelCase							(						self							:    Any				,	snake_case_							:    Tuple				,	snake_case_							:    List[str]				,	snake_case_							:    Optional[Any])->							str:
						__lowerCAmelCase	   =FocalNetForMaskedImageModeling(config=_UpperCamelCase)
						model.to(_UpperCamelCase)
						model.eval()
						__lowerCAmelCase	   =model(_UpperCamelCase)
						self.parent.assertEqual(
						    result.reconstruction.shape				,	(self.batch_size, self.num_channels, self.image_size, self.image_size))

						# test greyscale images
						__lowerCAmelCase	   =1
						__lowerCAmelCase	   =FocalNetForMaskedImageModeling(_UpperCamelCase)
						model.to(_UpperCamelCase)
						model.eval()

						__lowerCAmelCase	   =floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
						__lowerCAmelCase	   =model(_UpperCamelCase)
						self.parent.assertEqual(result.reconstruction.shape				,	(self.batch_size, 1, self.image_size, self.image_size))



	def 		UpperCamelCase							(						self							:    Union[str, Any]				,	snake_case_							:    Union[str, Any]				,	snake_case_							:    List[str]				,	snake_case_							:    Dict)->							Dict:
						__lowerCAmelCase	   =self.type_sequence_label_size
						__lowerCAmelCase	   =FocalNetForImageClassification(_UpperCamelCase)
						model.to(_UpperCamelCase)
						model.eval()
						__lowerCAmelCase	   =model(_UpperCamelCase				,	labels=_UpperCamelCase)
						self.parent.assertEqual(result.logits.shape				,	(self.batch_size, self.type_sequence_label_size))

						# test greyscale images
						__lowerCAmelCase	   =1
						__lowerCAmelCase	   =FocalNetForImageClassification(_UpperCamelCase)
						model.to(_UpperCamelCase)
						model.eval()

						__lowerCAmelCase	   =floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
						__lowerCAmelCase	   =model(_UpperCamelCase)
						self.parent.assertEqual(result.logits.shape				,	(self.batch_size, self.type_sequence_label_size))



	def 		UpperCamelCase							(						self							:    int)->							Optional[int]:
						__lowerCAmelCase	   =self.prepare_config_and_inputs()

						__lowerCAmelCase	   =config_and_inputs
						__lowerCAmelCase	   ={"""pixel_values""": pixel_values}
						return config, inputs_dict






@require_torch
class 						__a (     __lowerCAmelCase	,    __lowerCAmelCase	,    unittest.TestCase				):
	SCREAMING_SNAKE_CASE       =       (
	    (
	        FocalNetModel,
	        FocalNetForImageClassification,
	        FocalNetForMaskedImageModeling,
	        FocalNetBackbone,
	    )
	    if is_torch_available()
	    else ()
	)
	SCREAMING_SNAKE_CASE       =       (
	    {"feature-extraction": FocalNetModel, "image-classification": FocalNetForImageClassification}
	    if is_torch_available()
	    else {}
	)
	SCREAMING_SNAKE_CASE       =       False

	SCREAMING_SNAKE_CASE       =       False
	SCREAMING_SNAKE_CASE       =       False
	SCREAMING_SNAKE_CASE       =       False
	SCREAMING_SNAKE_CASE       =       False



	def 		UpperCamelCase							(						self							:    int)->							Tuple:
						__lowerCAmelCase	   =FocalNetModelTester(self)
						__lowerCAmelCase	   =ConfigTester(self				,	config_class=_UpperCamelCase				,	embed_dim=37				,	has_text_modality=_UpperCamelCase)



	def 		UpperCamelCase							(						self							:    Dict)->							List[str]:
						self.create_and_test_config_common_properties()
						self.config_tester.create_and_test_config_to_json_string()
						self.config_tester.create_and_test_config_to_json_file()
						self.config_tester.create_and_test_config_from_and_save_pretrained()
						self.config_tester.create_and_test_config_with_num_labels()
						self.config_tester.check_config_can_be_init_without_params()
						self.config_tester.check_config_arguments_init()



	def 		UpperCamelCase							(						self							:    int)->							List[Any]:
						return



	def 		UpperCamelCase							(						self							:    Any)->							Tuple:
						__lowerCAmelCase	   =self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*_UpperCamelCase)



	def 		UpperCamelCase							(						self							:    int)->							Any:
						__lowerCAmelCase	   =self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_backbone(*_UpperCamelCase)



	def 		UpperCamelCase							(						self							:    List[str])->							List[str]:
						__lowerCAmelCase	   =self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_masked_image_modeling(*_UpperCamelCase)



	def 		UpperCamelCase							(						self							:    Optional[int])->							int:
						__lowerCAmelCase	   =self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_image_classification(*_UpperCamelCase)



	@unittest.skip(reason="""FocalNet does not use inputs_embeds""")
	def 		UpperCamelCase							(						self							:    str)->							Tuple:
						pass



	@unittest.skip(reason="""FocalNet does not use feedforward chunking""")
	def 		UpperCamelCase							(						self							:    List[str])->							int:
						pass



	def 		UpperCamelCase							(						self							:    List[Any])->							Union[str, Any]:
						__lowerCAmelCase	   =self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes[:-1]:
											__lowerCAmelCase	   =model_class(_UpperCamelCase)
											self.assertIsInstance(model.get_input_embeddings()				,	(nn.Module))
											__lowerCAmelCase	   =model.get_output_embeddings()
											self.assertTrue(x is None or isinstance(_UpperCamelCase				,	nn.Linear))



	def 		UpperCamelCase							(						self							:    List[Any])->							Union[str, Any]:
						__lowerCAmelCase	   =self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes[:-1]:
											__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)



	def 		UpperCamelCase							(						self							:    List[Any]				,	snake_case_							:    str				,	snake_case_							:    List[str]				,	snake_case_							:    Union[str, Any]				,	snake_case_							:    int)->							str:
						__lowerCAmelCase	   =model_class(_UpperCamelCase)
						model.to(_UpperCamelCase)
						model.eval()

						with torch.no_grad():
											__lowerCAmelCase	   =model(**self._prepare_for_class(_UpperCamelCase				,	_UpperCamelCase))

						__lowerCAmelCase	   =outputs.hidden_states

						__lowerCAmelCase	   =getattr(
						    self.model_tester				,	"""expected_num_hidden_layers"""				,	len(self.model_tester.depths) + 1)
						self.assertEqual(len(_UpperCamelCase)				,	_UpperCamelCase)

						# FocalNet has a different seq_length
						__lowerCAmelCase	   =(
						    config.patch_size
						    if isinstance(config.patch_size				,	collections.abc.Iterable)
						    else (config.patch_size, config.patch_size)
						)

						__lowerCAmelCase	   =(image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])

						self.assertListEqual(
						    list(hidden_states[0].shape[-2:])				,	[num_patches, self.model_tester.embed_dim]				,	)

						__lowerCAmelCase	   =outputs.reshaped_hidden_states
						self.assertEqual(len(_UpperCamelCase)				,	_UpperCamelCase)

						__lowerCAmelCase	   =reshaped_hidden_states[0].shape
						__lowerCAmelCase	   =(
						    reshaped_hidden_states[0].view(_UpperCamelCase				,	_UpperCamelCase				,	height * width).permute(0				,	2				,	1)
						)
						self.assertListEqual(
						    list(reshaped_hidden_states.shape[-2:])				,	[num_patches, self.model_tester.embed_dim]				,	)



	def 		UpperCamelCase							(						self							:    Tuple)->							Any:
						__lowerCAmelCase	   =self.model_tester.prepare_config_and_inputs_for_common()

						__lowerCAmelCase	   =(
						    self.model_tester.image_size
						    if isinstance(self.model_tester.image_size				,	collections.abc.Iterable)
						    else (self.model_tester.image_size, self.model_tester.image_size)
						)

						for model_class in self.all_model_classes[:-1]:
											__lowerCAmelCase	   =True
											self.check_hidden_states_output(_UpperCamelCase				,	_UpperCamelCase				,	_UpperCamelCase				,	_UpperCamelCase)

											# check that output_hidden_states also work using config
											del inputs_dict["output_hidden_states"]
											__lowerCAmelCase	   =True

											self.check_hidden_states_output(_UpperCamelCase				,	_UpperCamelCase				,	_UpperCamelCase				,	_UpperCamelCase)



	def 		UpperCamelCase							(						self							:    Optional[int])->							List[str]:
						__lowerCAmelCase	   =self.model_tester.prepare_config_and_inputs_for_common()
						__lowerCAmelCase	   =3

						__lowerCAmelCase	   =(
						    self.model_tester.image_size
						    if isinstance(self.model_tester.image_size				,	collections.abc.Iterable)
						    else (self.model_tester.image_size, self.model_tester.image_size)
						)
						__lowerCAmelCase	   =(
						    config.patch_size
						    if isinstance(config.patch_size				,	collections.abc.Iterable)
						    else (config.patch_size, config.patch_size)
						)

						__lowerCAmelCase	   =image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
						__lowerCAmelCase	   =image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

						for model_class in self.all_model_classes[:-1]:
											__lowerCAmelCase	   =True
											self.check_hidden_states_output(_UpperCamelCase				,	_UpperCamelCase				,	_UpperCamelCase				,	(padded_height, padded_width))

											# check that output_hidden_states also work using config
											del inputs_dict["output_hidden_states"]
											__lowerCAmelCase	   =True
											self.check_hidden_states_output(_UpperCamelCase				,	_UpperCamelCase				,	_UpperCamelCase				,	(padded_height, padded_width))



	@slow
	def 		UpperCamelCase							(						self							:    List[str])->							Optional[int]:


						for model_name in FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
											__lowerCAmelCase	   =FocalNetModel.from_pretrained(_UpperCamelCase)
											self.assertIsNotNone(_UpperCamelCase)



	def 		UpperCamelCase							(						self							:    Dict)->							int:
						__lowerCAmelCase	   =self.model_tester.prepare_config_and_inputs_for_common()

						__lowerCAmelCase	   =_config_zero_init(_UpperCamelCase)
						for model_class in self.all_model_classes:
											__lowerCAmelCase	   =model_class(config=_UpperCamelCase)
											for name, param in model.named_parameters():
																if "embeddings" not in name and param.requires_grad:
																					self.assertIn(
																					    ((param.data.mean() * 1e9).round() / 1e9).item()				,	[0.0, 1.0]				,	msg=F"""Parameter {name} of model {model_class} seems not properly initialized"""				,	)






@require_vision
@require_torch
class 						__a (     unittest.TestCase				):



	@cached_property
	def 		UpperCamelCase							(						self							:    Optional[Any])->							int:
						return AutoImageProcessor.from_pretrained("""microsoft/focalnet-tiny""") if is_vision_available() else None



	@slow
	def 		UpperCamelCase							(						self							:    Dict)->							Tuple:
						__lowerCAmelCase	   =FocalNetForImageClassification.from_pretrained("""microsoft/focalnet-tiny""").to(_UpperCamelCase)
						__lowerCAmelCase	   =self.default_image_processor

						__lowerCAmelCase	   =Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""")
						__lowerCAmelCase	   =image_processor(images=_UpperCamelCase				,	return_tensors="""pt""").to(_UpperCamelCase)

						# forward pass
						with torch.no_grad():
											__lowerCAmelCase	   =model(**_UpperCamelCase)

						# verify the logits
						__lowerCAmelCase	   =torch.Size((1, 10_00))
						self.assertEqual(outputs.logits.shape				,	_UpperCamelCase)
						__lowerCAmelCase	   =torch.tensor([0.2_1_6_6, -0.4_3_6_8, 0.2_1_9_1]).to(_UpperCamelCase)
						self.assertTrue(torch.allclose(outputs.logits[0, :3]				,	_UpperCamelCase				,	atol=1e-4))
						self.assertTrue(outputs.logits.argmax(dim=-1).item()				,	2_81)






@require_torch
class 						__a (     __lowerCAmelCase	,    unittest.TestCase				):
	SCREAMING_SNAKE_CASE       =       (FocalNetBackbone,) if is_torch_available() else ()
	SCREAMING_SNAKE_CASE       =       FocalNetConfig

	SCREAMING_SNAKE_CASE       =       False



	def 		UpperCamelCase							(						self							:    Union[str, Any])->							Optional[Any]:
						__lowerCAmelCase	   =FocalNetModelTester(self)









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 						__a :



	def __init__(						self							:    Optional[int]				,	snake_case_							:    int				,	snake_case_							:    Optional[Any]=13				,	snake_case_							:    List[str]=7				,	snake_case_							:    Tuple=True				,	snake_case_							:    Optional[Any]=True				,	snake_case_							:    Optional[Any]=True				,	snake_case_							:    str=True				,	snake_case_							:    Optional[Any]=True				,	snake_case_							:    List[Any]=False				,	snake_case_							:    str=False				,	snake_case_							:    List[str]=False				,	snake_case_							:    List[Any]=2				,	snake_case_							:    List[Any]=99				,	snake_case_							:    Tuple=0				,	snake_case_							:    Optional[int]=32				,	snake_case_							:    Union[str, Any]=5				,	snake_case_							:    Any=4				,	snake_case_							:    str=0.1				,	snake_case_							:    List[Any]=0.1				,	snake_case_							:    Optional[Any]=5_12				,	snake_case_							:    str=2				,	snake_case_							:    List[str]=0.0_2				,	snake_case_							:    Optional[int]=2				,	snake_case_							:    Union[str, Any]=4				,	snake_case_							:    str="last"				,	snake_case_							:    Union[str, Any]=True				,	snake_case_							:    int=None				,	snake_case_							:    Any=0				,	)->							Tuple:
						__lowerCAmelCase	   =parent
						__lowerCAmelCase	   =batch_size
						__lowerCAmelCase	   =seq_length
						__lowerCAmelCase	   =is_training
						__lowerCAmelCase	   =use_input_lengths
						__lowerCAmelCase	   =use_token_type_ids
						__lowerCAmelCase	   =use_labels
						__lowerCAmelCase	   =gelu_activation
						__lowerCAmelCase	   =sinusoidal_embeddings
						__lowerCAmelCase	   =causal
						__lowerCAmelCase	   =asm
						__lowerCAmelCase	   =n_langs
						__lowerCAmelCase	   =vocab_size
						__lowerCAmelCase	   =n_special
						__lowerCAmelCase	   =hidden_size
						__lowerCAmelCase	   =num_hidden_layers
						__lowerCAmelCase	   =num_attention_heads
						__lowerCAmelCase	   =hidden_dropout_prob
						__lowerCAmelCase	   =attention_probs_dropout_prob
						__lowerCAmelCase	   =max_position_embeddings
						__lowerCAmelCase	   =type_sequence_label_size
						__lowerCAmelCase	   =initializer_range
						__lowerCAmelCase	   =num_labels
						__lowerCAmelCase	   =num_choices
						__lowerCAmelCase	   =summary_type
						__lowerCAmelCase	   =use_proj
						__lowerCAmelCase	   =scope
						__lowerCAmelCase	   =bos_token_id



	def 		UpperCamelCase							(						self							:    Tuple)->							int:
						__lowerCAmelCase	   =ids_tensor([self.batch_size, self.seq_length]				,	self.vocab_size)
						__lowerCAmelCase	   =random_attention_mask([self.batch_size, self.seq_length])

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

						__lowerCAmelCase	   =None
						if self.use_token_type_ids:
											__lowerCAmelCase	   =ids_tensor([self.batch_size, self.seq_length]				,	self.n_langs)

						__lowerCAmelCase	   =None
						__lowerCAmelCase	   =None
						__lowerCAmelCase	   =None
						if self.use_labels:
											__lowerCAmelCase	   =ids_tensor([self.batch_size]				,	self.type_sequence_label_size)
											__lowerCAmelCase	   =ids_tensor([self.batch_size, self.seq_length]				,	self.num_labels)
											__lowerCAmelCase	   =ids_tensor([self.batch_size]				,	2).float()
											__lowerCAmelCase	   =ids_tensor([self.batch_size]				,	self.num_choices)

						__lowerCAmelCase	   =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							:    Tuple)->							Union[str, Any]:
						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							:    Any				,	snake_case_							:    List[str]				,	snake_case_							:    Union[str, Any]				,	snake_case_							:    Dict				,	snake_case_							:    List[Any]				,	snake_case_							:    Dict				,	snake_case_							:    Union[str, Any]				,	snake_case_							:    Any				,	snake_case_							:    Optional[int]				,	snake_case_							:    List[Any]				,	)->							Tuple:
						__lowerCAmelCase	   =XLMModel(config=snake_case_)
						model.to(snake_case_)
						model.eval()
						__lowerCAmelCase	   =model(snake_case_				,	lengths=snake_case_				,	langs=snake_case_)
						__lowerCAmelCase	   =model(snake_case_				,	langs=snake_case_)
						__lowerCAmelCase	   =model(snake_case_)
						self.parent.assertEqual(result.last_hidden_state.shape				,	(self.batch_size, self.seq_length, self.hidden_size))



	def 		UpperCamelCase							(						self							:    str				,	snake_case_							:    str				,	snake_case_							:    List[Any]				,	snake_case_							:    str				,	snake_case_							:    Dict				,	snake_case_							:    Optional[Any]				,	snake_case_							:    Dict				,	snake_case_							:    Optional[int]				,	snake_case_							:    int				,	snake_case_							:    int				,	)->							Dict:
						__lowerCAmelCase	   =XLMWithLMHeadModel(snake_case_)
						model.to(snake_case_)
						model.eval()

						__lowerCAmelCase	   =model(snake_case_				,	token_type_ids=snake_case_				,	labels=snake_case_)
						self.parent.assertEqual(result.loss.shape				,	())
						self.parent.assertEqual(result.logits.shape				,	(self.batch_size, self.seq_length, self.vocab_size))



	def 		UpperCamelCase							(						self							:    Any				,	snake_case_							:    Union[str, Any]				,	snake_case_							:    str				,	snake_case_							:    Any				,	snake_case_							:    str				,	snake_case_							:    Union[str, Any]				,	snake_case_							:    Dict				,	snake_case_							:    int				,	snake_case_							:    List[Any]				,	snake_case_							:    Tuple				,	)->							Dict:
						__lowerCAmelCase	   =XLMForQuestionAnsweringSimple(snake_case_)
						model.to(snake_case_)
						model.eval()

						__lowerCAmelCase	   =model(snake_case_)

						__lowerCAmelCase	   =model(snake_case_				,	start_positions=snake_case_				,	end_positions=snake_case_)
						__lowerCAmelCase	   =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							:    Tuple				,	snake_case_							:    List[Any]				,	snake_case_							:    Optional[Any]				,	snake_case_							:    int				,	snake_case_							:    int				,	snake_case_							:    str				,	snake_case_							:    List[Any]				,	snake_case_							:    Optional[Any]				,	snake_case_							:    List[Any]				,	snake_case_							:    Tuple				,	)->							Optional[int]:
						__lowerCAmelCase	   =XLMForQuestionAnswering(snake_case_)
						model.to(snake_case_)
						model.eval()

						__lowerCAmelCase	   =model(snake_case_)

						__lowerCAmelCase	   =model(
						    snake_case_				,	start_positions=snake_case_				,	end_positions=snake_case_				,	cls_index=snake_case_				,	is_impossible=snake_case_				,	p_mask=snake_case_				,	)

						__lowerCAmelCase	   =model(
						    snake_case_				,	start_positions=snake_case_				,	end_positions=snake_case_				,	cls_index=snake_case_				,	is_impossible=snake_case_				,	)

						((__lowerCAmelCase)   ,	)	   =result_with_labels.to_tuple()

						__lowerCAmelCase	   =model(snake_case_				,	start_positions=snake_case_				,	end_positions=snake_case_)

						((__lowerCAmelCase)   ,	)	   =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							:    Tuple				,	snake_case_							:    Optional[Any]				,	snake_case_							:    List[Any]				,	snake_case_							:    Optional[int]				,	snake_case_							:    str				,	snake_case_							:    int				,	snake_case_							:    Optional[int]				,	snake_case_							:    Union[str, Any]				,	snake_case_							:    str				,	snake_case_							:    Optional[Any]				,	)->							int:
						__lowerCAmelCase	   =XLMForSequenceClassification(snake_case_)
						model.to(snake_case_)
						model.eval()

						__lowerCAmelCase	   =model(snake_case_)
						__lowerCAmelCase	   =model(snake_case_				,	labels=snake_case_)
						self.parent.assertEqual(result.loss.shape				,	())
						self.parent.assertEqual(result.logits.shape				,	(self.batch_size, self.type_sequence_label_size))



	def 		UpperCamelCase							(						self							:    Optional[Any]				,	snake_case_							:    Optional[int]				,	snake_case_							:    str				,	snake_case_							:    str				,	snake_case_							:    List[str]				,	snake_case_							:    int				,	snake_case_							:    Union[str, Any]				,	snake_case_							:    str				,	snake_case_							:    List[str]				,	snake_case_							:    Union[str, Any]				,	)->							Optional[Any]:
						__lowerCAmelCase	   =self.num_labels
						__lowerCAmelCase	   =XLMForTokenClassification(snake_case_)
						model.to(snake_case_)
						model.eval()

						__lowerCAmelCase	   =model(snake_case_				,	attention_mask=snake_case_				,	labels=snake_case_)
						self.parent.assertEqual(result.logits.shape				,	(self.batch_size, self.seq_length, self.num_labels))



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



	def 		UpperCamelCase							(						self							:    Optional[Any])->							List[Any]:
						__lowerCAmelCase	   =self.prepare_config_and_inputs()
						(
						    (
						    __lowerCAmelCase
						)   ,	(
						    __lowerCAmelCase
						)   ,	(
						    __lowerCAmelCase
						)   ,	(
						    __lowerCAmelCase
						)   ,	(
						    __lowerCAmelCase
						)   ,	(
						    __lowerCAmelCase
						)   ,	(
						    __lowerCAmelCase
						)   ,	(
						    __lowerCAmelCase
						)   ,	(
						    __lowerCAmelCase
						)   ,	
						)	   =config_and_inputs
						__lowerCAmelCase	   ={"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """lengths""": input_lengths}
						return config, inputs_dict






@require_torch
class 						__a (     SCREAMING_SNAKE_CASE	,    SCREAMING_SNAKE_CASE	,    SCREAMING_SNAKE_CASE	,    unittest.TestCase				):
	SCREAMING_SNAKE_CASE       =       (
	    (
	        XLMModel,
	        XLMWithLMHeadModel,
	        XLMForQuestionAnswering,
	        XLMForSequenceClassification,
	        XLMForQuestionAnsweringSimple,
	        XLMForTokenClassification,
	        XLMForMultipleChoice,
	    )
	    if is_torch_available()
	    else ()
	)
	SCREAMING_SNAKE_CASE       =       (
	    (XLMWithLMHeadModel,) if is_torch_available() else ()
	)  # TODO (PVP): Check other models whether language generation is also applicable
	SCREAMING_SNAKE_CASE       =       (
	    {
	        "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							:    List[str]				,	snake_case_							:    str				,	snake_case_							:    str				,	snake_case_							:    str				,	snake_case_							:    int				,	snake_case_							:    str)->							Tuple:
						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							:    int				,	snake_case_							:    Tuple				,	snake_case_							:    Any				,	snake_case_							:    str=False)->							str:
						__lowerCAmelCase	   =super()._prepare_for_class(snake_case_				,	snake_case_				,	return_labels=snake_case_)

						if return_labels:
											if model_class.__name__ == "XLMForQuestionAnswering":
																__lowerCAmelCase	   =torch.zeros(
																    self.model_tester.batch_size				,	dtype=torch.long				,	device=snake_case_)
																__lowerCAmelCase	   =torch.zeros(
																    self.model_tester.batch_size				,	dtype=torch.long				,	device=snake_case_)

						return inputs_dict



	def 		UpperCamelCase							(						self							:    int)->							List[Any]:
						__lowerCAmelCase	   =XLMModelTester(self)
						__lowerCAmelCase	   =ConfigTester(self				,	config_class=snake_case_				,	emb_dim=37)



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



	def 		UpperCamelCase							(						self							:    Optional[int])->							Union[str, Any]:
						__lowerCAmelCase	   =self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_xlm_model(*snake_case_)



	def 		UpperCamelCase							(						self							:    Any)->							int:
						__lowerCAmelCase	   =self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_xlm_lm_head(*snake_case_)



	def 		UpperCamelCase							(						self							:    Dict)->							str:
						__lowerCAmelCase	   =self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_xlm_simple_qa(*snake_case_)



	def 		UpperCamelCase							(						self							:    List[Any])->							Union[str, Any]:
						__lowerCAmelCase	   =self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_xlm_qa(*snake_case_)



	def 		UpperCamelCase							(						self							:    List[str])->							Dict:
						__lowerCAmelCase	   =self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_xlm_sequence_classif(*snake_case_)



	def 		UpperCamelCase							(						self							:    List[Any])->							int:
						__lowerCAmelCase	   =self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_xlm_token_classif(*snake_case_)



	def 		UpperCamelCase							(						self							:    str)->							str:
						__lowerCAmelCase	   =self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_xlm_for_multiple_choice(*snake_case_)



	def 		UpperCamelCase							(						self							:    Union[str, Any]				,	snake_case_							:    Tuple				,	snake_case_							:    Optional[Any]				,	snake_case_							:    List[Any]				,	snake_case_							:    Any				,	snake_case_							:    int				,	snake_case_							:    Optional[int]=False				,	snake_case_							:    List[Any]=1)->							Optional[Any]:
						self.assertIsInstance(snake_case_				,	snake_case_)
						self.assertListEqual(
						    [isinstance(snake_case_				,	snake_case_) for iter_attentions in attentions]				,	[True] * len(snake_case_))
						self.assertEqual(len(snake_case_)				,	(max_length - min_length) * num_beam_groups)

						for idx, iter_attentions in enumerate(snake_case_):
											# adds PAD dummy token
											__lowerCAmelCase	   =min_length + idx + 1
											__lowerCAmelCase	   =min_length + idx + 1

											__lowerCAmelCase	   =(
											    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(snake_case_))



	def 		UpperCamelCase							(						self							:    List[Any]				,	snake_case_							:    Any				,	snake_case_							:    str				,	snake_case_							:    Any				,	snake_case_							:    List[Any]				,	snake_case_							:    Dict				,	snake_case_							:    List[str]=False				,	snake_case_							:    Any=1)->							Any:
						self.assertIsInstance(snake_case_				,	snake_case_)
						self.assertListEqual(
						    [isinstance(snake_case_				,	snake_case_) for iter_hidden_states in hidden_states]				,	[True] * len(snake_case_)				,	)
						self.assertEqual(len(snake_case_)				,	(max_length - min_length) * num_beam_groups)

						for idx, iter_hidden_states in enumerate(snake_case_):
											# adds PAD dummy token
											__lowerCAmelCase	   =min_length + idx + 1
											__lowerCAmelCase	   =(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(snake_case_)				,	)
						pass



	@slow
	def 		UpperCamelCase							(						self							:    Any)->							List[str]:
						for model_name in XLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
											__lowerCAmelCase	   =XLMModel.from_pretrained(snake_case_)
											self.assertIsNotNone(snake_case_)






@require_torch
class 						__a (     unittest.TestCase				):



	@slow
	def 		UpperCamelCase							(						self							:    int)->							List[str]:
						__lowerCAmelCase	   =XLMWithLMHeadModel.from_pretrained("""xlm-mlm-en-2048""")
						model.to(snake_case_)
						__lowerCAmelCase	   =torch.tensor([[14, 4_47]]				,	dtype=torch.long				,	device=snake_case_)  # the president
						__lowerCAmelCase	   =[
						    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
						__lowerCAmelCase	   =model.generate(snake_case_				,	do_sample=snake_case_)
						self.assertListEqual(output_ids[0].cpu().numpy().tolist()				,	snake_case_)




