






"""simple docstring"""


import argparse
import pathlib
from pathlib import Path
from tempfile import TemporaryDirectory

import esm as esm_module
import torch
from esm.esmfold.va.misc import batch_encode_sequences as esmfold_encode_sequences
from esm.esmfold.va.pretrained import esmfold_va

from transformers.models.esm.configuration_esm import EsmConfig, EsmFoldConfig
from transformers.models.esm.modeling_esm import (
    EsmForMaskedLM,
    EsmForSequenceClassification,
    EsmIntermediate,
    EsmLayer,
    EsmOutput,
    EsmSelfAttention,
    EsmSelfOutput,
)
from transformers.models.esm.modeling_esmfold import EsmForProteinFolding
from transformers.models.esm.tokenization_esm import EsmTokenizer
from transformers.utils import logging


logging.set_verbosity_info()
_UpperCamelCase							:       Optional[Any]       					=		logging.get_logger(__name__)

_UpperCamelCase							:       List[Any]       					=		[
    (
        'protein1',
        'MNGTEGPNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQHKKLRTPLNYILLNLAVADLFMVLGGFTSTLYTSLHGYFVFGPTGCNLEGFFATLGGEIALWSLVVLAIERYVVVCKPMSNFRFGENHAIMGVAFTWVMALACAAPPLAGWSRYIPEGLQCSCGIDYYTLKPEVNNESFVIYMFVVHFTIPMIIIFFCYGQLVFTVKEAAAQQQESATTQKAEKEVTRMVIIMVIAFLICWVPYASVAFYIFTHQGSNFGPIFMTIPAFFAKSAAIYNPVIYIMMNKQFRNCMLTTICCGKNPLGDDEASATVSKTETSQVAPA',
    ),
    ('protein2', 'MKTVRQERLKSIVRILERSKEPVSGAQLAEELSVSRQVIVQDIAYLRSLGYNIVATPRGYVLA'),
    ('protein3', 'MKTVRQERLKSI<mask>RILERSKEPVSGAQLAEELS<mask>SRQVIVQDIAYLRSLGYN<mask>VATPRGYVLAGG'),
    ('protein4', 'MKTVRQERLKSI<mask>RILERSKEPVSGAQLAEELS<mask>SRQVIVQDIAYLRSLGYN<mask>VATPRGYVLA'),
]

_UpperCamelCase							:       Any       					=		{
    'esm1b_t33_650M_UR50S': esm_module.pretrained.esm1b_t33_650M_UR50S,
    'esm1v_t33_650M_UR90S_1': esm_module.pretrained.esm1v_t33_650M_UR90S_1,
    'esm1v_t33_650M_UR90S_2': esm_module.pretrained.esm1v_t33_650M_UR90S_2,
    'esm1v_t33_650M_UR90S_3': esm_module.pretrained.esm1v_t33_650M_UR90S_3,
    'esm1v_t33_650M_UR90S_4': esm_module.pretrained.esm1v_t33_650M_UR90S_4,
    'esm1v_t33_650M_UR90S_5': esm_module.pretrained.esm1v_t33_650M_UR90S_5,
    'esm2_t48_15B_UR50D': esm_module.pretrained.esm2_t48_15B_UR50D,
    'esm2_t36_3B_UR50D': esm_module.pretrained.esm2_t36_3B_UR50D,
    'esm2_t33_650M_UR50D': esm_module.pretrained.esm2_t33_650M_UR50D,
    'esm2_t30_150M_UR50D': esm_module.pretrained.esm2_t30_150M_UR50D,
    'esm2_t12_35M_UR50D': esm_module.pretrained.esm2_t12_35M_UR50D,
    'esm2_t6_8M_UR50D': esm_module.pretrained.esm2_t6_8M_UR50D,
    'esmfold_v1': esmfold_va,
}

_UpperCamelCase							:       Optional[Any]       					=		list('ARNDCQEGHILKMFPSTWYV')

_UpperCamelCase							:       Dict       					=		restypes + ['X']
_UpperCamelCase							:       Any       					=		restypes_with_x + ['<pad>', '<mask>', '<cls>', '<sep>', '<eos>']




