
"""simple docstring"""


import bza
import gzip
import lzma
import os
import shutil
import struct
import tarfile
import warnings
import zipfile
from abc import ABC, abstractmethod
from pathlib import Path
from typing import Dict, List, Optional, Type, Union

from .. import config
from .filelock import FileLock
from .logging import get_logger


_lowercase							   =				get_logger(__name__)







class 				lowerCAmelCase_				:



						'''simple docstring'''


						def __init__( self     :      List[Any]  ,A_     :      Optional[str] = None      )     ->   str:
							A						   =   (
							    os.path.join(A_  ,config.EXTRACTED_DATASETS_DIR      ) if cache_dir else config.EXTRACTED_DATASETS_PATH
							)
							A						   =   Extractor


						def 						_SCREAMING_SNAKE_CASE      ( self     :      Optional[int]  ,A_     :      str      )     ->   str:
							from .file_utils import hash_url_to_filename

							# Path where we extract compressed archives
							# We extract in the cache dir, and get the extracted path name by hashing the original path"
							A						   =   os.path.abspath(A_      )
							return os.path.join(self.extract_dir  ,hash_url_to_filename(A_      )      )


						def 						_SCREAMING_SNAKE_CASE      ( self     :      Any  ,A_     :      str  ,A_     :      bool      )     ->   bool:
							return force_extract or (
							    not os.path.isfile(A_      ) and not (os.path.isdir(A_      ) and os.listdir(A_      ))
							)




						def 						_SCREAMING_SNAKE_CASE      ( self     :      List[str]  ,A_     :      str  ,A_     :      bool = False      )     ->   str:
							A						   =   self.extractor.infer_extractor_format(A_      )
							if not extractor_format:
								return input_path
							A						   =   self._get_output_path(A_      )
							if self._do_extract(A_  ,A_      ):
								self.extractor.extract(A_  ,A_  ,A_      )
							return output_path







class 				lowerCAmelCase_				(      _lowercase    ):



						'''simple docstring'''


						@classmethod
						@abstractmethod
						def 						_SCREAMING_SNAKE_CASE      ( cls     :      str  ,A_     :      Union[Path, str]  ,**A_     :      Union[str, Any]      )     ->   bool:
							...




						@staticmethod
						@abstractmethod
						def 						_SCREAMING_SNAKE_CASE      ( A_     :      Union[Path, str]  ,A_     :      Union[Path, str]      )     ->   None:
							...







class 				lowerCAmelCase_				(      _lowercase		,					_lowercase    ):



						'''simple docstring'''


						_lowerCamelCase:    List[bytes]      =    []


						@staticmethod
						def 						_SCREAMING_SNAKE_CASE      ( A_     :      Union[Path, str]  ,A_     :      int      )     ->   List[Any]:
							with open(A_  ,'rb'      ) as f:
								return f.read(A_      )




						@classmethod
						def 						_SCREAMING_SNAKE_CASE      ( cls     :      str  ,A_     :      Union[Path, str]  ,A_     :      bytes = b""      )     ->   bool:
							if not magic_number:
								A						   =   max(len(A_      ) for cls_magic_number in cls.magic_numbers      )
								try:
									A						   =   cls.read_magic_number(A_  ,A_      )
								except OSError:
									return False
							return any(magic_number.startswith(A_      ) for cls_magic_number in cls.magic_numbers      )







class 				lowerCAmelCase_				(      _lowercase    ):



						'''simple docstring'''


						@classmethod
						def 						_SCREAMING_SNAKE_CASE      ( cls     :      Dict  ,A_     :      Union[Path, str]  ,**A_     :      Tuple      )     ->   bool:
							return tarfile.is_tarfile(A_      )


						@staticmethod
						def 						_SCREAMING_SNAKE_CASE      ( A_     :      Dict  ,A_     :      Optional[Any]      )     ->   Optional[Any]:

							def resolved(A_     :      str      ) -> str:
								return os.path.realpath(os.path.abspath(A_      )      )

							def badpath(A_     :      str  ,A_     :      str      ) -> bool:
								# joinpath will ignore base if path is absolute
								return not resolved(os.path.join(A_  ,A_      )      ).startswith(A_      )

							def badlink(A_     :      Tuple  ,A_     :      str      ) -> bool:
								# Links are interpreted relative to the directory containing the link
								A						   =   resolved(os.path.join(A_  ,os.path.dirname(info.name      )      )      )
								return badpath(info.linkname  ,base=A_      )

							A						   =   resolved(A_      )

							for finfo in members:
								if badpath(finfo.name  ,A_      ):
									logger.error(F'Extraction of {finfo.name} is blocked (illegal path)'      )
								elif finfo.issym() and badlink(A_  ,A_      ):
									logger.error(F'Extraction of {finfo.name} is blocked: Symlink to {finfo.linkname}'      )
								elif finfo.islnk() and badlink(A_  ,A_      ):
									logger.error(F'Extraction of {finfo.name} is blocked: Hard link to {finfo.linkname}'      )
								else:
									yield finfo




						@staticmethod
						def 						_SCREAMING_SNAKE_CASE      ( A_     :      Union[Path, str]  ,A_     :      Union[Path, str]      )     ->   None:
							os.makedirs(A_  ,exist_ok=A_      )
							A						   =   tarfile.open(A_      )
							tar_file.extractall(A_  ,members=TarExtractor.safemembers(A_  ,A_      )      )
							tar_file.close()







