configuration_deberta.py 8.5 KB

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