Aluode/PerceptionLabPortable
0
1# coding=utf-82# Copyright Deepmind and The HuggingFace Inc. team. All rights reserved.3#4# Licensed under the Apache License, Version 2.0 (the "License");5# you may not use this file except in compliance with the License.6# You may obtain a copy of the License at7#8# http://www.apache.org/licenses/LICENSE-2.09#10# Unless required by applicable law or agreed to in writing, software11# distributed under the License is distributed on an "AS IS" BASIS,12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13# See the License for the specific language governing permissions and14# limitations under the License.15"""Perceiver model configuration"""16 17from collections import OrderedDict18from collections.abc import Mapping19from typing import Any, Optional, Union20 21from ...configuration_utils import PretrainedConfig22from ...feature_extraction_utils import FeatureExtractionMixin23from ...onnx import OnnxConfig24from ...onnx.utils import compute_effective_axis_dimension25from ...tokenization_utils_base import PreTrainedTokenizerBase26from ...utils import TensorType, logging27 28 29logger = logging.get_logger(__name__)30 31 32class PerceiverConfig(PretrainedConfig):33 r"""34 This is the configuration class to store the configuration of a [`PerceiverModel`]. It is used to instantiate an35 Perceiver model according to the specified arguments, defining the model architecture. Instantiating a36 configuration with the defaults will yield a similar configuration to that of the Perceiver37 [deepmind/language-perceiver](https://huggingface.co/deepmind/language-perceiver) architecture.38 39 Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the40 documentation from [`PretrainedConfig`] for more information.41 42 Args:43 num_latents (`int`, *optional*, defaults to 256):44 The number of latents.45 d_latents (`int`, *optional*, defaults to 1280):46 Dimension of the latent embeddings.47 d_model (`int`, *optional*, defaults to 768):48 Dimension of the inputs. Should only be provided in case [*PerceiverTextPreprocessor*] is used or no49 preprocessor is provided.50 num_blocks (`int`, *optional*, defaults to 1):51 Number of blocks in the Transformer encoder.52 num_self_attends_per_block (`int`, *optional*, defaults to 26):53 The number of self-attention layers per block.54 num_self_attention_heads (`int`, *optional*, defaults to 8):55 Number of attention heads for each self-attention layer in the Transformer encoder.56 num_cross_attention_heads (`int`, *optional*, defaults to 8):57 Number of attention heads for each cross-attention layer in the Transformer encoder.58 qk_channels (`int`, *optional*):59 Dimension to project the queries + keys before applying attention in the cross-attention and self-attention60 layers of the encoder. Will default to preserving the dimension of the queries if not specified.61 v_channels (`int`, *optional*):62 Dimension to project the values before applying attention in the cross-attention and self-attention layers63 of the encoder. Will default to preserving the dimension of the queries if not specified.64 cross_attention_shape_for_attention (`str`, *optional*, defaults to `"kv"`):65 Dimension to use when downsampling the queries and keys in the cross-attention layer of the encoder.66 self_attention_widening_factor (`int`, *optional*, defaults to 1):67 Dimension of the feed-forward layer in the cross-attention layer of the Transformer encoder.68 cross_attention_widening_factor (`int`, *optional*, defaults to 1):69 Dimension of the feed-forward layer in the self-attention layers of the Transformer encoder.70 hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):71 The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,72 `"relu"`, `"selu"` and `"gelu_new"` are supported.73 attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):74 The dropout ratio for the attention probabilities.75 initializer_range (`float`, *optional*, defaults to 0.02):76 The standard deviation of the truncated_normal_initializer for initializing all weight matrices.77 layer_norm_eps (`float`, *optional*, defaults to 1e-12):78 The epsilon used by the layer normalization layers.79 use_query_residual (`float`, *optional*, defaults to `True`):80 Whether to add a query residual in the cross-attention layer of the encoder.81 vocab_size (`int`, *optional*, defaults to 262):82 Vocabulary size for the masked language modeling model.83 max_position_embeddings (`int`, *optional*, defaults to 2048):84 The maximum sequence length that the masked language modeling model might ever be used with. Typically set85 this to something large just in case (e.g., 512 or 1024 or 2048).86 image_size (`int`, *optional*, defaults to 56):87 Size of the images after preprocessing, for [`PerceiverForImageClassificationLearned`].88 train_size (`list[int]`, *optional*, defaults to `[368, 496]`):89 Training size of the images for the optical flow model.90 num_frames (`int`, *optional*, defaults to 16):91 Number of video frames used for the multimodal autoencoding model.92 audio_samples_per_frame (`int`, *optional*, defaults to 1920):93 Number of audio samples per frame for the multimodal autoencoding model.94 samples_per_patch (`int`, *optional*, defaults to 16):95 Number of audio samples per patch when preprocessing the audio for the multimodal autoencoding model.96 output_shape (`list[int]`, *optional*, defaults to `[1, 16, 224, 224]`):97 Shape of the output (batch_size, num_frames, height, width) for the video decoder queries of the multimodal98 autoencoding model. This excludes the channel dimension.99 output_num_channels (`int`, *optional*, defaults to 512):100 Number of output channels for each modalitiy decoder.101 102 Example:103 104 ```python105 >>> from transformers import PerceiverModel, PerceiverConfig106 107 >>> # Initializing a Perceiver deepmind/language-perceiver style configuration108 >>> configuration = PerceiverConfig()109 110 >>> # Initializing a model from the deepmind/language-perceiver style configuration111 >>> model = PerceiverModel(configuration)112 113 >>> # Accessing the model configuration114 >>> configuration = model.config115 ```"""116 117 model_type = "perceiver"118 119 def __init__(120 self,121 num_latents=256,122 d_latents=1280,123 d_model=768,124 num_blocks=1,125 num_self_attends_per_block=26,126 num_self_attention_heads=8,127 num_cross_attention_heads=8,128 qk_channels=None,129 v_channels=None,130 cross_attention_shape_for_attention="kv",131 self_attention_widening_factor=1,132 cross_attention_widening_factor=1,133 hidden_act="gelu",134 attention_probs_dropout_prob=0.1,135 initializer_range=0.02,136 layer_norm_eps=1e-12,137 use_query_residual=True,138 vocab_size=262,139 max_position_embeddings=2048,140 image_size=56,141 train_size=[368, 496],142 num_frames=16,143 audio_samples_per_frame=1920,144 samples_per_patch=16,145 output_shape=[1, 16, 224, 224],146 output_num_channels=512,147 _label_trainable_num_channels=1024,148 **kwargs,149 ):150 super().__init__(**kwargs)151 152 self.num_latents = num_latents153 self.d_latents = d_latents154 self.d_model = d_model155 self.num_blocks = num_blocks156 self.num_self_attends_per_block = num_self_attends_per_block157 self.num_self_attention_heads = num_self_attention_heads158 self.num_cross_attention_heads = num_cross_attention_heads159 self.qk_channels = qk_channels160 self.v_channels = v_channels161 self.cross_attention_shape_for_attention = cross_attention_shape_for_attention162 self.self_attention_widening_factor = self_attention_widening_factor163 self.cross_attention_widening_factor = cross_attention_widening_factor164 self.hidden_act = hidden_act165 self.attention_probs_dropout_prob = attention_probs_dropout_prob166 self.initializer_range = initializer_range167 self.layer_norm_eps = layer_norm_eps168 self.use_query_residual = use_query_residual169 # masked language modeling attributes170 self.vocab_size = vocab_size171 self.max_position_embeddings = max_position_embeddings172 # image classification attributes173 self.image_size = image_size174 # flow attributes175 self.train_size = train_size176 # multimodal autoencoding attributes177 self.num_frames = num_frames178 self.audio_samples_per_frame = audio_samples_per_frame179 self.samples_per_patch = samples_per_patch180 self.output_shape = output_shape181 self.output_num_channels = output_num_channels182 self._label_trainable_num_channels = _label_trainable_num_channels183 184 185class PerceiverOnnxConfig(OnnxConfig):186 @property187 def inputs(self) -> Mapping[str, Mapping[int, str]]:188 if self.task == "multiple-choice":189 dynamic_axis = {0: "batch", 1: "choice", 2: "sequence"}190 else:191 dynamic_axis = {0: "batch", 1: "sequence"}192 return OrderedDict(193 [194 ("inputs", dynamic_axis),195 ("attention_mask", dynamic_axis),196 ]197 )198 199 @property200 def atol_for_validation(self) -> float:201 return 1e-4202 203 def generate_dummy_inputs(204 self,205 preprocessor: Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"],206 batch_size: int = -1,207 seq_length: int = -1,208 num_choices: int = -1,209 is_pair: bool = False,210 framework: Optional[TensorType] = None,211 num_channels: int = 3,212 image_width: int = 40,213 image_height: int = 40,214 ) -> Mapping[str, Any]:215 # copied from `transformers.onnx.config.OnnxConfig` and slightly altered/simplified216 217 if isinstance(preprocessor, PreTrainedTokenizerBase):218 # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX219 batch_size = compute_effective_axis_dimension(220 batch_size, fixed_dimension=OnnxConfig.default_fixed_batch, num_token_to_add=0221 )222 # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX223 token_to_add = preprocessor.num_special_tokens_to_add(is_pair)224 seq_length = compute_effective_axis_dimension(225 seq_length, fixed_dimension=OnnxConfig.default_fixed_sequence, num_token_to_add=token_to_add226 )227 # Generate dummy inputs according to compute batch and sequence228 dummy_input = [" ".join(["a"]) * seq_length] * batch_size229 inputs = dict(preprocessor(dummy_input, return_tensors=framework))230 inputs["inputs"] = inputs.pop("input_ids")231 return inputs232 elif isinstance(preprocessor, FeatureExtractionMixin) and preprocessor.model_input_names[0] == "pixel_values":233 # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX234 batch_size = compute_effective_axis_dimension(batch_size, fixed_dimension=OnnxConfig.default_fixed_batch)235 dummy_input = self._generate_dummy_images(batch_size, num_channels, image_height, image_width)236 inputs = dict(preprocessor(images=dummy_input, return_tensors=framework))237 inputs["inputs"] = inputs.pop("pixel_values")238 return inputs239 else:240 raise ValueError(241 "Unable to generate dummy inputs for the model. Please provide a tokenizer or a preprocessor."242 )243 244 245__all__ = ["PerceiverConfig", "PerceiverOnnxConfig"]246 