


"""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


lowerCamelCase_       :       str      						=  logging.get_logger(__name__)

lowerCamelCase_       :       List[Any]      						=  {
    '''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 				__A    (	_a      ):






 """simple docstring"""




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


 def __init__(		self			,   __A=5_0265			,   __A=1024			,   __A=12			,   __A=4096			,   __A=16			,   __A=12			,   __A=4096			,   __A=16			,   __A=0.0			,   __A=0.0			,   __A="gelu"			,   __A=1024			,   __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			,   ) ->					int:
     a					=vocab_size
     a					=max_position_embeddings
     a					=d_model
     a					=encoder_ffn_dim
     a					=encoder_layers
     a					=encoder_attention_heads
     a					=decoder_ffn_dim
     a					=decoder_layers
     a					=decoder_attention_heads
     a					=dropout
     a					=attention_dropout
     a					=activation_dropout
     a					=activation_function
     a					=init_std
     a					=encoder_layerdrop
     a					=decoder_layerdrop
     a					=classifier_dropout
     a					=use_cache
     a					=encoder_layers
     a					=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						):
         a					=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 				__A    (	_a      ):






 """simple docstring"""




 @property
 def 				SCREAMING_SNAKE_CASE							(		self						) ->					Union[str, Any]:
     if self.task in ["default", "seq2seq-lm"]:
         a					=OrderedDict(
             [
                 ('''input_ids''', {0: '''batch''', 1: '''encoder_sequence'''}),
                 ('''attention_mask''', {0: '''batch''', 1: '''encoder_sequence'''}),
             ]						)

         if self.use_past:
             a					={0: """batch"""}
             a					={0: """batch""", 1: """past_decoder_sequence + sequence"""}
         else:
             a					={0: """batch""", 1: """decoder_sequence"""}
             a					={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.
         a					=OrderedDict(
             [
                 ('''input_ids''', {0: '''batch''', 1: '''encoder_sequence'''}),
                 ('''attention_mask''', {0: '''batch''', 1: '''encoder_sequence'''}),
             ]						)
         if self.use_past:
             a					=self.num_layers
             for i in range(__lowerCamelCase						):
                 a					={0: """batch""", 2: """past_sequence + sequence"""}
                 a					={0: """batch""", 2: """past_sequence + sequence"""}
     else:
         a					=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 				SCREAMING_SNAKE_CASE							(		self						) ->					Optional[Any]:
     if self.task in ["default", "seq2seq-lm"]:
         a					=super().outputs
     else:
         a					=super(__lowerCamelCase			,   self						).outputs
         if self.use_past:
             a					=self.num_layers
             for i in range(__lowerCamelCase						):
                 a					={0: """batch""", 2: """past_sequence + sequence"""}
                 a					={0: """batch""", 2: """past_sequence + sequence"""}
     return common_outputs


 def 				SCREAMING_SNAKE_CASE							(		self			,   __A			,   __A = -1			,   __A = -1			,   __A = False			,   __A = None			,   ) ->					List[Any]:
     a					=self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
         __lowerCamelCase			,   __lowerCamelCase			,   __lowerCamelCase			,   __lowerCamelCase			,   __lowerCamelCase						)

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

         a					=torch.cat(
             [common_inputs['''decoder_attention_mask'''], torch.ones(__lowerCamelCase			,   __lowerCamelCase						)]			,   dim=1						)

         a					=[]
         # If the number of encoder and decoder layers are present in the model configuration, both are considered
         a					=self.num_layers
         a					=min(__lowerCamelCase			,   __lowerCamelCase						)
         a					=max(__lowerCamelCase			,   __lowerCamelCase						) - min_num_layers
         a					="""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.
         a					=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 				SCREAMING_SNAKE_CASE							(		self			,   __A			,   __A = -1			,   __A = -1			,   __A = False			,   __A = None			,   ) ->					List[Any]:
     a					=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
         a					=common_inputs["""input_ids"""].shape
         # Not using the same length for past_key_values
         a					=seqlen + 2
         a					=self.num_layers
         a					=self.num_attention_heads
         a					=(
             batch,
             num_encoder_attention_heads,
             past_key_values_length,
             self._config.hidden_size // num_encoder_attention_heads,
         )

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


 def 				SCREAMING_SNAKE_CASE							(		self			,   __A			,   __A = -1			,   __A = -1			,   __A = False			,   __A = None			,   ) ->					List[str]:
     # 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
     a					=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
     a					=tokenizer.num_special_tokens_to_add(__lowerCamelCase						)
     a					=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
     a					=[""" """.join([tokenizer.unk_token]						) * seq_length] * batch_size
     a					=dict(tokenizer(__lowerCamelCase			,   return_tensors=__lowerCamelCase						)						)
     return common_inputs


 def 				SCREAMING_SNAKE_CASE							(		self			,   __A			,   __A = -1			,   __A = -1			,   __A = False			,   __A = None			,   ) ->					int:
     if self.task in ["default", "seq2seq-lm"]:
         a					=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":
         a					=self._generate_dummy_inputs_for_causal_lm(
             __lowerCamelCase			,   batch_size=__lowerCamelCase			,   seq_length=__lowerCamelCase			,   is_pair=__lowerCamelCase			,   framework=__lowerCamelCase						)
     else:
         a					=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 				SCREAMING_SNAKE_CASE							(		self			,   __A			,   __A			,   __A			,   __A						) ->					Dict:
     if self.task in ["default", "seq2seq-lm"]:
         a					=super()._flatten_past_key_values_(__lowerCamelCase			,   __lowerCamelCase			,   __lowerCamelCase			,   __lowerCamelCase						)
     else:
         a					=super(__lowerCamelCase			,   self						)._flatten_past_key_values_(
             __lowerCamelCase			,   __lowerCamelCase			,   __lowerCamelCase			,   __lowerCamelCase						)



