




from typing import List, Optional, Union

import numpy as np
import tensorflow as tf

from .utils import logging


lowerCamelCase	:	List[str]				=   logging.get_logger(__name__)




def 						SCREAMING_SNAKE_CASE__ (   lowercase					)  ->       List[int]:
   if isinstance(lowercase						,np.ndarray					):
      return list(tensor.shape					)

   snake_case				:    Dict           =	tf.shape(lowercase					)

   if tensor.shape == tf.TensorShape(lowercase					):
      return dynamic

   snake_case				:    Union[str, Any]           =	tensor.shape.as_list()

   return [dynamic[i] if s is None else s for i, s in enumerate(lowercase					)]




def 						SCREAMING_SNAKE_CASE__ (   lowercase						,lowercase = None						,lowercase = None					)  ->       tf.Tensor:
   return tf.nn.softmax(logits=logits + 1E-9						,axis=lowercase						,name=lowercase					)




def 						SCREAMING_SNAKE_CASE__ (   lowercase						,lowercase						,lowercase						,lowercase=1E-5						,lowercase=-1					)  ->       Optional[Any]:
   # This is a very simplified functional layernorm, designed to duplicate
   # the functionality of PyTorch nn.functional.layer_norm when this is needed to port
   # models in Transformers.

   if weight.shape.rank != 1 or bias.shape.rank != 1 or not isinstance(lowercase						,lowercase					):
      raise NotImplementedError("""Only 1D weight and bias tensors are supported for now, with only a single axis."""					)

   # Get mean and variance on the axis to be normalized
   snake_case     , snake_case				:    int           =	tf.nn.moments(lowercase						,axes=[axis]						,keepdims=lowercase					)

   if axis != -1:
      # Reshape scale and weight to have the same rank as inputs, but with 1 dimensions
      # on every dimension except axis
      snake_case				:    List[str]           =	[1] * inputs.shape.rank
      snake_case				:    str           =	shape_list(lowercase					)[axis]
      snake_case				:    int           =	tf.reshape(lowercase						,lowercase					)
      snake_case				:    Optional[Any]           =	tf.reshape(lowercase						,lowercase					)

   # Compute layer normalization using the batch_normalization
   # function.
   snake_case				:    str           =	tf.nn.batch_normalization(
       lowercase						,lowercase						,lowercase						,offset=lowercase						,scale=lowercase						,variance_epsilon=lowercase						,)
   return outputs




def 						SCREAMING_SNAKE_CASE__ (   lowercase						,lowercase=0						,lowercase=-1					)  ->       List[str]:
   # Replicates the behavior of torch.flatten in TF

   # If end_dim or start_dim is negative, count them from the end
   if end_dim < 0:
      end_dim += input.shape.rank
   if start_dim < 0:
      start_dim += input.shape.rank

   if start_dim == end_dim:
      return input

   snake_case				:    Optional[Any]           =	tf.shape(lowercase					)
   snake_case				:    str           =	tf.math.reduce_prod(in_shape[start_dim : end_dim + 1]					)
   snake_case				:    int           =	tf.concat([in_shape[:start_dim], [flattened_dim], in_shape[end_dim + 1 :]]						,axis=0					)
   return tf.reshape(lowercase						,lowercase					)




def 						SCREAMING_SNAKE_CASE__ (   lowercase					)  ->       tf.Tensor:
   if not isinstance(lowercase						,tf.Tensor					):
      snake_case				:    Any           =	tf.convert_to_tensor(lowercase					)  # Catches stray NumPy inputs
   if encoder_attention_mask.shape.rank == 3:
      snake_case				:    Optional[Any]           =	encoder_attention_mask[:, None, :, :]
   if encoder_attention_mask.shape.rank == 2:
      snake_case				:    Any           =	encoder_attention_mask[:, None, None, :]
   # T5 has a mask that can compare sequence ids, we can simulate this here with this transposition
   # Cf. https://github.com/tensorflow/mesh/blob/8d2465e9bc93129b913b5ccc6a59aa97abd96ec6/mesh_tensorflow
   # /transformer/transformer_layers.py#L270
   # encoder_extended_attention_mask = (encoder_extended_attention_mask ==
   # encoder_extended_attention_mask.transpose(-1, -2))
   snake_case				:    Union[str, Any]           =	(
       tf.cast(1						,encoder_attention_mask.dtype					) - encoder_extended_attention_mask
   ) * encoder_extended_attention_mask.dtype.min

   return encoder_extended_attention_mask




def 						SCREAMING_SNAKE_CASE__ (   lowercase						,lowercase						,lowercase = "input_ids"					)  ->       None:
   tf.debugging.assert_less(
       lowercase						,tf.cast(lowercase						,dtype=tensor.dtype					)						,message=(
           f"""The maximum value of {tensor_name} ({tf.math.reduce_max(lowercase					)}) must be smaller than the embedding """
           f"""layer's input dimension ({embed_dim}). The likely cause is some problem at tokenization time."""
       )						,)




