






"""simple docstring"""







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

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


_UpperCamelCase     			=  logging.get_logger(__name__)

_UpperCamelCase     			=  {
    """facebook/blenderbot-3B""": """https://huggingface.co/facebook/blenderbot-3B/resolve/main/config.json""",
    # See all Blenderbot models at https://huggingface.co/models?filter=blenderbot
}







class 					lowerCamelCase__					(       snake_case ):
    SCREAMING_SNAKE_CASE		=			'''blenderbot'''
    SCREAMING_SNAKE_CASE		=			['''past_key_values''']
    SCREAMING_SNAKE_CASE		=			{'''num_attention_heads''': '''encoder_attention_heads''', '''hidden_size''': '''d_model'''}






    def __init__( self	,A=8_008	,A=128	,A=2	,A=10_240	,A=32	,A=24	,A=10_240	,A=32	,A=0.0	,A=0.0	,A=True	,A=True	,A="gelu"	,A=2_560	,A=0.1	,A=0.0	,A=0.0	,A=0.02	,A=1	,A=False	,A=0	,A=1	,A=2	,A=3	,A=2	,**A	,):
          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=A	,bos_token_id=A	,eos_token_id=A	,is_encoder_decoder=A	,decoder_start_token_id=A	,encoder_no_repeat_ngram_size=A	,forced_eos_token_id=A	,**A	,)







