configuration_xlnet.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. # coding=utf-8
  2. # Copyright 2018 Google AI, Google Brain and Carnegie Mellon University 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. """XLNet configuration"""
  17. import warnings
  18. from ...configuration_utils import PretrainedConfig
  19. from ...utils import logging
  20. logger = logging.get_logger(__name__)
  21. class XLNetConfig(PretrainedConfig):
  22. """
  23. This is the configuration class to store the configuration of a [`XLNetModel`] or a [`TFXLNetModel`]. It is used to
  24. instantiate a XLNet model according to the specified arguments, defining the model architecture. Instantiating a
  25. configuration with the defaults will yield a similar configuration to that of the
  26. [xlnet/xlnet-large-cased](https://huggingface.co/xlnet/xlnet-large-cased) architecture.
  27. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  28. documentation from [`PretrainedConfig`] for more information.
  29. Args:
  30. vocab_size (`int`, *optional*, defaults to 32000):
  31. Vocabulary size of the XLNet model. Defines the number of different tokens that can be represented by the
  32. `inputs_ids` passed when calling [`XLNetModel`] or [`TFXLNetModel`].
  33. d_model (`int`, *optional*, defaults to 1024):
  34. Dimensionality of the encoder layers and the pooler layer.
  35. n_layer (`int`, *optional*, defaults to 24):
  36. Number of hidden layers in the Transformer encoder.
  37. n_head (`int`, *optional*, defaults to 16):
  38. Number of attention heads for each attention layer in the Transformer encoder.
  39. d_inner (`int`, *optional*, defaults to 4096):
  40. Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
  41. ff_activation (`str` or `Callable`, *optional*, defaults to `"gelu"`):
  42. The non-linear activation function (function or string) in the If string, `"gelu"`, `"relu"`, `"silu"` and
  43. `"gelu_new"` are supported.
  44. untie_r (`bool`, *optional*, defaults to `True`):
  45. Whether or not to untie relative position biases
  46. attn_type (`str`, *optional*, defaults to `"bi"`):
  47. The attention type used by the model. Set `"bi"` for XLNet, `"uni"` for Transformer-XL.
  48. initializer_range (`float`, *optional*, defaults to 0.02):
  49. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  50. layer_norm_eps (`float`, *optional*, defaults to 1e-12):
  51. The epsilon used by the layer normalization layers.
  52. dropout (`float`, *optional*, defaults to 0.1):
  53. The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
  54. mem_len (`int` or `None`, *optional*):
  55. The number of tokens to cache. The key/value pairs that have already been pre-computed in a previous
  56. forward pass won't be re-computed. See the
  57. [quickstart](https://huggingface.co/transformers/quickstart.html#using-the-past) for more information.
  58. reuse_len (`int`, *optional*):
  59. The number of tokens in the current batch to be cached and reused in the future.
  60. bi_data (`bool`, *optional*, defaults to `False`):
  61. Whether or not to use bidirectional input pipeline. Usually set to `True` during pretraining and `False`
  62. during finetuning.
  63. clamp_len (`int`, *optional*, defaults to -1):
  64. Clamp all relative distances larger than clamp_len. Setting this attribute to -1 means no clamping.
  65. same_length (`bool`, *optional*, defaults to `False`):
  66. Whether or not to use the same attention length for each token.
  67. summary_type (`str`, *optional*, defaults to "last"):
  68. Argument used when doing sequence summary. Used in the sequence classification and multiple choice models.
  69. Has to be one of the following options:
  70. - `"last"`: Take the last token hidden state (like XLNet).
  71. - `"first"`: Take the first token hidden state (like BERT).
  72. - `"mean"`: Take the mean of all tokens hidden states.
  73. - `"cls_index"`: Supply a Tensor of classification token position (like GPT/GPT-2).
  74. - `"attn"`: Not implemented now, use multi-head attention.
  75. summary_use_proj (`bool`, *optional*, defaults to `True`):
  76. Argument used when doing sequence summary. Used in the sequence classification and multiple choice models.
  77. Whether or not to add a projection after the vector extraction.
  78. summary_activation (`str`, *optional*):
  79. Argument used when doing sequence summary. Used in the sequence classification and multiple choice models.
  80. Pass `"tanh"` for a tanh activation to the output, any other value will result in no activation.
  81. summary_proj_to_labels (`boo`, *optional*, defaults to `True`):
  82. Used in the sequence classification and multiple choice models.
  83. Whether the projection outputs should have `config.num_labels` or `config.hidden_size` classes.
  84. summary_last_dropout (`float`, *optional*, defaults to 0.1):
  85. Used in the sequence classification and multiple choice models.
  86. The dropout ratio to be used after the projection and activation.
  87. start_n_top (`int`, *optional*, defaults to 5):
  88. Used in the SQuAD evaluation script.
  89. end_n_top (`int`, *optional*, defaults to 5):
  90. Used in the SQuAD evaluation script.
  91. use_mems_eval (`bool`, *optional*, defaults to `True`):
  92. Whether or not the model should make use of the recurrent memory mechanism in evaluation mode.
  93. use_mems_train (`bool`, *optional*, defaults to `False`):
  94. Whether or not the model should make use of the recurrent memory mechanism in train mode.
  95. <Tip>
  96. For pretraining, it is recommended to set `use_mems_train` to `True`. For fine-tuning, it is recommended to
  97. set `use_mems_train` to `False` as discussed
  98. [here](https://github.com/zihangdai/xlnet/issues/41#issuecomment-505102587). If `use_mems_train` is set to
  99. `True`, one has to make sure that the train batches are correctly pre-processed, *e.g.* `batch_1 = [[This
  100. line is], [This is the]]` and `batch_2 = [[ the first line], [ second line]]` and that all batches are of
  101. equal size.
  102. </Tip>
  103. Examples:
  104. ```python
  105. >>> from transformers import XLNetConfig, XLNetModel
  106. >>> # Initializing a XLNet configuration
  107. >>> configuration = XLNetConfig()
  108. >>> # Initializing a model (with random weights) from the configuration
  109. >>> model = XLNetModel(configuration)
  110. >>> # Accessing the model configuration
  111. >>> configuration = model.config
  112. ```"""
  113. model_type = "xlnet"
  114. keys_to_ignore_at_inference = ["mems"]
  115. attribute_map = {
  116. "n_token": "vocab_size", # Backward compatibility
  117. "hidden_size": "d_model",
  118. "num_attention_heads": "n_head",
  119. "num_hidden_layers": "n_layer",
  120. }
  121. def __init__(
  122. self,
  123. vocab_size=32000,
  124. d_model=1024,
  125. n_layer=24,
  126. n_head=16,
  127. d_inner=4096,
  128. ff_activation="gelu",
  129. untie_r=True,
  130. attn_type="bi",
  131. initializer_range=0.02,
  132. layer_norm_eps=1e-12,
  133. dropout=0.1,
  134. mem_len=512,
  135. reuse_len=None,
  136. use_mems_eval=True,
  137. use_mems_train=False,
  138. bi_data=False,
  139. clamp_len=-1,
  140. same_length=False,
  141. summary_type="last",
  142. summary_use_proj=True,
  143. summary_activation="tanh",
  144. summary_last_dropout=0.1,
  145. start_n_top=5,
  146. end_n_top=5,
  147. pad_token_id=5,
  148. bos_token_id=1,
  149. eos_token_id=2,
  150. **kwargs,
  151. ):
  152. """Constructs XLNetConfig."""
  153. self.vocab_size = vocab_size
  154. self.d_model = d_model
  155. self.n_layer = n_layer
  156. self.n_head = n_head
  157. if d_model % n_head != 0:
  158. raise ValueError(f"'d_model % n_head' ({d_model % n_head}) should be equal to 0")
  159. if "d_head" in kwargs:
  160. if kwargs["d_head"] != d_model // n_head:
  161. raise ValueError(
  162. f"`d_head` ({kwargs['d_head']}) should be equal to `d_model // n_head` ({d_model // n_head})"
  163. )
  164. self.d_head = d_model // n_head
  165. self.ff_activation = ff_activation
  166. self.d_inner = d_inner
  167. self.untie_r = untie_r
  168. self.attn_type = attn_type
  169. self.initializer_range = initializer_range
  170. self.layer_norm_eps = layer_norm_eps
  171. self.dropout = dropout
  172. self.mem_len = mem_len
  173. self.reuse_len = reuse_len
  174. self.bi_data = bi_data
  175. self.clamp_len = clamp_len
  176. self.same_length = same_length
  177. self.summary_type = summary_type
  178. self.summary_use_proj = summary_use_proj
  179. self.summary_activation = summary_activation
  180. self.summary_last_dropout = summary_last_dropout
  181. self.start_n_top = start_n_top
  182. self.end_n_top = end_n_top
  183. self.bos_token_id = bos_token_id
  184. self.pad_token_id = pad_token_id
  185. self.eos_token_id = eos_token_id
  186. if "use_cache" in kwargs:
  187. warnings.warn(
  188. "The `use_cache` argument is deprecated and will be removed in a future version, use `use_mems_eval`"
  189. " instead.",
  190. FutureWarning,
  191. )
  192. use_mems_eval = kwargs["use_cache"]
  193. self.use_mems_eval = use_mems_eval
  194. self.use_mems_train = use_mems_train
  195. super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
  196. @property
  197. def max_position_embeddings(self):
  198. logger.info(f"The model {self.model_type} is one of the few models that has no sequence length limit.")
  199. return -1
  200. @max_position_embeddings.setter
  201. def max_position_embeddings(self, value):
  202. # Message copied from Transformer-XL documentation
  203. raise NotImplementedError(
  204. f"The model {self.model_type} is one of the few models that has no sequence length limit."
  205. )
  206. __all__ = ["XLNetConfig"]