configuration.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  1. # Copyright (c) Alibaba, Inc. and its affiliates.
  2. # Copyright 2018 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. """ BERT model configuration """
  17. from collections import OrderedDict
  18. from typing import Mapping
  19. from transformers.configuration_utils import PretrainedConfig
  20. from transformers.onnx import OnnxConfig
  21. from modelscope.utils.logger import get_logger
  22. logger = get_logger()
  23. class BertConfig(PretrainedConfig):
  24. r"""
  25. This is the configuration class to store the configuration of a
  26. [`BertModel`] or a [`TFBertModel`]. It is used to instantiate a BERT model
  27. according to the specified arguments, defining the model architecture.
  28. Instantiating a configuration with the defaults will yield a similar
  29. configuration to that of the BERT
  30. [bert-base-uncased](https://huggingface.co/bert-base-uncased) architecture.
  31. Configuration objects inherit from [`PretrainedConfig`] and can be used to
  32. control the model outputs. Read the documentation from [`PretrainedConfig`]
  33. for more information.
  34. Args:
  35. vocab_size (`int`, *optional*, defaults to 30522):
  36. Vocabulary size of the BERT model. Defines the number of different
  37. tokens that can be represented by the `inputs_ids` passed when
  38. calling [`BertModel`] or [`TFBertModel`].
  39. hidden_size (`int`, *optional*, defaults to 768):
  40. Dimensionality of the encoder layers and the pooler layer.
  41. num_hidden_layers (`int`, *optional*, defaults to 12):
  42. Number of hidden layers in the Transformer encoder.
  43. num_attention_heads (`int`, *optional*, defaults to 12):
  44. Number of attention heads for each attention layer in the
  45. Transformer encoder.
  46. intermediate_size (`int`, *optional*, defaults to 3072):
  47. Dimensionality of the "intermediate" (often named feed-forward)
  48. layer in the Transformer encoder.
  49. hidden_act (`str` or `Callable`, *optional*, defaults to `"gelu"`):
  50. The non-linear activation function (function or string) in the
  51. encoder and pooler. If string, `"gelu"`, `"relu"`, `"silu"` and
  52. `"gelu_new"` are supported.
  53. hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
  54. The dropout probability for all fully connected layers in the
  55. embeddings, encoder, and pooler.
  56. attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
  57. The dropout ratio for the attention probabilities.
  58. max_position_embeddings (`int`, *optional*, defaults to 512):
  59. The maximum sequence length that this model might ever be used with.
  60. Typically set this to something large just in case (e.g., 512 or
  61. 1024 or 2048).
  62. type_vocab_size (`int`, *optional*, defaults to 2):
  63. The vocabulary size of the `token_type_ids` passed when calling
  64. [`BertModel`] or [`TFBertModel`].
  65. initializer_range (`float`, *optional*, defaults to 0.02):
  66. The standard deviation of the truncated_normal_initializer for
  67. initializing all weight matrices.
  68. layer_norm_eps (`float`, *optional*, defaults to 1e-12):
  69. The epsilon used by the layer normalization layers.
  70. position_embedding_type (`str`, *optional*, defaults to `"absolute"`):
  71. Type of position embedding. Choose one of `"absolute"`,
  72. `"relative_key"`, `"relative_key_query"`. For positional embeddings
  73. use `"absolute"`. For more information on `"relative_key"`, please
  74. refer to [Self-Attention with Relative Position Representations
  75. (Shaw et al.)](https://arxiv.org/abs/1803.02155). For more
  76. information on `"relative_key_query"`, please refer to *Method 4* in
  77. [Improve Transformer Models with Better Relative Position Embeddings
  78. (Huang et al.)](https://arxiv.org/abs/2009.13658).
  79. use_cache (`bool`, *optional*, defaults to `True`):
  80. Whether or not the model should return the last key/values
  81. attentions (not used by all models). Only relevant if
  82. `config.is_decoder=True`.
  83. classifier_dropout (`float`, *optional*):
  84. The dropout ratio for the classification head.
  85. Examples:
  86. >>> from transformers import BertModel, BertConfig
  87. >>> # Initializing a BERT bert-base-uncased style configuration
  88. >>> configuration = BertConfig()
  89. >>> # Initializing a model from the bert-base-uncased style configuration
  90. >>> model = BertModel(configuration)
  91. >>> # Accessing the model configuration
  92. >>> configuration = model.config
  93. """
  94. model_type = 'bert'
  95. def __init__(self,
  96. vocab_size=30522,
  97. hidden_size=768,
  98. num_hidden_layers=12,
  99. num_attention_heads=12,
  100. intermediate_size=3072,
  101. hidden_act='gelu',
  102. hidden_dropout_prob=0.1,
  103. attention_probs_dropout_prob=0.1,
  104. max_position_embeddings=512,
  105. type_vocab_size=2,
  106. initializer_range=0.02,
  107. layer_norm_eps=1e-12,
  108. pad_token_id=0,
  109. position_embedding_type='absolute',
  110. use_cache=True,
  111. classifier_dropout=None,
  112. **kwargs):
  113. super().__init__(pad_token_id=pad_token_id, **kwargs)
  114. self.vocab_size = vocab_size
  115. self.hidden_size = hidden_size
  116. self.num_hidden_layers = num_hidden_layers
  117. self.num_attention_heads = num_attention_heads
  118. self.hidden_act = hidden_act
  119. self.intermediate_size = intermediate_size
  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.layer_norm_eps = layer_norm_eps
  126. self.position_embedding_type = position_embedding_type
  127. self.use_cache = use_cache
  128. self.classifier_dropout = classifier_dropout
  129. class BertOnnxConfig(OnnxConfig):
  130. @property
  131. def inputs(self) -> Mapping[str, Mapping[int, str]]:
  132. return OrderedDict([
  133. ('input_ids', {
  134. 0: 'batch',
  135. 1: 'sequence'
  136. }),
  137. ('attention_mask', {
  138. 0: 'batch',
  139. 1: 'sequence'
  140. }),
  141. ('token_type_ids', {
  142. 0: 'batch',
  143. 1: 'sequence'
  144. }),
  145. ])