configuration_xlnet.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. # Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HuggingFace Inc. team.
  2. # Copyright (c) 2018, NVIDIA CORPORATION. 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. """XLNet configuration"""
  16. from huggingface_hub.dataclasses import strict
  17. from ...configuration_utils import PreTrainedConfig
  18. from ...utils import auto_docstring, logging
  19. logger = logging.get_logger(__name__)
  20. @auto_docstring(checkpoint="xlnet/xlnet-large-cased")
  21. @strict
  22. class XLNetConfig(PreTrainedConfig):
  23. r"""
  24. ff_activation (`str` or `Callable`, *optional*, defaults to `"gelu"`):
  25. The non-linear activation function (function or string) in the If string, `"gelu"`, `"relu"`, `"silu"` and
  26. `"gelu_new"` are supported.
  27. attn_type (`str`, *optional*, defaults to `"bi"`):
  28. The attention type used by the model. Set `"bi"` for XLNet, `"uni"` for Transformer-XL.
  29. mem_len (`int` or `None`, *optional*):
  30. The number of tokens to cache. The key/value pairs that have already been pre-computed in a previous
  31. forward pass won't be re-computed. See the
  32. [quickstart](https://huggingface.co/transformers/quickstart.html#using-the-past) for more information.
  33. reuse_len (`int`, *optional*):
  34. The number of tokens in the current batch to be cached and reused in the future.
  35. use_mems_eval (`bool`, *optional*, defaults to `True`):
  36. Whether or not the model should make use of the recurrent memory mechanism in evaluation mode.
  37. use_mems_train (`bool`, *optional*, defaults to `False`):
  38. Whether or not the model should make use of the recurrent memory mechanism in train mode.
  39. <Tip>
  40. For pretraining, it is recommended to set `use_mems_train` to `True`. For fine-tuning, it is recommended to
  41. set `use_mems_train` to `False` as discussed
  42. [here](https://github.com/zihangdai/xlnet/issues/41#issuecomment-505102587). If `use_mems_train` is set to
  43. `True`, one has to make sure that the train batches are correctly pre-processed, *e.g.* `batch_1 = [[This
  44. line is], [This is the]]` and `batch_2 = [[ the first line], [ second line]]` and that all batches are of
  45. equal size.
  46. </Tip>
  47. bi_data (`bool`, *optional*, defaults to `False`):
  48. Whether or not to use bidirectional input pipeline. Usually set to `True` during pretraining and `False`
  49. during finetuning.
  50. clamp_len (`int`, *optional*, defaults to -1):
  51. Clamp all relative distances larger than clamp_len. Setting this attribute to -1 means no clamping.
  52. same_length (`bool`, *optional*, defaults to `False`):
  53. Whether or not to use the same attention length for each token.
  54. summary_type (`str`, *optional*, defaults to "last"):
  55. Argument used when doing sequence summary. Used in the sequence classification and multiple choice models.
  56. Has to be one of the following options:
  57. - `"last"`: Take the last token hidden state (like XLNet).
  58. - `"first"`: Take the first token hidden state (like BERT).
  59. - `"mean"`: Take the mean of all tokens hidden states.
  60. - `"cls_index"`: Supply a Tensor of classification token position (like GPT/GPT-2).
  61. - `"attn"`: Not implemented now, use multi-head attention.
  62. summary_use_proj (`bool`, *optional*, defaults to `True`):
  63. Argument used when doing sequence summary. Used in the sequence classification and multiple choice models.
  64. Whether or not to add a projection after the vector extraction.
  65. summary_activation (`str`, *optional*):
  66. Argument used when doing sequence summary. Used in the sequence classification and multiple choice models.
  67. Pass `"tanh"` for a tanh activation to the output, any other value will result in no activation.
  68. summary_last_dropout (`float`, *optional*, defaults to 0.1):
  69. Used in the sequence classification and multiple choice models.
  70. The dropout ratio to be used after the projection and activation.
  71. start_n_top (`int`, *optional*, defaults to 5):
  72. Used in the SQuAD evaluation script.
  73. end_n_top (`int`, *optional*, defaults to 5):
  74. Used in the SQuAD evaluation script.
  75. Examples:
  76. ```python
  77. >>> from transformers import XLNetConfig, XLNetModel
  78. >>> # Initializing a XLNet configuration
  79. >>> configuration = XLNetConfig()
  80. >>> # Initializing a model (with random weights) from the configuration
  81. >>> model = XLNetModel(configuration)
  82. >>> # Accessing the model configuration
  83. >>> configuration = model.config
  84. ```"""
  85. model_type = "xlnet"
  86. keys_to_ignore_at_inference = ["mems"]
  87. attribute_map = {
  88. "n_token": "vocab_size", # Backward compatibility
  89. "hidden_size": "d_model",
  90. "num_attention_heads": "n_head",
  91. "num_hidden_layers": "n_layer",
  92. }
  93. vocab_size: int = 32000
  94. d_model: int = 1024
  95. n_layer: int = 24
  96. n_head: int = 16
  97. d_inner: int = 4096
  98. d_head: int | None = None
  99. ff_activation: str = "gelu"
  100. attn_type: str = "bi"
  101. initializer_range: float = 0.02
  102. layer_norm_eps: float = 1e-12
  103. dropout: float | int = 0.1
  104. mem_len: int | None = 512
  105. reuse_len: int | None = None
  106. use_mems_eval: bool = True
  107. use_mems_train: bool = False
  108. bi_data: bool = False
  109. clamp_len: int = -1
  110. same_length: bool = False
  111. summary_type: str = "last"
  112. summary_use_proj: bool = True
  113. summary_activation: str = "tanh"
  114. summary_last_dropout: float | int = 0.1
  115. start_n_top: int = 5
  116. end_n_top: int = 5
  117. pad_token_id: int | None = 5
  118. bos_token_id: int | None = 1
  119. eos_token_id: int | list[int] | None = 2
  120. tie_word_embeddings: bool = True
  121. def __post_init__(self, **kwargs):
  122. self.d_head = self.d_head or self.d_model // self.n_head
  123. super().__post_init__(**kwargs)
  124. def validate_architecture(self):
  125. """Part of `@strict`-powered validation. Validates the architecture of the config."""
  126. if self.d_model % self.n_head != 0:
  127. raise ValueError(f"'d_model % n_head' ({self.d_model % self.n_head}) should be equal to 0")
  128. if self.d_head != self.d_model // self.n_head:
  129. raise ValueError(
  130. f"`d_head` ({self.d_head}) should be equal to `d_model // n_head` ({self.d_model // self.n_head})"
  131. )
  132. @property
  133. def max_position_embeddings(self):
  134. logger.info(f"The model {self.model_type} is one of the few models that has no sequence length limit.")
  135. return -1
  136. @max_position_embeddings.setter
  137. def max_position_embeddings(self, value):
  138. # Message copied from Transformer-XL documentation
  139. raise NotImplementedError(
  140. f"The model {self.model_type} is one of the few models that has no sequence length limit."
  141. )
  142. __all__ = ["XLNetConfig"]