

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







	'''simple docstring'''





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





	def   __snake_case				(			self		):
					A__  :	Optional[Any]         =							ids_tensor([self.batch_size, self.seq_length]				,       self.vocab_size		)
					A__  :	List[str]         =							random_attention_mask([self.batch_size, self.seq_length]		)

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

					A__  :	Union[str, Any]         =							None
					if self.use_token_type_ids:
									A__  :	Optional[int]         =							ids_tensor([self.batch_size, self.seq_length]				,       self.n_langs		)

					A__  :	Any         =							None
					A__  :	Any         =							None
					A__  :	str         =							None
					if self.use_labels:
									A__  :	List[str]         =							ids_tensor([self.batch_size]				,       self.type_sequence_label_size		)
									A__  :	Union[str, Any]         =							ids_tensor([self.batch_size, self.seq_length]				,       self.num_labels		)
									A__  :	Tuple         =							ids_tensor([self.batch_size]				,       2		).float()
									A__  :	Any         =							ids_tensor([self.batch_size]				,       self.num_choices		)

					A__  :	Any         =							self.get_config()

					return (
					    config,
					    input_ids,
					    token_type_ids,
					    input_lengths,
					    sequence_labels,
					    token_labels,
					    is_impossible_labels,
					    choice_labels,
					    input_mask,
					)





	def   __snake_case				(			self		):
					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   __snake_case				(			self				,       UpperCamelCase__				,       UpperCamelCase__				,       UpperCamelCase__				,       UpperCamelCase__				,       UpperCamelCase__				,       UpperCamelCase__				,       UpperCamelCase__				,       UpperCamelCase__				,       UpperCamelCase__				,       ):
					A__  :	int         =							XLMModel(config=UpperCamelCase__		)
					model.to(UpperCamelCase__		)
					model.eval()
					A__  :	Optional[Any]         =							model(UpperCamelCase__				,       lengths=UpperCamelCase__				,       langs=UpperCamelCase__		)
					A__  :	str         =							model(UpperCamelCase__				,       langs=UpperCamelCase__		)
					A__  :	str         =							model(UpperCamelCase__		)
					self.parent.assertEqual(result.last_hidden_state.shape				,       (self.batch_size, self.seq_length, self.hidden_size)		)





	def   __snake_case				(			self				,       UpperCamelCase__				,       UpperCamelCase__				,       UpperCamelCase__				,       UpperCamelCase__				,       UpperCamelCase__				,       UpperCamelCase__				,       UpperCamelCase__				,       UpperCamelCase__				,       UpperCamelCase__				,       ):
					A__  :	Optional[Any]         =							XLMWithLMHeadModel(UpperCamelCase__		)
					model.to(UpperCamelCase__		)
					model.eval()

					A__  :	Tuple         =							model(UpperCamelCase__				,       token_type_ids=UpperCamelCase__				,       labels=UpperCamelCase__		)
					self.parent.assertEqual(result.loss.shape				,       ()		)
					self.parent.assertEqual(result.logits.shape				,       (self.batch_size, self.seq_length, self.vocab_size)		)





	def   __snake_case				(			self				,       UpperCamelCase__				,       UpperCamelCase__				,       UpperCamelCase__				,       UpperCamelCase__				,       UpperCamelCase__				,       UpperCamelCase__				,       UpperCamelCase__				,       UpperCamelCase__				,       UpperCamelCase__				,       ):
					A__  :	List[str]         =							XLMForQuestionAnsweringSimple(UpperCamelCase__		)
					model.to(UpperCamelCase__		)
					model.eval()

					A__  :	Optional[int]         =							model(UpperCamelCase__		)

					A__  :	Optional[Any]         =							model(UpperCamelCase__				,       start_positions=UpperCamelCase__				,       end_positions=UpperCamelCase__		)
					A__  :	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   __snake_case				(			self				,       UpperCamelCase__				,       UpperCamelCase__				,       UpperCamelCase__				,       UpperCamelCase__				,       UpperCamelCase__				,       UpperCamelCase__				,       UpperCamelCase__				,       UpperCamelCase__				,       UpperCamelCase__				,       ):
					A__  :	List[str]         =							XLMForQuestionAnswering(UpperCamelCase__		)
					model.to(UpperCamelCase__		)
					model.eval()

					A__  :	Optional[Any]         =							model(UpperCamelCase__		)

					A__  :	List[Any]         =							model(
					    UpperCamelCase__				,       start_positions=UpperCamelCase__				,       end_positions=UpperCamelCase__				,       cls_index=UpperCamelCase__				,       is_impossible=UpperCamelCase__				,       p_mask=UpperCamelCase__				,       )

					A__  :	int         =							model(
					    UpperCamelCase__				,       start_positions=UpperCamelCase__				,       end_positions=UpperCamelCase__				,       cls_index=UpperCamelCase__				,       is_impossible=UpperCamelCase__				,       )

					(A__							)  :	Union[str, Any]         =							result_with_labels.to_tuple()

					A__  :	str         =							model(UpperCamelCase__				,       start_positions=UpperCamelCase__				,       end_positions=UpperCamelCase__		)

					(A__							)  :	List[str]         =							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   __snake_case				(			self				,       UpperCamelCase__				,       UpperCamelCase__				,       UpperCamelCase__				,       UpperCamelCase__				,       UpperCamelCase__				,       UpperCamelCase__				,       UpperCamelCase__				,       UpperCamelCase__				,       UpperCamelCase__				,       ):
					A__  :	Any         =							XLMForSequenceClassification(UpperCamelCase__		)
					model.to(UpperCamelCase__		)
					model.eval()

					A__  :	Tuple         =							model(UpperCamelCase__		)
					A__  :	Any         =							model(UpperCamelCase__				,       labels=UpperCamelCase__		)
					self.parent.assertEqual(result.loss.shape				,       ()		)
					self.parent.assertEqual(result.logits.shape				,       (self.batch_size, self.type_sequence_label_size)		)





	def   __snake_case				(			self				,       UpperCamelCase__				,       UpperCamelCase__				,       UpperCamelCase__				,       UpperCamelCase__				,       UpperCamelCase__				,       UpperCamelCase__				,       UpperCamelCase__				,       UpperCamelCase__				,       UpperCamelCase__				,       ):
					A__  :	List[str]         =							self.num_labels
					A__  :	Union[str, Any]         =							XLMForTokenClassification(UpperCamelCase__		)
					model.to(UpperCamelCase__		)
					model.eval()

					A__  :	List[Any]         =							model(UpperCamelCase__				,       attention_mask=UpperCamelCase__				,       labels=UpperCamelCase__		)
					self.parent.assertEqual(result.logits.shape				,       (self.batch_size, self.seq_length, self.num_labels)		)





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





	def   __snake_case				(			self		):
					A__  :	Dict         =							self.prepare_config_and_inputs()
					(
					    A__							
					)  :	Optional[int]         =							config_and_inputs
					A__  :	Any         =							{'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''lengths''': input_lengths}
					return config, inputs_dict