def 						SCREAMING_SNAKE_CASE__ (   lowercase						,lowercase						,lowercase					)  ->       Tuple:
   snake_case				:    Optional[int]           =	64512
   # Check that no item in `data` is larger than `HDF5_OBJECT_HEADER_LIMIT`
   # because in that case even chunking the array would not make the saving
   # possible.
   snake_case				:    Dict           =	[x for x in data if len(lowercase					) > HDF5_OBJECT_HEADER_LIMIT]

   # Expecting this to never be true.
   if bad_attributes:
      raise RuntimeError(
          """The following attributes cannot be saved to HDF5 file because """
          f"""they are larger than {HDF5_OBJECT_HEADER_LIMIT} """
          f"""bytes: {bad_attributes}"""					)

   snake_case				:    str           =	np.asarray(lowercase					)

   snake_case				:    Union[str, Any]           =	1
   snake_case				:    List[str]           =	np.array_split(lowercase						,lowercase					)

   # This will never loop forever thanks to the test above.
   while any(x.nbytes > HDF5_OBJECT_HEADER_LIMIT for x in chunked_data					):
      num_chunks += 1
      snake_case				:    str           =	np.array_split(lowercase						,lowercase					)

   if num_chunks > 1:
      for chunk_id, chunk_data in enumerate(lowercase					):
         snake_case				:    Optional[Any]           =	chunk_data
   else:
      snake_case				:    Tuple           =	data




def 						SCREAMING_SNAKE_CASE__ (   lowercase						,lowercase					)  ->       Tuple:
   if name in group.attrs:
      snake_case				:    List[Any]           =	[n.decode("""utf8"""					) if hasattr(lowercase						,"""decode"""					) else n for n in group.attrs[name]]
   else:
      snake_case				:    Tuple           =	[]
      snake_case				:    List[str]           =	0
      while "%s%d" % (name, chunk_id) in group.attrs:
         data.extend(
             [n.decode("""utf8"""					) if hasattr(lowercase						,"""decode"""					) else n for n in group.attrs["""%s%d""" % (name, chunk_id)]]					)
         chunk_id += 1
   return data




def 						SCREAMING_SNAKE_CASE__ (   lowercase					)  ->       Optional[int]:

   def _expand_single_ad_tensor(lowercase					):
      if isinstance(lowercase						,tf.Tensor					) and t.shape.rank == 1:
         return tf.expand_dims(lowercase						,axis=-1					)
      return t

   return tf.nest.map_structure(_expand_single_ad_tensor						,lowercase					)











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	:	Optional[Any]				=   logging.get_logger(__name__)

