configuration_deberta.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. # coding=utf-8
  2. # Copyright 2020, Microsoft and 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. """DeBERTa model configuration"""
  16. from collections import OrderedDict
  17. from collections.abc import Mapping
  18. from typing import TYPE_CHECKING, Any, Optional, Union
  19. from ...configuration_utils import PretrainedConfig
  20. from ...onnx import OnnxConfig
  21. from ...utils import logging
  22. if TYPE_CHECKING:
  23. from ... import FeatureExtractionMixin, PreTrainedTokenizerBase, TensorType
  24. logger = logging.get_logger(__name__)
  25. class DebertaConfig(PretrainedConfig):
  26. r"""
  27. This is the configuration class to store the configuration of a [`DebertaModel`] or a [`TFDebertaModel`]. It is
  28. used to instantiate a DeBERTa 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 DeBERTa
  30. [microsoft/deberta-base](https://huggingface.co/microsoft/deberta-base) 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. Arguments:
  34. vocab_size (`int`, *optional*, defaults to 50265):
  35. Vocabulary size of the DeBERTa model. Defines the number of different tokens that can be represented by the
  36. `inputs_ids` passed when calling [`DebertaModel`] or [`TFDebertaModel`].
  37. hidden_size (`int`, *optional*, defaults to 768):
  38. Dimensionality of the encoder layers and the pooler layer.
  39. num_hidden_layers (`int`, *optional*, defaults to 12):
  40. Number of hidden layers in the Transformer encoder.
  41. num_attention_heads (`int`, *optional*, defaults to 12):
  42. Number of attention heads for each attention layer in the Transformer encoder.
  43. intermediate_size (`int`, *optional*, defaults to 3072):
  44. Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
  45. hidden_act (`str` or `Callable`, *optional*, defaults to `"gelu"`):
  46. The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
  47. `"relu"`, `"silu"`, `"gelu"`, `"tanh"`, `"gelu_fast"`, `"mish"`, `"linear"`, `"sigmoid"` and `"gelu_new"`
  48. are supported.
  49. hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
  50. The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
  51. attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
  52. The dropout ratio for the attention probabilities.
  53. max_position_embeddings (`int`, *optional*, defaults to 512):
  54. The maximum sequence length that this model might ever be used with. Typically set this to something large
  55. just in case (e.g., 512 or 1024 or 2048).
  56. type_vocab_size (`int`, *optional*, defaults to 0):
  57. The vocabulary size of the `token_type_ids` passed when calling [`DebertaModel`] or [`TFDebertaModel`].
  58. initializer_range (`float`, *optional*, defaults to 0.02):
  59. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  60. layer_norm_eps (`float`, *optional*, defaults to 1e-12):
  61. The epsilon used by the layer normalization layers.
  62. relative_attention (`bool`, *optional*, defaults to `False`):
  63. Whether use relative position encoding.
  64. max_relative_positions (`int`, *optional*, defaults to 1):
  65. The range of relative positions `[-max_position_embeddings, max_position_embeddings]`. Use the same value
  66. as `max_position_embeddings`.
  67. pad_token_id (`int`, *optional*, defaults to 0):
  68. The value used to pad input_ids.
  69. position_biased_input (`bool`, *optional*, defaults to `True`):
  70. Whether add absolute position embedding to content embedding.
  71. pos_att_type (`list[str]`, *optional*):
  72. The type of relative position attention, it can be a combination of `["p2c", "c2p"]`, e.g. `["p2c"]`,
  73. `["p2c", "c2p"]`.
  74. layer_norm_eps (`float`, *optional*, defaults to 1e-12):
  75. The epsilon used by the layer normalization layers.
  76. legacy (`bool`, *optional*, defaults to `True`):
  77. Whether or not the model should use the legacy `LegacyDebertaOnlyMLMHead`, which does not work properly
  78. for mask infilling tasks.
  79. Example:
  80. ```python
  81. >>> from transformers import DebertaConfig, DebertaModel
  82. >>> # Initializing a DeBERTa microsoft/deberta-base style configuration
  83. >>> configuration = DebertaConfig()
  84. >>> # Initializing a model (with random weights) from the microsoft/deberta-base style configuration
  85. >>> model = DebertaModel(configuration)
  86. >>> # Accessing the model configuration
  87. >>> configuration = model.config
  88. ```"""
  89. model_type = "deberta"
  90. def __init__(
  91. self,
  92. vocab_size=50265,
  93. hidden_size=768,
  94. num_hidden_layers=12,
  95. num_attention_heads=12,
  96. intermediate_size=3072,
  97. hidden_act="gelu",
  98. hidden_dropout_prob=0.1,
  99. attention_probs_dropout_prob=0.1,
  100. max_position_embeddings=512,
  101. type_vocab_size=0,
  102. initializer_range=0.02,
  103. layer_norm_eps=1e-7,
  104. relative_attention=False,
  105. max_relative_positions=-1,
  106. pad_token_id=0,
  107. position_biased_input=True,
  108. pos_att_type=None,
  109. pooler_dropout=0,
  110. pooler_hidden_act="gelu",
  111. legacy=True,
  112. **kwargs,
  113. ):
  114. super().__init__(**kwargs)
  115. self.hidden_size = hidden_size
  116. self.num_hidden_layers = num_hidden_layers
  117. self.num_attention_heads = num_attention_heads
  118. self.intermediate_size = intermediate_size
  119. self.hidden_act = hidden_act
  120. self.hidden_dropout_prob = hidden_dropout_prob
  121. self.attention_probs_dropout_prob = attention_probs_dropout_prob
  122. self.max_position_embeddings = max_position_embeddings
  123. self.type_vocab_size = type_vocab_size
  124. self.initializer_range = initializer_range
  125. self.relative_attention = relative_attention
  126. self.max_relative_positions = max_relative_positions
  127. self.pad_token_id = pad_token_id
  128. self.position_biased_input = position_biased_input
  129. # Backwards compatibility
  130. if isinstance(pos_att_type, str):
  131. pos_att_type = [x.strip() for x in pos_att_type.lower().split("|")]
  132. self.pos_att_type = pos_att_type
  133. self.vocab_size = vocab_size
  134. self.layer_norm_eps = layer_norm_eps
  135. self.pooler_hidden_size = kwargs.get("pooler_hidden_size", hidden_size)
  136. self.pooler_dropout = pooler_dropout
  137. self.pooler_hidden_act = pooler_hidden_act
  138. self.legacy = legacy
  139. # Copied from transformers.models.deberta_v2.configuration_deberta_v2.DebertaV2OnnxConfig
  140. class DebertaOnnxConfig(OnnxConfig):
  141. @property
  142. def inputs(self) -> Mapping[str, Mapping[int, str]]:
  143. if self.task == "multiple-choice":
  144. dynamic_axis = {0: "batch", 1: "choice", 2: "sequence"}
  145. else:
  146. dynamic_axis = {0: "batch", 1: "sequence"}
  147. if self._config.type_vocab_size > 0:
  148. return OrderedDict(
  149. [("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ("token_type_ids", dynamic_axis)]
  150. )
  151. else:
  152. return OrderedDict([("input_ids", dynamic_axis), ("attention_mask", dynamic_axis)])
  153. @property
  154. def default_onnx_opset(self) -> int:
  155. return 12
  156. def generate_dummy_inputs(
  157. self,
  158. preprocessor: Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"],
  159. batch_size: int = -1,
  160. seq_length: int = -1,
  161. num_choices: int = -1,
  162. is_pair: bool = False,
  163. framework: Optional["TensorType"] = None,
  164. num_channels: int = 3,
  165. image_width: int = 40,
  166. image_height: int = 40,
  167. tokenizer: "PreTrainedTokenizerBase" = None,
  168. ) -> Mapping[str, Any]:
  169. dummy_inputs = super().generate_dummy_inputs(preprocessor=preprocessor, framework=framework)
  170. if self._config.type_vocab_size == 0 and "token_type_ids" in dummy_inputs:
  171. del dummy_inputs["token_type_ids"]
  172. return dummy_inputs
  173. __all__ = ["DebertaConfig", "DebertaOnnxConfig"]