class 				lowerCAmelCase_				(      _lowercase    ):



						'''simple docstring'''


						_lowerCamelCase:    Optional[Any]      =    [B'''\x1F\x8B''']


						@staticmethod
						def 						_SCREAMING_SNAKE_CASE      ( A_     :      Union[Path, str]  ,A_     :      Union[Path, str]      )     ->   None:
							with gzip.open(A_  ,'rb'      ) as gzip_file:
								with open(A_  ,'wb'      ) as extracted_file:
									shutil.copyfileobj(A_  ,A_      )







class 				lowerCAmelCase_				(      _lowercase    ):



						'''simple docstring'''


						_lowerCamelCase:    int      =    [
						    B'''PK\x03\x04''',
						    B'''PK\x05\x06''',  # empty archive
						    B'''PK\x07\x08''',  # spanned archive
						]


						@classmethod
						def 						_SCREAMING_SNAKE_CASE      ( cls     :      Any  ,A_     :      Union[Path, str]  ,A_     :      bytes = b""      )     ->   bool:
							if super().is_extractable(A_  ,magic_number=A_      ):
								return True
							try:
								# Alternative version of zipfile.is_zipfile that has less false positives, but misses executable zip archives.
								# From: https://github.com/python/cpython/pull/5053
								from zipfile import (
								    _CD_SIGNATURE,
								    _ECD_DISK_NUMBER,
								    _ECD_DISK_START,
								    _ECD_ENTRIES_TOTAL,
								    _ECD_OFFSET,
								    _ECD_SIZE,
								    _EndRecData,
								    sizeCentralDir,
								    stringCentralDir,
								    structCentralDir,
								)

								with open(A_  ,'rb'      ) as fp:
									A						   =   _EndRecData(A_      )
									if endrec:
										if endrec[_ECD_ENTRIES_TOTAL] == 0 and endrec[_ECD_SIZE] == 0 and endrec[_ECD_OFFSET] == 0:
											return True  # Empty zipfiles are still zipfiles
										elif endrec[_ECD_DISK_NUMBER] == endrec[_ECD_DISK_START]:
											fp.seek(endrec[_ECD_OFFSET]      )  # Central directory is on the same disk
											if fp.tell() == endrec[_ECD_OFFSET] and endrec[_ECD_SIZE] >= sizeCentralDir:
												A						   =   fp.read(A_      )  # CD is where we expect it to be
												if len(A_      ) == sizeCentralDir:
													A						   =   struct.unpack(A_  ,A_      )  # CD is the right size
													if centdir[_CD_SIGNATURE] == stringCentralDir:
														return True  # First central directory entry  has correct magic number
								return False
							except Exception:  # catch all errors in case future python versions change the zipfile internals
								return False




						@staticmethod
						def 						_SCREAMING_SNAKE_CASE      ( A_     :      Union[Path, str]  ,A_     :      Union[Path, str]      )     ->   None:
							os.makedirs(A_  ,exist_ok=A_      )
							with zipfile.ZipFile(A_  ,'r'      ) as zip_file:
								zip_file.extractall(A_      )
								zip_file.close()







class 				lowerCAmelCase_				(      _lowercase    ):



						'''simple docstring'''


						_lowerCamelCase:    Union[str, Any]      =    [B'''\xFD\x37\x7A\x58\x5A\x00''']


						@staticmethod
						def 						_SCREAMING_SNAKE_CASE      ( A_     :      Union[Path, str]  ,A_     :      Union[Path, str]      )     ->   None:
							with lzma.open(A_      ) as compressed_file:
								with open(A_  ,'wb'      ) as extracted_file:
									shutil.copyfileobj(A_  ,A_      )







