




from collections import OrderedDict
from typing import Any, Mapping, Optional

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


_lowerCAmelCase    : str		= logging.get_logger(__name__)

_lowerCAmelCase    : List[Any]		= {
    "facebook/m2m100_418M": "https://huggingface.co/facebook/m2m100_418M/resolve/main/config.json",
    # See all M2M100 models at https://huggingface.co/models?filter=m2m_100
}
class       _UpperCamelCase   (					lowerCAmelCase		):
      UpperCAmelCase_          =		"""m2m_100"""
      UpperCAmelCase_          =		["""past_key_values"""]
      UpperCAmelCase_          =		{"""num_attention_heads""": """encoder_attention_heads""", """hidden_size""": """d_model"""}
      def __init__(      self :Any			,   lowerCamelCase :int=12_8112			,   lowerCamelCase :str=1024			,   lowerCamelCase :Union[str, Any]=12			,   lowerCamelCase :Any=4096			,   lowerCamelCase :Optional[int]=16			,   lowerCamelCase :List[str]=12			,   lowerCamelCase :str=4096			,   lowerCamelCase :int=16			,   lowerCamelCase :Optional[int]=0.05			,   lowerCamelCase :int=0.05			,   lowerCamelCase :Optional[Any]=True			,   lowerCamelCase :str=True			,   lowerCamelCase :str="relu"			,   lowerCamelCase :Dict=1024			,   lowerCamelCase :List[str]=0.1			,   lowerCamelCase :Dict=0.1			,   lowerCamelCase :Union[str, Any]=0.0			,   lowerCamelCase :List[Any]=0.02			,   lowerCamelCase :Union[str, Any]=2			,   lowerCamelCase :Optional[int]=True			,   lowerCamelCase :str=1			,   lowerCamelCase :Optional[Any]=0			,   lowerCamelCase :Tuple=2			,   **lowerCamelCase :Union[str, Any]			,   )  ->      Dict:
       UpperCAmelCase__							=    vocab_size
       UpperCAmelCase__							=    max_position_embeddings
       UpperCAmelCase__							=    d_model
       UpperCAmelCase__							=    encoder_ffn_dim
       UpperCAmelCase__							=    encoder_layers
       UpperCAmelCase__							=    encoder_attention_heads
       UpperCAmelCase__							=    decoder_ffn_dim
       UpperCAmelCase__							=    decoder_layers
       UpperCAmelCase__							=    decoder_attention_heads
       UpperCAmelCase__							=    dropout
       UpperCAmelCase__							=    attention_dropout
       UpperCAmelCase__							=    activation_dropout
       UpperCAmelCase__							=    activation_function
       UpperCAmelCase__							=    init_std
       UpperCAmelCase__							=    encoder_layerdrop
       UpperCAmelCase__							=    decoder_layerdrop
       UpperCAmelCase__							=    use_cache
       UpperCAmelCase__							=    encoder_layers
       UpperCAmelCase__							=    scale_embedding  # scale factor will be sqrt(d_model) if True

       super().__init__(
           pad_token_id=lowerCamelCase			,   bos_token_id=lowerCamelCase			,   eos_token_id=lowerCamelCase			,   is_encoder_decoder=lowerCamelCase			,   decoder_start_token_id=lowerCamelCase			,   **lowerCamelCase			,   )



