




"""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    (					lowercase_						):
   _lowerCamelCase    :Optional[Any]     				=     "bart"
   _lowerCamelCase    :List[str]     				=     ["past_key_values"]
   _lowerCamelCase    :List[Any]     				=     {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"}






   def __init__(		self       :		Optional[Any]   ,     UpperCamelCase       :		Tuple=5_02_65   ,     UpperCamelCase       :		List[Any]=10_24   ,     UpperCamelCase       :		Any=12   ,     UpperCamelCase       :		List[str]=40_96   ,     UpperCamelCase       :		Union[str, Any]=16   ,     UpperCamelCase       :		Tuple=12   ,     UpperCamelCase       :		str=40_96   ,     UpperCamelCase       :		List[Any]=16   ,     UpperCamelCase       :		Optional[int]=0.0   ,     UpperCamelCase       :		Any=0.0   ,     UpperCamelCase       :		List[str]="gelu"   ,     UpperCamelCase       :		List[str]=10_24   ,     UpperCamelCase       :		int=0.1   ,     UpperCamelCase       :		Optional[Any]=0.0   ,     UpperCamelCase       :		Union[str, Any]=0.0   ,     UpperCamelCase       :		str=0.02   ,     UpperCamelCase       :		Dict=0.0   ,     UpperCamelCase       :		List[str]=False   ,     UpperCamelCase       :		List[str]=True   ,     UpperCamelCase       :		Tuple=3   ,     UpperCamelCase       :		Optional[Any]=1   ,     UpperCamelCase       :		Any=0   ,     UpperCamelCase       :		str=2   ,     UpperCamelCase       :		Optional[int]=True   ,     UpperCamelCase       :		Tuple=2   ,     UpperCamelCase       :		Union[str, Any]=2   ,     **UpperCamelCase       :		int   ,     )			->						Dict:

         """simple docstring"""
         lowerCAmelCase__      :			int   =	vocab_size
         lowerCAmelCase__      :			Union[str, Any]   =	max_position_embeddings
         lowerCAmelCase__      :			Union[str, Any]   =	d_model
         lowerCAmelCase__      :			List[str]   =	encoder_ffn_dim
         lowerCAmelCase__      :			str   =	encoder_layers
         lowerCAmelCase__      :			Optional[Any]   =	encoder_attention_heads
         lowerCAmelCase__      :			List[Any]   =	decoder_ffn_dim
         lowerCAmelCase__      :			Tuple   =	decoder_layers
         lowerCAmelCase__      :			List[str]   =	decoder_attention_heads
         lowerCAmelCase__      :			Dict   =	dropout
         lowerCAmelCase__      :			Dict   =	attention_dropout
         lowerCAmelCase__      :			Dict   =	activation_dropout
         lowerCAmelCase__      :			Tuple   =	activation_function
         lowerCAmelCase__      :			List[str]   =	init_std
         lowerCAmelCase__      :			List[str]   =	encoder_layerdrop
         lowerCAmelCase__      :			Dict   =	decoder_layerdrop
         lowerCAmelCase__      :			Any   =	classifier_dropout
         lowerCAmelCase__      :			Optional[int]   =	use_cache
         lowerCAmelCase__      :			Optional[Any]   =	encoder_layers
         lowerCAmelCase__      :			Optional[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__   ):
               lowerCAmelCase__      :			str   =	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    (					lowercase_						):






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

         """simple docstring"""




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

               if self.use_past:
                     lowerCAmelCase__      :			int   =	{0: """batch"""}
                     lowerCAmelCase__      :			Dict   =	{0: """batch""", 1: """past_decoder_sequence + sequence"""}
               else:
                     lowerCAmelCase__      :			List[Any]   =	{0: """batch""", 1: """decoder_sequence"""}
                     lowerCAmelCase__      :			str   =	{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.
               lowerCAmelCase__      :			Union[str, Any]   =	OrderedDict(
                   [
                       ("""input_ids""", {0: """batch""", 1: """encoder_sequence"""}),
                       ("""attention_mask""", {0: """batch""", 1: """encoder_sequence"""}),
                   ]   )
               if self.use_past:
                     lowerCAmelCase__ ,   lowerCAmelCase__      :			Optional[Any]   =	self.num_layers
                     for i in range(a__   ):
                           lowerCAmelCase__      :			Optional[Any]   =	{0: """batch""", 2: """past_sequence + sequence"""}
                           lowerCAmelCase__      :			Tuple   =	{0: """batch""", 2: """past_sequence + sequence"""}
         else:
               lowerCAmelCase__      :			int   =	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 	_lowerCAmelCase   (		self       :		Optional[Any]   )			->						Mapping[str, Mapping[int, str]]:

         """simple docstring"""




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






   def 	_lowerCAmelCase   (		self       :		List[str]   ,     UpperCamelCase       :		Union[str, Any]   ,     UpperCamelCase       :		List[Any] = -1   ,     UpperCamelCase       :		Tuple = -1   ,     UpperCamelCase       :		Optional[int] = False   ,     UpperCamelCase       :		str = None   ,     )			->						Mapping[str, Any]:

         """simple docstring"""
         lowerCAmelCase__      :			Optional[int]   =	self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
             a__   ,     a__   ,     a__   ,     a__   ,     a__   )

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

               lowerCAmelCase__      :			int   =	torch.cat(
                   [common_inputs["""decoder_attention_mask"""], torch.ones(a__   ,     a__   )]   ,     dim=1   )

               lowerCAmelCase__      :			Union[str, Any]   =	[]
               # If the number of encoder and decoder layers are present in the model configuration, both are considered
               lowerCAmelCase__ ,   lowerCAmelCase__      :			Union[str, Any]   =	self.num_layers
               lowerCAmelCase__      :			Tuple   =	min(a__   ,     a__   )
               lowerCAmelCase__      :			List[str]   =	max(a__   ,     a__   ) - min_num_layers
               lowerCAmelCase__      :			int   =	"""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.
               lowerCAmelCase__      :			str   =	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 	_lowerCAmelCase   (		self       :		int   ,     UpperCamelCase       :		List[Any]   ,     UpperCamelCase       :		Union[str, Any] = -1   ,     UpperCamelCase       :		Optional[Any] = -1   ,     UpperCamelCase       :		Any = False   ,     UpperCamelCase       :		Any = None   ,     )			->						Mapping[str, Any]:

         """simple docstring"""
         lowerCAmelCase__      :			Dict   =	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
               lowerCAmelCase__ ,   lowerCAmelCase__      :			List[Any]   =	common_inputs["""input_ids"""].shape
               # Not using the same length for past_key_values
               lowerCAmelCase__      :			Any   =	seqlen + 2
               lowerCAmelCase__ ,   lowerCAmelCase__      :			Union[str, Any]   =	self.num_layers
               lowerCAmelCase__ ,   lowerCAmelCase__      :			int   =	self.num_attention_heads
               lowerCAmelCase__      :			Dict   =	(
                   batch,
                   num_encoder_attention_heads,
                   past_key_values_length,
                   self._config.hidden_size // num_encoder_attention_heads,
               )

               lowerCAmelCase__      :			int   =	common_inputs["""attention_mask"""].dtype
               lowerCAmelCase__      :			List[str]   =	torch.cat(
                   [common_inputs["""attention_mask"""], torch.ones(a__   ,     a__   ,     dtype=a__   )]   ,     dim=1   )
               lowerCAmelCase__      :			List[Any]   =	[
                   (torch.zeros(a__   ), torch.zeros(a__   )) for _ in range(a__   )
               ]
         return common_inputs






   def 	_lowerCAmelCase   (		self       :		Optional[Any]   ,     UpperCamelCase       :		int   ,     UpperCamelCase       :		List[Any] = -1   ,     UpperCamelCase       :		int = -1   ,     UpperCamelCase       :		str = False   ,     UpperCamelCase       :		List[Any] = None   ,     )			->						Mapping[str, Any]:

         """simple docstring"""
         lowerCAmelCase__      :			str   =	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
         lowerCAmelCase__      :			Tuple   =	tokenizer.num_special_tokens_to_add(a__   )
         lowerCAmelCase__      :			Optional[int]   =	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
         lowerCAmelCase__      :			Optional[Any]   =	[""" """.join([tokenizer.unk_token]   ) * seq_length] * batch_size
         lowerCAmelCase__      :			str   =	dict(tokenizer(a__   ,     return_tensors=a__   )   )
         return common_inputs






   def 	_lowerCAmelCase   (		self       :		int   ,     UpperCamelCase       :		str   ,     UpperCamelCase       :		List[Any] = -1   ,     UpperCamelCase       :		List[str] = -1   ,     UpperCamelCase       :		Optional[int] = False   ,     UpperCamelCase       :		Optional[Any] = None   ,     )			->						Mapping[str, Any]:

         """simple docstring"""




         if self.task in ["default", "seq2seq-lm"]:
               lowerCAmelCase__      :			List[str]   =	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":
               lowerCAmelCase__      :			List[Any]   =	self._generate_dummy_inputs_for_causal_lm(
                   a__   ,     batch_size=a__   ,     seq_length=a__   ,     is_pair=a__   ,     framework=a__   )
         else:
               lowerCAmelCase__      :			Optional[int]   =	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 	_lowerCAmelCase   (		self       :		Any   ,     UpperCamelCase       :		List[str]   ,     UpperCamelCase       :		Any   ,     UpperCamelCase       :		int   ,     UpperCamelCase       :		str   )			->						List[Any]:

         """simple docstring"""




         if self.task in ["default", "seq2seq-lm"]:
               lowerCAmelCase__      :			Tuple   =	super()._flatten_past_key_values_(a__   ,     a__   ,     a__   ,     a__   )
         else:
               lowerCAmelCase__      :			int   =	super(a__   ,     self   )._flatten_past_key_values_(
                   a__   ,     a__   ,     a__   ,     a__   )











