configuration_flaubert.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. # coding=utf-8
  2. # Copyright 2019-present CNRS, Facebook Inc. and the HuggingFace Inc. team.
  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. """Flaubert configuration"""
  16. from collections import OrderedDict
  17. from collections.abc 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 FlaubertConfig(PretrainedConfig):
  23. """
  24. This is the configuration class to store the configuration of a [`FlaubertModel`] or a [`TFFlaubertModel`]. It is
  25. used to instantiate a FlauBERT 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 FlauBERT
  27. [flaubert/flaubert_base_uncased](https://huggingface.co/flaubert/flaubert_base_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. pre_norm (`bool`, *optional*, defaults to `False`):
  32. Whether to apply the layer normalization before or after the feed forward layer following the attention in
  33. each layer (Vaswani et al., Tensor2Tensor for Neural Machine Translation. 2018)
  34. layerdrop (`float`, *optional*, defaults to 0.0):
  35. Probability to drop layers during training (Fan et al., Reducing Transformer Depth on Demand with
  36. Structured Dropout. ICLR 2020)
  37. vocab_size (`int`, *optional*, defaults to 30145):
  38. Vocabulary size of the FlauBERT model. Defines the number of different tokens that can be represented by
  39. the `inputs_ids` passed when calling [`FlaubertModel`] or [`TFFlaubertModel`].
  40. emb_dim (`int`, *optional*, defaults to 2048):
  41. Dimensionality of the encoder layers and the pooler layer.
  42. n_layer (`int`, *optional*, defaults to 12):
  43. Number of hidden layers in the Transformer encoder.
  44. n_head (`int`, *optional*, defaults to 16):
  45. Number of attention heads for each attention layer in the Transformer encoder.
  46. dropout (`float`, *optional*, defaults to 0.1):
  47. The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
  48. attention_dropout (`float`, *optional*, defaults to 0.1):
  49. The dropout probability for the attention mechanism
  50. gelu_activation (`bool`, *optional*, defaults to `True`):
  51. Whether or not to use a *gelu* activation instead of *relu*.
  52. sinusoidal_embeddings (`bool`, *optional*, defaults to `False`):
  53. Whether or not to use sinusoidal positional embeddings instead of absolute positional embeddings.
  54. causal (`bool`, *optional*, defaults to `False`):
  55. Whether or not the model should behave in a causal manner. Causal models use a triangular attention mask in
  56. order to only attend to the left-side context instead if a bidirectional context.
  57. asm (`bool`, *optional*, defaults to `False`):
  58. Whether or not to use an adaptive log softmax projection layer instead of a linear layer for the prediction
  59. layer.
  60. n_langs (`int`, *optional*, defaults to 1):
  61. The number of languages the model handles. Set to 1 for monolingual models.
  62. use_lang_emb (`bool`, *optional*, defaults to `True`)
  63. Whether to use language embeddings. Some models use additional language embeddings, see [the multilingual
  64. models page](http://huggingface.co/transformers/multilingual.html#xlm-language-embeddings) for information
  65. on how to use them.
  66. max_position_embeddings (`int`, *optional*, defaults to 512):
  67. The maximum sequence length that this model might ever be used with. Typically set this to something large
  68. just in case (e.g., 512 or 1024 or 2048).
  69. embed_init_std (`float`, *optional*, defaults to 2048^-0.5):
  70. The standard deviation of the truncated_normal_initializer for initializing the embedding matrices.
  71. init_std (`int`, *optional*, defaults to 50257):
  72. The standard deviation of the truncated_normal_initializer for initializing all weight matrices except the
  73. embedding matrices.
  74. layer_norm_eps (`float`, *optional*, defaults to 1e-12):
  75. The epsilon used by the layer normalization layers.
  76. bos_index (`int`, *optional*, defaults to 0):
  77. The index of the beginning of sentence token in the vocabulary.
  78. eos_index (`int`, *optional*, defaults to 1):
  79. The index of the end of sentence token in the vocabulary.
  80. pad_index (`int`, *optional*, defaults to 2):
  81. The index of the padding token in the vocabulary.
  82. unk_index (`int`, *optional*, defaults to 3):
  83. The index of the unknown token in the vocabulary.
  84. mask_index (`int`, *optional*, defaults to 5):
  85. The index of the masking token in the vocabulary.
  86. is_encoder(`bool`, *optional*, defaults to `True`):
  87. Whether or not the initialized model should be a transformer encoder or decoder as seen in Vaswani et al.
  88. summary_type (`string`, *optional*, defaults to "first"):
  89. Argument used when doing sequence summary. Used in the sequence classification and multiple choice models.
  90. Has to be one of the following options:
  91. - `"last"`: Take the last token hidden state (like XLNet).
  92. - `"first"`: Take the first token hidden state (like BERT).
  93. - `"mean"`: Take the mean of all tokens hidden states.
  94. - `"cls_index"`: Supply a Tensor of classification token position (like GPT/GPT-2).
  95. - `"attn"`: Not implemented now, use multi-head attention.
  96. summary_use_proj (`bool`, *optional*, defaults to `True`):
  97. Argument used when doing sequence summary. Used in the sequence classification and multiple choice models.
  98. Whether or not to add a projection after the vector extraction.
  99. summary_activation (`str`, *optional*):
  100. Argument used when doing sequence summary. Used in the sequence classification and multiple choice models.
  101. Pass `"tanh"` for a tanh activation to the output, any other value will result in no activation.
  102. summary_proj_to_labels (`bool`, *optional*, defaults to `True`):
  103. Used in the sequence classification and multiple choice models.
  104. Whether the projection outputs should have `config.num_labels` or `config.hidden_size` classes.
  105. summary_first_dropout (`float`, *optional*, defaults to 0.1):
  106. Used in the sequence classification and multiple choice models.
  107. The dropout ratio to be used after the projection and activation.
  108. start_n_top (`int`, *optional*, defaults to 5):
  109. Used in the SQuAD evaluation script.
  110. end_n_top (`int`, *optional*, defaults to 5):
  111. Used in the SQuAD evaluation script.
  112. mask_token_id (`int`, *optional*, defaults to 0):
  113. Model agnostic parameter to identify masked tokens when generating text in an MLM context.
  114. lang_id (`int`, *optional*, defaults to 1):
  115. The ID of the language used by the model. This parameter is used when generating text in a given language.
  116. """
  117. model_type = "flaubert"
  118. attribute_map = {
  119. "hidden_size": "emb_dim",
  120. "num_attention_heads": "n_heads",
  121. "num_hidden_layers": "n_layers",
  122. "n_words": "vocab_size", # For backward compatibility
  123. }
  124. def __init__(
  125. self,
  126. pre_norm=False,
  127. layerdrop=0.0,
  128. vocab_size=30145,
  129. emb_dim=2048,
  130. n_layers=12,
  131. n_heads=16,
  132. dropout=0.1,
  133. attention_dropout=0.1,
  134. gelu_activation=True,
  135. sinusoidal_embeddings=False,
  136. causal=False,
  137. asm=False,
  138. n_langs=1,
  139. use_lang_emb=True,
  140. max_position_embeddings=512,
  141. embed_init_std=2048**-0.5,
  142. layer_norm_eps=1e-12,
  143. init_std=0.02,
  144. bos_index=0,
  145. eos_index=1,
  146. pad_index=2,
  147. unk_index=3,
  148. mask_index=5,
  149. is_encoder=True,
  150. summary_type="first",
  151. summary_use_proj=True,
  152. summary_activation=None,
  153. summary_proj_to_labels=True,
  154. summary_first_dropout=0.1,
  155. start_n_top=5,
  156. end_n_top=5,
  157. mask_token_id=0,
  158. lang_id=0,
  159. pad_token_id=2,
  160. bos_token_id=0,
  161. **kwargs,
  162. ):
  163. """Constructs FlaubertConfig."""
  164. self.pre_norm = pre_norm
  165. self.layerdrop = layerdrop
  166. self.vocab_size = vocab_size
  167. self.emb_dim = emb_dim
  168. self.n_layers = n_layers
  169. self.n_heads = n_heads
  170. self.dropout = dropout
  171. self.attention_dropout = attention_dropout
  172. self.gelu_activation = gelu_activation
  173. self.sinusoidal_embeddings = sinusoidal_embeddings
  174. self.causal = causal
  175. self.asm = asm
  176. self.n_langs = n_langs
  177. self.use_lang_emb = use_lang_emb
  178. self.layer_norm_eps = layer_norm_eps
  179. self.bos_index = bos_index
  180. self.eos_index = eos_index
  181. self.pad_index = pad_index
  182. self.unk_index = unk_index
  183. self.mask_index = mask_index
  184. self.is_encoder = is_encoder
  185. self.max_position_embeddings = max_position_embeddings
  186. self.embed_init_std = embed_init_std
  187. self.init_std = init_std
  188. self.summary_type = summary_type
  189. self.summary_use_proj = summary_use_proj
  190. self.summary_activation = summary_activation
  191. self.summary_proj_to_labels = summary_proj_to_labels
  192. self.summary_first_dropout = summary_first_dropout
  193. self.start_n_top = start_n_top
  194. self.end_n_top = end_n_top
  195. self.mask_token_id = mask_token_id
  196. self.lang_id = lang_id
  197. if "n_words" in kwargs:
  198. self.n_words = kwargs["n_words"]
  199. super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, **kwargs)
  200. class FlaubertOnnxConfig(OnnxConfig):
  201. @property
  202. def inputs(self) -> Mapping[str, Mapping[int, str]]:
  203. if self.task == "multiple-choice":
  204. dynamic_axis = {0: "batch", 1: "choice", 2: "sequence"}
  205. else:
  206. dynamic_axis = {0: "batch", 1: "sequence"}
  207. return OrderedDict(
  208. [
  209. ("input_ids", dynamic_axis),
  210. ("attention_mask", dynamic_axis),
  211. ]
  212. )
  213. __all__ = ["FlaubertConfig", "FlaubertOnnxConfig"]