
import os
import tempfile
import unittest

from transformers.models.marian.convert_marian_tatoeba_to_pytorch import DEFAULT_REPO, TatoebaConverter
from transformers.testing_utils import slow
from transformers.utils import cached_property



@unittest.skipUnless(os.path.exists(lowerCAmelCase__				)	,    'Tatoeba directory does not exist.'				)
class    _snake_case (						unittest.TestCase				):


 @cached_property
 def   lowercase__  (       self):


   '''simple docstring'''




   lowercase__	: Any     		=   tempfile.mkdtemp()
   return TatoebaConverter(save_dir=_lowerCamelCase)


 @slow
 def   lowercase__  (       self):


   '''simple docstring'''




   self.resolver.convert_models(["""heb-eng"""])



 @slow
 def   lowercase__  (       self):


   '''simple docstring'''




   lowercase__	: str     		=   self.resolver.write_model_card("""opus-mt-he-en"""       ,	dry_run=_lowerCamelCase)
   assert mmeta["long_pair"] == "heb-eng"









"""simple docstring"""
import warnings
from collections import OrderedDict
from typing import Any, Mapping, Optional

from ... import PreTrainedTokenizer
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast
from ...onnx.utils import compute_effective_axis_dimension
from ...utils import TensorType, is_torch_available, logging


_A							=  logging.get_logger(__name__)

_A							=  {
    """facebook/bart-large""": """https://huggingface.co/facebook/bart-large/resolve/main/config.json""",
    # See all BART models at https://huggingface.co/models?filter=bart
}

class       lowerCamelCase	(       lowerCAmelCase__   ):


  '''simple docstring'''







  SCREAMING_SNAKE_CASE					      =  'bart'
  SCREAMING_SNAKE_CASE					      =  ['past_key_values']
  SCREAMING_SNAKE_CASE					      =  {'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'}



  def __init__(self							,       _lowerCamelCase=50265							,       _lowerCamelCase=1024							,       _lowerCamelCase=12							,       _lowerCamelCase=4096							,       _lowerCamelCase=16							,       _lowerCamelCase=12							,       _lowerCamelCase=4096							,       _lowerCamelCase=16							,       _lowerCamelCase=0.0							,       _lowerCamelCase=0.0							,       _lowerCamelCase="gelu"							,       _lowerCamelCase=1024							,       _lowerCamelCase=0.1							,       _lowerCamelCase=0.0							,       _lowerCamelCase=0.0							,       _lowerCamelCase=0.02							,       _lowerCamelCase=0.0							,       _lowerCamelCase=False							,       _lowerCamelCase=True							,       _lowerCamelCase=3							,       _lowerCamelCase=1							,       _lowerCamelCase=0							,       _lowerCamelCase=2							,       _lowerCamelCase=True							,       _lowerCamelCase=2							,       _lowerCamelCase=2							,       **_lowerCamelCase							,       ):


        """simple docstring"""

        UpperCAmelCase__			:							str							=    vocab_size
        UpperCAmelCase__			:							Optional[Any]							=    max_position_embeddings
        UpperCAmelCase__			:							int							=    d_model
        UpperCAmelCase__			:							str							=    encoder_ffn_dim
        UpperCAmelCase__			:							List[str]							=    encoder_layers
        UpperCAmelCase__			:							Optional[int]							=    encoder_attention_heads
        UpperCAmelCase__			:							Optional[int]							=    decoder_ffn_dim
        UpperCAmelCase__			:							Dict							=    decoder_layers
        UpperCAmelCase__			:							int							=    decoder_attention_heads
        UpperCAmelCase__			:							Optional[Any]							=    dropout
        UpperCAmelCase__			:							int							=    attention_dropout
        UpperCAmelCase__			:							str							=    activation_dropout
        UpperCAmelCase__			:							Optional[int]							=    activation_function
        UpperCAmelCase__			:							List[str]							=    init_std
        UpperCAmelCase__			:							Dict							=    encoder_layerdrop
        UpperCAmelCase__			:							Any							=    decoder_layerdrop
        UpperCAmelCase__			:							List[str]							=    classifier_dropout
        UpperCAmelCase__			:							Any							=    use_cache
        UpperCAmelCase__			:							Union[str, Any]							=    encoder_layers
        UpperCAmelCase__			:							List[Any]							=    scale_embedding  # scale factor will be sqrt(d_model) if True

        super().__init__(
            num_labels=_lowerCamelCase							,       pad_token_id=_lowerCamelCase							,       bos_token_id=_lowerCamelCase							,       eos_token_id=_lowerCamelCase							,       is_encoder_decoder=_lowerCamelCase							,       decoder_start_token_id=_lowerCamelCase							,       forced_eos_token_id=_lowerCamelCase							,       **_lowerCamelCase							,       )

        # ensure backward compatibility for BART CNN models
        if self.forced_bos_token_id is None and kwargs.get("""force_bos_token_to_be_generated"""							,       _lowerCamelCase	):
              UpperCAmelCase__			:							List[Any]							=    self.bos_token_id
              warnings.warn(
                  F"""Please make sure the config includes `forced_bos_token_id={self.bos_token_id}` in future versions. """
                  """The config can simply be saved and uploaded again to be fixed."""	)




