configuration_perceiver.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. # coding=utf-8
  2. # 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 at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # 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 and
  14. # limitations under the License.
  15. """Perceiver model configuration"""
  16. from collections import OrderedDict
  17. from collections.abc import Mapping
  18. from typing import Any, Optional, Union
  19. from ...configuration_utils import PretrainedConfig
  20. from ...feature_extraction_utils import FeatureExtractionMixin
  21. from ...onnx import OnnxConfig
  22. from ...onnx.utils import compute_effective_axis_dimension
  23. from ...tokenization_utils_base import PreTrainedTokenizerBase
  24. from ...utils import TensorType, logging
  25. logger = logging.get_logger(__name__)
  26. class PerceiverConfig(PretrainedConfig):
  27. r"""
  28. This is the configuration class to store the configuration of a [`PerceiverModel`]. It is used to instantiate an
  29. Perceiver model according to the specified arguments, defining the model architecture. Instantiating a
  30. configuration with the defaults will yield a similar configuration to that of the Perceiver
  31. [deepmind/language-perceiver](https://huggingface.co/deepmind/language-perceiver) architecture.
  32. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  33. documentation from [`PretrainedConfig`] for more information.
  34. Args:
  35. num_latents (`int`, *optional*, defaults to 256):
  36. The number of latents.
  37. d_latents (`int`, *optional*, defaults to 1280):
  38. Dimension of the latent embeddings.
  39. d_model (`int`, *optional*, defaults to 768):
  40. Dimension of the inputs. Should only be provided in case [*PerceiverTextPreprocessor*] is used or no
  41. preprocessor is provided.
  42. num_blocks (`int`, *optional*, defaults to 1):
  43. Number of blocks in the Transformer encoder.
  44. num_self_attends_per_block (`int`, *optional*, defaults to 26):
  45. The number of self-attention layers per block.
  46. num_self_attention_heads (`int`, *optional*, defaults to 8):
  47. Number of attention heads for each self-attention layer in the Transformer encoder.
  48. num_cross_attention_heads (`int`, *optional*, defaults to 8):
  49. Number of attention heads for each cross-attention layer in the Transformer encoder.
  50. qk_channels (`int`, *optional*):
  51. Dimension to project the queries + keys before applying attention in the cross-attention and self-attention
  52. layers of the encoder. Will default to preserving the dimension of the queries if not specified.
  53. v_channels (`int`, *optional*):
  54. Dimension to project the values before applying attention in the cross-attention and self-attention layers
  55. of the encoder. Will default to preserving the dimension of the queries if not specified.
  56. cross_attention_shape_for_attention (`str`, *optional*, defaults to `"kv"`):
  57. Dimension to use when downsampling the queries and keys in the cross-attention layer of the encoder.
  58. self_attention_widening_factor (`int`, *optional*, defaults to 1):
  59. Dimension of the feed-forward layer in the cross-attention layer of the Transformer encoder.
  60. cross_attention_widening_factor (`int`, *optional*, defaults to 1):
  61. Dimension of the feed-forward layer in the self-attention layers of the Transformer encoder.
  62. hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
  63. The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
  64. `"relu"`, `"selu"` and `"gelu_new"` are supported.
  65. attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
  66. The dropout ratio for the attention probabilities.
  67. initializer_range (`float`, *optional*, defaults to 0.02):
  68. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  69. layer_norm_eps (`float`, *optional*, defaults to 1e-12):
  70. The epsilon used by the layer normalization layers.
  71. use_query_residual (`float`, *optional*, defaults to `True`):
  72. Whether to add a query residual in the cross-attention layer of the encoder.
  73. vocab_size (`int`, *optional*, defaults to 262):
  74. Vocabulary size for the masked language modeling model.
  75. max_position_embeddings (`int`, *optional*, defaults to 2048):
  76. The maximum sequence length that the masked language modeling model might ever be used with. Typically set
  77. this to something large just in case (e.g., 512 or 1024 or 2048).
  78. image_size (`int`, *optional*, defaults to 56):
  79. Size of the images after preprocessing, for [`PerceiverForImageClassificationLearned`].
  80. train_size (`list[int]`, *optional*, defaults to `[368, 496]`):
  81. Training size of the images for the optical flow model.
  82. num_frames (`int`, *optional*, defaults to 16):
  83. Number of video frames used for the multimodal autoencoding model.
  84. audio_samples_per_frame (`int`, *optional*, defaults to 1920):
  85. Number of audio samples per frame for the multimodal autoencoding model.
  86. samples_per_patch (`int`, *optional*, defaults to 16):
  87. Number of audio samples per patch when preprocessing the audio for the multimodal autoencoding model.
  88. output_shape (`list[int]`, *optional*, defaults to `[1, 16, 224, 224]`):
  89. Shape of the output (batch_size, num_frames, height, width) for the video decoder queries of the multimodal
  90. autoencoding model. This excludes the channel dimension.
  91. output_num_channels (`int`, *optional*, defaults to 512):
  92. Number of output channels for each modalitiy decoder.
  93. Example:
  94. ```python
  95. >>> from transformers import PerceiverModel, PerceiverConfig
  96. >>> # Initializing a Perceiver deepmind/language-perceiver style configuration
  97. >>> configuration = PerceiverConfig()
  98. >>> # Initializing a model from the deepmind/language-perceiver style configuration
  99. >>> model = PerceiverModel(configuration)
  100. >>> # Accessing the model configuration
  101. >>> configuration = model.config
  102. ```"""
  103. model_type = "perceiver"
  104. def __init__(
  105. self,
  106. num_latents=256,
  107. d_latents=1280,
  108. d_model=768,
  109. num_blocks=1,
  110. num_self_attends_per_block=26,
  111. num_self_attention_heads=8,
  112. num_cross_attention_heads=8,
  113. qk_channels=None,
  114. v_channels=None,
  115. cross_attention_shape_for_attention="kv",
  116. self_attention_widening_factor=1,
  117. cross_attention_widening_factor=1,
  118. hidden_act="gelu",
  119. attention_probs_dropout_prob=0.1,
  120. initializer_range=0.02,
  121. layer_norm_eps=1e-12,
  122. use_query_residual=True,
  123. vocab_size=262,
  124. max_position_embeddings=2048,
  125. image_size=56,
  126. train_size=[368, 496],
  127. num_frames=16,
  128. audio_samples_per_frame=1920,
  129. samples_per_patch=16,
  130. output_shape=[1, 16, 224, 224],
  131. output_num_channels=512,
  132. _label_trainable_num_channels=1024,
  133. **kwargs,
  134. ):
  135. super().__init__(**kwargs)
  136. self.num_latents = num_latents
  137. self.d_latents = d_latents
  138. self.d_model = d_model
  139. self.num_blocks = num_blocks
  140. self.num_self_attends_per_block = num_self_attends_per_block
  141. self.num_self_attention_heads = num_self_attention_heads
  142. self.num_cross_attention_heads = num_cross_attention_heads
  143. self.qk_channels = qk_channels
  144. self.v_channels = v_channels
  145. self.cross_attention_shape_for_attention = cross_attention_shape_for_attention
  146. self.self_attention_widening_factor = self_attention_widening_factor
  147. self.cross_attention_widening_factor = cross_attention_widening_factor
  148. self.hidden_act = hidden_act
  149. self.attention_probs_dropout_prob = attention_probs_dropout_prob
  150. self.initializer_range = initializer_range
  151. self.layer_norm_eps = layer_norm_eps
  152. self.use_query_residual = use_query_residual
  153. # masked language modeling attributes
  154. self.vocab_size = vocab_size
  155. self.max_position_embeddings = max_position_embeddings
  156. # image classification attributes
  157. self.image_size = image_size
  158. # flow attributes
  159. self.train_size = train_size
  160. # multimodal autoencoding attributes
  161. self.num_frames = num_frames
  162. self.audio_samples_per_frame = audio_samples_per_frame
  163. self.samples_per_patch = samples_per_patch
  164. self.output_shape = output_shape
  165. self.output_num_channels = output_num_channels
  166. self._label_trainable_num_channels = _label_trainable_num_channels
  167. class PerceiverOnnxConfig(OnnxConfig):
  168. @property
  169. def inputs(self) -> Mapping[str, Mapping[int, str]]:
  170. if self.task == "multiple-choice":
  171. dynamic_axis = {0: "batch", 1: "choice", 2: "sequence"}
  172. else:
  173. dynamic_axis = {0: "batch", 1: "sequence"}
  174. return OrderedDict(
  175. [
  176. ("inputs", dynamic_axis),
  177. ("attention_mask", dynamic_axis),
  178. ]
  179. )
  180. @property
  181. def atol_for_validation(self) -> float:
  182. return 1e-4
  183. def generate_dummy_inputs(
  184. self,
  185. preprocessor: Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"],
  186. batch_size: int = -1,
  187. seq_length: int = -1,
  188. num_choices: int = -1,
  189. is_pair: bool = False,
  190. framework: Optional[TensorType] = None,
  191. num_channels: int = 3,
  192. image_width: int = 40,
  193. image_height: int = 40,
  194. ) -> Mapping[str, Any]:
  195. # copied from `transformers.onnx.config.OnnxConfig` and slightly altered/simplified
  196. if isinstance(preprocessor, PreTrainedTokenizerBase):
  197. # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
  198. batch_size = compute_effective_axis_dimension(
  199. batch_size, fixed_dimension=OnnxConfig.default_fixed_batch, num_token_to_add=0
  200. )
  201. # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX
  202. token_to_add = preprocessor.num_special_tokens_to_add(is_pair)
  203. seq_length = compute_effective_axis_dimension(
  204. seq_length, fixed_dimension=OnnxConfig.default_fixed_sequence, num_token_to_add=token_to_add
  205. )
  206. # Generate dummy inputs according to compute batch and sequence
  207. dummy_input = [" ".join(["a"]) * seq_length] * batch_size
  208. inputs = dict(preprocessor(dummy_input, return_tensors=framework))
  209. inputs["inputs"] = inputs.pop("input_ids")
  210. return inputs
  211. elif isinstance(preprocessor, FeatureExtractionMixin) and preprocessor.model_input_names[0] == "pixel_values":
  212. # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
  213. batch_size = compute_effective_axis_dimension(batch_size, fixed_dimension=OnnxConfig.default_fixed_batch)
  214. dummy_input = self._generate_dummy_images(batch_size, num_channels, image_height, image_width)
  215. inputs = dict(preprocessor(images=dummy_input, return_tensors=framework))
  216. inputs["inputs"] = inputs.pop("pixel_values")
  217. return inputs
  218. else:
  219. raise ValueError(
  220. "Unable to generate dummy inputs for the model. Please provide a tokenizer or a preprocessor."
  221. )
  222. __all__ = ["PerceiverConfig", "PerceiverOnnxConfig"]