"""simple docstring"""


from typing import List, Optional, Union

from ...image_utils import ImageInput
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
from ...utils import TensorType


class _lowerCamelCase    (					a_						):
   _lowerCamelCase    :Dict     				=     ["image_processor", "tokenizer"]
   _lowerCamelCase    :Dict     				=     "BlipImageProcessor"
   _lowerCamelCase    :Any     				=     ("BertTokenizer", "BertTokenizerFast")






   def __init__(		self       :		Dict   ,     UpperCamelCase       :		Optional[int]   ,     UpperCamelCase       :		Union[str, Any]   )			->						str:

         """simple docstring"""
         lowerCAmelCase__      :			Optional[Any]   =	False
         super().__init__(UpperCamelCase   ,     UpperCamelCase   )
         lowerCAmelCase__      :			List[Any]   =	self.image_processor






   def __call__(		self       :		int   ,     UpperCamelCase       :		ImageInput = None   ,     UpperCamelCase       :		Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None   ,     UpperCamelCase       :		bool = True   ,     UpperCamelCase       :		Union[bool, str, PaddingStrategy] = False   ,     UpperCamelCase       :		Union[bool, str, TruncationStrategy] = None   ,     UpperCamelCase       :		Optional[int] = None   ,     UpperCamelCase       :		int = 0   ,     UpperCamelCase       :		Optional[int] = None   ,     UpperCamelCase       :		Optional[bool] = None   ,     UpperCamelCase       :		bool = False   ,     UpperCamelCase       :		bool = False   ,     UpperCamelCase       :		bool = False   ,     UpperCamelCase       :		bool = False   ,     UpperCamelCase       :		bool = False   ,     UpperCamelCase       :		bool = True   ,     UpperCamelCase       :		Optional[Union[str, TensorType]] = None   ,     **UpperCamelCase       :		Optional[int]   ,     )			->						BatchEncoding:

         """simple docstring"""
         if images is None and text is None:
               raise ValueError("""You have to specify either images or text."""   )

         # Get only text
         if images is None:
               lowerCAmelCase__      :			Any   =	self.tokenizer
               lowerCAmelCase__      :			Optional[int]   =	self.tokenizer(
                   text=UpperCamelCase   ,     add_special_tokens=UpperCamelCase   ,     padding=UpperCamelCase   ,     truncation=UpperCamelCase   ,     max_length=UpperCamelCase   ,     stride=UpperCamelCase   ,     pad_to_multiple_of=UpperCamelCase   ,     return_attention_mask=UpperCamelCase   ,     return_overflowing_tokens=UpperCamelCase   ,     return_special_tokens_mask=UpperCamelCase   ,     return_offsets_mapping=UpperCamelCase   ,     return_token_type_ids=UpperCamelCase   ,     return_length=UpperCamelCase   ,     verbose=UpperCamelCase   ,     return_tensors=UpperCamelCase   ,     **UpperCamelCase   ,     )
               return text_encoding

         # add pixel_values
         lowerCAmelCase__      :			Tuple   =	self.image_processor(UpperCamelCase   ,     return_tensors=UpperCamelCase   )

         if text is not None:
               lowerCAmelCase__      :			Optional[int]   =	self.tokenizer(
                   text=UpperCamelCase   ,     add_special_tokens=UpperCamelCase   ,     padding=UpperCamelCase   ,     truncation=UpperCamelCase   ,     max_length=UpperCamelCase   ,     stride=UpperCamelCase   ,     pad_to_multiple_of=UpperCamelCase   ,     return_attention_mask=UpperCamelCase   ,     return_overflowing_tokens=UpperCamelCase   ,     return_special_tokens_mask=UpperCamelCase   ,     return_offsets_mapping=UpperCamelCase   ,     return_token_type_ids=UpperCamelCase   ,     return_length=UpperCamelCase   ,     verbose=UpperCamelCase   ,     return_tensors=UpperCamelCase   ,     **UpperCamelCase   ,     )
         else:
               lowerCAmelCase__      :			Tuple   =	None

         if text_encoding is not None:
               encoding_image_processor.update(UpperCamelCase   )

         return encoding_image_processor






   def 	_lowerCAmelCase   (		self       :		int   ,     *UpperCamelCase       :		Union[str, Any]   ,     **UpperCamelCase       :		List[str]   )			->						Dict:

         """simple docstring"""
         return self.tokenizer.batch_decode(*UpperCamelCase   ,     **UpperCamelCase   )






   def 	_lowerCAmelCase   (		self       :		List[Any]   ,     *UpperCamelCase       :		Tuple   ,     **UpperCamelCase       :		List[str]   )			->						List[Any]:

         """simple docstring"""
         return self.tokenizer.decode(*UpperCamelCase   ,     **UpperCamelCase   )






   @property
   def 	_lowerCAmelCase   (		self       :		List[Any]   )			->						Tuple:

         """simple docstring"""
         lowerCAmelCase__      :			Optional[int]   =	self.tokenizer.model_input_names
         lowerCAmelCase__      :			Union[str, Any]   =	self.image_processor.model_input_names
         return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names   )   )