class 					lowerCamelCase__					(       snake_case ):






    @property
    def 				_UpperCamelCase							( self					):
          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_(A	,direction="""inputs"""					)
          elif self.task == "causal-lm":
                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(A					):
                            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
    # Copied from transformers.models.bart.configuration_bart.BartOnnxConfig.outputs
    def 				_UpperCamelCase							( self					):
          if self.task in ["default", "seq2seq-lm"]:
                UpperCAmelCase							=       super().outputs
          else:
                UpperCAmelCase							=       super(A	,self					).outputs
                if self.use_past:
                      UpperCAmelCase			,					UpperCAmelCase							=       self.num_layers
                      for i in range(A					):
                            UpperCAmelCase							=       {0: """batch""", 2: """past_sequence + sequence"""}
                            UpperCAmelCase							=       {0: """batch""", 2: """past_sequence + sequence"""}
          return common_outputs






    def 				_UpperCamelCase							( self	,A	,A = -1	,A = -1	,A = False	,A = None	,):
          UpperCAmelCase							=       self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
              A	,A	,A	,A	,A					)
          # Generate decoder inputs
          UpperCAmelCase							=       seq_length if not self.use_past else 1
          UpperCAmelCase							=       self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
              A	,A	,A	,A	,A					)
          UpperCAmelCase							=       {F'''decoder_{name}''': tensor for name, tensor in decoder_inputs.items()}
          UpperCAmelCase							=       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
                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
                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(A	,A					)]	,dim=1					)
                UpperCAmelCase							=       []
                UpperCAmelCase			,					UpperCAmelCase							=       self.num_layers

                for _ in range(A					):
                      common_inputs["past_key_values"].append(
                          (
                              torch.zeros(A					),
                              torch.zeros(A					),
                              torch.zeros(A					),
                              torch.zeros(A					),
                          )					)
          return common_inputs






    def 				_UpperCamelCase							( self	,A	,A = -1	,A = -1	,A = False	,A = None	,):
          UpperCAmelCase							=       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
                UpperCAmelCase			,					UpperCAmelCase							=       common_inputs["""input_ids"""].shape
                UpperCAmelCase							=       seqlen
                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(A	,A	,dtype=A					)]	,dim=1					)
                UpperCAmelCase							=       [
                    (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	,):
          # 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(
              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
          UpperCAmelCase							=       tokenizer.num_special_tokens_to_add(A					)
          UpperCAmelCase							=       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
          UpperCAmelCase							=       [""" """.join([tokenizer.unk_token]					) * seq_length] * batch_size
          UpperCAmelCase							=       dict(tokenizer(A	,return_tensors=A					)					)
          return common_inputs






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






    def 				_UpperCamelCase							( self	,A	,A					):
          if direction not in ["inputs", "outputs"]:
                raise ValueError(F'''direction must either be "inputs" or "outputs", but {direction} was given'''					)

          UpperCAmelCase							=       """past_key_values""" if direction == """inputs""" else """present"""
          UpperCAmelCase			,					UpperCAmelCase							=       self.num_layers

          UpperCAmelCase							=       """past_encoder_sequence"""
          UpperCAmelCase							=       """past_decoder_sequence""" if direction == """inputs""" else """past_decoder_sequence + sequence"""

          for i in range(A					):
                UpperCAmelCase							=       {0: """batch""", 2: decoder_sequence}
                UpperCAmelCase							=       {0: """batch""", 2: decoder_sequence}
                UpperCAmelCase							=       {0: """batch""", 2: encoder_sequence}
                UpperCAmelCase							=       {0: """batch""", 2: encoder_sequence}











"""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 normalize, rescale, resize, to_channel_dimension_format
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, logging


_UpperCamelCase     			=  logging.get_logger(__name__)







class 					lowerCamelCase__					(       snake_case ):
    SCREAMING_SNAKE_CASE		=			['''pixel_values''']






    def __init__( self	,A = True	,A = None	,A = PILImageResampling.BILINEAR	,A = True	,A = 1 / 255	,A = True	,A = None	,A = None	,**A	,):
          super().__init__(**A					)
          UpperCAmelCase							=       size if size is not None else {"""height""": 224, """width""": 224}
          UpperCAmelCase							=       get_size_dict(A					)
          UpperCAmelCase							=       do_resize
          UpperCAmelCase							=       do_rescale
          UpperCAmelCase							=       do_normalize
          UpperCAmelCase							=       size
          UpperCAmelCase							=       resample
          UpperCAmelCase							=       rescale_factor
          UpperCAmelCase							=       image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
          UpperCAmelCase							=       image_std if image_std is not None else IMAGENET_STANDARD_STD






    def 				_UpperCamelCase							( self	,A	,A	,A = PILImageResampling.BILINEAR	,A = None	,**A	,):
          UpperCAmelCase							=       get_size_dict(A					)
          if "height" not in size or "width" not in size:
                raise ValueError(F'''The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}'''					)
          return resize(
              A	,size=(size["""height"""], size["""width"""])	,resample=A	,data_format=A	,**A					)






    def 				_UpperCamelCase							( self	,A	,A	,A = None	,**A					):
          return rescale(A	,scale=A	,data_format=A	,**A					)






    def 				_UpperCamelCase							( self	,A	,A	,A	,A = None	,**A	,):
          return normalize(A	,mean=A	,std=A	,data_format=A	,**A					)






    def 				_UpperCamelCase							( self	,A	,A = None	,A = None	,A = None	,A = None	,A = None	,A = None	,A = None	,A = None	,A = None	,A = ChannelDimension.FIRST	,**A	,):
          UpperCAmelCase							=       do_resize if do_resize is not None else self.do_resize
          UpperCAmelCase							=       do_rescale if do_rescale is not None else self.do_rescale
          UpperCAmelCase							=       do_normalize if do_normalize is not None else self.do_normalize
          UpperCAmelCase							=       resample if resample is not None else self.resample
          UpperCAmelCase							=       rescale_factor if rescale_factor is not None else self.rescale_factor
          UpperCAmelCase							=       image_mean if image_mean is not None else self.image_mean
          UpperCAmelCase							=       image_std if image_std is not None else self.image_std

          UpperCAmelCase							=       size if size is not None else self.size
          UpperCAmelCase							=       get_size_dict(A					)

          UpperCAmelCase							=       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_rescale and rescale_factor is None:
                raise ValueError("""Rescale factor must be specified if do_rescale is True."""					)

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

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

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

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

          UpperCAmelCase							=       [to_channel_dimension_format(A	,A					) for image in images]

          UpperCAmelCase							=       {"""pixel_values""": images}
          return BatchFeature(data=A	,tensor_type=A					)



