configuration_ernie.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  1. # coding=utf-8
  2. # Copyright 2022 The Google AI Language Team Authors and The HuggingFace Inc. team.
  3. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. """ERNIE model configuration"""
  17. from collections import OrderedDict
  18. from collections.abc import Mapping
  19. from ...configuration_utils import PretrainedConfig
  20. from ...onnx import OnnxConfig
  21. from ...utils import logging
  22. logger = logging.get_logger(__name__)
  23. class ErnieConfig(PretrainedConfig):
  24. r"""
  25. This is the configuration class to store the configuration of a [`ErnieModel`] or a [`TFErnieModel`]. It is used to
  26. instantiate a ERNIE model according to the specified arguments, defining the model architecture. Instantiating a
  27. configuration with the defaults will yield a similar configuration to that of the ERNIE
  28. [nghuyong/ernie-3.0-base-zh](https://huggingface.co/nghuyong/ernie-3.0-base-zh) architecture.
  29. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  30. documentation from [`PretrainedConfig`] for more information.
  31. Args:
  32. vocab_size (`int`, *optional*, defaults to 30522):
  33. Vocabulary size of the ERNIE model. Defines the number of different tokens that can be represented by the
  34. `inputs_ids` passed when calling [`ErnieModel`] or [`TFErnieModel`].
  35. hidden_size (`int`, *optional*, defaults to 768):
  36. Dimensionality of the encoder layers and the pooler layer.
  37. num_hidden_layers (`int`, *optional*, defaults to 12):
  38. Number of hidden layers in the Transformer encoder.
  39. num_attention_heads (`int`, *optional*, defaults to 12):
  40. Number of attention heads for each attention layer in the Transformer encoder.
  41. intermediate_size (`int`, *optional*, defaults to 3072):
  42. Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
  43. hidden_act (`str` or `Callable`, *optional*, defaults to `"gelu"`):
  44. The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
  45. `"relu"`, `"silu"` and `"gelu_new"` are supported.
  46. hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
  47. The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
  48. attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
  49. The dropout ratio for the attention probabilities.
  50. max_position_embeddings (`int`, *optional*, defaults to 512):
  51. The maximum sequence length that this model might ever be used with. Typically set this to something large
  52. just in case (e.g., 512 or 1024 or 2048).
  53. type_vocab_size (`int`, *optional*, defaults to 2):
  54. The vocabulary size of the `token_type_ids` passed when calling [`ErnieModel`] or [`TFErnieModel`].
  55. task_type_vocab_size (`int`, *optional*, defaults to 3):
  56. The vocabulary size of the `task_type_ids` for ERNIE2.0/ERNIE3.0 model
  57. use_task_id (`bool`, *optional*, defaults to `False`):
  58. Whether or not the model support `task_type_ids`
  59. initializer_range (`float`, *optional*, defaults to 0.02):
  60. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  61. layer_norm_eps (`float`, *optional*, defaults to 1e-12):
  62. The epsilon used by the layer normalization layers.
  63. pad_token_id (`int`, *optional*, defaults to 0):
  64. Padding token id.
  65. position_embedding_type (`str`, *optional*, defaults to `"absolute"`):
  66. Type of position embedding. Choose one of `"absolute"`, `"relative_key"`, `"relative_key_query"`. For
  67. positional embeddings use `"absolute"`. For more information on `"relative_key"`, please refer to
  68. [Self-Attention with Relative Position Representations (Shaw et al.)](https://huggingface.co/papers/1803.02155).
  69. For more information on `"relative_key_query"`, please refer to *Method 4* in [Improve Transformer Models
  70. with Better Relative Position Embeddings (Huang et al.)](https://huggingface.co/papers/2009.13658).
  71. use_cache (`bool`, *optional*, defaults to `True`):
  72. Whether or not the model should return the last key/values attentions (not used by all models). Only
  73. relevant if `config.is_decoder=True`.
  74. classifier_dropout (`float`, *optional*):
  75. The dropout ratio for the classification head.
  76. Examples:
  77. ```python
  78. >>> from transformers import ErnieConfig, ErnieModel
  79. >>> # Initializing a ERNIE nghuyong/ernie-3.0-base-zh style configuration
  80. >>> configuration = ErnieConfig()
  81. >>> # Initializing a model (with random weights) from the nghuyong/ernie-3.0-base-zh style configuration
  82. >>> model = ErnieModel(configuration)
  83. >>> # Accessing the model configuration
  84. >>> configuration = model.config
  85. ```"""
  86. model_type = "ernie"
  87. def __init__(
  88. self,
  89. vocab_size=30522,
  90. hidden_size=768,
  91. num_hidden_layers=12,
  92. num_attention_heads=12,
  93. intermediate_size=3072,
  94. hidden_act="gelu",
  95. hidden_dropout_prob=0.1,
  96. attention_probs_dropout_prob=0.1,
  97. max_position_embeddings=512,
  98. type_vocab_size=2,
  99. task_type_vocab_size=3,
  100. use_task_id=False,
  101. initializer_range=0.02,
  102. layer_norm_eps=1e-12,
  103. pad_token_id=0,
  104. position_embedding_type="absolute",
  105. use_cache=True,
  106. classifier_dropout=None,
  107. **kwargs,
  108. ):
  109. super().__init__(pad_token_id=pad_token_id, **kwargs)
  110. self.vocab_size = vocab_size
  111. self.hidden_size = hidden_size
  112. self.num_hidden_layers = num_hidden_layers
  113. self.num_attention_heads = num_attention_heads
  114. self.hidden_act = hidden_act
  115. self.intermediate_size = intermediate_size
  116. self.hidden_dropout_prob = hidden_dropout_prob
  117. self.attention_probs_dropout_prob = attention_probs_dropout_prob
  118. self.max_position_embeddings = max_position_embeddings
  119. self.type_vocab_size = type_vocab_size
  120. self.task_type_vocab_size = task_type_vocab_size
  121. self.use_task_id = use_task_id
  122. self.initializer_range = initializer_range
  123. self.layer_norm_eps = layer_norm_eps
  124. self.position_embedding_type = position_embedding_type
  125. self.use_cache = use_cache
  126. self.classifier_dropout = classifier_dropout
  127. class ErnieOnnxConfig(OnnxConfig):
  128. @property
  129. def inputs(self) -> Mapping[str, Mapping[int, str]]:
  130. if self.task == "multiple-choice":
  131. dynamic_axis = {0: "batch", 1: "choice", 2: "sequence"}
  132. else:
  133. dynamic_axis = {0: "batch", 1: "sequence"}
  134. return OrderedDict(
  135. [
  136. ("input_ids", dynamic_axis),
  137. ("attention_mask", dynamic_axis),
  138. ("token_type_ids", dynamic_axis),
  139. ("task_type_ids", dynamic_axis),
  140. ]
  141. )
  142. __all__ = ["ErnieConfig", "ErnieOnnxConfig"]