configuration_mobilebert.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. # coding=utf-8
  2. # Copyright 2020 The HuggingFace Team. All rights reserved.
  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. """MobileBERT model configuration"""
  16. from collections import OrderedDict
  17. from typing import Mapping
  18. from ...configuration_utils import PretrainedConfig
  19. from ...onnx import OnnxConfig
  20. from ...utils import logging
  21. logger = logging.get_logger(__name__)
  22. class MobileBertConfig(PretrainedConfig):
  23. r"""
  24. This is the configuration class to store the configuration of a [`MobileBertModel`] or a [`TFMobileBertModel`]. It
  25. is used to instantiate a MobileBERT model according to the specified arguments, defining the model architecture.
  26. Instantiating a configuration with the defaults will yield a similar configuration to that of the MobileBERT
  27. [google/mobilebert-uncased](https://huggingface.co/google/mobilebert-uncased) architecture.
  28. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  29. documentation from [`PretrainedConfig`] for more information.
  30. Args:
  31. vocab_size (`int`, *optional*, defaults to 30522):
  32. Vocabulary size of the MobileBERT model. Defines the number of different tokens that can be represented by
  33. the `inputs_ids` passed when calling [`MobileBertModel`] or [`TFMobileBertModel`].
  34. hidden_size (`int`, *optional*, defaults to 512):
  35. Dimensionality of the encoder layers and the pooler layer.
  36. num_hidden_layers (`int`, *optional*, defaults to 24):
  37. Number of hidden layers in the Transformer encoder.
  38. num_attention_heads (`int`, *optional*, defaults to 4):
  39. Number of attention heads for each attention layer in the Transformer encoder.
  40. intermediate_size (`int`, *optional*, defaults to 512):
  41. Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
  42. hidden_act (`str` or `function`, *optional*, defaults to `"relu"`):
  43. The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
  44. `"relu"`, `"silu"` and `"gelu_new"` are supported.
  45. hidden_dropout_prob (`float`, *optional*, defaults to 0.0):
  46. The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
  47. attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
  48. The dropout ratio for the attention probabilities.
  49. max_position_embeddings (`int`, *optional*, defaults to 512):
  50. The maximum sequence length that this model might ever be used with. Typically set this to something large
  51. just in case (e.g., 512 or 1024 or 2048).
  52. type_vocab_size (`int`, *optional*, defaults to 2):
  53. The vocabulary size of the `token_type_ids` passed when calling [`MobileBertModel`] or
  54. [`TFMobileBertModel`].
  55. initializer_range (`float`, *optional*, defaults to 0.02):
  56. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  57. layer_norm_eps (`float`, *optional*, defaults to 1e-12):
  58. The epsilon used by the layer normalization layers.
  59. pad_token_id (`int`, *optional*, defaults to 0):
  60. The ID of the token in the word embedding to use as padding.
  61. embedding_size (`int`, *optional*, defaults to 128):
  62. The dimension of the word embedding vectors.
  63. trigram_input (`bool`, *optional*, defaults to `True`):
  64. Use a convolution of trigram as input.
  65. use_bottleneck (`bool`, *optional*, defaults to `True`):
  66. Whether to use bottleneck in BERT.
  67. intra_bottleneck_size (`int`, *optional*, defaults to 128):
  68. Size of bottleneck layer output.
  69. use_bottleneck_attention (`bool`, *optional*, defaults to `False`):
  70. Whether to use attention inputs from the bottleneck transformation.
  71. key_query_shared_bottleneck (`bool`, *optional*, defaults to `True`):
  72. Whether to use the same linear transformation for query&key in the bottleneck.
  73. num_feedforward_networks (`int`, *optional*, defaults to 4):
  74. Number of FFNs in a block.
  75. normalization_type (`str`, *optional*, defaults to `"no_norm"`):
  76. The normalization type in MobileBERT.
  77. classifier_dropout (`float`, *optional*):
  78. The dropout ratio for the classification head.
  79. Examples:
  80. ```python
  81. >>> from transformers import MobileBertConfig, MobileBertModel
  82. >>> # Initializing a MobileBERT configuration
  83. >>> configuration = MobileBertConfig()
  84. >>> # Initializing a model (with random weights) from the configuration above
  85. >>> model = MobileBertModel(configuration)
  86. >>> # Accessing the model configuration
  87. >>> configuration = model.config
  88. ```
  89. """
  90. model_type = "mobilebert"
  91. def __init__(
  92. self,
  93. vocab_size=30522,
  94. hidden_size=512,
  95. num_hidden_layers=24,
  96. num_attention_heads=4,
  97. intermediate_size=512,
  98. hidden_act="relu",
  99. hidden_dropout_prob=0.0,
  100. attention_probs_dropout_prob=0.1,
  101. max_position_embeddings=512,
  102. type_vocab_size=2,
  103. initializer_range=0.02,
  104. layer_norm_eps=1e-12,
  105. pad_token_id=0,
  106. embedding_size=128,
  107. trigram_input=True,
  108. use_bottleneck=True,
  109. intra_bottleneck_size=128,
  110. use_bottleneck_attention=False,
  111. key_query_shared_bottleneck=True,
  112. num_feedforward_networks=4,
  113. normalization_type="no_norm",
  114. classifier_activation=True,
  115. classifier_dropout=None,
  116. **kwargs,
  117. ):
  118. super().__init__(pad_token_id=pad_token_id, **kwargs)
  119. self.vocab_size = vocab_size
  120. self.hidden_size = hidden_size
  121. self.num_hidden_layers = num_hidden_layers
  122. self.num_attention_heads = num_attention_heads
  123. self.hidden_act = hidden_act
  124. self.intermediate_size = intermediate_size
  125. self.hidden_dropout_prob = hidden_dropout_prob
  126. self.attention_probs_dropout_prob = attention_probs_dropout_prob
  127. self.max_position_embeddings = max_position_embeddings
  128. self.type_vocab_size = type_vocab_size
  129. self.initializer_range = initializer_range
  130. self.layer_norm_eps = layer_norm_eps
  131. self.embedding_size = embedding_size
  132. self.trigram_input = trigram_input
  133. self.use_bottleneck = use_bottleneck
  134. self.intra_bottleneck_size = intra_bottleneck_size
  135. self.use_bottleneck_attention = use_bottleneck_attention
  136. self.key_query_shared_bottleneck = key_query_shared_bottleneck
  137. self.num_feedforward_networks = num_feedforward_networks
  138. self.normalization_type = normalization_type
  139. self.classifier_activation = classifier_activation
  140. if self.use_bottleneck:
  141. self.true_hidden_size = intra_bottleneck_size
  142. else:
  143. self.true_hidden_size = hidden_size
  144. self.classifier_dropout = classifier_dropout
  145. # Copied from transformers.models.bert.configuration_bert.BertOnnxConfig with Bert->MobileBert
  146. class MobileBertOnnxConfig(OnnxConfig):
  147. @property
  148. def inputs(self) -> Mapping[str, Mapping[int, str]]:
  149. if self.task == "multiple-choice":
  150. dynamic_axis = {0: "batch", 1: "choice", 2: "sequence"}
  151. else:
  152. dynamic_axis = {0: "batch", 1: "sequence"}
  153. return OrderedDict(
  154. [
  155. ("input_ids", dynamic_axis),
  156. ("attention_mask", dynamic_axis),
  157. ("token_type_ids", dynamic_axis),
  158. ]
  159. )