configuration.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. # Copyright 2021-2022 The Alibaba DAMO NLP Team Authors.
  2. # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
  3. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
  4. # 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. """ StructBERT model configuration, mainly copied from :class:`~transformers.BertConfig` """
  18. from transformers import PretrainedConfig
  19. from modelscope.utils import logger as logging
  20. logger = logging.get_logger()
  21. class SbertConfig(PretrainedConfig):
  22. r"""
  23. This is the configuration class to store the configuration
  24. of a :class:`~modelscope.models.nlp.structbert.SbertModel`.
  25. It is used to instantiate a StructBERT model according to the specified arguments.
  26. Configuration objects inherit from :class:`~transformers.PretrainedConfig` and can be used to control the model
  27. outputs. Read the documentation from :class:`~transformers.PretrainedConfig` for more information.
  28. Args:
  29. vocab_size (:obj:`int`, `optional`, defaults to 30522):
  30. Vocabulary size of the BERT model. Defines the number of different tokens that can be represented by the
  31. :obj:`inputs_ids` passed when calling :class:`~transformers.BertModel` or
  32. :class:`~transformers.TFBertModel`.
  33. hidden_size (:obj:`int`, `optional`, defaults to 768):
  34. Dimensionality of the encoder layers and the pooler layer.
  35. num_hidden_layers (:obj:`int`, `optional`, defaults to 12):
  36. Number of hidden layers in the Transformer encoder.
  37. num_attention_heads (:obj:`int`, `optional`, defaults to 12):
  38. Number of attention heads for each attention layer in the Transformer encoder.
  39. intermediate_size (:obj:`int`, `optional`, defaults to 3072):
  40. Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
  41. hidden_act (:obj:`str` or :obj:`Callable`, `optional`, defaults to :obj:`"gelu"`):
  42. The non-linear activation function (function or string) in the encoder and pooler. If string,
  43. :obj:`"gelu"`, :obj:`"relu"`, :obj:`"silu"` and :obj:`"gelu_new"` are supported.
  44. hidden_dropout_prob (:obj:`float`, `optional`, defaults to 0.1):
  45. The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
  46. attention_probs_dropout_prob (:obj:`float`, `optional`, defaults to 0.1):
  47. The dropout ratio for the attention probabilities.
  48. max_position_embeddings (:obj:`int`, `optional`, defaults to 512):
  49. The maximum sequence length that this model might ever be used with. Typically set this to something large
  50. just in case (e.g., 512 or 1024 or 2048).
  51. type_vocab_size (:obj:`int`, `optional`, defaults to 2):
  52. The vocabulary size of the :obj:`token_type_ids` passed when calling :class:`~transformers.BertModel` or
  53. :class:`~transformers.TFBertModel`.
  54. initializer_range (:obj:`float`, `optional`, defaults to 0.02):
  55. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  56. layer_norm_eps (:obj:`float`, `optional`, defaults to 1e-12):
  57. The epsilon used by the layer normalization layers.
  58. position_embedding_type (:obj:`str`, `optional`, defaults to :obj:`"absolute"`):
  59. Type of position embedding. Choose one of :obj:`"absolute"`, :obj:`"relative_key"`,
  60. :obj:`"relative_key_query"`. For positional embeddings use :obj:`"absolute"`. For more information on
  61. :obj:`"relative_key"`, please refer to `Self-Attention with Relative Position Representations (Shaw et al.)
  62. <https://arxiv.org/abs/1803.02155>`__. For more information on :obj:`"relative_key_query"`, please refer to
  63. `Method 4` in `Improve Transformer Models with Better Relative Position Embeddings (Huang et al.)
  64. <https://arxiv.org/abs/2009.13658>`__.
  65. use_cache (:obj:`bool`, `optional`, defaults to :obj:`True`):
  66. Whether or not the model should return the last key/values attentions (not used by all models). Only
  67. relevant if ``config.is_decoder=True``.
  68. classifier_dropout (:obj:`float`, `optional`):
  69. The dropout ratio for the classification head.
  70. adv_grad_factor (:obj:`float`, `optional`): This factor will be multiplied by the KL loss grad and then
  71. the result will be added to the original embedding.
  72. More details please check:https://arxiv.org/abs/1908.04577
  73. The range of this value should between 1e-3~1e-7
  74. adv_bound (:obj:`float`, `optional`): adv_bound is used to cut the top and the bottom bound of
  75. the produced embedding.
  76. If not provided, 2 * sigma will be used as the adv_bound factor
  77. sigma (:obj:`float`, `optional`): The std factor used to produce a 0 mean normal distribution.
  78. If adv_bound not provided, 2 * sigma will be used as the adv_bound factor
  79. """
  80. model_type = 'structbert'
  81. def __init__(self,
  82. vocab_size=30522,
  83. hidden_size=768,
  84. num_hidden_layers=12,
  85. num_attention_heads=12,
  86. intermediate_size=3072,
  87. hidden_act='gelu',
  88. hidden_dropout_prob=0.1,
  89. attention_probs_dropout_prob=0.1,
  90. max_position_embeddings=512,
  91. type_vocab_size=2,
  92. initializer_range=0.02,
  93. layer_norm_eps=1e-12,
  94. pad_token_id=0,
  95. position_embedding_type='absolute',
  96. use_cache=True,
  97. classifier_dropout=None,
  98. **kwargs):
  99. super().__init__(pad_token_id=pad_token_id, **kwargs)
  100. self.vocab_size = vocab_size
  101. self.hidden_size = hidden_size
  102. self.num_hidden_layers = num_hidden_layers
  103. self.num_attention_heads = num_attention_heads
  104. self.hidden_act = hidden_act
  105. self.intermediate_size = intermediate_size
  106. self.hidden_dropout_prob = hidden_dropout_prob
  107. self.attention_probs_dropout_prob = attention_probs_dropout_prob
  108. self.max_position_embeddings = max_position_embeddings
  109. self.type_vocab_size = type_vocab_size
  110. self.initializer_range = initializer_range
  111. self.layer_norm_eps = layer_norm_eps
  112. self.position_embedding_type = position_embedding_type
  113. self.use_cache = use_cache
  114. self.classifier_dropout = classifier_dropout
  115. # adv_grad_factor, used in adv loss.
  116. # Users can check adv_utils.py for details.
  117. # if adv_grad_factor set to None, no adv loss will not applied to the model.
  118. self.adv_grad_factor = 5e-5 if 'adv_grad_factor' not in kwargs else kwargs[
  119. 'adv_grad_factor']
  120. # sigma value, used in adv loss.
  121. self.sigma = 5e-6 if 'sigma' not in kwargs else kwargs['sigma']
  122. # adv_bound value, used in adv loss.
  123. self.adv_bound = 2 * self.sigma if 'adv_bound' not in kwargs else kwargs[
  124. 'adv_bound']