configuration_gemma3.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  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. # coding=utf-8
  8. # Copyright 2025 Google Inc. HuggingFace Inc. team. All rights reserved.
  9. #
  10. #
  11. # Licensed under the Apache License, Version 2.0 (the "License");
  12. # you may not use this file except in compliance with the License.
  13. # You may obtain a copy of the License at
  14. #
  15. # http://www.apache.org/licenses/LICENSE-2.0
  16. #
  17. # Unless required by applicable law or agreed to in writing, software
  18. # distributed under the License is distributed on an "AS IS" BASIS,
  19. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20. # See the License for the specific language governing permissions and
  21. # limitations under the License.
  22. from typing import Any, Optional, Union
  23. from ...configuration_utils import PretrainedConfig, layer_type_validation
  24. from ...modeling_rope_utils import rope_config_validation
  25. from ...utils import logging
  26. from ..siglip import SiglipVisionConfig
  27. logger = logging.get_logger(__name__)
  28. class Gemma3TextConfig(PretrainedConfig):
  29. r"""
  30. This is the configuration class to store the configuration of a [`Gemma3TextModel`]. It is used to instantiate an Gemma3Text
  31. model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
  32. defaults will yield a similar configuration to that of the Gemma3Text-7B.
  33. e.g. [google/gemma3_text-7b](https://huggingface.co/google/gemma3_text-7b)
  34. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  35. documentation from [`PretrainedConfig`] for more information.
  36. Args:
  37. vocab_size (`int`, *optional*, defaults to 262208):
  38. Vocabulary size of the Gemma3Text model. Defines the number of different tokens that can be represented by the
  39. `inputs_ids` passed when calling [`Gemma3TextModel`]
  40. hidden_size (`int`, *optional*, defaults to 2304):
  41. Dimension of the hidden representations.
  42. intermediate_size (`int`, *optional*, defaults to 9216):
  43. Dimension of the MLP representations.
  44. num_hidden_layers (`int`, *optional*, defaults to 26):
  45. Number of hidden layers in the Transformer decoder.
  46. num_attention_heads (`int`, *optional*, defaults to 8):
  47. Number of attention heads for each attention layer in the Transformer decoder.
  48. num_key_value_heads (`int`, *optional*, defaults to 4):
  49. This is the number of key_value heads that should be used to implement Grouped Query Attention. If
  50. `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
  51. `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
  52. converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
  53. by meanpooling all the original heads within that group. For more details, check out [this
  54. paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to
  55. `num_attention_heads`.
  56. head_dim (`int`, *optional*, defaults to 256):
  57. The attention head dimension.
  58. hidden_activation (`str` or `function`, *optional*, defaults to `"gelu_pytorch_tanh"`):
  59. The non-linear activation function (function or string) in the decoder. Will default to `"gelu_pytorch_tanh"`
  60. if not specified. `"gelu_pytorch_tanh"` uses an approximation of the `"gelu"` activation function.
  61. max_position_embeddings (`int`, *optional*, defaults to 131072):
  62. The maximum sequence length that this model might ever be used with.
  63. initializer_range (`float`, *optional*, defaults to 0.02):
  64. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  65. rms_norm_eps (`float`, *optional*, defaults to 1e-06):
  66. The epsilon used by the rms normalization layers.
  67. use_cache (`bool`, *optional*, defaults to `True`):
  68. Whether or not the model should return the last key/values attentions (not used by all models). Only
  69. relevant if `config.is_decoder=True`.
  70. pad_token_id (`int`, *optional*, defaults to 0):
  71. Padding token id.
  72. eos_token_id (`int`, *optional*, defaults to 1):
  73. End of stream token id.
  74. bos_token_id (`int`, *optional*, defaults to 2):
  75. Beginning of stream token id.
  76. tie_word_embeddings (`bool`, *optional*, defaults to `True`):
  77. Whether to tie weight embeddings
  78. rope_theta (`float`, *optional*, defaults to 1000000.0):
  79. The base period of the RoPE embeddings.
  80. attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
  81. Whether to use a bias in the query, key, value and output projection layers during self-attention.
  82. attention_dropout (`float`, *optional*, defaults to 0.0):
  83. The dropout ratio for the attention probabilities.
  84. query_pre_attn_scalar (`float`, *optional*, defaults to 256):
  85. Scaling factor used on the attention scores
  86. sliding_window (`int`, *optional*, defaults to 4096):
  87. In Gemma3Text, every other layer uses sliding window attention. This is the size of the sliding window.
  88. layer_types (`list`, *optional*):
  89. Attention pattern for each layer.
  90. final_logit_softcapping (`float`, *optional*):
  91. Scaling factor when applying tanh softcapping on the logits.
  92. attn_logit_softcapping (`float`, *optional*):
  93. Scaling factor when applying tanh softcapping on the attention scores.
  94. rope_scaling (`Dict`, *optional*):
  95. Dictionary containing the scaling configuration for the RoPE embeddings used in global attention. NOTE: if you apply new rope type
  96. and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
  97. accordingly.
  98. Expected contents:
  99. `rope_type` (`str`):
  100. The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
  101. 'llama3'], with 'default' being the original RoPE implementation.
  102. `factor` (`float`, *optional*):
  103. Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
  104. most scaling types, a `factor` of x will enable the model to handle sequences of length x *
  105. original maximum pre-trained length.
  106. `original_max_position_embeddings` (`int`, *optional*):
  107. Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
  108. pretraining.
  109. `attention_factor` (`float`, *optional*):
  110. Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
  111. computation. If unspecified, it defaults to value recommended by the implementation, using the
  112. `factor` field to infer the suggested value.
  113. `beta_fast` (`float`, *optional*):
  114. Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
  115. ramp function. If unspecified, it defaults to 32.
  116. `beta_slow` (`float`, *optional*):
  117. Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
  118. ramp function. If unspecified, it defaults to 1.
  119. `short_factor` (`list[float]`, *optional*):
  120. Only used with 'longrope'. The scaling factor to be applied to short contexts (<
  121. `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
  122. size divided by the number of attention heads divided by 2
  123. `long_factor` (`list[float]`, *optional*):
  124. Only used with 'longrope'. The scaling factor to be applied to long contexts (<
  125. `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
  126. size divided by the number of attention heads divided by 2
  127. `low_freq_factor` (`float`, *optional*):
  128. Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
  129. `high_freq_factor` (`float`, *optional*):
  130. Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
  131. rope_local_base_freq (float, *optional*, defaults to 10000.0):
  132. The base period of the RoPE embeddings for local attention.
  133. use_bidirectional_attention (`bool`, *optional*, defaults to `False`): If True, the model will attend to all
  134. text tokens instead of using a causal mask. This does not change behavior for vision tokens.
  135. ```python
  136. >>> from transformers import Gemma3TextModel, Gemma3TextConfig
  137. >>> # Initializing a Gemma3Text gemma3_text-7b style configuration
  138. >>> configuration = Gemma3TextConfig()
  139. >>> # Initializing a model from the gemma3_text-7b style configuration
  140. >>> model = Gemma3TextModel(configuration)
  141. >>> # Accessing the model configuration
  142. >>> configuration = model.config
  143. ```
  144. """
  145. model_type = "gemma3_text"
  146. keys_to_ignore_at_inference = ["past_key_values"]
  147. base_model_tp_plan = {
  148. "layers.*.self_attn.q_proj": "colwise",
  149. "layers.*.self_attn.k_proj": "colwise",
  150. "layers.*.self_attn.v_proj": "colwise",
  151. "layers.*.self_attn.o_proj": "rowwise",
  152. "layers.*.mlp.gate_proj": "colwise",
  153. "layers.*.mlp.up_proj": "colwise",
  154. "layers.*.mlp.down_proj": "rowwise",
  155. }
  156. base_model_pp_plan = {
  157. "embed_tokens": (["input_ids"], ["inputs_embeds"]),
  158. "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
  159. "norm": (["hidden_states"], ["hidden_states"]),
  160. }
  161. def __init__(
  162. self,
  163. vocab_size=262_208,
  164. hidden_size=2304,
  165. intermediate_size=9216,
  166. num_hidden_layers=26,
  167. num_attention_heads=8,
  168. num_key_value_heads=4,
  169. head_dim=256,
  170. hidden_activation="gelu_pytorch_tanh",
  171. max_position_embeddings=131_072,
  172. initializer_range=0.02,
  173. rms_norm_eps=1e-6,
  174. use_cache=True,
  175. pad_token_id=0,
  176. eos_token_id=1,
  177. bos_token_id=2,
  178. tie_word_embeddings=True,
  179. rope_theta=1_000_000.0,
  180. attention_bias=False,
  181. attention_dropout=0.0,
  182. query_pre_attn_scalar=256,
  183. sliding_window=4096,
  184. layer_types=None,
  185. final_logit_softcapping=None,
  186. attn_logit_softcapping=None,
  187. rope_scaling=None,
  188. rope_local_base_freq=10_000.0,
  189. use_bidirectional_attention=False,
  190. **kwargs,
  191. ):
  192. super().__init__(
  193. pad_token_id=pad_token_id,
  194. bos_token_id=bos_token_id,
  195. eos_token_id=eos_token_id,
  196. tie_word_embeddings=tie_word_embeddings,
  197. **kwargs,
  198. )
  199. self.vocab_size = vocab_size
  200. self.max_position_embeddings = max_position_embeddings
  201. self.hidden_size = hidden_size
  202. self.intermediate_size = intermediate_size
  203. self.num_hidden_layers = num_hidden_layers
  204. self.num_attention_heads = num_attention_heads
  205. self.head_dim = head_dim
  206. self.num_key_value_heads = num_key_value_heads
  207. self.initializer_range = initializer_range
  208. self.rms_norm_eps = rms_norm_eps
  209. self.use_cache = use_cache
  210. self.rope_theta = rope_theta
  211. self.attention_bias = attention_bias
  212. self.attention_dropout = attention_dropout
  213. self.hidden_activation = hidden_activation
  214. self.query_pre_attn_scalar = query_pre_attn_scalar
  215. self.sliding_window = sliding_window
  216. self.final_logit_softcapping = final_logit_softcapping
  217. self.attn_logit_softcapping = attn_logit_softcapping
  218. self.layer_types = layer_types
  219. self.use_bidirectional_attention = use_bidirectional_attention
  220. if use_bidirectional_attention:
  221. self.sliding_window = (self.sliding_window // 2) + 1 # due to fa we set exclusive bounds
  222. self.rope_local_base_freq = rope_local_base_freq
  223. self.rope_scaling = rope_scaling
  224. rope_config_validation(self)
  225. # BC -> the pattern used to be a simple int, and it's still present in configs on the Hub
  226. self._sliding_window_pattern = kwargs.get("sliding_window_pattern", 6)
  227. if self.layer_types is None:
  228. self.layer_types = [
  229. "sliding_attention" if bool((i + 1) % self._sliding_window_pattern) else "full_attention"
  230. for i in range(self.num_hidden_layers)
  231. ]
  232. layer_type_validation(self.layer_types, self.num_hidden_layers)
  233. class Gemma3Config(PretrainedConfig):
  234. r"""
  235. This is the configuration class to store the configuration of a [`Gemma3ForConditionalGeneration`]. It is used to instantiate an
  236. Gemma3ForConditionalGeneration according to the specified arguments, defining the model architecture. Instantiating a configuration
  237. with the defaults will yield a similar configuration to that of the PaliGemma-2B.
  238. e.g. [google/gemma-3-4b](https://huggingface.co/google/gemma-3-4b)
  239. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  240. documentation from [`PretrainedConfig`] for more information.
  241. Args:
  242. text_config (`Union[Gemma3TextConfig, dict]`, *optional*):
  243. The config object of the text backbone.
  244. vision_config (`Union[AutoConfig, dict]`, *optional*):
  245. Custom vision config or dict.
  246. mm_tokens_per_image (`int`, *optional*, defaults to 256):
  247. The number of tokens per image embedding.
  248. boi_token_index (`int`, *optional*, defaults to 255999):
  249. The begin-of-image token index to wrap the image prompt.
  250. eoi_token_index (`int`, *optional*, defaults to 256000):
  251. The end-of-image token index to wrap the image prompt.
  252. image_token_index (`int`, *optional*, defaults to 262144):
  253. The image token index to encode the image prompt.
  254. initializer_range (`float`, *optional*, defaults to 0.02):
  255. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  256. Example:
  257. ```python
  258. >>> from transformers import Gemma3ForConditionalGeneration, Gemma3Config, SiglipVisionConfig, Gemma3TextConfig
  259. >>> # Initializing a Siglip-like vision config
  260. >>> vision_config = SiglipVisionConfig()
  261. >>> # Initializing a Gemma3 Text config
  262. >>> text_config = Gemma3TextConfig()
  263. >>> # Initializing a Gemma3 gemma-3-4b style configuration
  264. >>> configuration = Gemma3Config(vision_config, text_config)
  265. >>> # Initializing a model from the gemma-3-4b style configuration
  266. >>> model = Gemma3TextConfig(configuration)
  267. >>> # Accessing the model configuration
  268. >>> configuration = model.config
  269. ```"""
  270. model_type = "gemma3"
  271. attribute_map = {
  272. "image_token_id": "image_token_index",
  273. "boi_token_id": "boi_token_index",
  274. "eoi_token_id": "eoi_token_index",
  275. }
  276. sub_configs = {
  277. "text_config": Gemma3TextConfig,
  278. "vision_config": SiglipVisionConfig,
  279. }
  280. def __init__(
  281. self,
  282. text_config: Optional[Union[Gemma3TextConfig, dict[str, Any]]] = None,
  283. vision_config: Optional[Union[SiglipVisionConfig, dict[str, Any]]] = None,
  284. mm_tokens_per_image: int = 256,
  285. boi_token_index: int = 255_999,
  286. eoi_token_index: int = 256_000,
  287. image_token_index: int = 262_144,
  288. initializer_range: float = 0.02,
  289. **kwargs,
  290. ):
  291. if text_config is None:
  292. text_config = Gemma3TextConfig()
  293. logger.info("text_config is None, using default Gemma3TextConfig text config.")
  294. elif isinstance(text_config, dict):
  295. text_config = Gemma3TextConfig(**text_config)
  296. if isinstance(vision_config, dict):
  297. vision_config = SiglipVisionConfig(**vision_config)
  298. elif vision_config is None:
  299. vision_config = SiglipVisionConfig()
  300. logger.info("vision_config is None, using default SiglipVisionConfig vision config.")
  301. self.text_config = text_config
  302. self.vision_config = vision_config
  303. self.mm_tokens_per_image = mm_tokens_per_image
  304. self.boi_token_index = boi_token_index
  305. self.eoi_token_index = eoi_token_index
  306. self.image_token_index = image_token_index
  307. self.initializer_range = initializer_range
  308. super().__init__(**kwargs)
  309. __all__ = ["Gemma3Config", "Gemma3TextConfig"]