






"""simple docstring"""


import json
import os
import re
import warnings
from pathlib import Path
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple, Union

import sentencepiece

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging


_UpperCamelCase							:       Tuple       					=		logging.get_logger(__name__)

_UpperCamelCase							:       Any       					=		{
    'source_spm': 'source.spm',
    'target_spm': 'target.spm',
    'vocab': 'vocab.json',
    'target_vocab_file': 'target_vocab.json',
    'tokenizer_config_file': 'tokenizer_config.json',
}

_UpperCamelCase							:       Optional[int]       					=		{
    'source_spm': {
        'Helsinki-NLP/opus-mt-en-de': 'https://huggingface.co/Helsinki-NLP/opus-mt-en-de/resolve/main/source.spm'
    },
    'target_spm': {
        'Helsinki-NLP/opus-mt-en-de': 'https://huggingface.co/Helsinki-NLP/opus-mt-en-de/resolve/main/target.spm'
    },
    'vocab': {
        'Helsinki-NLP/opus-mt-en-de': 'https://huggingface.co/Helsinki-NLP/opus-mt-en-de/resolve/main/vocab.json'
    },
    'tokenizer_config_file': {
        'Helsinki-NLP/opus-mt-en-de': (
            'https://huggingface.co/Helsinki-NLP/opus-mt-en-de/resolve/main/tokenizer_config.json'
        )
    },
}

_UpperCamelCase							:       Union[str, Any]       					=		{'Helsinki-NLP/opus-mt-en-de': 512}
_UpperCamelCase							:       Optional[Any]       					=		{}