class       _UpperCamelCase   (					lowerCAmelCase		):
      @property
      def 						UpperCAmelCase_    (      self :Dict   )  ->      Mapping[str, Mapping[int, str]]:
       UpperCAmelCase__							=    OrderedDict(
           [
               ("input_ids", {0: "batch", 1: "encoder_sequence"}),
               ("attention_mask", {0: "batch", 1: "encoder_sequence"}),
           ]   )

       if self.use_past:
        UpperCAmelCase__							=    {0: "batch"}
        UpperCAmelCase__							=    {0: "batch", 1: "past_decoder_sequence + sequence"}
       else:
        UpperCAmelCase__							=    {0: "batch", 1: "decoder_sequence"}
        UpperCAmelCase__							=    {0: "batch", 1: "decoder_sequence"}

       if self.use_past:
        self.fill_with_past_key_values_(lowerCamelCase			,   direction="inputs"   )
       return common_inputs
      def 						UpperCAmelCase_    (      self :Dict			,   lowerCamelCase :PreTrainedTokenizer			,   lowerCamelCase :int = -1			,   lowerCamelCase :int = -1			,   lowerCamelCase :bool = False			,   lowerCamelCase :Optional[TensorType] = None			,   )  ->      Mapping[str, Any]:
       # Copied from OnnxConfig.generate_dummy_inputs
       # Did not use super(OnnxConfigWithPast, self).generate_dummy_inputs for code clarity.
       # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
       UpperCAmelCase__							=    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__							=    tokenizer.num_special_tokens_to_add(lowerCamelCase   )
       UpperCAmelCase__							=    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__							=    [" ".join([tokenizer.unk_token]   ) * seq_length] * batch_size
       UpperCAmelCase__							=    dict(tokenizer(lowerCamelCase			,   return_tensors=lowerCamelCase   )   )
       return common_inputs
      def 						UpperCAmelCase_    (      self :Optional[int]			,   lowerCamelCase :PreTrainedTokenizer			,   lowerCamelCase :int = -1			,   lowerCamelCase :int = -1			,   lowerCamelCase :bool = False			,   lowerCamelCase :Optional[TensorType] = None			,   )  ->      Mapping[str, Any]:
       UpperCAmelCase__							=    self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
           lowerCamelCase			,   lowerCamelCase			,   lowerCamelCase			,   lowerCamelCase			,   lowerCamelCase   )

       # Generate decoder inputs
       UpperCAmelCase__							=    seq_length if not self.use_past else 1
       UpperCAmelCase__							=    self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
           lowerCamelCase			,   lowerCamelCase			,   lowerCamelCase			,   lowerCamelCase			,   lowerCamelCase   )
       UpperCAmelCase__							=    {f'''decoder_{name}''': tensor for name, tensor in decoder_inputs.items()}
       UpperCAmelCase__							=    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__							=    common_inputs["input_ids"].shape
        UpperCAmelCase__							=    common_inputs["decoder_input_ids"].shape[1]
        UpperCAmelCase__			,			UpperCAmelCase__							=    self.num_attention_heads
        UpperCAmelCase__							=    (
            batch,
            num_encoder_attention_heads,
            encoder_seq_length,
            self._config.hidden_size // num_encoder_attention_heads,
        )
        UpperCAmelCase__							=    decoder_seq_length + 3
        UpperCAmelCase__							=    (
            batch,
            num_decoder_attention_heads,
            decoder_past_length,
            self._config.hidden_size // num_decoder_attention_heads,
        )

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

        UpperCAmelCase__							=    []
        # If the number of encoder and decoder layers are present in the model configuration, both are considered
        UpperCAmelCase__			,			UpperCAmelCase__							=    self.num_layers
        UpperCAmelCase__							=    min(lowerCamelCase			,   lowerCamelCase   )
        UpperCAmelCase__							=    max(lowerCamelCase			,   lowerCamelCase   ) - min_num_layers
        UpperCAmelCase__							=    "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__							=    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







      UpperCAmelCase_          =		_generate_dummy_inputs_for_default_and_seqaseq_lm











from typing import Optional

from ..utils.logging import get_logger
from .audio_classificiation import AudioClassification
from .automatic_speech_recognition import AutomaticSpeechRecognition
from .base import TaskTemplate
from .image_classification import ImageClassification
from .language_modeling import LanguageModeling
from .question_answering import QuestionAnsweringExtractive
from .summarization import Summarization
from .text_classification import TextClassification


_lowerCAmelCase    : Any		= [
    "AutomaticSpeechRecognition",
    "AudioClassification",
    "ImageClassification",
    "LanguageModeling",
    "QuestionAnsweringExtractive",
    "Summarization",
    "TaskTemplate",
    "TextClassification",
]

_lowerCAmelCase    : Dict		= get_logger(__name__)


_lowerCAmelCase    : Optional[Any]		= {
    AutomaticSpeechRecognition.task: AutomaticSpeechRecognition,
    AudioClassification.task: AudioClassification,
    ImageClassification.task: ImageClassification,
    LanguageModeling.task: LanguageModeling,
    QuestionAnsweringExtractive.task: QuestionAnsweringExtractive,
    Summarization.task: Summarization,
    TextClassification.task: TextClassification,
}



def     lowerCAmelCase		(		_lowerCAmelCase				: dict						):




 """simple docstring"""







 UpperCAmelCase__							=    task_template_dict.get("task"						)
 if task_name is None:
  logger.warning(F'''Couldn\'t find template for task \'{task_name}\'. Available templates: {list(_lowerCAmelCase						)}'''						)
  return None
 UpperCAmelCase__							=    NAMEaTEMPLATE.get(_lowerCAmelCase						)
 return template.from_dict(_lowerCAmelCase						)





