configuration_modernbert.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  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 huggingface_hub.dataclasses import strict
  23. from ...configuration_utils import PreTrainedConfig
  24. from ...utils import auto_docstring
  25. @auto_docstring(checkpoint="answerdotai/ModernBERT-base")
  26. @strict
  27. class ModernBertConfig(PreTrainedConfig):
  28. r"""
  29. initializer_cutoff_factor (`float`, *optional*, defaults to 2.0):
  30. The cutoff factor for the truncated_normal_initializer for initializing all weight matrices.
  31. norm_eps (`float`, *optional*, defaults to 1e-05):
  32. The epsilon used by the rms normalization layers.
  33. norm_bias (`bool`, *optional*, defaults to `False`):
  34. Whether to use bias in the normalization layers.
  35. local_attention (`int`, *optional*, defaults to 128):
  36. The window size for local attention.
  37. mlp_dropout (`float`, *optional*, defaults to 0.0):
  38. The dropout ratio for the MLP layers.
  39. decoder_bias (`bool`, *optional*, defaults to `True`):
  40. Whether to use bias in the decoder layers.
  41. classifier_pooling (`str`, *optional*, defaults to `"cls"`):
  42. The pooling method for the classifier. Should be either `"cls"` or `"mean"`. In local attention layers, the
  43. CLS token doesn't attend to all tokens on long sequences.
  44. classifier_bias (`bool`, *optional*, defaults to `False`):
  45. Whether to use bias in the classifier.
  46. classifier_activation (`str`, *optional*, defaults to `"gelu"`):
  47. The activation function for the classifier.
  48. deterministic_flash_attn (`bool`, *optional*, defaults to `False`):
  49. Whether to use deterministic flash attention. If `False`, inference will be faster but not deterministic.
  50. sparse_prediction (`bool`, *optional*, defaults to `False`):
  51. Whether to use sparse prediction for the masked language model instead of returning the full dense logits.
  52. sparse_pred_ignore_index (`int`, *optional*, defaults to -100):
  53. The index to ignore for the sparse prediction.
  54. Examples:
  55. ```python
  56. >>> from transformers import ModernBertModel, ModernBertConfig
  57. >>> # Initializing a ModernBert style configuration
  58. >>> configuration = ModernBertConfig()
  59. >>> # Initializing a model from the modernbert-base style configuration
  60. >>> model = ModernBertModel(configuration)
  61. >>> # Accessing the model configuration
  62. >>> configuration = model.config
  63. ```"""
  64. model_type = "modernbert"
  65. keys_to_ignore_at_inference = ["past_key_values"]
  66. default_theta = {"global": 160_000.0, "local": 10_000.0}
  67. vocab_size: int = 50368
  68. hidden_size: int = 768
  69. intermediate_size: int = 1152
  70. num_hidden_layers: int = 22
  71. num_attention_heads: int = 12
  72. hidden_activation: str = "gelu"
  73. max_position_embeddings: int = 8192
  74. initializer_range: float = 0.02
  75. initializer_cutoff_factor: float = 2.0
  76. norm_eps: float = 1e-5
  77. norm_bias: bool = False
  78. pad_token_id: int | None = 50283
  79. eos_token_id: int | list[int] | None = 50282
  80. bos_token_id: int | None = 50281
  81. cls_token_id: int | None = 50281
  82. sep_token_id: int | None = 50282
  83. attention_bias: bool = False
  84. attention_dropout: float | int = 0.0
  85. layer_types: list[str] | None = None
  86. rope_parameters: dict[Literal["full_attention", "sliding_attention"], dict] | None = None
  87. local_attention: int = 128
  88. embedding_dropout: float | int = 0.0
  89. mlp_bias: bool = False
  90. mlp_dropout: float | int = 0.0
  91. decoder_bias: bool = True
  92. classifier_pooling: Literal["cls", "mean"] = "cls"
  93. classifier_dropout: float | int = 0.0
  94. classifier_bias: bool = False
  95. classifier_activation: str = "gelu"
  96. deterministic_flash_attn: bool = False
  97. sparse_prediction: bool = False
  98. sparse_pred_ignore_index: int = -100
  99. tie_word_embeddings: bool = True
  100. def __post_init__(self, **kwargs):
  101. # BC -> the pattern used to be a simple int, and it's still present in configs on the Hub
  102. global_attn_every_n_layers = kwargs.get("global_attn_every_n_layers", 3)
  103. if self.layer_types is None:
  104. self.layer_types = [
  105. "sliding_attention" if bool(i % global_attn_every_n_layers) else "full_attention"
  106. for i in range(self.num_hidden_layers)
  107. ]
  108. super().__post_init__(**kwargs)
  109. def convert_rope_params_to_dict(self, **kwargs):
  110. rope_scaling = kwargs.pop("rope_scaling", None)
  111. # Try to set `rope_scaling` if available, otherwise use `rope_parameters`. If we find `rope_parameters`
  112. # as arg in the inputs, we can safely assume that it is in the new format. New naming used -> new format
  113. default_rope_params = {
  114. "sliding_attention": {"rope_type": "default"},
  115. "full_attention": {"rope_type": "default"},
  116. }
  117. self.rope_parameters = self.rope_parameters if self.rope_parameters is not None else default_rope_params
  118. if rope_scaling is not None:
  119. self.rope_parameters["full_attention"].update(rope_scaling)
  120. self.rope_parameters["sliding_attention"].update(rope_scaling)
  121. # Set default values if not present
  122. if self.rope_parameters.get("full_attention") is None:
  123. self.rope_parameters["full_attention"] = {"rope_type": "default"}
  124. self.rope_parameters["full_attention"].setdefault(
  125. "rope_theta", kwargs.pop("global_rope_theta", self.default_theta["global"])
  126. )
  127. if self.rope_parameters.get("sliding_attention") is None:
  128. self.rope_parameters["sliding_attention"] = {"rope_type": "default"}
  129. self.rope_parameters["sliding_attention"].setdefault(
  130. "rope_theta", kwargs.pop("local_rope_theta", self.default_theta["local"])
  131. )
  132. # Standardize and validate the correctness of rotary position embeddings parameters
  133. self.standardize_rope_params()
  134. return kwargs
  135. def to_dict(self):
  136. output = super().to_dict()
  137. output.pop("reference_compile", None)
  138. return output
  139. @property
  140. def sliding_window(self):
  141. """Half-window size: `local_attention` is the total window, so we divide by 2."""
  142. return self.local_attention // 2
  143. @sliding_window.setter
  144. def sliding_window(self, value):
  145. """Set sliding_window by updating local_attention to 2 * value."""
  146. self.local_attention = value * 2
  147. __all__ = ["ModernBertConfig"]