@require_torch
class  UpperCamelCase__		(    SCREAMING_SNAKE_CASE_,			SCREAMING_SNAKE_CASE_,			SCREAMING_SNAKE_CASE_,			unittest.TestCase   ):







	'''simple docstring'''
	_lowerCAmelCase							       =				(
	    (
	        XLMModel,
	        XLMWithLMHeadModel,
	        XLMForQuestionAnswering,
	        XLMForSequenceClassification,
	        XLMForQuestionAnsweringSimple,
	        XLMForTokenClassification,
	        XLMForMultipleChoice,
	    )
	    if is_torch_available()
	    else ()
	)
	_lowerCAmelCase							       =				(
	    (XLMWithLMHeadModel,) if is_torch_available() else ()
	)  # TODO (PVP): Check other models whether language generation is also applicable
	_lowerCAmelCase							       =				(
	    {
	        "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   __snake_case				(			self				,       UpperCamelCase__				,       UpperCamelCase__				,       UpperCamelCase__				,       UpperCamelCase__				,       UpperCamelCase__		):
					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   __snake_case				(			self				,       UpperCamelCase__				,       UpperCamelCase__				,       UpperCamelCase__=False		):
					A__  :	Union[str, Any]         =							super()._prepare_for_class(UpperCamelCase__				,       UpperCamelCase__				,       return_labels=UpperCamelCase__		)

					if return_labels:
									if model_class.__name__ == "XLMForQuestionAnswering":
													A__  :	Optional[int]         =							torch.zeros(
													    self.model_tester.batch_size				,       dtype=torch.long				,       device=UpperCamelCase__		)
													A__  :	Optional[Any]         =							torch.zeros(
													    self.model_tester.batch_size				,       dtype=torch.long				,       device=UpperCamelCase__		)

					return inputs_dict





	def   __snake_case				(			self		):
					A__  :	Optional[Any]         =							XLMModelTester(self		)
					A__  :	Optional[Any]         =							ConfigTester(self				,       config_class=UpperCamelCase__				,       emb_dim=37		)





	def   __snake_case				(			self		):
					self.config_tester.run_common_tests()





	def   __snake_case				(			self		):
					A__  :	Optional[int]         =							self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_xlm_model(*UpperCamelCase__		)





	def   __snake_case				(			self		):
					A__  :	Optional[Any]         =							self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_xlm_lm_head(*UpperCamelCase__		)





	def   __snake_case				(			self		):
					A__  :	int         =							self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_xlm_simple_qa(*UpperCamelCase__		)





	def   __snake_case				(			self		):
					A__  :	int         =							self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_xlm_qa(*UpperCamelCase__		)





	def   __snake_case				(			self		):
					A__  :	Optional[Any]         =							self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_xlm_sequence_classif(*UpperCamelCase__		)





	def   __snake_case				(			self		):
					A__  :	Optional[int]         =							self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_xlm_token_classif(*UpperCamelCase__		)





	def   __snake_case				(			self		):
					A__  :	List[str]         =							self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_xlm_for_multiple_choice(*UpperCamelCase__		)





	def   __snake_case				(			self				,       UpperCamelCase__				,       UpperCamelCase__				,       UpperCamelCase__				,       UpperCamelCase__				,       UpperCamelCase__				,       UpperCamelCase__=False				,       UpperCamelCase__=1		):
					self.assertIsInstance(UpperCamelCase__				,       UpperCamelCase__		)
					self.assertListEqual(
					    [isinstance(UpperCamelCase__				,       UpperCamelCase__		) for iter_attentions in attentions]				,       [True] * len(UpperCamelCase__		)		)
					self.assertEqual(len(UpperCamelCase__		)				,       (max_length - min_length) * num_beam_groups		)

					for idx, iter_attentions in enumerate(UpperCamelCase__		):
									# adds PAD dummy token
									A__  :	str         =							min_length + idx + 1
									A__  :	Any         =							min_length + idx + 1

									A__  :	str         =							(
									    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(UpperCamelCase__		)		)





	def   __snake_case				(			self				,       UpperCamelCase__				,       UpperCamelCase__				,       UpperCamelCase__				,       UpperCamelCase__				,       UpperCamelCase__				,       UpperCamelCase__=False				,       UpperCamelCase__=1		):
					self.assertIsInstance(UpperCamelCase__				,       UpperCamelCase__		)
					self.assertListEqual(
					    [isinstance(UpperCamelCase__				,       UpperCamelCase__		) for iter_hidden_states in hidden_states]				,       [True] * len(UpperCamelCase__		)				,       )
					self.assertEqual(len(UpperCamelCase__		)				,       (max_length - min_length) * num_beam_groups		)

					for idx, iter_hidden_states in enumerate(UpperCamelCase__		):
									# adds PAD dummy token
									A__  :	List[Any]         =							min_length + idx + 1
									A__  :	str         =							(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(UpperCamelCase__		)				,       )
					pass





	@slow
	def   __snake_case				(			self		):
					for model_name in XLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
									A__  :	Dict         =							XLMModel.from_pretrained(UpperCamelCase__		)
									self.assertIsNotNone(UpperCamelCase__		)







@require_torch
class  UpperCamelCase__		(    unittest.TestCase   ):







	'''simple docstring'''





	@slow
	def   __snake_case				(			self		):
					A__  :	str         =							XLMWithLMHeadModel.from_pretrained('''xlm-mlm-en-2048'''		)
					model.to(UpperCamelCase__		)
					A__  :	Union[str, Any]         =							torch.tensor([[14, 447]]				,       dtype=torch.long				,       device=UpperCamelCase__		)  # the president
					A__  :	Union[str, Any]         =							[
					    14,
					    447,
					    14,
					    447,
					    14,
					    447,
					    14,
					    447,
					    14,
					    447,
					    14,
					    447,
					    14,
					    447,
					    14,
					    447,
					    14,
					    447,
					    14,
					    447,
					]  # 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
					A__  :	Tuple         =							model.generate(UpperCamelCase__				,       do_sample=UpperCamelCase__		)
					self.assertListEqual(output_ids[0].cpu().numpy().tolist()				,       UpperCamelCase__		)

import json
import os
import tempfile

from transformers.testing_utils import check_json_file_has_correct_format







class  UpperCamelCase__		:







	'''simple docstring'''
	_lowerCAmelCase							       =				None





	def   __snake_case				(			self		):
					A__  :	Dict         =							self.feature_extraction_class(**self.feat_extract_dict		)
					A__  :	Tuple         =							json.loads(feat_extract.to_json_string()		)
					for key, value in self.feat_extract_dict.items():
									self.assertEqual(obj[key]				,       UpperCamelCase__		)





	def   __snake_case				(			self		):
					A__  :	Any         =							self.feature_extraction_class(**self.feat_extract_dict		)

					with tempfile.TemporaryDirectory() as tmpdirname:
									A__  :	Any         =							os.path.join(UpperCamelCase__				,       '''feat_extract.json'''		)
									feat_extract_first.to_json_file(UpperCamelCase__		)
									A__  :	Dict         =							self.feature_extraction_class.from_json_file(UpperCamelCase__		)

					self.assertEqual(feat_extract_second.to_dict()				,       feat_extract_first.to_dict()		)





	def   __snake_case				(			self		):
					A__  :	Any         =							self.feature_extraction_class(**self.feat_extract_dict		)

					with tempfile.TemporaryDirectory() as tmpdirname:
									A__  :	Any         =							feat_extract_first.save_pretrained(UpperCamelCase__		)[0]
									check_json_file_has_correct_format(UpperCamelCase__		)
									A__  :	Optional[int]         =							self.feature_extraction_class.from_pretrained(UpperCamelCase__		)

					self.assertEqual(feat_extract_second.to_dict()				,       feat_extract_first.to_dict()		)





	def   __snake_case				(			self		):
					A__  :	str         =							self.feature_extraction_class()
					self.assertIsNotNone(UpperCamelCase__		)