"""simple docstring"""







from typing import Dict, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    center_crop,
    convert_to_rgb,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    OPENAI_CLIP_MEAN,
    OPENAI_CLIP_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


lowerCamelCase_       :       List[Any]      						=  logging.get_logger(__name__)


if is_vision_available():
       import PIL






class 				__A    (	_SCREAMING_SNAKE_CASE      ):






 """simple docstring"""




 __lowerCAmelCase			 =  ["pixel_values"]


 def __init__(		self			,   __A = True			,   __A = None			,   __A = PILImageResampling.BICUBIC			,   __A = True			,   __A = None			,   __A = True			,   __A = 1 / 255			,   __A = True			,   __A = None			,   __A = None			,   __A = True			,   **__A			,   ) ->					None:
     super().__init__(**__A						)
     a					=size if size is not None else {'''shortest_edge''': 224}
     a					=get_size_dict(__A			,   default_to_square=__A						)
     a					=crop_size if crop_size is not None else {'''height''': 224, '''width''': 224}
     a					=get_size_dict(__A			,   default_to_square=__A			,   param_name='''crop_size'''						)

     a					=do_resize
     a					=size
     a					=resample
     a					=do_center_crop
     a					=crop_size
     a					=do_rescale
     a					=rescale_factor
     a					=do_normalize
     a					=image_mean if image_mean is not None else OPENAI_CLIP_MEAN
     a					=image_std if image_std is not None else OPENAI_CLIP_STD
     a					=do_convert_rgb


 def 				SCREAMING_SNAKE_CASE							(		self			,   __A			,   __A			,   __A = PILImageResampling.BICUBIC			,   __A = None			,   **__A			,   ) ->					np.ndarray:
     a					=get_size_dict(__A			,   default_to_square=__A						)
     if "shortest_edge" not in size:
         raise ValueError(f'''The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}'''						)
     a					=get_resize_output_image_size(__A			,   size=size['''shortest_edge''']			,   default_to_square=__A						)
     return resize(__A			,   size=__A			,   resample=__A			,   data_format=__A			,   **__A						)


 def 				SCREAMING_SNAKE_CASE							(		self			,   __A			,   __A			,   __A = None			,   **__A			,   ) ->					np.ndarray:
     a					=get_size_dict(__A						)
     if "height" not in size or "width" not in size:
         raise ValueError(f'''The `size` parameter must contain the keys (height, width). Got {size.keys()}'''						)
     return center_crop(__A			,   size=(size['''height'''], size['''width'''])			,   data_format=__A			,   **__A						)


 def 				SCREAMING_SNAKE_CASE							(		self			,   __A			,   __A			,   __A = None			,   **__A			,   ) ->					Any:
     return rescale(__A			,   scale=__A			,   data_format=__A			,   **__A						)


 def 				SCREAMING_SNAKE_CASE							(		self			,   __A			,   __A			,   __A			,   __A = None			,   **__A			,   ) ->					np.ndarray:
     return normalize(__A			,   mean=__A			,   std=__A			,   data_format=__A			,   **__A						)





 def 				SCREAMING_SNAKE_CASE							(		self			,   __A			,   __A = None			,   __A = None			,   __A = None			,   __A = None			,   __A = None			,   __A = None			,   __A = None			,   __A = None			,   __A = None			,   __A = None			,   __A = None			,   __A = None			,   __A = ChannelDimension.FIRST			,   **__A			,   ) ->					PIL.Image.Image:
     a					=do_resize if do_resize is not None else self.do_resize
     a					=size if size is not None else self.size
     a					=get_size_dict(__A			,   param_name='''size'''			,   default_to_square=__A						)
     a					=resample if resample is not None else self.resample
     a					=do_center_crop if do_center_crop is not None else self.do_center_crop
     a					=crop_size if crop_size is not None else self.crop_size
     a					=get_size_dict(__A			,   param_name='''crop_size'''			,   default_to_square=__A						)
     a					=do_rescale if do_rescale is not None else self.do_rescale
     a					=rescale_factor if rescale_factor is not None else self.rescale_factor
     a					=do_normalize if do_normalize is not None else self.do_normalize
     a					=image_mean if image_mean is not None else self.image_mean
     a					=image_std if image_std is not None else self.image_std
     a					=do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb

     a					=make_list_of_images(__A						)

     if not valid_images(__A						):
         raise ValueError(
             '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '''
             '''torch.Tensor, tf.Tensor or jax.ndarray.'''						)

     if do_resize and size is None:
         raise ValueError('''Size must be specified if do_resize is True.'''						)

     if do_center_crop and crop_size is None:
         raise ValueError('''Crop size must be specified if do_center_crop is True.'''						)

     if do_rescale and rescale_factor is None:
         raise ValueError('''Rescale factor must be specified if do_rescale is True.'''						)

     if do_normalize and (image_mean is None or image_std is None):
         raise ValueError('''Image mean and std must be specified if do_normalize is True.'''						)

     # PIL RGBA images are converted to RGB
     if do_convert_rgb:
         a					=[convert_to_rgb(__A						) for image in images]

     # All transformations expect numpy arrays.
     a					=[to_numpy_array(__A						) for image in images]

     if do_resize:
         a					=[self.resize(image=__A			,   size=__A			,   resample=__A						) for image in images]

     if do_center_crop:
         a					=[self.center_crop(image=__A			,   size=__A						) for image in images]

     if do_rescale:
         a					=[self.rescale(image=__A			,   scale=__A						) for image in images]

     if do_normalize:
         a					=[self.normalize(image=__A			,   mean=__A			,   std=__A						) for image in images]

     a					=[to_channel_dimension_format(__A			,   __A						) for image in images]

     a					={'''pixel_values''': images}
     return BatchFeature(data=__A			,   tensor_type=__A						)