configuration_fsmt.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. # coding=utf-8
  2. # Copyright 2019-present, 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. """FSMT configuration"""
  16. from ...configuration_utils import PretrainedConfig
  17. from ...utils import logging
  18. logger = logging.get_logger(__name__)
  19. class DecoderConfig(PretrainedConfig):
  20. r"""
  21. Configuration class for FSMT's decoder specific things. note: this is a private helper class
  22. """
  23. model_type = "fsmt_decoder"
  24. def __init__(self, vocab_size=0, bos_token_id=0, is_encoder_decoder=True, **kwargs):
  25. super().__init__(**kwargs)
  26. self.vocab_size = vocab_size
  27. self.bos_token_id = bos_token_id
  28. self.is_encoder_decoder = is_encoder_decoder
  29. class FSMTConfig(PretrainedConfig):
  30. r"""
  31. This is the configuration class to store the configuration of a [`FSMTModel`]. It is used to instantiate a FSMT
  32. model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
  33. defaults will yield a similar configuration to that of the FSMT
  34. [facebook/wmt19-en-ru](https://huggingface.co/facebook/wmt19-en-ru) architecture.
  35. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  36. documentation from [`PretrainedConfig`] for more information.
  37. Args:
  38. langs (`list[str]`):
  39. A list with source language and target_language (e.g., ['en', 'ru']).
  40. src_vocab_size (`int`):
  41. Vocabulary size of the encoder. Defines the number of different tokens that can be represented by the
  42. `inputs_ids` passed to the forward method in the encoder.
  43. tgt_vocab_size (`int`):
  44. Vocabulary size of the decoder. Defines the number of different tokens that can be represented by the
  45. `inputs_ids` passed to the forward method in the decoder.
  46. d_model (`int`, *optional*, defaults to 1024):
  47. Dimensionality of the layers and the pooler layer.
  48. encoder_layers (`int`, *optional*, defaults to 12):
  49. Number of encoder layers.
  50. decoder_layers (`int`, *optional*, defaults to 12):
  51. Number of decoder layers.
  52. encoder_attention_heads (`int`, *optional*, defaults to 16):
  53. Number of attention heads for each attention layer in the Transformer encoder.
  54. decoder_attention_heads (`int`, *optional*, defaults to 16):
  55. Number of attention heads for each attention layer in the Transformer decoder.
  56. decoder_ffn_dim (`int`, *optional*, defaults to 4096):
  57. Dimensionality of the "intermediate" (often named feed-forward) layer in decoder.
  58. encoder_ffn_dim (`int`, *optional*, defaults to 4096):
  59. Dimensionality of the "intermediate" (often named feed-forward) layer in decoder.
  60. activation_function (`str` or `Callable`, *optional*, defaults to `"relu"`):
  61. The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
  62. `"relu"`, `"silu"` and `"gelu_new"` are supported.
  63. dropout (`float`, *optional*, defaults to 0.1):
  64. The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
  65. attention_dropout (`float`, *optional*, defaults to 0.0):
  66. The dropout ratio for the attention probabilities.
  67. activation_dropout (`float`, *optional*, defaults to 0.0):
  68. The dropout ratio for activations inside the fully connected layer.
  69. max_position_embeddings (`int`, *optional*, defaults to 1024):
  70. The maximum sequence length that this model might ever be used with. Typically set this to something large
  71. just in case (e.g., 512 or 1024 or 2048).
  72. init_std (`float`, *optional*, defaults to 0.02):
  73. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  74. scale_embedding (`bool`, *optional*, defaults to `True`):
  75. Scale embeddings by diving by sqrt(d_model).
  76. bos_token_id (`int`, *optional*, defaults to 0)
  77. Beginning of stream token id.
  78. pad_token_id (`int`, *optional*, defaults to 1)
  79. Padding token id.
  80. eos_token_id (`int`, *optional*, defaults to 2)
  81. End of stream token id.
  82. decoder_start_token_id (`int`, *optional*):
  83. This model starts decoding with `eos_token_id`
  84. encoder_layerdrop (`float`, *optional*, defaults to 0.0):
  85. Google "layerdrop arxiv", as its not explainable in one line.
  86. decoder_layerdrop (`float`, *optional*, defaults to 0.0):
  87. Google "layerdrop arxiv", as its not explainable in one line.
  88. is_encoder_decoder (`bool`, *optional*, defaults to `True`):
  89. Whether this is an encoder/decoder model.
  90. tie_word_embeddings (`bool`, *optional*, defaults to `False`):
  91. Whether to tie input and output embeddings.
  92. num_beams (`int`, *optional*, defaults to 5)
  93. Number of beams for beam search that will be used by default in the `generate` method of the model. 1 means
  94. no beam search.
  95. length_penalty (`float`, *optional*, defaults to 1)
  96. Exponential penalty to the length that is used with beam-based generation. It is applied as an exponent to
  97. the sequence length, which in turn is used to divide the score of the sequence. Since the score is the log
  98. likelihood of the sequence (i.e. negative), `length_penalty` > 0.0 promotes longer sequences, while
  99. `length_penalty` < 0.0 encourages shorter sequences.
  100. early_stopping (`bool`, *optional*, defaults to `False`)
  101. Flag that will be used by default in the `generate` method of the model. Whether to stop the beam search
  102. when at least `num_beams` sentences are finished per batch or not.
  103. use_cache (`bool`, *optional*, defaults to `True`):
  104. Whether or not the model should return the last key/values attentions (not used by all models).
  105. forced_eos_token_id (`int`, *optional*, defaults to 2):
  106. The id of the token to force as the last generated token when `max_length` is reached. Usually set to
  107. `eos_token_id`.
  108. Examples:
  109. ```python
  110. >>> from transformers import FSMTConfig, FSMTModel
  111. >>> # Initializing a FSMT facebook/wmt19-en-ru style configuration
  112. >>> config = FSMTConfig()
  113. >>> # Initializing a model (with random weights) from the configuration
  114. >>> model = FSMTModel(config)
  115. >>> # Accessing the model configuration
  116. >>> configuration = model.config
  117. ```"""
  118. model_type = "fsmt"
  119. attribute_map = {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"}
  120. sub_configs = {"decoder": DecoderConfig}
  121. # update the defaults from config file
  122. def __init__(
  123. self,
  124. langs=["en", "de"],
  125. src_vocab_size=42024,
  126. tgt_vocab_size=42024,
  127. activation_function="relu",
  128. d_model=1024,
  129. max_length=200,
  130. max_position_embeddings=1024,
  131. encoder_ffn_dim=4096,
  132. encoder_layers=12,
  133. encoder_attention_heads=16,
  134. encoder_layerdrop=0.0,
  135. decoder_ffn_dim=4096,
  136. decoder_layers=12,
  137. decoder_attention_heads=16,
  138. decoder_layerdrop=0.0,
  139. attention_dropout=0.0,
  140. dropout=0.1,
  141. activation_dropout=0.0,
  142. init_std=0.02,
  143. decoder_start_token_id=2,
  144. is_encoder_decoder=True,
  145. scale_embedding=True,
  146. tie_word_embeddings=False,
  147. num_beams=5,
  148. length_penalty=1.0,
  149. early_stopping=False,
  150. use_cache=True,
  151. pad_token_id=1,
  152. bos_token_id=0,
  153. eos_token_id=2,
  154. forced_eos_token_id=2,
  155. **common_kwargs,
  156. ):
  157. self.langs = langs
  158. self.src_vocab_size = src_vocab_size
  159. self.tgt_vocab_size = tgt_vocab_size
  160. self.d_model = d_model # encoder_embed_dim and decoder_embed_dim
  161. self.encoder_ffn_dim = encoder_ffn_dim
  162. self.encoder_layers = self.num_hidden_layers = encoder_layers
  163. self.encoder_attention_heads = encoder_attention_heads
  164. self.encoder_layerdrop = encoder_layerdrop
  165. self.decoder_layerdrop = decoder_layerdrop
  166. self.decoder_ffn_dim = decoder_ffn_dim
  167. self.decoder_layers = decoder_layers
  168. self.decoder_attention_heads = decoder_attention_heads
  169. self.max_position_embeddings = max_position_embeddings
  170. self.init_std = init_std # Normal(0, this parameter)
  171. self.activation_function = activation_function
  172. self.decoder = DecoderConfig(
  173. vocab_size=tgt_vocab_size,
  174. bos_token_id=eos_token_id,
  175. is_encoder_decoder=is_encoder_decoder,
  176. num_hidden_layers=encoder_layers,
  177. )
  178. if "decoder" in common_kwargs:
  179. del common_kwargs["decoder"]
  180. self.scale_embedding = scale_embedding # scale factor will be sqrt(d_model) if True
  181. # 3 Types of Dropout
  182. self.attention_dropout = attention_dropout
  183. self.activation_dropout = activation_dropout
  184. self.dropout = dropout
  185. self.use_cache = use_cache
  186. super().__init__(
  187. pad_token_id=pad_token_id,
  188. bos_token_id=bos_token_id,
  189. eos_token_id=eos_token_id,
  190. decoder_start_token_id=decoder_start_token_id,
  191. is_encoder_decoder=is_encoder_decoder,
  192. tie_word_embeddings=tie_word_embeddings,
  193. forced_eos_token_id=forced_eos_token_id,
  194. max_length=max_length,
  195. num_beams=num_beams,
  196. length_penalty=length_penalty,
  197. early_stopping=early_stopping,
  198. **common_kwargs,
  199. )
  200. __all__ = ["FSMTConfig"]