configuration_gemma3.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
  2. # This file was automatically generated from src/transformers/models/gemma3/modular_gemma3.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_gemma3.py file directly. One of our CI enforces this.
  6. # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
  7. # Copyright 2025 Google Inc. 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 Any
  22. from huggingface_hub.dataclasses import strict
  23. from ...configuration_utils import PreTrainedConfig
  24. from ...utils import auto_docstring, logging
  25. from ..siglip import SiglipVisionConfig
  26. logger = logging.get_logger(__name__)
  27. @auto_docstring(checkpoint="google/gemma-3-4b-it")
  28. @strict
  29. class Gemma3TextConfig(PreTrainedConfig):
  30. r"""
  31. query_pre_attn_scalar (`float`, *optional*, defaults to 256):
  32. scaling factor used on the attention scores
  33. final_logit_softcapping (`float`, *optional*):
  34. Scaling factor when applying tanh softcapping on the logits.
  35. attn_logit_softcapping (`float`, *optional*):
  36. Scaling factor when applying tanh softcapping on the attention scores.
  37. use_bidirectional_attention (`bool`, *optional*, defaults to `False`):
  38. If True, the model will attend to all text tokens instead of using a causal mask. This does not change
  39. behavior for vision tokens.
  40. ```python
  41. >>> from transformers import Gemma3TextModel, Gemma3TextConfig
  42. >>> # Initializing a Gemma3Text gemma3_text-7b style configuration
  43. >>> configuration = Gemma3TextConfig()
  44. >>> # Initializing a model from the gemma3_text-7b style configuration
  45. >>> model = Gemma3TextModel(configuration)
  46. >>> # Accessing the model configuration
  47. >>> configuration = model.config
  48. ```
  49. """
  50. model_type = "gemma3_text"
  51. keys_to_ignore_at_inference = ["past_key_values"]
  52. base_model_tp_plan = {
  53. "layers.*.self_attn.q_proj": "colwise",
  54. "layers.*.self_attn.k_proj": "colwise",
  55. "layers.*.self_attn.v_proj": "colwise",
  56. "layers.*.self_attn.q_norm": "replicated_with_grad_allreduce",
  57. "layers.*.self_attn.k_norm": "replicated_with_grad_allreduce",
  58. "layers.*.self_attn.o_proj": "rowwise",
  59. "layers.*.mlp.gate_proj": "colwise",
  60. "layers.*.mlp.up_proj": "colwise",
  61. "layers.*.mlp.down_proj": "rowwise",
  62. }
  63. base_model_pp_plan = {
  64. "embed_tokens": (["input_ids"], ["inputs_embeds"]),
  65. "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
  66. "norm": (["hidden_states"], ["hidden_states"]),
  67. }
  68. vocab_size: int = 262_208
  69. hidden_size: int = 2304
  70. intermediate_size: int = 9216
  71. num_hidden_layers: int = 26
  72. num_attention_heads: int = 8
  73. num_key_value_heads: int = 4
  74. head_dim: int = 256
  75. hidden_activation: str = "gelu_pytorch_tanh"
  76. max_position_embeddings: int = 131_072
  77. initializer_range: float = 0.02
  78. rms_norm_eps: float = 1e-6
  79. use_cache: bool = True
  80. pad_token_id: int | None = 0
  81. eos_token_id: int | list[int] | None = 1
  82. bos_token_id: int | None = 2
  83. tie_word_embeddings: bool = True
  84. rope_parameters: dict | None = None
  85. attention_bias: bool = False
  86. attention_dropout: int | float | None = 0.0
  87. query_pre_attn_scalar: int = 256
  88. sliding_window: int | None = 4096
  89. layer_types: list[str] | None = None
  90. final_logit_softcapping: float | None = None
  91. attn_logit_softcapping: float | None = None
  92. use_bidirectional_attention: bool | None = False
  93. default_theta = {"global": 1_000_000.0, "local": 10_000.0}
  94. def __post_init__(self, **kwargs):
  95. if self.use_bidirectional_attention:
  96. self.sliding_window = (self.sliding_window // 2) + 1 # due to fa we set exclusive bounds
  97. # BC -> the pattern used to be a simple int, and it's still present in configs on the Hub
  98. self._sliding_window_pattern = kwargs.get("sliding_window_pattern", 6)
  99. if self.layer_types is None:
  100. self.layer_types = [
  101. "sliding_attention" if bool((i + 1) % self._sliding_window_pattern) else "full_attention"
  102. for i in range(self.num_hidden_layers)
  103. ]
  104. super().__post_init__(**kwargs)
  105. def validate_architecture(self):
  106. """Part of `@strict`-powered validation. Validates the architecture of the config."""
  107. if self.hidden_size % self.num_attention_heads != 0:
  108. raise ValueError(
  109. f"The hidden size ({self.hidden_size}) is not a multiple of the number of attention "
  110. f"heads ({self.num_attention_heads})."
  111. )
  112. def convert_rope_params_to_dict(self, **kwargs):
  113. rope_scaling = kwargs.pop("rope_scaling", None)
  114. # Try to set `rope_scaling` if available, otherwise use `rope_parameters`. If we find `rope_parameters`
  115. # as arg in the inputs, we can safely assume that it is in the new format. New naming used -> new format
  116. default_rope_params = {
  117. "sliding_attention": {"rope_type": "default"},
  118. "full_attention": {"rope_type": "default"},
  119. }
  120. self.rope_parameters = self.rope_parameters if self.rope_parameters is not None else default_rope_params
  121. if rope_scaling is not None:
  122. self.rope_parameters["full_attention"].update(rope_scaling)
  123. # Set default values if not present
  124. if self.rope_parameters.get("full_attention") is None:
  125. self.rope_parameters["full_attention"] = {"rope_type": "default"}
  126. self.rope_parameters["full_attention"].setdefault(
  127. "rope_theta", kwargs.pop("rope_theta", self.default_theta["global"])
  128. )
  129. if self.rope_parameters.get("sliding_attention") is None:
  130. self.rope_parameters["sliding_attention"] = {"rope_type": "default"}
  131. self.rope_parameters["sliding_attention"].setdefault(
  132. "rope_theta", kwargs.pop("rope_local_base_freq", self.default_theta["local"])
  133. )
  134. # Standardize and validate the correctness of rotary position embeddings parameters
  135. self.standardize_rope_params()
  136. return kwargs
  137. @auto_docstring(checkpoint="google/gemma-3-4b-it")
  138. @strict
  139. class Gemma3Config(PreTrainedConfig):
  140. r"""
  141. mm_tokens_per_image (`int`, *optional*, defaults to 256):
  142. The number of tokens per image embedding.
  143. boi_token_index (`int`, *optional*, defaults to 255999):
  144. The begin-of-image token index to wrap the image prompt.
  145. eoi_token_index (`int`, *optional*, defaults to 256000):
  146. The end-of-image token index to wrap the image prompt.
  147. Example:
  148. ```python
  149. >>> from transformers import Gemma3ForConditionalGeneration, Gemma3Config, SiglipVisionConfig, Gemma3TextConfig
  150. >>> # Initializing a Siglip-like vision config
  151. >>> vision_config = SiglipVisionConfig()
  152. >>> # Initializing a Gemma3 Text config
  153. >>> text_config = Gemma3TextConfig()
  154. >>> # Initializing a Gemma3 gemma-3-4b style configuration
  155. >>> configuration = Gemma3Config(vision_config, text_config)
  156. >>> # Initializing a model from the gemma-3-4b style configuration
  157. >>> model = Gemma3TextConfig(configuration)
  158. >>> # Accessing the model configuration
  159. >>> configuration = model.config
  160. ```"""
  161. model_type = "gemma3"
  162. attribute_map = {
  163. "image_token_id": "image_token_index",
  164. "boi_token_id": "boi_token_index",
  165. "eoi_token_id": "eoi_token_index",
  166. }
  167. sub_configs = {
  168. "text_config": Gemma3TextConfig,
  169. "vision_config": SiglipVisionConfig,
  170. }
  171. text_config: Gemma3TextConfig | dict[str, Any] | None = None
  172. vision_config: SiglipVisionConfig | dict[str, Any] | None = None
  173. mm_tokens_per_image: int | None = 256
  174. boi_token_index: int | None = 255_999
  175. eoi_token_index: int | None = 256_000
  176. image_token_index: int | None = 262_144
  177. initializer_range: float | None = 0.02
  178. tie_word_embeddings: bool | None = True
  179. def __post_init__(self, **kwargs):
  180. if self.text_config is None:
  181. self.text_config = Gemma3TextConfig()
  182. logger.info("text_config is None, using default Gemma3TextConfig text config.")
  183. elif isinstance(self.text_config, dict):
  184. self.text_config = Gemma3TextConfig(**self.text_config)
  185. if isinstance(self.vision_config, dict):
  186. self.vision_config = SiglipVisionConfig(**self.vision_config)
  187. elif self.vision_config is None:
  188. self.vision_config = SiglipVisionConfig()
  189. logger.info("vision_config is None, using default SiglipVisionConfig vision config.")
  190. super().__post_init__(**kwargs)
  191. __all__ = ["Gemma3Config", "Gemma3TextConfig"]