lowerCamelCase	:	Optional[int]				=   {
    '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 						__lowercase		(UpperCamelCase__							):




      """simple docstring"""





      _snake_case												=						"""bart"""
      _snake_case												=						["""past_key_values"""]
      _snake_case												=						{"""num_attention_heads""": """encoder_attention_heads""", """hidden_size""": """d_model"""}

      def __init__(				self    ,				A=5_0_2_6_5    ,				A=1_0_2_4    ,				A=1_2    ,				A=4_0_9_6    ,				A=1_6    ,				A=1_2    ,				A=4_0_9_6    ,				A=1_6    ,				A=0.0    ,				A=0.0    ,				A="gelu"    ,				A=1_0_2_4    ,				A=0.1    ,				A=0.0    ,				A=0.0    ,				A=0.02    ,				A=0.0    ,				A=False    ,				A=True    ,				A=3    ,				A=1    ,				A=0    ,				A=2    ,				A=True    ,				A=2    ,				A=2    ,				**A    ,				)		->    Any:
         snake_case				:    Optional[int]           =	vocab_size
         snake_case				:    Union[str, Any]           =	max_position_embeddings
         snake_case				:    List[str]           =	d_model
         snake_case				:    List[Any]           =	encoder_ffn_dim
         snake_case				:    Optional[Any]           =	encoder_layers
         snake_case				:    Union[str, Any]           =	encoder_attention_heads
         snake_case				:    str           =	decoder_ffn_dim
         snake_case				:    Union[str, Any]           =	decoder_layers
         snake_case				:    Any           =	decoder_attention_heads
         snake_case				:    Union[str, Any]           =	dropout
         snake_case				:    List[str]           =	attention_dropout
         snake_case				:    List[Any]           =	activation_dropout
         snake_case				:    Optional[int]           =	activation_function
         snake_case				:    Union[str, Any]           =	init_std
         snake_case				:    List[str]           =	encoder_layerdrop
         snake_case				:    int           =	decoder_layerdrop
         snake_case				:    str           =	classifier_dropout
         snake_case				:    List[str]           =	use_cache
         snake_case				:    Tuple           =	encoder_layers
         snake_case				:    int           =	scale_embedding  # scale factor will be sqrt(d_model) if True

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

         # ensure backward compatibility for BART CNN models
         if self.forced_bos_token_id is None and kwargs.get("""force_bos_token_to_be_generated"""    ,				A     ):
            snake_case				:    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 						__lowercase		(UpperCamelCase__							):




      """simple docstring"""





      @property
      def      UpperCAmelCase				(				self     )		->    Mapping[str, Mapping[int, str]]:
         if self.task in ["default", "seq2seq-lm"]:
            snake_case				:    Optional[Any]           =	OrderedDict(
                [
                    ("""input_ids""", {0: """batch""", 1: """encoder_sequence"""}),
                    ("""attention_mask""", {0: """batch""", 1: """encoder_sequence"""}),
                ]     )

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

            if self.use_past:
               self.fill_with_past_key_values_(A    ,				direction="""inputs"""     )
         elif self.task == "causal-lm":
            # TODO: figure this case out.
            snake_case				:    Union[str, Any]           =	OrderedDict(
                [
                    ("""input_ids""", {0: """batch""", 1: """encoder_sequence"""}),
                    ("""attention_mask""", {0: """batch""", 1: """encoder_sequence"""}),
                ]     )
            if self.use_past:
               snake_case     , snake_case				:    List[Any]           =	self.num_layers
               for i in range(A     ):
                  snake_case				:    List[Any]           =	{0: """batch""", 2: """past_sequence + sequence"""}
                  snake_case				:    Optional[int]           =	{0: """batch""", 2: """past_sequence + sequence"""}
         else:
            snake_case				:    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      UpperCAmelCase				(				self     )		->    Mapping[str, Mapping[int, str]]:
         if self.task in ["default", "seq2seq-lm"]:
            snake_case				:    Any           =	super().outputs
         else:
            snake_case				:    Any           =	super(A    ,				self     ).outputs
            if self.use_past:
               snake_case     , snake_case				:    Any           =	self.num_layers
               for i in range(A     ):
                  snake_case				:    Any           =	{0: """batch""", 2: """past_sequence + sequence"""}
                  snake_case				:    Union[str, Any]           =	{0: """batch""", 2: """past_sequence + sequence"""}
         return common_outputs

      def      UpperCAmelCase				(				self    ,				A    ,				A = -1    ,				A = -1    ,				A = False    ,				A = None    ,				)		->    Mapping[str, Any]:
         snake_case				:    Optional[Any]           =	self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
             A    ,				A    ,				A    ,				A    ,				A     )

         # Generate decoder inputs
         snake_case				:    Any           =	seq_length if not self.use_past else 1
         snake_case				:    List[str]           =	self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
             A    ,				A    ,				A    ,				A    ,				A     )
         snake_case				:    Optional[int]           =	{f"""decoder_{name}""": tensor for name, tensor in decoder_inputs.items()}
         snake_case				:    List[str]           =	dict(**A    ,				**A     )

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

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

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

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

      def      UpperCAmelCase				(				self    ,				A    ,				A = -1    ,				A = -1    ,				A = False    ,				A = None    ,				)		->    Mapping[str, Any]:
         snake_case				:    str           =	self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
             A    ,				A    ,				A    ,				A    ,				A     )

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

            snake_case				:    Optional[Any]           =	common_inputs["""attention_mask"""].dtype
            snake_case				:    int           =	torch.cat(
                [common_inputs["""attention_mask"""], torch.ones(A    ,				A    ,				dtype=A     )]    ,				dim=1     )
            snake_case				:    Union[str, Any]           =	[
                (torch.zeros(A     ), torch.zeros(A     )) for _ in range(A     )
            ]
         return common_inputs

      def      UpperCAmelCase				(				self    ,				A    ,				A = -1    ,				A = -1    ,				A = False    ,				A = 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
         snake_case				:    int           =	compute_effective_axis_dimension(
             A    ,				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
         snake_case				:    int           =	tokenizer.num_special_tokens_to_add(A     )
         snake_case				:    Tuple           =	compute_effective_axis_dimension(
             A    ,				fixed_dimension=OnnxConfig.default_fixed_sequence    ,				num_token_to_add=A     )

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

      def      UpperCAmelCase				(				self    ,				A    ,				A = -1    ,				A = -1    ,				A = False    ,				A = None    ,				)		->    Mapping[str, Any]:
         if self.task in ["default", "seq2seq-lm"]:
            snake_case				:    Optional[Any]           =	self._generate_dummy_inputs_for_default_and_seqaseq_lm(
                A    ,				batch_size=A    ,				seq_length=A    ,				is_pair=A    ,				framework=A     )

         elif self.task == "causal-lm":
            snake_case				:    Optional[int]           =	self._generate_dummy_inputs_for_causal_lm(
                A    ,				batch_size=A    ,				seq_length=A    ,				is_pair=A    ,				framework=A     )
         else:
            snake_case				:    List[Any]           =	self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
                A    ,				batch_size=A    ,				seq_length=A    ,				is_pair=A    ,				framework=A     )

         return common_inputs

      def      UpperCAmelCase				(				self    ,				A    ,				A    ,				A    ,				A     )		->    Union[str, Any]:
         if self.task in ["default", "seq2seq-lm"]:
            snake_case				:    Optional[Any]           =	super()._flatten_past_key_values_(A    ,				A    ,				A    ,				A     )
         else:
            snake_case				:    Union[str, Any]           =	super(A    ,				self     )._flatten_past_key_values_(
                A    ,				A    ,				A    ,				A     )