class 				lowerCAmelCase_				(      _lowercase    ):



						'''simple docstring'''


						_lowerCamelCase:    Optional[int]      =    [B'''Rar!\x1a\x07\x00''', B'''Rar!\x1a\x07\x01\x00''']  # RAR_ID  # RAR5_ID


						@staticmethod
						def 						_SCREAMING_SNAKE_CASE      ( A_     :      Union[Path, str]  ,A_     :      Union[Path, str]      )     ->   None:
							if not config.RARFILE_AVAILABLE:
								raise ImportError('Please pip install rarfile'      )
							import rarfile

							os.makedirs(A_  ,exist_ok=A_      )
							A						   =   rarfile.RarFile(A_      )
							rf.extractall(A_      )
							rf.close()







class 				lowerCAmelCase_				(      _lowercase    ):



						'''simple docstring'''


						_lowerCamelCase:    str      =    [B'''\x28\xb5\x2F\xFD''']


						@staticmethod
						def 						_SCREAMING_SNAKE_CASE      ( A_     :      Union[Path, str]  ,A_     :      Union[Path, str]      )     ->   None:
							if not config.ZSTANDARD_AVAILABLE:
								raise ImportError('Please pip install zstandard'      )
							import zstandard as zstd

							A						   =   zstd.ZstdDecompressor()
							with open(A_  ,'rb'      ) as ifh, open(A_  ,'wb'      ) as ofh:
								dctx.copy_stream(A_  ,A_      )







class 				lowerCAmelCase_				(      _lowercase    ):



						'''simple docstring'''


						_lowerCamelCase:    Union[str, Any]      =    [B'''\x42\x5A\x68''']


						@staticmethod
						def 						_SCREAMING_SNAKE_CASE      ( A_     :      Union[Path, str]  ,A_     :      Union[Path, str]      )     ->   None:
							with bza.open(A_  ,'rb'      ) as compressed_file:
								with open(A_  ,'wb'      ) as extracted_file:
									shutil.copyfileobj(A_  ,A_      )







class 				lowerCAmelCase_				(      _lowercase    ):



						'''simple docstring'''


						_lowerCamelCase:    Dict      =    [B'''\x37\x7A\xBC\xAF\x27\x1C''']


						@staticmethod
						def 						_SCREAMING_SNAKE_CASE      ( A_     :      Union[Path, str]  ,A_     :      Union[Path, str]      )     ->   None:
							if not config.PY7ZR_AVAILABLE:
								raise ImportError('Please pip install py7zr'      )
							import pyazr

							os.makedirs(A_  ,exist_ok=A_      )
							with pyazr.SevenZipFile(A_  ,'r'      ) as archive:
								archive.extractall(A_      )







class 				lowerCAmelCase_				(      _lowercase    ):



						'''simple docstring'''


						_lowerCamelCase:    Optional[Any]      =    [B'''\x04\x22\x4D\x18''']


						@staticmethod
						def 						_SCREAMING_SNAKE_CASE      ( A_     :      Union[Path, str]  ,A_     :      Union[Path, str]      )     ->   None:
							if not config.LZ4_AVAILABLE:
								raise ImportError('Please pip install lz4'      )
							import lza.frame

							with lza.frame.open(A_  ,'rb'      ) as compressed_file:
								with open(A_  ,'wb'      ) as extracted_file:
									shutil.copyfileobj(A_  ,A_      )







