configuration_ibert.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. # coding=utf-8
  2. # Copyright 2021 The I-BERT Authors (Sehoon Kim, Amir Gholami, Zhewei Yao,
  3. # Michael Mahoney, Kurt Keutzer - UC Berkeley) and The HuggingFace Inc. team.
  4. # Copyright (c) 20121, NVIDIA CORPORATION. All rights reserved.
  5. #
  6. # Licensed under the Apache License, Version 2.0 (the "License");
  7. # you may not use this file except in compliance with the License.
  8. # You may obtain a copy of the License at
  9. #
  10. # http://www.apache.org/licenses/LICENSE-2.0
  11. #
  12. # Unless required by applicable law or agreed to in writing, software
  13. # distributed under the License is distributed on an "AS IS" BASIS,
  14. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. # See the License for the specific language governing permissions and
  16. # limitations under the License.
  17. """I-BERT configuration"""
  18. from collections import OrderedDict
  19. from collections.abc import Mapping
  20. from ...configuration_utils import PretrainedConfig
  21. from ...onnx import OnnxConfig
  22. from ...utils import logging
  23. logger = logging.get_logger(__name__)
  24. class IBertConfig(PretrainedConfig):
  25. """
  26. This is the configuration class to store the configuration of a [`IBertModel`]. It is used to instantiate a I-BERT
  27. model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
  28. defaults will yield a similar configuration to that of the IBERT
  29. [kssteven/ibert-roberta-base](https://huggingface.co/kssteven/ibert-roberta-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. Args:
  33. vocab_size (`int`, *optional*, defaults to 30522):
  34. Vocabulary size of the I-BERT model. Defines the number of different tokens that can be represented by the
  35. `inputs_ids` passed when calling [`IBertModel`]
  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"` and `"gelu_new"` are supported.
  47. hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
  48. The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
  49. attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
  50. The dropout ratio for the attention probabilities.
  51. max_position_embeddings (`int`, *optional*, defaults to 512):
  52. The maximum sequence length that this model might ever be used with. Typically set this to something large
  53. just in case (e.g., 512 or 1024 or 2048).
  54. type_vocab_size (`int`, *optional*, defaults to 2):
  55. The vocabulary size of the `token_type_ids` passed when calling [`IBertModel`]
  56. initializer_range (`float`, *optional*, defaults to 0.02):
  57. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  58. layer_norm_eps (`float`, *optional*, defaults to 1e-12):
  59. The epsilon used by the layer normalization layers.
  60. position_embedding_type (`str`, *optional*, defaults to `"absolute"`):
  61. Type of position embedding. Choose one of `"absolute"`, `"relative_key"`, `"relative_key_query"`. For
  62. positional embeddings use `"absolute"`. For more information on `"relative_key"`, please refer to
  63. [Self-Attention with Relative Position Representations (Shaw et al.)](https://huggingface.co/papers/1803.02155).
  64. For more information on `"relative_key_query"`, please refer to *Method 4* in [Improve Transformer Models
  65. with Better Relative Position Embeddings (Huang et al.)](https://huggingface.co/papers/2009.13658).
  66. quant_mode (`bool`, *optional*, defaults to `False`):
  67. Whether to quantize the model or not.
  68. force_dequant (`str`, *optional*, defaults to `"none"`):
  69. Force dequantize specific nonlinear layer. Dequantized layers are then executed with full precision.
  70. `"none"`, `"gelu"`, `"softmax"`, `"layernorm"` and `"nonlinear"` are supported. As default, it is set as
  71. `"none"`, which does not dequantize any layers. Please specify `"gelu"`, `"softmax"`, or `"layernorm"` to
  72. dequantize GELU, Softmax, or LayerNorm, respectively. `"nonlinear"` will dequantize all nonlinear layers,
  73. i.e., GELU, Softmax, and LayerNorm.
  74. """
  75. model_type = "ibert"
  76. def __init__(
  77. self,
  78. vocab_size=30522,
  79. hidden_size=768,
  80. num_hidden_layers=12,
  81. num_attention_heads=12,
  82. intermediate_size=3072,
  83. hidden_act="gelu",
  84. hidden_dropout_prob=0.1,
  85. attention_probs_dropout_prob=0.1,
  86. max_position_embeddings=512,
  87. type_vocab_size=2,
  88. initializer_range=0.02,
  89. layer_norm_eps=1e-12,
  90. pad_token_id=1,
  91. bos_token_id=0,
  92. eos_token_id=2,
  93. position_embedding_type="absolute",
  94. quant_mode=False,
  95. force_dequant="none",
  96. **kwargs,
  97. ):
  98. super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
  99. self.vocab_size = vocab_size
  100. self.hidden_size = hidden_size
  101. self.num_hidden_layers = num_hidden_layers
  102. self.num_attention_heads = num_attention_heads
  103. self.hidden_act = hidden_act
  104. self.intermediate_size = intermediate_size
  105. self.hidden_dropout_prob = hidden_dropout_prob
  106. self.attention_probs_dropout_prob = attention_probs_dropout_prob
  107. self.max_position_embeddings = max_position_embeddings
  108. self.type_vocab_size = type_vocab_size
  109. self.initializer_range = initializer_range
  110. self.layer_norm_eps = layer_norm_eps
  111. self.position_embedding_type = position_embedding_type
  112. self.quant_mode = quant_mode
  113. self.force_dequant = force_dequant
  114. class IBertOnnxConfig(OnnxConfig):
  115. @property
  116. def inputs(self) -> Mapping[str, Mapping[int, str]]:
  117. if self.task == "multiple-choice":
  118. dynamic_axis = {0: "batch", 1: "choice", 2: "sequence"}
  119. else:
  120. dynamic_axis = {0: "batch", 1: "sequence"}
  121. return OrderedDict(
  122. [
  123. ("input_ids", dynamic_axis),
  124. ("attention_mask", dynamic_axis),
  125. ]
  126. )
  127. __all__ = ["IBertConfig", "IBertOnnxConfig"]