class       lowerCamelCase	(       lowerCAmelCase__   ):


  '''simple docstring'''







  @property
  def  _a      (self	):


        """simple docstring"""

        if self.task in ["default", "seq2seq-lm"]:
              UpperCAmelCase__			:							int							=    OrderedDict(
                  [
                      ("""input_ids""", {0: """batch""", 1: """encoder_sequence"""}),
                      ("""attention_mask""", {0: """batch""", 1: """encoder_sequence"""}),
                  ]	)

              if self.use_past:
                    UpperCAmelCase__			:							Dict							=    {0: """batch"""}
                    UpperCAmelCase__			:							Tuple							=    {0: """batch""", 1: """past_decoder_sequence + sequence"""}
              else:
                    UpperCAmelCase__			:							Dict							=    {0: """batch""", 1: """decoder_sequence"""}
                    UpperCAmelCase__			:							List[str]							=    {0: """batch""", 1: """decoder_sequence"""}

              if self.use_past:
                    self.fill_with_past_key_values_(_lowerCamelCase							,       direction="""inputs"""	)
        elif self.task == "causal-lm":
              # TODO: figure this case out.
              UpperCAmelCase__			:							str							=    OrderedDict(
                  [
                      ("""input_ids""", {0: """batch""", 1: """encoder_sequence"""}),
                      ("""attention_mask""", {0: """batch""", 1: """encoder_sequence"""}),
                  ]	)
              if self.use_past:
                    UpperCAmelCase__					,		UpperCAmelCase__			:							List[str]							=    self.num_layers
                    for i in range(_lowerCamelCase	):
                          UpperCAmelCase__			:							Optional[int]							=    {0: """batch""", 2: """past_sequence + sequence"""}
                          UpperCAmelCase__			:							int							=    {0: """batch""", 2: """past_sequence + sequence"""}
        else:
              UpperCAmelCase__			:							Union[str, Any]							=    OrderedDict(
                  [
                      ("""input_ids""", {0: """batch""", 1: """encoder_sequence"""}),
                      ("""attention_mask""", {0: """batch""", 1: """encoder_sequence"""}),
                      ("""decoder_input_ids""", {0: """batch""", 1: """decoder_sequence"""}),
                      ("""decoder_attention_mask""", {0: """batch""", 1: """decoder_sequence"""}),
                  ]	)

        return common_inputs



  @property
  def  _a      (self	):


        """simple docstring"""

        if self.task in ["default", "seq2seq-lm"]:
              UpperCAmelCase__			:							Any							=    super().outputs
        else:
              UpperCAmelCase__			:							Union[str, Any]							=    super(_lowerCamelCase							,       self	).outputs
              if self.use_past:
                    UpperCAmelCase__					,		UpperCAmelCase__			:							Dict							=    self.num_layers
                    for i in range(_lowerCamelCase	):
                          UpperCAmelCase__			:							List[str]							=    {0: """batch""", 2: """past_sequence + sequence"""}
                          UpperCAmelCase__			:							int							=    {0: """batch""", 2: """past_sequence + sequence"""}
        return common_outputs



  def  _a      (self							,       _lowerCamelCase							,       _lowerCamelCase = -1							,       _lowerCamelCase = -1							,       _lowerCamelCase = False							,       _lowerCamelCase = None							,       ):


        """simple docstring"""

        UpperCAmelCase__			:							int							=    self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
            _lowerCamelCase							,       _lowerCamelCase							,       _lowerCamelCase							,       _lowerCamelCase							,       _lowerCamelCase	)

        # Generate decoder inputs
        UpperCAmelCase__			:							int							=    seq_length if not self.use_past else 1
        UpperCAmelCase__			:							str							=    self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
            _lowerCamelCase							,       _lowerCamelCase							,       _lowerCamelCase							,       _lowerCamelCase							,       _lowerCamelCase	)
        UpperCAmelCase__			:							str							=    {F"""decoder_{name}""": tensor for name, tensor in decoder_inputs.items()}
        UpperCAmelCase__			:							Union[str, Any]							=    dict(**_lowerCamelCase							,       **_lowerCamelCase	)

        if self.use_past:
              if not is_torch_available():
                    raise ValueError("""Cannot generate dummy past_keys inputs without PyTorch installed."""	)
              else:
                    import torch
              UpperCAmelCase__					,		UpperCAmelCase__			:							str							=    common_inputs["""input_ids"""].shape
              UpperCAmelCase__			:							int							=    common_inputs["""decoder_input_ids"""].shape[1]
              UpperCAmelCase__					,		UpperCAmelCase__			:							List[str]							=    self.num_attention_heads
              UpperCAmelCase__			:							str							=    (
                  batch,
                  num_encoder_attention_heads,
                  encoder_seq_length,
                  self._config.hidden_size // num_encoder_attention_heads,
              )
              UpperCAmelCase__			:							Optional[int]							=    decoder_seq_length + 3
              UpperCAmelCase__			:							Any							=    (
                  batch,
                  num_decoder_attention_heads,
                  decoder_past_length,
                  self._config.hidden_size // num_decoder_attention_heads,
              )

              UpperCAmelCase__			:							str							=    torch.cat(
                  [common_inputs["""decoder_attention_mask"""], torch.ones(_lowerCamelCase							,       _lowerCamelCase	)]							,       dim=1	)

              UpperCAmelCase__			:							List[str]							=    []
              # If the number of encoder and decoder layers are present in the model configuration, both are considered
              UpperCAmelCase__					,		UpperCAmelCase__			:							Dict							=    self.num_layers
              UpperCAmelCase__			:							Union[str, Any]							=    min(_lowerCamelCase							,       _lowerCamelCase	)
              UpperCAmelCase__			:							str							=    max(_lowerCamelCase							,       _lowerCamelCase	) - min_num_layers
              UpperCAmelCase__			:							Dict							=    """encoder""" if num_encoder_layers > num_decoder_layers else """decoder"""

              for _ in range(_lowerCamelCase	):
                    common_inputs["past_key_values"].append(
                        (
                            torch.zeros(_lowerCamelCase	),
                            torch.zeros(_lowerCamelCase	),
                            torch.zeros(_lowerCamelCase	),
                            torch.zeros(_lowerCamelCase	),
                        )	)
              # TODO: test this.
              UpperCAmelCase__			:							Dict							=    encoder_shape if remaining_side_name == """encoder""" else decoder_shape
              for _ in range(_lowerCamelCase							,       _lowerCamelCase	):
                    common_inputs["past_key_values"].append((torch.zeros(_lowerCamelCase	), torch.zeros(_lowerCamelCase	))	)
        return common_inputs



  def  _a      (self							,       _lowerCamelCase							,       _lowerCamelCase = -1							,       _lowerCamelCase = -1							,       _lowerCamelCase = False							,       _lowerCamelCase = None							,       ):


        """simple docstring"""

        UpperCAmelCase__			:							Any							=    self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
            _lowerCamelCase							,       _lowerCamelCase							,       _lowerCamelCase							,       _lowerCamelCase							,       _lowerCamelCase	)

        if self.use_past:
              if not is_torch_available():
                    raise ValueError("""Cannot generate dummy past_keys inputs without PyTorch installed."""	)
              else:
                    import torch
              UpperCAmelCase__					,		UpperCAmelCase__			:							Optional[int]							=    common_inputs["""input_ids"""].shape
              # Not using the same length for past_key_values
              UpperCAmelCase__			:							int							=    seqlen + 2
              UpperCAmelCase__					,		UpperCAmelCase__			:							Optional[int]							=    self.num_layers
              UpperCAmelCase__					,		UpperCAmelCase__			:							str							=    self.num_attention_heads
              UpperCAmelCase__			:							Tuple							=    (
                  batch,
                  num_encoder_attention_heads,
                  past_key_values_length,
                  self._config.hidden_size // num_encoder_attention_heads,
              )

              UpperCAmelCase__			:							Optional[int]							=    common_inputs["""attention_mask"""].dtype
              UpperCAmelCase__			:							List[str]							=    torch.cat(
                  [common_inputs["""attention_mask"""], torch.ones(_lowerCamelCase							,       _lowerCamelCase							,       dtype=_lowerCamelCase	)]							,       dim=1	)
              UpperCAmelCase__			:							Tuple							=    [
                  (torch.zeros(_lowerCamelCase	), torch.zeros(_lowerCamelCase	)) for _ in range(_lowerCamelCase	)
              ]
        return common_inputs



  def  _a      (self							,       _lowerCamelCase							,       _lowerCamelCase = -1							,       _lowerCamelCase = -1							,       _lowerCamelCase = False							,       _lowerCamelCase = None							,       ):


        """simple docstring"""

        UpperCAmelCase__			:							Tuple							=    compute_effective_axis_dimension(
            _lowerCamelCase							,       fixed_dimension=OnnxConfig.default_fixed_batch							,       num_token_to_add=0	)

        # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX
        UpperCAmelCase__			:							Optional[int]							=    tokenizer.num_special_tokens_to_add(_lowerCamelCase	)
        UpperCAmelCase__			:							int							=    compute_effective_axis_dimension(
            _lowerCamelCase							,       fixed_dimension=OnnxConfig.default_fixed_sequence							,       num_token_to_add=_lowerCamelCase	)

        # Generate dummy inputs according to compute batch and sequence
        UpperCAmelCase__			:							List[Any]							=    [""" """.join([tokenizer.unk_token]	) * seq_length] * batch_size
        UpperCAmelCase__			:							Optional[int]							=    dict(tokenizer(_lowerCamelCase							,       return_tensors=_lowerCamelCase	)	)
        return common_inputs



  def  _a      (self							,       _lowerCamelCase							,       _lowerCamelCase = -1							,       _lowerCamelCase = -1							,       _lowerCamelCase = False							,       _lowerCamelCase = None							,       ):


        """simple docstring"""

        if self.task in ["default", "seq2seq-lm"]:
              UpperCAmelCase__			:							Tuple							=    self._generate_dummy_inputs_for_default_and_seqaseq_lm(
                  _lowerCamelCase							,       batch_size=_lowerCamelCase							,       seq_length=_lowerCamelCase							,       is_pair=_lowerCamelCase							,       framework=_lowerCamelCase	)

        elif self.task == "causal-lm":
              UpperCAmelCase__			:							Optional[int]							=    self._generate_dummy_inputs_for_causal_lm(
                  _lowerCamelCase							,       batch_size=_lowerCamelCase							,       seq_length=_lowerCamelCase							,       is_pair=_lowerCamelCase							,       framework=_lowerCamelCase	)
        else:
              UpperCAmelCase__			:							Dict							=    self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
                  _lowerCamelCase							,       batch_size=_lowerCamelCase							,       seq_length=_lowerCamelCase							,       is_pair=_lowerCamelCase							,       framework=_lowerCamelCase	)

        return common_inputs




  def  _a      (self							,       _lowerCamelCase							,       _lowerCamelCase							,       _lowerCamelCase							,       _lowerCamelCase	):


        """simple docstring"""

        if self.task in ["default", "seq2seq-lm"]:
              UpperCAmelCase__			:							Union[str, Any]							=    super()._flatten_past_key_values_(_lowerCamelCase							,       _lowerCamelCase							,       _lowerCamelCase							,       _lowerCamelCase	)
        else:
              UpperCAmelCase__			:							Optional[int]							=    super(_lowerCamelCase							,       self	)._flatten_past_key_values_(
                  _lowerCamelCase							,       _lowerCamelCase							,       _lowerCamelCase							,       _lowerCamelCase	)