def      snake_case    ():







  '''simple docstring'''

  with TemporaryDirectory() as tempdir:
    a	:     Optional[int]							=  '\n'.join(A_ )
    a	:     List[Any]							=  Path(A_ ) / 'vocab.txt'
    vocab_file.write_text(A_ )
    a	:     Union[str, Any]							=  EsmTokenizer(vocab_file=str(A_ ) )
  a	:     Tuple							=  0  # Overlaps with 'A' but that seems to be what they want
  return hf_tokenizer




def      snake_case    (A_ :Optional[Any]      ,     A_ :Tuple ):







  '''simple docstring'''

  a	:     Union[str, Any]							=  our_module.load_state_dict(original_module.state_dict() )
  if status.missing_keys:
    raise ValueError(f'''Missing keys: {status.missing_keys}''' )
  if status.unexpected_keys:
    raise ValueError(f'''Unexpected keys: {status.unexpected_keys}''' )




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







  '''simple docstring'''

  if model.startswith('esmfold' ):
    a	:     Any							=  MODEL_MAPPING[model]()
  else:
    a,	a	:     Dict							=  MODEL_MAPPING[model]()
  esm.eval()  # disable dropout

  if model.startswith('esmfold' ):
    a	:     Any							=  esm.esm.embed_dim
    a	:     int							=  esm.esm.num_layers
    a	:     Dict							=  esm.esm.attention_heads
    a	:     int							=  4 * embed_dim
    a	:     Optional[int]							=  esm.esm.token_dropout
    a	:     Union[str, Any]							=  False  # This code path does not exist in ESM-2
    a	:     List[Any]							=  'rotary'
    a	:     str							=  True
    a	:     Tuple							=  EsmFoldConfig()
    for key, val in esm.cfg.items():
      if hasattr(A_      ,     A_ ) and key != "trunk":
        setattr(A_      ,     A_      ,     A_ )
    for key, val in esm.cfg.trunk.items():
      if hasattr(esmfold_config.trunk      ,     A_ ) and key != "structure_module":
        setattr(esmfold_config.trunk      ,     A_      ,     A_ )
    for key, val in esm.cfg.trunk.structure_module.items():
      if hasattr(esmfold_config.trunk.structure_module      ,     A_ ):
        setattr(esmfold_config.trunk.structure_module      ,     A_      ,     A_ )
  elif hasattr(A_      ,     'args' ):
    # Indicates an ESM-1b or ESM-1v model
    a	:     List[str]							=  esm.args.embed_dim
    a	:     List[Any]							=  esm.args.layers
    a	:     List[str]							=  esm.args.attention_heads
    a	:     Optional[int]							=  esm.args.ffn_embed_dim
    a	:     Any							=  esm.args.token_dropout
    a	:     List[Any]							=  True if esm.emb_layer_norm_before else False
    a	:     Union[str, Any]							=  'absolute'
    a	:     Optional[Any]							=  False
    a	:     Any							=  None
  else:
    # Indicates an ESM-2 model
    a	:     Dict							=  esm.embed_dim
    a	:     Optional[Any]							=  esm.num_layers
    a	:     Optional[Any]							=  esm.attention_heads
    a	:     Optional[Any]							=  4 * embed_dim  # This is hardcoded in ESM-2
    a	:     Optional[int]							=  esm.token_dropout
    a	:     Tuple							=  False  # This code path does not exist in ESM-2
    a	:     int							=  'rotary'
    a	:     Dict							=  False
    a	:     Dict							=  None

  if is_folding_model:
    a	:     str							=  esm.esm.alphabet
  a	:     List[Any]							=  tuple(alphabet.all_toks )
  a	:     str							=  alphabet.mask_idx
  a	:     Union[str, Any]							=  alphabet.padding_idx

  if is_folding_model:
    a	:     List[Any]							=  esm.esm
  else:
    a	:     List[Any]							=  esm

  a	:     Union[str, Any]							=  EsmConfig(
      vocab_size=original_esm_model.embed_tokens.num_embeddings      ,     mask_token_id=A_      ,     hidden_size=A_      ,     num_hidden_layers=A_      ,     num_attention_heads=A_      ,     intermediate_size=A_      ,     max_position_embeddings=1_0_2_6      ,     layer_norm_eps=1E-5      ,     attention_probs_dropout_prob=0.0      ,     hidden_dropout_prob=0.0      ,     pad_token_id=A_      ,     emb_layer_norm_before=A_      ,     token_dropout=A_      ,     position_embedding_type=A_      ,     is_folding_model=A_      ,     esmfold_config=A_      ,     vocab_list=A_      ,     )
  if classification_head:
    a	:     str							=  esm.classification_heads['mnli'].out_proj.weight.shape[0]
  print('Our ESM config:'      ,     A_ )

  if model.startswith('esmfold' ):
    a	:     List[Any]							=  EsmForProteinFolding
  elif classification_head:
    a	:     Union[str, Any]							=  EsmForSequenceClassification
  else:
    a	:     str							=  EsmForMaskedLM
  a	:     str							=  model_class(A_ )
  model.eval()

  # Now let's copy all the weights.
  # Embeddings
  a	:     Union[str, Any]							=  original_esm_model.embed_tokens.weight
  if position_embedding_type == "absolute":
    a	:     Union[str, Any]							=  original_esm_model.embed_positions.weight

  if config.emb_layer_norm_before:
    a	:     Any							=  original_esm_model.emb_layer_norm_before.weight
    a	:     List[str]							=  original_esm_model.emb_layer_norm_before.bias

  a	:     List[Any]							=  original_esm_model.emb_layer_norm_after.weight
  a	:     Optional[Any]							=  original_esm_model.emb_layer_norm_after.bias

  for i in range(config.num_hidden_layers ):
    # Encoder: start of layer
    a	:     EsmLayer							=  model.esm.encoder.layer[i]
    # esm_layer: TransformerSentenceEncoderLayer = original_esm_model.layers[i]
    a	:     List[Any]							=  original_esm_model.layers[i]

    # self attention
    a	:     EsmSelfAttention							=  layer.attention.self
    assert (
        esm_layer.self_attn.k_proj.weight.data.shape
        == esm_layer.self_attn.q_proj.weight.data.shape
        == esm_layer.self_attn.v_proj.weight.data.shape
        == torch.Size((config.hidden_size, config.hidden_size) )
    )

    a	:     List[str]							=  esm_layer.self_attn.q_proj.weight
    a	:     int							=  esm_layer.self_attn.q_proj.bias
    a	:     List[Any]							=  esm_layer.self_attn.k_proj.weight
    a	:     Optional[Any]							=  esm_layer.self_attn.k_proj.bias
    a	:     Optional[int]							=  esm_layer.self_attn.v_proj.weight
    a	:     Any							=  esm_layer.self_attn.v_proj.bias

    if getattr(esm_layer.self_attn      ,     'rot_emb'      ,     A_ ) is not None:
      # Matt: Although inv_freq is not a trainable weight, it is computed at model init and cached.
      # During the training of ESM-2 the model was converted to float16 precision, which also converts
      # the inv_freq tensor, and the loss of precision remains even if the model is loaded later as float32.
      # If we recompute inv_freq without this loss of precision then we will get subtly different rotary
      # embeddings, which are enough to cause significant discrepancies in model outputs. To avoid this,
      # we make sure the new model copies the data from the old inv_freq.
      a	:     Any							=  esm_layer.self_attn.rot_emb.inv_freq

    # LayerNorm changes for pre-activation
    a	:     List[Any]							=  esm_layer.self_attn_layer_norm.weight
    a	:     Dict							=  esm_layer.self_attn_layer_norm.bias
    a	:     Tuple							=  esm_layer.final_layer_norm.weight
    a	:     Any							=  esm_layer.final_layer_norm.bias

    # self-attention output
    a	:     EsmSelfOutput							=  layer.attention.output
    assert self_output.dense.weight.shape == esm_layer.self_attn.out_proj.weight.shape
    a	:     int							=  esm_layer.self_attn.out_proj.weight
    a	:     str							=  esm_layer.self_attn.out_proj.bias

    # intermediate
    a	:     EsmIntermediate							=  layer.intermediate
    assert intermediate.dense.weight.shape == esm_layer.fca.weight.shape
    a	:     Tuple							=  esm_layer.fca.weight
    a	:     Dict							=  esm_layer.fca.bias

    # output
    a	:     EsmOutput							=  layer.output
    assert bert_output.dense.weight.shape == esm_layer.fca.weight.shape
    a	:     List[Any]							=  esm_layer.fca.weight
    a	:     List[Any]							=  esm_layer.fca.bias
    # end of layer

  if is_folding_model:
    a	:     Any							=  esm.esm_s_combine.data
    a	:     int							=  esm.afa_to_esm.data
    transfer_and_check_weights(esm.embedding      ,     model.embedding )
    transfer_and_check_weights(esm.esm_s_mlp      ,     model.esm_s_mlp )
    transfer_and_check_weights(esm.trunk      ,     model.trunk )
    transfer_and_check_weights(esm.distogram_head      ,     model.distogram_head )
    transfer_and_check_weights(esm.ptm_head      ,     model.ptm_head )
    transfer_and_check_weights(esm.lm_head      ,     model.lm_head )
    transfer_and_check_weights(esm.lddt_head      ,     model.lddt_head )

  elif classification_head:
    a	:     int							=  esm.esm.classification_heads['mnli'].dense.weight
    a	:     Tuple							=  esm.classification_heads['mnli'].dense.bias
    a	:     List[Any]							=  esm.classification_heads['mnli'].out_proj.weight
    a	:     List[Any]							=  esm.classification_heads['mnli'].out_proj.bias
  else:
    # LM Head
    a	:     Optional[int]							=  esm.lm_head.dense.weight
    a	:     str							=  esm.lm_head.dense.bias
    a	:     Any							=  esm.lm_head.layer_norm.weight
    a	:     Optional[Any]							=  esm.lm_head.layer_norm.bias
    a	:     Optional[int]							=  esm.lm_head.weight
    a	:     Optional[int]							=  esm.lm_head.bias

  # Contact prediction head
  transfer_and_check_weights(esm.contact_head      ,     model.esm.contact_head )

  # Prepare data (first 2 sequences from ESMStructuralSplitDataset superfamily / 4)
  if is_folding_model:
    # Folding models aren't trained on masked inputs and don't like mask tokens.
    a	:     Union[str, Any]							=  SAMPLE_DATA[:2]
  else:
    a	:     str							=  SAMPLE_DATA

  if is_folding_model:
    a	:     int							=  get_esmfold_tokenizer()
    a	:     List[Any]							=  hf_tokenizer(
        [row[1] for row in sample_data]      ,     return_tensors='pt'      ,     padding=A_      ,     add_special_tokens=A_ )
    a,	a,	a,	a,	a	:     List[Any]							=  esmfold_encode_sequences([row[1] for row in sample_data] )
    a	:     Dict							=  torch.all(hf_tokens['input_ids'] == esmfold_aas ) and torch.all(
        hf_tokens['attention_mask'] == esmfold_mask )
  else:
    # Let's check that we get the same results.
    a	:     List[Any]							=  alphabet.get_batch_converter()
    a,	a,	a	:     str							=  batch_converter(A_ )
    # Prepare tokenizer and make sure it matches
    with TemporaryDirectory() as tempdir:
      a	:     Union[str, Any]							=  '\n'.join(alphabet.all_toks )
      a	:     Any							=  Path(A_ ) / 'vocab.txt'
      vocab_file.write_text(A_ )
      a	:     str							=  EsmTokenizer(vocab_file=str(A_ ) )

    a	:     Dict							=  hf_tokenizer([row[1] for row in sample_data]      ,     return_tensors='pt'      ,     padding=A_ )
    a	:     Optional[int]							=  torch.all(hf_tokens['input_ids'] == batch_tokens )

  print('Do both models tokenizers output the same tokens?'      ,     '🔥' if success else '💩' )
  if not success:
    raise Exception('Tokenization does not match!' )

  with torch.no_grad():
    if is_folding_model:
      # Let's test the model in parts
      # ESMFold always converts the ESM stem to float16, which requires float16 ops
      # that don't exist on CPU. Therefore, to test it we need to run it on GPU. However,
      # ESMFold is what we in the community call a "big boy" and so we desperately avoid putting both the
      # original and the converted model on the GPU at the same time.
      a	:     Optional[Any]							=  esm.cuda().infer([row[1] for row in sample_data] )
      a	:     Dict							=  model.cuda()(
          input_ids=hf_tokens['input_ids'].cuda()      ,     attention_mask=hf_tokens['attention_mask'].cuda() )
    else:
      a	:     Any							=  model(**A_      ,     output_hidden_states=A_ )
      a	:     int							=  our_output['logits']
      if classification_head:
        a	:     Dict							=  esm.model.classification_heads['mnli'](esm.extract_features(A_ ) )
      else:
        a	:     Union[str, Any]							=  esm(hf_tokens['input_ids']      ,     repr_layers=list(range(9_9_9 ) ) )
        a	:     Any							=  their_output['logits']

    if is_folding_model:
      a	:     Union[str, Any]							=  torch.max(torch.abs(our_output['positions'] - their_output['positions'] ) ).item()
      a	:     Union[str, Any]							=  torch.allclose(our_output['positions']      ,     their_output['positions']      ,     atol=1E-5 )
    else:
      a	:     str							=  torch.max(torch.abs(our_output - their_output ) ).item()
      a	:     Tuple							=  torch.allclose(A_      ,     A_      ,     atol=1E-5 )

    print(f'''max_absolute_diff = {max_absolute_diff}''' )  # ~ 1e-5
    print('Do both models output the same tensors?'      ,     '🔥' if success else '💩' )

    if not success:
      raise Exception('Something went wRoNg' )

    if not is_folding_model:
      # Let's check contact prediction too
      a	:     Optional[Any]							=  model.predict_contacts(hf_tokens['input_ids']      ,     hf_tokens['attention_mask'] )
      a	:     Optional[int]							=  esm.predict_contacts(hf_tokens['input_ids'] )
      a	:     Tuple							=  torch.max(torch.abs(our_output - their_output ) ).item()
      a	:     Union[str, Any]							=  torch.allclose(A_      ,     A_      ,     atol=1E-5 )

      print('Contact prediction testing:' )
      print(f'''max_absolute_diff = {max_absolute_diff}''' )  # ~ 1e-5
      print('Do both models output the same tensors?'      ,     '🔥' if success else '💩' )

      if not success:
        raise Exception('Something went wRoNg' )

    pathlib.Path(A_ ).mkdir(parents=A_      ,     exist_ok=A_ )
    print(f'''Saving model to {pytorch_dump_folder_path}''' )
    model.save_pretrained(A_ )

    del esm  # Free up some memory before continuing

  print(f'''Saving tokenizer to {pytorch_dump_folder_path}''' )
  hf_tokenizer.save_pretrained(A_ )

  if push_to_repo:
    model.push_to_hub(repo_id=A_      ,     use_auth_token=A_ )
    hf_tokenizer.push_to_hub(repo_id=A_      ,     use_auth_token=A_ )


if __name__ == "__main__":
   _UpperCamelCase							:       List[str]       					=		argparse.ArgumentParser()
   # Required parameters
   parser.add_argument(
       '--pytorch_dump_folder_path', type=str, required=True, help='Path to the output PyTorch model.'
   )
   parser.add_argument(
       '--classification_head', action='store_true', help='Whether to convert a final classification head.'
   )
   parser.add_argument('--model', default=None, type=str, required=True, help='Name of model to convert.')
   parser.add_argument('--push_to_repo', type=str, help='Repo to upload to (including username!).')
   parser.add_argument('--auth_token', type=str, help='HuggingFace auth token.')
   _UpperCamelCase							:       Union[str, Any]       					=		parser.parse_args()
   convert_esm_checkpoint_to_pytorch(
       args.model, args.pytorch_dump_folder_path, args.classification_head, args.push_to_repo, args.auth_token
   )












"""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     )




