configuration_modernbert.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
  2. # This file was automatically generated from src/transformers/models/modernbert/modular_modernbert.py.
  3. # Do NOT edit this file manually as any edits will be overwritten by the generation of
  4. # the file from the modular. If any change should be done, please apply the change to the
  5. # modular_modernbert.py file directly. One of our CI enforces this.
  6. # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
  7. # Copyright 2024 Answer.AI, LightOn, and contributors, and the HuggingFace Inc. team. All rights reserved.
  8. #
  9. #
  10. # Licensed under the Apache License, Version 2.0 (the "License");
  11. # you may not use this file except in compliance with the License.
  12. # You may obtain a copy of the License at
  13. #
  14. # http://www.apache.org/licenses/LICENSE-2.0
  15. #
  16. # Unless required by applicable law or agreed to in writing, software
  17. # distributed under the License is distributed on an "AS IS" BASIS,
  18. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19. # See the License for the specific language governing permissions and
  20. # limitations under the License.
  21. from typing import Literal
  22. from ...configuration_utils import PretrainedConfig
  23. class ModernBertConfig(PretrainedConfig):
  24. r"""
  25. This is the configuration class to store the configuration of a [`ModernBertModel`]. It is used to instantiate an ModernBert
  26. model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
  27. defaults will yield a similar configuration to that of the ModernBERT-base.
  28. e.g. [answerdotai/ModernBERT-base](https://huggingface.co/answerdotai/ModernBERT-base)
  29. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  30. documentation from [`PretrainedConfig`] for more information.
  31. Args:
  32. vocab_size (`int`, *optional*, defaults to 50368):
  33. Vocabulary size of the ModernBert model. Defines the number of different tokens that can be represented by the
  34. `inputs_ids` passed when calling [`ModernBertModel`]
  35. hidden_size (`int`, *optional*, defaults to 768):
  36. Dimension of the hidden representations.
  37. intermediate_size (`int`, *optional*, defaults to 1152):
  38. Dimension of the MLP representations.
  39. num_hidden_layers (`int`, *optional*, defaults to 22):
  40. Number of hidden layers in the Transformer decoder.
  41. num_attention_heads (`int`, *optional*, defaults to 12):
  42. Number of attention heads for each attention layer in the Transformer decoder.
  43. hidden_activation (`str` or `function`, *optional*, defaults to `"gelu"`):
  44. The non-linear activation function (function or string) in the decoder. Will default to `"gelu"`
  45. if not specified.
  46. max_position_embeddings (`int`, *optional*, defaults to 8192):
  47. The maximum sequence length that this model might ever be used with.
  48. initializer_range (`float`, *optional*, defaults to 0.02):
  49. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  50. initializer_cutoff_factor (`float`, *optional*, defaults to 2.0):
  51. The cutoff factor for the truncated_normal_initializer for initializing all weight matrices.
  52. norm_eps (`float`, *optional*, defaults to 1e-05):
  53. The epsilon used by the rms normalization layers.
  54. norm_bias (`bool`, *optional*, defaults to `False`):
  55. Whether to use bias in the normalization layers.
  56. pad_token_id (`int`, *optional*, defaults to 50283):
  57. Padding token id.
  58. eos_token_id (`int`, *optional*, defaults to 50282):
  59. End of stream token id.
  60. bos_token_id (`int`, *optional*, defaults to 50281):
  61. Beginning of stream token id.
  62. cls_token_id (`int`, *optional*, defaults to 50281):
  63. Classification token id.
  64. sep_token_id (`int`, *optional*, defaults to 50282):
  65. Separation token id.
  66. global_rope_theta (`float`, *optional*, defaults to 160000.0):
  67. The base period of the global RoPE embeddings.
  68. attention_bias (`bool`, *optional*, defaults to `False`):
  69. Whether to use a bias in the query, key, value and output projection layers during self-attention.
  70. attention_dropout (`float`, *optional*, defaults to 0.0):
  71. The dropout ratio for the attention probabilities.
  72. global_attn_every_n_layers (`int`, *optional*, defaults to 3):
  73. The number of layers between global attention layers.
  74. local_attention (`int`, *optional*, defaults to 128):
  75. The window size for local attention.
  76. local_rope_theta (`float`, *optional*, defaults to 10000.0):
  77. The base period of the local RoPE embeddings.
  78. embedding_dropout (`float`, *optional*, defaults to 0.0):
  79. The dropout ratio for the embeddings.
  80. mlp_bias (`bool`, *optional*, defaults to `False`):
  81. Whether to use bias in the MLP layers.
  82. mlp_dropout (`float`, *optional*, defaults to 0.0):
  83. The dropout ratio for the MLP layers.
  84. decoder_bias (`bool`, *optional*, defaults to `True`):
  85. Whether to use bias in the decoder layers.
  86. classifier_pooling (`str`, *optional*, defaults to `"cls"`):
  87. The pooling method for the classifier. Should be either `"cls"` or `"mean"`. In local attention layers, the
  88. CLS token doesn't attend to all tokens on long sequences.
  89. classifier_dropout (`float`, *optional*, defaults to 0.0):
  90. The dropout ratio for the classifier.
  91. classifier_bias (`bool`, *optional*, defaults to `False`):
  92. Whether to use bias in the classifier.
  93. classifier_activation (`str`, *optional*, defaults to `"gelu"`):
  94. The activation function for the classifier.
  95. deterministic_flash_attn (`bool`, *optional*, defaults to `False`):
  96. Whether to use deterministic flash attention. If `False`, inference will be faster but not deterministic.
  97. sparse_prediction (`bool`, *optional*, defaults to `False`):
  98. Whether to use sparse prediction for the masked language model instead of returning the full dense logits.
  99. sparse_pred_ignore_index (`int`, *optional*, defaults to -100):
  100. The index to ignore for the sparse prediction.
  101. reference_compile (`bool`, *optional*):
  102. Whether to compile the layers of the model which were compiled during pretraining. If `None`, then parts of
  103. the model will be compiled if 1) `triton` is installed, 2) the model is not on MPS, 3) the model is not
  104. shared between devices, and 4) the model is not resized after initialization. If `True`, then the model may
  105. be faster in some scenarios.
  106. repad_logits_with_grad (`bool`, *optional*, defaults to `False`):
  107. When True, ModernBertForMaskedLM keeps track of the logits' gradient when repadding for output. This only
  108. applies when using Flash Attention 2 with passed labels. Otherwise output logits always have a gradient.
  109. Examples:
  110. ```python
  111. >>> from transformers import ModernBertModel, ModernBertConfig
  112. >>> # Initializing a ModernBert style configuration
  113. >>> configuration = ModernBertConfig()
  114. >>> # Initializing a model from the modernbert-base style configuration
  115. >>> model = ModernBertModel(configuration)
  116. >>> # Accessing the model configuration
  117. >>> configuration = model.config
  118. ```"""
  119. model_type = "modernbert"
  120. attribute_map = {"rope_theta": "global_rope_theta"}
  121. keys_to_ignore_at_inference = ["past_key_values"]
  122. def __init__(
  123. self,
  124. vocab_size=50368,
  125. hidden_size=768,
  126. intermediate_size=1152,
  127. num_hidden_layers=22,
  128. num_attention_heads=12,
  129. hidden_activation="gelu",
  130. max_position_embeddings=8192,
  131. initializer_range=0.02,
  132. initializer_cutoff_factor=2.0,
  133. norm_eps=1e-5,
  134. norm_bias=False,
  135. pad_token_id=50283,
  136. eos_token_id=50282,
  137. bos_token_id=50281,
  138. cls_token_id=50281,
  139. sep_token_id=50282,
  140. global_rope_theta=160000.0,
  141. attention_bias=False,
  142. attention_dropout=0.0,
  143. global_attn_every_n_layers=3,
  144. local_attention=128,
  145. local_rope_theta=10000.0,
  146. embedding_dropout=0.0,
  147. mlp_bias=False,
  148. mlp_dropout=0.0,
  149. decoder_bias=True,
  150. classifier_pooling: Literal["cls", "mean"] = "cls",
  151. classifier_dropout=0.0,
  152. classifier_bias=False,
  153. classifier_activation="gelu",
  154. deterministic_flash_attn=False,
  155. sparse_prediction=False,
  156. sparse_pred_ignore_index=-100,
  157. reference_compile=None,
  158. repad_logits_with_grad=False,
  159. **kwargs,
  160. ):
  161. super().__init__(
  162. pad_token_id=pad_token_id,
  163. bos_token_id=bos_token_id,
  164. eos_token_id=eos_token_id,
  165. cls_token_id=cls_token_id,
  166. sep_token_id=sep_token_id,
  167. **kwargs,
  168. )
  169. self.vocab_size = vocab_size
  170. self.max_position_embeddings = max_position_embeddings
  171. self.hidden_size = hidden_size
  172. self.intermediate_size = intermediate_size
  173. self.num_hidden_layers = num_hidden_layers
  174. self.num_attention_heads = num_attention_heads
  175. self.initializer_range = initializer_range
  176. self.initializer_cutoff_factor = initializer_cutoff_factor
  177. self.norm_eps = norm_eps
  178. self.norm_bias = norm_bias
  179. self.global_rope_theta = global_rope_theta
  180. self.attention_bias = attention_bias
  181. self.attention_dropout = attention_dropout
  182. self.hidden_activation = hidden_activation
  183. self.global_attn_every_n_layers = global_attn_every_n_layers
  184. self.local_attention = local_attention
  185. self.local_rope_theta = local_rope_theta
  186. self.embedding_dropout = embedding_dropout
  187. self.mlp_bias = mlp_bias
  188. self.mlp_dropout = mlp_dropout
  189. self.decoder_bias = decoder_bias
  190. self.classifier_pooling = classifier_pooling
  191. self.classifier_dropout = classifier_dropout
  192. self.classifier_bias = classifier_bias
  193. self.classifier_activation = classifier_activation
  194. self.deterministic_flash_attn = deterministic_flash_attn
  195. self.sparse_prediction = sparse_prediction
  196. self.sparse_pred_ignore_index = sparse_pred_ignore_index
  197. self.reference_compile = reference_compile
  198. self.repad_logits_with_grad = repad_logits_with_grad
  199. if self.classifier_pooling not in ["cls", "mean"]:
  200. raise ValueError(
  201. f'Invalid value for `classifier_pooling`, should be either "cls" or "mean", but is {self.classifier_pooling}.'
  202. )
  203. def to_dict(self):
  204. output = super().to_dict()
  205. output.pop("reference_compile", None)
  206. return output
  207. __all__ = ["ModernBertConfig"]