configuration_imagegpt.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. # coding=utf-8
  2. # Copyright 2021 The HuggingFace Inc. team.
  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. """OpenAI ImageGPT configuration"""
  16. from collections import OrderedDict
  17. from collections.abc import Mapping
  18. from typing import TYPE_CHECKING, Any, Optional
  19. from ...configuration_utils import PretrainedConfig
  20. from ...onnx import OnnxConfig
  21. from ...utils import logging
  22. if TYPE_CHECKING:
  23. from ... import FeatureExtractionMixin, TensorType
  24. logger = logging.get_logger(__name__)
  25. class ImageGPTConfig(PretrainedConfig):
  26. """
  27. This is the configuration class to store the configuration of a [`ImageGPTModel`] or a [`TFImageGPTModel`]. It is
  28. used to instantiate a GPT-2 model according to the specified arguments, defining the model architecture.
  29. Instantiating a configuration with the defaults will yield a similar configuration to that of the ImageGPT
  30. [openai/imagegpt-small](https://huggingface.co/openai/imagegpt-small) architecture.
  31. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  32. documentation from [`PretrainedConfig`] for more information.
  33. Args:
  34. vocab_size (`int`, *optional*, defaults to 512):
  35. Vocabulary size of the GPT-2 model. Defines the number of different tokens that can be represented by the
  36. `inputs_ids` passed when calling [`ImageGPTModel`] or [`TFImageGPTModel`].
  37. n_positions (`int`, *optional*, defaults to 32*32):
  38. The maximum sequence length that this model might ever be used with. Typically set this to something large
  39. just in case (e.g., 512 or 1024 or 2048).
  40. n_embd (`int`, *optional*, defaults to 512):
  41. Dimensionality of the embeddings and hidden states.
  42. n_layer (`int`, *optional*, defaults to 24):
  43. Number of hidden layers in the Transformer encoder.
  44. n_head (`int`, *optional*, defaults to 8):
  45. Number of attention heads for each attention layer in the Transformer encoder.
  46. n_inner (`int`, *optional*, defaults to None):
  47. Dimensionality of the inner feed-forward layers. `None` will set it to 4 times n_embd
  48. activation_function (`str`, *optional*, defaults to `"quick_gelu"`):
  49. Activation function (can be one of the activation functions defined in src/transformers/activations.py).
  50. Defaults to "quick_gelu".
  51. resid_pdrop (`float`, *optional*, defaults to 0.1):
  52. The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
  53. embd_pdrop (`int`, *optional*, defaults to 0.1):
  54. The dropout ratio for the embeddings.
  55. attn_pdrop (`float`, *optional*, defaults to 0.1):
  56. The dropout ratio for the attention.
  57. layer_norm_epsilon (`float`, *optional*, defaults to 1e-5):
  58. The epsilon to use in the layer normalization layers.
  59. initializer_range (`float`, *optional*, defaults to 0.02):
  60. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  61. scale_attn_weights (`bool`, *optional*, defaults to `True`):
  62. Scale attention weights by dividing by sqrt(hidden_size)..
  63. use_cache (`bool`, *optional*, defaults to `True`):
  64. Whether or not the model should return the last key/values attentions (not used by all models).
  65. scale_attn_by_inverse_layer_idx (`bool`, *optional*, defaults to `False`):
  66. Whether to additionally scale attention weights by `1 / layer_idx + 1`.
  67. reorder_and_upcast_attn (`bool`, *optional*, defaults to `False`):
  68. Whether to scale keys (K) prior to computing attention (dot-product) and upcast attention
  69. dot-product/softmax to float() when training with mixed precision.
  70. Example:
  71. ```python
  72. >>> from transformers import ImageGPTConfig, ImageGPTModel
  73. >>> # Initializing a ImageGPT configuration
  74. >>> configuration = ImageGPTConfig()
  75. >>> # Initializing a model (with random weights) from the configuration
  76. >>> model = ImageGPTModel(configuration)
  77. >>> # Accessing the model configuration
  78. >>> configuration = model.config
  79. ```"""
  80. model_type = "imagegpt"
  81. keys_to_ignore_at_inference = ["past_key_values"]
  82. attribute_map = {
  83. "hidden_size": "n_embd",
  84. "max_position_embeddings": "n_positions",
  85. "num_attention_heads": "n_head",
  86. "num_hidden_layers": "n_layer",
  87. }
  88. def __init__(
  89. self,
  90. vocab_size=512 + 1, # add one for start of sentence (sos) token
  91. n_positions=32 * 32,
  92. n_embd=512,
  93. n_layer=24,
  94. n_head=8,
  95. n_inner=None,
  96. activation_function="quick_gelu",
  97. resid_pdrop=0.1,
  98. embd_pdrop=0.1,
  99. attn_pdrop=0.1,
  100. layer_norm_epsilon=1e-5,
  101. initializer_range=0.02,
  102. scale_attn_weights=True,
  103. use_cache=True,
  104. tie_word_embeddings=False,
  105. scale_attn_by_inverse_layer_idx=False,
  106. reorder_and_upcast_attn=False,
  107. **kwargs,
  108. ):
  109. self.vocab_size = vocab_size
  110. self.n_positions = n_positions
  111. self.n_embd = n_embd
  112. self.n_layer = n_layer
  113. self.n_head = n_head
  114. self.n_inner = n_inner
  115. self.activation_function = activation_function
  116. self.resid_pdrop = resid_pdrop
  117. self.embd_pdrop = embd_pdrop
  118. self.attn_pdrop = attn_pdrop
  119. self.layer_norm_epsilon = layer_norm_epsilon
  120. self.initializer_range = initializer_range
  121. self.scale_attn_weights = scale_attn_weights
  122. self.use_cache = use_cache
  123. self.scale_attn_by_inverse_layer_idx = scale_attn_by_inverse_layer_idx
  124. self.reorder_and_upcast_attn = reorder_and_upcast_attn
  125. self.tie_word_embeddings = tie_word_embeddings
  126. super().__init__(tie_word_embeddings=tie_word_embeddings, **kwargs)
  127. class ImageGPTOnnxConfig(OnnxConfig):
  128. @property
  129. def inputs(self) -> Mapping[str, Mapping[int, str]]:
  130. return OrderedDict(
  131. [
  132. ("input_ids", {0: "batch", 1: "sequence"}),
  133. ]
  134. )
  135. def generate_dummy_inputs(
  136. self,
  137. preprocessor: "FeatureExtractionMixin",
  138. batch_size: int = 1,
  139. seq_length: int = -1,
  140. is_pair: bool = False,
  141. framework: Optional["TensorType"] = None,
  142. num_channels: int = 3,
  143. image_width: int = 32,
  144. image_height: int = 32,
  145. ) -> Mapping[str, Any]:
  146. """
  147. Generate inputs to provide to the ONNX exporter for the specific framework
  148. Args:
  149. preprocessor ([`PreTrainedTokenizerBase`] or [`FeatureExtractionMixin`]):
  150. The preprocessor associated with this model configuration.
  151. batch_size (`int`, *optional*, defaults to -1):
  152. The batch size to export the model for (-1 means dynamic axis).
  153. num_choices (`int`, *optional*, defaults to -1):
  154. The number of candidate answers provided for multiple choice task (-1 means dynamic axis).
  155. seq_length (`int`, *optional*, defaults to -1):
  156. The sequence length to export the model for (-1 means dynamic axis).
  157. is_pair (`bool`, *optional*, defaults to `False`):
  158. Indicate if the input is a pair (sentence 1, sentence 2)
  159. framework (`TensorType`, *optional*, defaults to `None`):
  160. The framework (PyTorch or TensorFlow) that the tokenizer will generate tensors for.
  161. num_channels (`int`, *optional*, defaults to 3):
  162. The number of channels of the generated images.
  163. image_width (`int`, *optional*, defaults to 40):
  164. The width of the generated images.
  165. image_height (`int`, *optional*, defaults to 40):
  166. The height of the generated images.
  167. Returns:
  168. Mapping[str, Tensor] holding the kwargs to provide to the model's forward function
  169. """
  170. input_image = self._generate_dummy_images(batch_size, num_channels, image_height, image_width)
  171. inputs = dict(preprocessor(images=input_image, return_tensors=framework))
  172. return inputs
  173. __all__ = ["ImageGPTConfig", "ImageGPTOnnxConfig"]