class 		snake_case    (    UpperCAmelCase			):
    __magic_name__       	=	VOCAB_FILES_NAMES
    __magic_name__       	=	PRETRAINED_VOCAB_FILES_MAP
    __magic_name__       	=	PRETRAINED_INIT_CONFIGURATION
    __magic_name__       	=	PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
    __magic_name__       	=	['''input_ids''', '''attention_mask''']
    __magic_name__       	=	re.compile('''>>.+<<'''			)  # type: re.Pattern





    def __init__(				self      :   List[str]							,						A      :   str							,						A      :   Union[str, Any]							,						A      :   Optional[int]							,						A      :   Dict=None							,						A      :   Optional[Any]=None							,						A      :   Any=None							,						A      :   Any="<unk>"							,						A      :   Any="</s>"							,						A      :   int="<pad>"							,						A      :   Optional[Any]=5_1_2							,						A      :   Optional[Dict[str, Any]] = None							,						A      :   Union[str, Any]=False							,						**A      :   Any							,						):


      '''simple docstring'''




      a	:     List[str]							=  {} if sp_model_kwargs is None else sp_model_kwargs

      super().__init__(
          # bos_token=bos_token,  unused. Start decoding with config.decoder_start_token_id
          source_lang=A							,						target_lang=A							,						unk_token=A							,						eos_token=A							,						pad_token=A							,						model_max_length=A							,						sp_model_kwargs=self.sp_model_kwargs							,						target_vocab_file=A							,						separate_vocabs=A							,						**A							,						)
      assert Path(A     ).exists(), F'''cannot find spm source {source_spm}'''

      a	:     List[Any]							=  separate_vocabs
      a	:     List[Any]							=  load_json(A     )
      if self.unk_token not in self.encoder:
        raise KeyError('<unk> token must be in vocab'     )
      assert self.pad_token in self.encoder

      if separate_vocabs:
        a	:     Optional[int]							=  load_json(A     )
        a	:     Any							=  {v: k for k, v in self.target_encoder.items()}
        a	:     Optional[Any]							=  []
      else:
        a	:     Optional[Any]							=  {v: k for k, v in self.encoder.items()}
        a	:     list							=  [k for k in self.encoder if k.startswith('>>'     ) and k.endswith('<<'     )]

      a	:     Any							=  source_lang
      a	:     Union[str, Any]							=  target_lang
      a	:     Optional[int]							=  [source_spm, target_spm]

      # load SentencePiece model for pre-processing
      a	:     str							=  load_spm(A							,						self.sp_model_kwargs     )
      a	:     Optional[Any]							=  load_spm(A							,						self.sp_model_kwargs     )
      a	:     str							=  self.spm_source
      a	:     Tuple							=  self.encoder

      # Multilingual target side: default to using first supported language code.

      self._setup_normalizer()





    def 							lowerCamelCase__ (				self      :   Optional[Any]     ):


      '''simple docstring'''




      try:
        from sacremoses import MosesPunctNormalizer

        a	:     Any							=  MosesPunctNormalizer(self.source_lang     ).normalize
      except (ImportError, FileNotFoundError):
        warnings.warn('Recommended: pip install sacremoses.'     )
        a	:     List[Any]							=  lambda A     : x





    def 							lowerCamelCase__ (				self      :   Tuple							,						A      :   str     ):


      '''simple docstring'''




      return self.punc_normalizer(A     ) if x else ""





    def 							lowerCamelCase__ (				self      :   int							,						A      :   int     ):


      '''simple docstring'''




      return self.current_encoder.get(A							,						self.current_encoder[self.unk_token]     )





    def 							lowerCamelCase__ (				self      :   Union[str, Any]							,						A      :   str     ):


      '''simple docstring'''




      a	:     Optional[int]							=  self.language_code_re.match(A     )
      a	:     list							=  [match.group(0     )] if match else []
      return code, self.language_code_re.sub(''							,						A     )





    def 							lowerCamelCase__ (				self      :   List[str]							,						A      :   str     ):


      '''simple docstring'''




      a,	a	:     int							=  self.remove_language_code(A     )
      a	:     Optional[Any]							=  self.current_spm.encode(A							,						out_type=A     )
      return code + pieces





    def 							lowerCamelCase__ (				self      :   Union[str, Any]							,						A      :   int     ):


      '''simple docstring'''




      return self.decoder.get(A							,						self.unk_token     )





    def 							lowerCamelCase__ (				self      :   Tuple							,						A      :   Optional[int]							,						**A      :   Dict     ):


      '''simple docstring'''




      return super().batch_decode(A							,						**A     )





    def 							lowerCamelCase__ (				self      :   str							,						A      :   str							,						**A      :   List[Any]     ):


      '''simple docstring'''




      return super().decode(A							,						**A     )





    def 							lowerCamelCase__ (				self      :   int							,						A      :   List[str]     ):


      '''simple docstring'''




      a	:     Dict							=  self.spm_source if self._decode_use_source_tokenizer else self.spm_target
      a	:     Any							=  []
      a	:     Any							=  ''
      for token in tokens:
        # make sure that special tokens are not decoded using sentencepiece model
        if token in self.all_special_tokens:
          out_string += sp_model.decode_pieces(A     ) + token + " "
          a	:     Dict							=  []
        else:
          current_sub_tokens.append(A     )
      out_string += sp_model.decode_pieces(A     )
      return out_string.strip()





    def 							lowerCamelCase__ (				self      :   Optional[int]							,						A      :   Optional[Any]							,						A      :   str=None     ):


      '''simple docstring'''




      if token_ids_a is None:
        return token_ids_a + [self.eos_token_id]
      # We don't expect to process pairs, but leave the pair logic for API consistency
      return token_ids_a + token_ids_a + [self.eos_token_id]





    def 							lowerCamelCase__ (				self      :   List[Any]     ):


      '''simple docstring'''




      a	:     int							=  self.spm_source
      a	:     str							=  self.encoder





    def 							lowerCamelCase__ (				self      :   Dict     ):


      '''simple docstring'''




      a	:     Any							=  self.spm_target
      if self.separate_vocabs:
        a	:     str							=  self.target_encoder





    @property
    def 							lowerCamelCase__ (				self      :   Union[str, Any]     ):


      '''simple docstring'''




      return len(self.encoder     )





    def 							lowerCamelCase__ (				self      :   str							,						A      :   str							,						A      :   Optional[str] = None     ):


      '''simple docstring'''




      if not os.path.isdir(A     ):
        logger.error(F'''Vocabulary path ({save_directory}) should be a directory'''     )
        return
      a	:     Tuple							=  []

      if self.separate_vocabs:
        a	:     Any							=  os.path.join(
            A							,						(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab']							,						)
        a	:     List[Any]							=  os.path.join(
            A							,						(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['target_vocab_file']							,						)
        save_json(self.encoder							,						A     )
        save_json(self.target_encoder							,						A     )
        saved_files.append(A     )
        saved_files.append(A     )
      else:
        a	:     Tuple							=  os.path.join(
            A							,						(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab']     )
        save_json(self.encoder							,						A     )
        saved_files.append(A     )

      for spm_save_filename, spm_orig_path, spm_model in zip(
          [VOCAB_FILES_NAMES['source_spm'], VOCAB_FILES_NAMES['target_spm']]							,						self.spm_files							,						[self.spm_source, self.spm_target]							,						):
        a	:     Dict							=  os.path.join(
            A							,						(filename_prefix + '-' if filename_prefix else '') + spm_save_filename     )
        if os.path.abspath(A     ) != os.path.abspath(A     ) and os.path.isfile(A     ):
          copyfile(A							,						A     )
          saved_files.append(A     )
        elif not os.path.isfile(A     ):
          with open(A							,						'wb'     ) as fi:
            a	:     Optional[int]							=  spm_model.serialized_model_proto()
            fi.write(A     )
          saved_files.append(A     )

      return tuple(A     )





    def 							lowerCamelCase__ (				self      :   List[str]     ):


      '''simple docstring'''




      return self.get_src_vocab()





    def 							lowerCamelCase__ (				self      :   List[Any]     ):


      '''simple docstring'''




      return dict(self.encoder							,						**self.added_tokens_encoder     )





    def 							lowerCamelCase__ (				self      :   Tuple     ):


      '''simple docstring'''




      return dict(self.target_encoder							,						**self.added_tokens_decoder     )





    def __getstate__(				self      :   Optional[int]     ):


      '''simple docstring'''




      a	:     List[str]							=  self.__dict__.copy()
      state.update(
          {k: None for k in ['spm_source', 'spm_target', 'current_spm', 'punc_normalizer', 'target_vocab_file']}     )
      return state





    def __setstate__(				self      :   str							,						A      :   Dict     ):


      '''simple docstring'''




      a	:     List[Any]							=  d

      # for backward compatibility
      if not hasattr(self							,						'sp_model_kwargs'     ):
        a	:     List[Any]							=  {}

      a,	a	:     Tuple							=  (load_spm(A							,						self.sp_model_kwargs     ) for f in self.spm_files)
      a	:     List[Any]							=  self.spm_source
      self._setup_normalizer()





    def 							lowerCamelCase__ (				self      :   Optional[int]							,						*A      :   int							,						**A      :   List[str]     ):


      '''simple docstring'''




      return 1





    def 							lowerCamelCase__ (				self      :   List[str]							,						A      :   int     ):


      '''simple docstring'''




      a	:     Optional[int]							=  set(self.all_special_ids     )  # call it once instead of inside list comp
      all_special_ids.remove(self.unk_token_id     )  # <unk> is only sometimes special
      return [1 if x in all_special_ids else 0 for x in seq]





    def 							lowerCamelCase__ (				self      :   Tuple							,						A      :   List							,						A      :   Optional[List] = None							,						A      :   bool = False     ):


      '''simple docstring'''




      if already_has_special_tokens:
        return self._special_token_mask(A     )
      elif token_ids_a is None:
        return self._special_token_mask(A     ) + [1]
      else:
        return self._special_token_mask(token_ids_a + token_ids_a     ) + [1]




def      snake_case    (A_ :str      ,     A_ :Dict[str, Any] ):







  '''simple docstring'''

  a	:     Union[str, Any]							=  sentencepiece.SentencePieceProcessor(**A_ )
  spm.Load(A_ )
  return spm




def      snake_case    (A_ :int      ,     A_ :str ):







  '''simple docstring'''

  with open(A_      ,     'w' ) as f:
    json.dump(A_      ,     A_      ,     indent=2 )






def      snake_case    (A_ :str ):







  '''simple docstring'''

  with open(A_      ,     'r' ) as f:
    return json.load(A_ )












"""simple docstring"""


from __future__ import annotations

import unittest

from transformers import is_tf_available
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
   import tensorflow as tf

   from transformers import (
       TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST,
       TFXLMForMultipleChoice,
       TFXLMForQuestionAnsweringSimple,
       TFXLMForSequenceClassification,
       TFXLMForTokenClassification,
       TFXLMModel,
       TFXLMWithLMHeadModel,
       XLMConfig,
   )






class 		snake_case    :





    def __init__(				self      :   Union[str, Any]							,						A      :   Optional[Any]							,						):


      '''simple docstring'''




      a	:     Union[str, Any]							=  parent
      a	:     str							=  1_3
      a	:     Optional[int]							=  7
      a	:     List[str]							=  True
      a	:     int							=  True
      a	:     Optional[Any]							=  True
      a	:     Tuple							=  True
      a	:     List[str]							=  True
      a	:     Union[str, Any]							=  False
      a	:     Optional[Any]							=  False
      a	:     List[str]							=  False
      a	:     Union[str, Any]							=  2
      a	:     Optional[int]							=  9_9
      a	:     Optional[Any]							=  0
      a	:     Tuple							=  3_2
      a	:     Union[str, Any]							=  2
      a	:     Optional[Any]							=  4
      a	:     Optional[int]							=  0.1
      a	:     List[str]							=  0.1
      a	:     int							=  5_1_2
      a	:     List[Any]							=  1_6
      a	:     Dict							=  2
      a	:     List[str]							=  0.02
      a	:     str							=  3
      a	:     Optional[Any]							=  4
      a	:     Optional[Any]							=  'last'
      a	:     Any							=  True
      a	:     Union[str, Any]							=  None
      a	:     int							=  0





    def 							lowerCamelCase__ (				self      :   Optional[int]     ):


      '''simple docstring'''




      a	:     Dict							=  ids_tensor([self.batch_size, self.seq_length]							,						self.vocab_size     )
      a	:     Dict							=  random_attention_mask([self.batch_size, self.seq_length]							,						dtype=tf.floataa     )

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

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

      a	:     Optional[int]							=  None
      a	:     Optional[Any]							=  None
      a	:     Tuple							=  None
      if self.use_labels:
        a	:     Union[str, Any]							=  ids_tensor([self.batch_size]							,						self.type_sequence_label_size     )
        a	:     Any							=  ids_tensor([self.batch_size, self.seq_length]							,						self.num_labels     )
        a	:     Dict							=  ids_tensor([self.batch_size]							,						2							,						dtype=tf.floataa     )
        a	:     Tuple							=  ids_tensor([self.batch_size]							,						self.num_choices     )

      a	:     str							=  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							,						bos_token_id=self.bos_token_id							,						)

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





    def 							lowerCamelCase__ (				self      :   List[str]							,						A      :   Union[str, Any]							,						A      :   Optional[Any]							,						A      :   List[str]							,						A      :   List[Any]							,						A      :   Union[str, Any]							,						A      :   Dict							,						A      :   Optional[int]							,						A      :   List[Any]							,						A      :   Optional[int]							,						):


      '''simple docstring'''




      a	:     int							=  TFXLMModel(config=A     )
      a	:     Optional[Any]							=  {'input_ids': input_ids, 'lengths': input_lengths, 'langs': token_type_ids}
      a	:     Dict							=  model(A     )

      a	:     List[str]							=  [input_ids, input_mask]
      a	:     Union[str, Any]							=  model(A     )
      self.parent.assertEqual(result.last_hidden_state.shape							,						(self.batch_size, self.seq_length, self.hidden_size)     )





    def 							lowerCamelCase__ (				self      :   str							,						A      :   List[Any]							,						A      :   List[Any]							,						A      :   int							,						A      :   int							,						A      :   Any							,						A      :   List[Any]							,						A      :   Tuple							,						A      :   str							,						A      :   List[str]							,						):


      '''simple docstring'''




      a	:     Union[str, Any]							=  TFXLMWithLMHeadModel(A     )

      a	:     str							=  {'input_ids': input_ids, 'lengths': input_lengths, 'langs': token_type_ids}
      a	:     List[str]							=  model(A     )

      a	:     Union[str, Any]							=  outputs

      self.parent.assertEqual(result.logits.shape							,						(self.batch_size, self.seq_length, self.vocab_size)     )





    def 							lowerCamelCase__ (				self      :   List[str]							,						A      :   int							,						A      :   List[str]							,						A      :   Tuple							,						A      :   Dict							,						A      :   Dict							,						A      :   str							,						A      :   Union[str, Any]							,						A      :   Optional[Any]							,						A      :   Union[str, Any]							,						):


      '''simple docstring'''




      a	:     Any							=  TFXLMForQuestionAnsweringSimple(A     )

      a	:     Optional[Any]							=  {'input_ids': input_ids, 'lengths': input_lengths}

      a	:     Any							=  model(A     )

      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 							lowerCamelCase__ (				self      :   Optional[int]							,						A      :   Optional[int]							,						A      :   Dict							,						A      :   int							,						A      :   Any							,						A      :   List[Any]							,						A      :   str							,						A      :   List[Any]							,						A      :   Dict							,						A      :   List[str]							,						):


      '''simple docstring'''




      a	:     Dict							=  TFXLMForSequenceClassification(A     )

      a	:     Optional[int]							=  {'input_ids': input_ids, 'lengths': input_lengths}

      a	:     Tuple							=  model(A     )

      self.parent.assertEqual(result.logits.shape							,						(self.batch_size, self.type_sequence_label_size)     )





    def 							lowerCamelCase__ (				self      :   int							,						A      :   Optional[Any]							,						A      :   str							,						A      :   Dict							,						A      :   Optional[Any]							,						A      :   List[str]							,						A      :   List[str]							,						A      :   List[Any]							,						A      :   List[Any]							,						A      :   str							,						):


      '''simple docstring'''




      a	:     Any							=  self.num_labels
      a	:     int							=  TFXLMForTokenClassification(config=A     )
      a	:     Union[str, Any]							=  {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids}
      a	:     int							=  model(A     )
      self.parent.assertEqual(result.logits.shape							,						(self.batch_size, self.seq_length, self.num_labels)     )





    def 							lowerCamelCase__ (				self      :   Optional[Any]							,						A      :   Any							,						A      :   Optional[Any]							,						A      :   List[Any]							,						A      :   Dict							,						A      :   List[Any]							,						A      :   Any							,						A      :   List[Any]							,						A      :   List[str]							,						A      :   str							,						):


      '''simple docstring'''




      a	:     Tuple							=  self.num_choices
      a	:     List[str]							=  TFXLMForMultipleChoice(config=A     )
      a	:     List[str]							=  tf.tile(tf.expand_dims(A							,						1     )							,						(1, self.num_choices, 1)     )
      a	:     str							=  tf.tile(tf.expand_dims(A							,						1     )							,						(1, self.num_choices, 1)     )
      a	:     Union[str, Any]							=  tf.tile(tf.expand_dims(A							,						1     )							,						(1, self.num_choices, 1)     )
      a	:     str							=  {
          'input_ids': multiple_choice_inputs_ids,
          'attention_mask': multiple_choice_input_mask,
          'token_type_ids': multiple_choice_token_type_ids,
      }
      a	:     str							=  model(A     )
      self.parent.assertEqual(result.logits.shape							,						(self.batch_size, self.num_choices)     )





    def 							lowerCamelCase__ (				self      :   Any     ):


      '''simple docstring'''




      a	:     Union[str, Any]							=  self.prepare_config_and_inputs()
      (
          (
          a
      ),	(
          a
      ),	(
          a
      ),	(
          a
      ),	(
          a
      ),	(
          a
      ),	(
          a
      ),	(
          a
      ),	(
          a
      ),	
      )	:     Dict							=  config_and_inputs
      a	:     Tuple							=  {
          'input_ids': input_ids,
          'token_type_ids': token_type_ids,
          'langs': token_type_ids,
          'lengths': input_lengths,
      }
      return config, inputs_dict






@require_tf
class 		snake_case    (    UpperCAmelCase  ,					UpperCAmelCase  ,					unittest.TestCase			):
    __magic_name__       	=	(
        (
            TFXLMModel,
            TFXLMWithLMHeadModel,
            TFXLMForSequenceClassification,
            TFXLMForQuestionAnsweringSimple,
            TFXLMForTokenClassification,
            TFXLMForMultipleChoice,
        )
        if is_tf_available()
        else ()
    )
    __magic_name__       	=	(
        (TFXLMWithLMHeadModel,) if is_tf_available() else ()
    )  # TODO (PVP): Check other models whether language generation is also applicable
    __magic_name__       	=	(
        {
            '''feature-extraction''': TFXLMModel,
            '''fill-mask''': TFXLMWithLMHeadModel,
            '''question-answering''': TFXLMForQuestionAnsweringSimple,
            '''text-classification''': TFXLMForSequenceClassification,
            '''text-generation''': TFXLMWithLMHeadModel,
            '''token-classification''': TFXLMForTokenClassification,
            '''zero-shot''': TFXLMForSequenceClassification,
        }
        if is_tf_available()
        else {}
    )
    __magic_name__       	=	False
    __magic_name__       	=	False





    def 							lowerCamelCase__ (				self      :   Any							,						A      :   List[Any]							,						A      :   Optional[Any]							,						A      :   str							,						A      :   Optional[Any]							,						A      :   List[str]     ):


      '''simple docstring'''




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

      return False





    def 							lowerCamelCase__ (				self      :   int     ):


      '''simple docstring'''




      a	:     str							=  TFXLMModelTester(self     )
      a	:     int							=  ConfigTester(self							,						config_class=A							,						emb_dim=3_7     )





    def 							lowerCamelCase__ (				self      :   str     ):


      '''simple docstring'''




      self.config_tester.run_common_tests()





    def 							lowerCamelCase__ (				self      :   int     ):


      '''simple docstring'''




      a	:     Optional[int]							=  self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_xlm_model(*A     )





    def 							lowerCamelCase__ (				self      :   Union[str, Any]     ):


      '''simple docstring'''




      a	:     Optional[Any]							=  self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_xlm_lm_head(*A     )





    def 							lowerCamelCase__ (				self      :   List[Any]     ):


      '''simple docstring'''




      a	:     Optional[int]							=  self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_xlm_qa(*A     )





    def 							lowerCamelCase__ (				self      :   int     ):


      '''simple docstring'''




      a	:     List[str]							=  self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_xlm_sequence_classif(*A     )





    def 							lowerCamelCase__ (				self      :   Any     ):


      '''simple docstring'''




      a	:     str							=  self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_xlm_for_token_classification(*A     )





    def 							lowerCamelCase__ (				self      :   Tuple     ):


      '''simple docstring'''




      a	:     Tuple							=  self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_xlm_for_multiple_choice(*A     )





    @slow
    def 							lowerCamelCase__ (				self      :   Optional[int]     ):


      '''simple docstring'''




      for model_name in TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        a	:     Any							=  TFXLMModel.from_pretrained(A     )
        self.assertIsNotNone(A     )






@require_tf
class 		snake_case    (    unittest.TestCase			):





    @slow
    def 							lowerCamelCase__ (				self      :   Dict     ):


      '''simple docstring'''




      a	:     List[Any]							=  TFXLMWithLMHeadModel.from_pretrained('xlm-mlm-en-2048'     )
      a	:     Optional[int]							=  tf.convert_to_tensor([[1_4, 4_4_7]]							,						dtype=tf.intaa     )  # the president
      a	:     List[Any]							=  [
          1_4,
          4_4_7,
          1_4,
          4_4_7,
          1_4,
          4_4_7,
          1_4,
          4_4_7,
          1_4,
          4_4_7,
          1_4,
          4_4_7,
          1_4,
          4_4_7,
          1_4,
          4_4_7,
          1_4,
          4_4_7,
          1_4,
          4_4_7,
      ]  # 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	:     Optional[Any]							=  model.generate(A							,						do_sample=A     )
      self.assertListEqual(output_ids[0].numpy().tolist()							,						A     )