class 				lowerCAmelCase_				:



						'''simple docstring'''


						_lowerCamelCase:    Dict[str, Type[BaseExtractor]]      =    {
						    "tar": TarExtractor,
						    "gzip": GzipExtractor,
						    "zip": ZipExtractor,
						    "xz": XzExtractor,
						    "rar": RarExtractor,
						    "zstd": ZstdExtractor,
						    "bz2": BzipaExtractor,
						    "7z": SevenZipExtractor,  # <Added version="2.4.0"/>
						    "lz4": LzaExtractor,  # <Added version="2.4.0"/>
						}


						@classmethod
						def 						_SCREAMING_SNAKE_CASE      ( cls     :      Optional[int]      )     ->   Union[str, Any]:
							return max(
							    len(A_      )
							    for extractor in cls.extractors.values()
							    if issubclass(A_  ,A_      )
							    for extractor_magic_number in extractor.magic_numbers      )


						@staticmethod
						def 						_SCREAMING_SNAKE_CASE      ( A_     :      Union[Path, str]  ,A_     :      int      )     ->   List[Any]:
							try:
								return MagicNumberBaseExtractor.read_magic_number(A_  ,magic_number_length=A_      )
							except OSError:
								return b""


						@classmethod
						def 						_SCREAMING_SNAKE_CASE      ( cls     :      Union[str, Any]  ,A_     :      Union[Path, str]  ,A_     :      bool = False      )     ->   bool:
							warnings.warn(
							    'Method \'is_extractable\' was deprecated in version 2.4.0 and will be removed in 3.0.0. '
							    'Use \'infer_extractor_format\' instead.'  ,category=A_  ,)
							A						   =   cls.infer_extractor_format(A_      )
							if extractor_format:
								return True if not return_extractor else (True, cls.extractors[extractor_format])
							return False if not return_extractor else (False, None)


						@classmethod
						def 						_SCREAMING_SNAKE_CASE      ( cls     :      Tuple  ,A_     :      Union[Path, str]      )     ->   str:  # <Added version="2.4.0"/>
							A						   =   cls._get_magic_number_max_length()
							A						   =   cls._read_magic_number(A_  ,A_      )
							for extractor_format, extractor in cls.extractors.items():
								if extractor.is_extractable(A_  ,magic_number=A_      ):
									return extractor_format




						@classmethod
						def 						_SCREAMING_SNAKE_CASE      ( cls     :      Optional[Any]  ,A_     :      Union[Path, str]  ,A_     :      Union[Path, str]  ,A_     :      Optional[str] = None  ,A_     :      Optional[BaseExtractor] = "deprecated"  ,)     ->   None:
							os.makedirs(os.path.dirname(A_      )  ,exist_ok=A_      )
							# Prevent parallel extractions
							A						   =   str(Path(A_      ).with_suffix('.lock'      )      )
							with FileLock(A_      ):
								shutil.rmtree(A_  ,ignore_errors=A_      )
								if extractor_format or extractor != "deprecated":
									if extractor != "deprecated" or not isinstance(A_  ,A_      ):  # passed as positional arg
										warnings.warn(
										    'Parameter \'extractor\' was deprecated in version 2.4.0 and will be removed in 3.0.0. '
										    'Use \'extractor_format\' instead.'  ,category=A_  ,)
										A						   =   extractor if extractor != 'deprecated' else extractor_format
									else:
										A						   =   cls.extractors[extractor_format]
									return extractor.extract(A_  ,A_      )
								else:
									warnings.warn(
									    'Parameter \'extractor_format\' was made required in version 2.4.0 and not passing it will raise an '
									    'exception in 3.0.0.'  ,category=A_  ,)
									for extractor in cls.extractors.values():
										if extractor.is_extractable(A_      ):
											return extractor.extract(A_  ,A_      )

"""simple docstring"""


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



						'''simple docstring'''


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


						def 						_SCREAMING_SNAKE_CASE      ( self     :      List[str]      )     ->   Dict:
							A						   =   ids_tensor([self.batch_size, self.seq_length]  ,self.vocab_size      )
							A						   =   random_attention_mask([self.batch_size, self.seq_length]      )

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

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

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

							A						   =   self.get_config()

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


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


						def 						_SCREAMING_SNAKE_CASE      ( self     :      int  ,A_     :      str  ,A_     :      Union[str, Any]  ,A_     :      Any  ,A_     :      Any  ,A_     :      Any  ,A_     :      Union[str, Any]  ,A_     :      List[str]  ,A_     :      List[str]  ,A_     :      List[str]  ,)     ->   Union[str, Any]:
							A						   =   XLMWithLMHeadModel(A_      )
							model.to(A_      )
							model.eval()

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


						def 						_SCREAMING_SNAKE_CASE      ( self     :      Union[str, Any]  ,A_     :      Tuple  ,A_     :      Tuple  ,A_     :      str  ,A_     :      int  ,A_     :      str  ,A_     :      Optional[Any]  ,A_     :      Any  ,A_     :      Any  ,A_     :      Dict  ,)     ->   List[str]:
							A						   =   XLMForQuestionAnsweringSimple(A_      )
							model.to(A_      )
							model.eval()

							A						   =   model(A_      )

							A						   =   model(A_  ,start_positions=A_  ,end_positions=A_      )
							A						   =   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 						_SCREAMING_SNAKE_CASE      ( self     :      Any  ,A_     :      Optional[int]  ,A_     :      Dict  ,A_     :      Optional[Any]  ,A_     :      List[Any]  ,A_     :      List[str]  ,A_     :      List[Any]  ,A_     :      Optional[Any]  ,A_     :      str  ,A_     :      Any  ,)     ->   Optional[int]:
							A						   =   XLMForQuestionAnswering(A_      )
							model.to(A_      )
							model.eval()

							A						   =   model(A_      )

							A						   =   model(
							    A_  ,start_positions=A_  ,end_positions=A_  ,cls_index=A_  ,is_impossible=A_  ,p_mask=A_  ,)

							A						   =   model(
							    A_  ,start_positions=A_  ,end_positions=A_  ,cls_index=A_  ,is_impossible=A_  ,)

							((A)   ,      )						   =   result_with_labels.to_tuple()

							A						   =   model(A_  ,start_positions=A_  ,end_positions=A_      )

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

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


						def 						_SCREAMING_SNAKE_CASE      ( self     :      Optional[int]  ,A_     :      Optional[Any]  ,A_     :      str  ,A_     :      Tuple  ,A_     :      List[str]  ,A_     :      Dict  ,A_     :      Dict  ,A_     :      Union[str, Any]  ,A_     :      Dict  ,A_     :      Any  ,)     ->   Any:
							A						   =   self.num_labels
							A						   =   XLMForTokenClassification(A_      )
							model.to(A_      )
							model.eval()

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


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




						def 						_SCREAMING_SNAKE_CASE      ( self     :      str      )     ->   List[Any]:
							A						   =   self.prepare_config_and_inputs()
							(
							    (
							    A
							)   ,      (
							    A
							)   ,      (
							    A
							)   ,      (
							    A
							)   ,      (
							    A
							)   ,      (
							    A
							)   ,      (
							    A
							)   ,      (
							    A
							)   ,      (
							    A
							)   ,      
							)						   =   config_and_inputs
							A						   =   {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'lengths': input_lengths}
							return config, inputs_dict







