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


lowerCamelCase__  =					logging.get_logger(__name__)

lowerCamelCase__  =					{
    '''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 					_UpperCAmelCase			(     lowerCAmelCase  ):



 '''simple docstring'''




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







 def __init__(		self				:   List[Any]							, lowercase_				:   Dict=50265							, lowercase_				:   List[Any]=1024							, lowercase_				:   List[str]=12							, lowercase_				:   Union[str, Any]=4096							, lowercase_				:   str=16							, lowercase_				:   Any=12							, lowercase_				:   Any=4096							, lowercase_				:   Tuple=16							, lowercase_				:   List[str]=0.0							, lowercase_				:   Optional[int]=0.0							, lowercase_				:   Optional[int]="gelu"							, lowercase_				:   List[Any]=1024							, lowercase_				:   int=0.1							, lowercase_				:   Any=0.0							, lowercase_				:   int=0.0							, lowercase_				:   Any=0.02							, lowercase_				:   List[str]=0.0							, lowercase_				:   int=False							, lowercase_				:   List[Any]=True							, lowercase_				:   str=3							, lowercase_				:   Any=1							, lowercase_				:   List[Any]=0							, lowercase_				:   Union[str, Any]=2							, lowercase_				:   Optional[int]=True							, lowercase_				:   List[str]=2							, lowercase_				:   List[str]=2							, **lowercase_				:   Dict							, )						->	Tuple:


   """simple docstring"""







   _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           =    classifier_dropout
   _UpperCamelCase           =    use_cache
   _UpperCamelCase           =    encoder_layers
   _UpperCamelCase           =    scale_embedding  # scale factor will be sqrt(d_model) if True

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

   # ensure backward compatibility for BART CNN models
   if self.forced_bos_token_id is None and kwargs.get("force_bos_token_to_be_generated"							, lowercase_):
     _UpperCamelCase           =    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 					_UpperCAmelCase			(     lowerCAmelCase  ):



 '''simple docstring'''




 @property
 def 		__UpperCAmelCase				(		self				:   Optional[Any])						->	Mapping[str, Mapping[int, str]]:


   """simple docstring"""







   if self.task in ["default", "seq2seq-lm"]:
     _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_(lowercase_							, direction="inputs")
   elif self.task == "causal-lm":
     # TODO: figure this case out.
     _UpperCamelCase           =    OrderedDict(
         [
             ("input_ids", {0: "batch", 1: "encoder_sequence"}),
             ("attention_mask", {0: "batch", 1: "encoder_sequence"}),
         ])
     if self.use_past:
       _UpperCamelCase      ,						_UpperCamelCase           =    self.num_layers
       for i in range(lowercase_):
         _UpperCamelCase           =    {0: "batch", 2: "past_sequence + sequence"}
         _UpperCamelCase           =    {0: "batch", 2: "past_sequence + sequence"}
   else:
     _UpperCamelCase           =    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 		__UpperCAmelCase				(		self				:   int)						->	Mapping[str, Mapping[int, str]]:


   """simple docstring"""







   if self.task in ["default", "seq2seq-lm"]:
     _UpperCamelCase           =    super().outputs
   else:
     _UpperCamelCase           =    super(lowercase_							, self).outputs
     if self.use_past:
       _UpperCamelCase      ,						_UpperCamelCase           =    self.num_layers
       for i in range(lowercase_):
         _UpperCamelCase           =    {0: "batch", 2: "past_sequence + sequence"}
         _UpperCamelCase           =    {0: "batch", 2: "past_sequence + sequence"}
   return common_outputs







 def 		__UpperCAmelCase				(		self				:   Union[str, Any]							, lowercase_				:   PreTrainedTokenizer							, lowercase_				:   int = -1							, lowercase_				:   int = -1							, lowercase_				:   bool = False							, lowercase_				:   Optional[TensorType] = None							, )						->	Mapping[str, Any]:


   """simple docstring"""







   _UpperCamelCase           =    self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
       lowercase_							, lowercase_							, lowercase_							, lowercase_							, lowercase_)

   # Generate decoder inputs
   _UpperCamelCase           =    seq_length if not self.use_past else 1
   _UpperCamelCase           =    self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
       lowercase_							, lowercase_							, lowercase_							, lowercase_							, lowercase_)
   _UpperCamelCase           =    {f'decoder_{name}': tensor for name, tensor in decoder_inputs.items()}
   _UpperCamelCase           =    dict(**lowercase_							, **lowercase_)

   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(lowercase_							, lowercase_)]							, 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(lowercase_							, lowercase_)
     _UpperCamelCase           =    max(lowercase_							, lowercase_) - min_num_layers
     _UpperCamelCase           =    "encoder" if num_encoder_layers > num_decoder_layers else "decoder"

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







 def 		__UpperCAmelCase				(		self				:   Optional[Any]							, lowercase_				:   PreTrainedTokenizer							, lowercase_				:   int = -1							, lowercase_				:   int = -1							, lowercase_				:   bool = False							, lowercase_				:   Optional[TensorType] = None							, )						->	Mapping[str, Any]:


   """simple docstring"""







   _UpperCamelCase           =    self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
       lowercase_							, lowercase_							, lowercase_							, lowercase_							, lowercase_)

   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
     # Not using the same length for past_key_values
     _UpperCamelCase           =    seqlen + 2
     _UpperCamelCase      ,						_UpperCamelCase           =    self.num_layers
     _UpperCamelCase      ,						_UpperCamelCase           =    self.num_attention_heads
     _UpperCamelCase           =    (
         batch,
         num_encoder_attention_heads,
         past_key_values_length,
         self._config.hidden_size // num_encoder_attention_heads,
     )

     _UpperCamelCase           =    common_inputs["attention_mask"].dtype
     _UpperCamelCase           =    torch.cat(
         [common_inputs["attention_mask"], torch.ones(lowercase_							, lowercase_							, dtype=lowercase_)]							, dim=1)
     _UpperCamelCase           =    [
         (torch.zeros(lowercase_), torch.zeros(lowercase_)) for _ in range(lowercase_)
     ]
   return common_inputs







 def 		__UpperCAmelCase				(		self				:   List[str]							, lowercase_				:   PreTrainedTokenizer							, lowercase_				:   int = -1							, lowercase_				:   int = -1							, lowercase_				:   bool = False							, lowercase_				:   Optional[TensorType] = None							, )						->	Mapping[str, Any]:


   """simple docstring"""







   _UpperCamelCase           =    compute_effective_axis_dimension(
       lowercase_							, 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(lowercase_)
   _UpperCamelCase           =    compute_effective_axis_dimension(
       lowercase_							, fixed_dimension=OnnxConfig.default_fixed_sequence							, num_token_to_add=lowercase_)

   # Generate dummy inputs according to compute batch and sequence
   _UpperCamelCase           =    [" ".join([tokenizer.unk_token]) * seq_length] * batch_size
   _UpperCamelCase           =    dict(tokenizer(lowercase_							, return_tensors=lowercase_))
   return common_inputs







 def 		__UpperCAmelCase				(		self				:   List[Any]							, lowercase_				:   PreTrainedTokenizer							, lowercase_				:   int = -1							, lowercase_				:   int = -1							, lowercase_				:   bool = False							, lowercase_				:   Optional[TensorType] = None							, )						->	Mapping[str, Any]:


   """simple docstring"""







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

   elif self.task == "causal-lm":
     _UpperCamelCase           =    self._generate_dummy_inputs_for_causal_lm(
         lowercase_							, batch_size=lowercase_							, seq_length=lowercase_							, is_pair=lowercase_							, framework=lowercase_)
   else:
     _UpperCamelCase           =    self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
         lowercase_							, batch_size=lowercase_							, seq_length=lowercase_							, is_pair=lowercase_							, framework=lowercase_)

   return common_inputs







 def 		__UpperCAmelCase				(		self				:   Dict							, lowercase_				:   str							, lowercase_				:   List[str]							, lowercase_				:   Union[str, Any]							, lowercase_				:   Any)						->	str:


   """simple docstring"""







   if self.task in ["default", "seq2seq-lm"]:
     _UpperCamelCase           =    super()._flatten_past_key_values_(lowercase_							, lowercase_							, lowercase_							, lowercase_)
   else:
     _UpperCamelCase           =    super(lowercase_							, self)._flatten_past_key_values_(
         lowercase_							, lowercase_							, lowercase_							, lowercase_)





# This code is adapted from OpenAI's release
# https://github.com/openai/human-eval/blob/master/human_eval/execution.py

import contextlib
import faulthandler
import io
import multiprocessing
import os
import platform
import signal
import tempfile


def 				lowerCAmelCase__       (			a__    ,     a__    ,     a__    ,     a__ )      ->str:




  '''simple docstring'''

  _UpperCamelCase           =    multiprocessing.Manager()
  _UpperCamelCase           =    manager.list()

  _UpperCamelCase           =    multiprocessing.Process(target=a__    ,     args=(check_program, result, timeout) )
  p.start()
  p.join(timeout=timeout + 1 )
  if p.is_alive():
    p.kill()

  if not result:
    result.append("timed out" )

  return {
      "task_id": task_id,
      "passed": result[0] == "passed",
      "result": result[0],
      "completion_id": completion_id,
  }


def 				lowerCAmelCase__       (			a__    ,     a__    ,     a__ )      ->Union[str, Any]:




  '''simple docstring'''

  with create_tempdir():
    # These system calls are needed when cleaning up tempdir.
    import os
    import shutil

    _UpperCamelCase           =    shutil.rmtree
    _UpperCamelCase           =    os.rmdir
    _UpperCamelCase           =    os.chdir

    # Disable functionalities that can make destructive changes to the test.
    reliability_guard()

    # Run program.
    try:
      _UpperCamelCase           =    {}
      with swallow_io():
        with time_limit(a__ ):
          exec(a__    ,     a__ )
      result.append("passed" )
    except TimeoutException:
      result.append("timed out" )
    except BaseException as e:
      result.append(f'failed: {e}' )

    # Needed for cleaning up.
    _UpperCamelCase           =    rmtree
    _UpperCamelCase           =    rmdir
    _UpperCamelCase           =    chdir


@contextlib.contextmanager
def 				lowerCAmelCase__       (			a__ )      ->Optional[Any]:




  '''simple docstring'''

  def signal_handler(a__    ,     a__ ):
    raise TimeoutException("Timed out!" )

  signal.setitimer(signal.ITIMER_REAL    ,     a__ )
  signal.signal(signal.SIGALRM    ,     a__ )
  try:
    yield
  finally:
    signal.setitimer(signal.ITIMER_REAL    ,     0 )


@contextlib.contextmanager
def 				lowerCAmelCase__       (			)      ->Optional[int]:




  '''simple docstring'''

  _UpperCamelCase           =    WriteOnlyStringIO()
  with contextlib.redirect_stdout(a__ ):
    with contextlib.redirect_stderr(a__ ):
      with redirect_stdin(a__ ):
        yield


@contextlib.contextmanager
def 				lowerCAmelCase__       (			)      ->Optional[int]:




  '''simple docstring'''

  with tempfile.TemporaryDirectory() as dirname:
    with chdir(a__ ):
      yield dirname




class 					_UpperCAmelCase			(     lowerCAmelCase  ):



 '''simple docstring'''




 pass




class 					_UpperCAmelCase			(     io.StringIO  ):



 '''simple docstring'''




 def 		__UpperCAmelCase				(		self				:   List[str]							, *lowercase_				:   str							, **lowercase_				:   List[str])						->	Optional[Any]:


   """simple docstring"""







   raise OSError







 def 		__UpperCAmelCase				(		self				:   Any							, *lowercase_				:   List[Any]							, **lowercase_				:   Optional[int])						->	Optional[int]:


   """simple docstring"""







   raise OSError







 def 		__UpperCAmelCase				(		self				:   int							, *lowercase_				:   int							, **lowercase_				:   str)						->	int:


   """simple docstring"""







   raise OSError







 def 		__UpperCAmelCase				(		self				:   List[Any]							, *lowercase_				:   Tuple							, **lowercase_				:   Tuple)						->	Tuple:


   """simple docstring"""







   return False




class 					_UpperCAmelCase			(     contextlib._RedirectStream  ):  # type: ignore



 '''simple docstring'''




 __A			       =					'''stdin'''


@contextlib.contextmanager
def 				lowerCAmelCase__       (			a__ )      ->str:




  '''simple docstring'''

  if root == ".":
    yield
    return
  _UpperCamelCase           =    os.getcwd()
  os.chdir(a__ )
  try:
    yield
  except BaseException as exc:
    raise exc
  finally:
    os.chdir(a__ )







def 				lowerCAmelCase__       (			a__=None )      ->Optional[int]:




  '''simple docstring'''

  if maximum_memory_bytes is not None:
    import resource

    resource.setrlimit(resource.RLIMIT_AS    ,     (maximum_memory_bytes, maximum_memory_bytes) )
    resource.setrlimit(resource.RLIMIT_DATA    ,     (maximum_memory_bytes, maximum_memory_bytes) )
    if not platform.uname().system == "Darwin":
      resource.setrlimit(resource.RLIMIT_STACK    ,     (maximum_memory_bytes, maximum_memory_bytes) )

  faulthandler.disable()

  import builtins

  _UpperCamelCase           =    None
  _UpperCamelCase           =    None

  import os

  _UpperCamelCase           =    "1"

  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None

  import shutil

  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None

  import subprocess

  _UpperCamelCase           =    None  # type: ignore

  _UpperCamelCase           =    None

  import sys

  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None