@require_torch
class 				lowerCAmelCase_				(      _lowercase		,					_lowercase		,					_lowercase		,					unittest.TestCase    ):



						'''simple docstring'''


						_lowerCamelCase:    Dict      =    (
						    (
						        XLMModel,
						        XLMWithLMHeadModel,
						        XLMForQuestionAnswering,
						        XLMForSequenceClassification,
						        XLMForQuestionAnsweringSimple,
						        XLMForTokenClassification,
						        XLMForMultipleChoice,
						    )
						    if is_torch_available()
						    else ()
						)
						_lowerCamelCase:    Dict      =    (
						    (XLMWithLMHeadModel,) if is_torch_available() else ()
						)  # TODO (PVP): Check other models whether language generation is also applicable
						_lowerCamelCase:    Optional[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 						_SCREAMING_SNAKE_CASE      ( self     :      List[str]  ,A_     :      Optional[int]  ,A_     :      Optional[int]  ,A_     :      Tuple  ,A_     :      Any  ,A_     :      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 						_SCREAMING_SNAKE_CASE      ( self     :      Optional[int]  ,A_     :      Optional[int]  ,A_     :      Tuple  ,A_     :      str=False      )     ->   Dict:
							A						   =   super()._prepare_for_class(A_  ,A_  ,return_labels=A_      )

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

							return inputs_dict


						def 						_SCREAMING_SNAKE_CASE      ( self     :      int      )     ->   List[str]:
							A						   =   XLMModelTester(self      )
							A						   =   ConfigTester(self  ,config_class=A_  ,emb_dim=37      )


						def 						_SCREAMING_SNAKE_CASE      ( self     :      Union[str, Any]      )     ->   str:
							self.config_tester.run_common_tests()


						def 						_SCREAMING_SNAKE_CASE      ( self     :      List[str]      )     ->   Optional[int]:
							A						   =   self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_xlm_model(*A_      )


						def 						_SCREAMING_SNAKE_CASE      ( self     :      Any      )     ->   Dict:
							A						   =   self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_xlm_lm_head(*A_      )


						def 						_SCREAMING_SNAKE_CASE      ( self     :      Union[str, Any]      )     ->   Dict:
							A						   =   self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_xlm_simple_qa(*A_      )


						def 						_SCREAMING_SNAKE_CASE      ( self     :      Optional[Any]      )     ->   Tuple:
							A						   =   self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_xlm_qa(*A_      )


						def 						_SCREAMING_SNAKE_CASE      ( self     :      str      )     ->   List[Any]:
							A						   =   self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_xlm_sequence_classif(*A_      )


						def 						_SCREAMING_SNAKE_CASE      ( self     :      List[Any]      )     ->   Tuple:
							A						   =   self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_xlm_token_classif(*A_      )


						def 						_SCREAMING_SNAKE_CASE      ( self     :      int      )     ->   Dict:
							A						   =   self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_xlm_for_multiple_choice(*A_      )


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

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

								A						   =   (
								    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(A_      )      )


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

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




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







@require_torch
class 				lowerCAmelCase_				(      unittest.TestCase    ):



						'''simple docstring'''


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