configuration_t5gemma2.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
  2. # This file was automatically generated from src/transformers/models/t5gemma2/modular_t5gemma2.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_t5gemma2.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/t5gemma-2-270m-270m")
  28. @strict
  29. class T5Gemma2TextConfig(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. """
  38. model_type = "t5gemma2_text"
  39. keys_to_ignore_at_inference = ["past_key_values"]
  40. base_model_tp_plan = {
  41. "layers.*.self_attn.q_proj": "colwise",
  42. "layers.*.self_attn.k_proj": "colwise",
  43. "layers.*.self_attn.v_proj": "colwise",
  44. "layers.*.self_attn.q_norm": "replicated_with_grad_allreduce",
  45. "layers.*.self_attn.k_norm": "replicated_with_grad_allreduce",
  46. "layers.*.self_attn.o_proj": "rowwise",
  47. "layers.*.mlp.gate_proj": "colwise",
  48. "layers.*.mlp.up_proj": "colwise",
  49. "layers.*.mlp.down_proj": "rowwise",
  50. }
  51. base_model_pp_plan = {
  52. "embed_tokens": (["input_ids"], ["inputs_embeds"]),
  53. "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
  54. "norm": (["hidden_states"], ["hidden_states"]),
  55. }
  56. vocab_size: int = 262_208
  57. hidden_size: int = 2304
  58. intermediate_size: int = 9216
  59. num_hidden_layers: int = 26
  60. num_attention_heads: int = 8
  61. num_key_value_heads: int = 4
  62. head_dim: int = 256
  63. hidden_activation: str = "gelu_pytorch_tanh"
  64. max_position_embeddings: int = 131_072
  65. initializer_range: float = 0.02
  66. rms_norm_eps: float = 1e-6
  67. use_cache: bool = True
  68. pad_token_id: int | None = 0
  69. eos_token_id: int | list[int] | None = 1
  70. bos_token_id: int | None = 2
  71. tie_word_embeddings: bool = True
  72. rope_parameters: dict | None = None
  73. attention_bias: bool = False
  74. attention_dropout: int | float | None = 0.0
  75. query_pre_attn_scalar: int = 256
  76. sliding_window: int | None = 4096
  77. layer_types: list[str] | None = None
  78. final_logit_softcapping: float | None = None
  79. attn_logit_softcapping: float | None = None
  80. default_theta = {"global": 1_000_000.0, "local": 10_000.0}
  81. def __post_init__(self, **kwargs):
  82. # BC -> the pattern used to be a simple int, and it's still present in configs on the Hub
  83. _sliding_window_pattern = kwargs.pop("sliding_window_pattern", 6)
  84. if self.layer_types is None:
  85. self.layer_types = [
  86. "sliding_attention" if bool((i + 1) % _sliding_window_pattern) else "full_attention"
  87. for i in range(self.num_hidden_layers)
  88. ]
  89. super().__post_init__(**kwargs)
  90. def validate_architecture(self):
  91. """Part of `@strict`-powered validation. Validates the architecture of the config."""
  92. if self.hidden_size % self.num_attention_heads != 0:
  93. raise ValueError(
  94. f"The hidden size ({self.hidden_size}) is not a multiple of the number of attention "
  95. f"heads ({self.num_attention_heads})."
  96. )
  97. def convert_rope_params_to_dict(self, **kwargs):
  98. rope_scaling = kwargs.pop("rope_scaling", None)
  99. # Try to set `rope_scaling` if available, otherwise use `rope_parameters`. If we find `rope_parameters`
  100. # as arg in the inputs, we can safely assume that it is in the new format. New naming used -> new format
  101. default_rope_params = {
  102. "sliding_attention": {"rope_type": "default"},
  103. "full_attention": {"rope_type": "default"},
  104. }
  105. self.rope_parameters = self.rope_parameters if self.rope_parameters is not None else default_rope_params
  106. if rope_scaling is not None:
  107. self.rope_parameters["full_attention"].update(rope_scaling)
  108. # Set default values if not present
  109. if self.rope_parameters.get("full_attention") is None:
  110. self.rope_parameters["full_attention"] = {"rope_type": "default"}
  111. self.rope_parameters["full_attention"].setdefault(
  112. "rope_theta", kwargs.pop("rope_theta", self.default_theta["global"])
  113. )
  114. if self.rope_parameters.get("sliding_attention") is None:
  115. self.rope_parameters["sliding_attention"] = {"rope_type": "default"}
  116. self.rope_parameters["sliding_attention"].setdefault(
  117. "rope_theta", kwargs.pop("rope_local_base_freq", self.default_theta["local"])
  118. )
  119. # Standardize and validate the correctness of rotary position embeddings parameters
  120. self.standardize_rope_params()
  121. return kwargs
  122. @auto_docstring(checkpoint="google/t5gemma-2-270m-270m")
  123. @strict
  124. class T5Gemma2EncoderConfig(PreTrainedConfig):
  125. r"""
  126. mm_tokens_per_image (`int`, *optional*, defaults to 256):
  127. The number of tokens per image embedding.
  128. boi_token_index (`int`, *optional*, defaults to 255999):
  129. The begin-of-image token index to wrap the image prompt.
  130. eoi_token_index (`int`, *optional*, defaults to 256000):
  131. The end-of-image token index to wrap the image prompt.
  132. Example:
  133. ```python
  134. >>> from transformers import T5Gemma2EncoderForConditionalGeneration, T5Gemma2EncoderConfig, SiglipVisionConfig, T5Gemma2EncoderTextConfig
  135. >>> # Initializing a Siglip-like vision config
  136. >>> vision_config = SiglipVisionConfig()
  137. >>> # Initializing a T5Gemma2Encoder Text config
  138. >>> text_config = T5Gemma2EncoderTextConfig()
  139. >>> # Initializing a T5Gemma2Encoder gemma-3-4b style configuration
  140. >>> configuration = T5Gemma2EncoderConfig(vision_config, text_config)
  141. >>> # Initializing a model from the gemma-3-4b style configuration
  142. >>> model = T5Gemma2EncoderTextConfig(configuration)
  143. >>> # Accessing the model configuration
  144. >>> configuration = model.config
  145. ```"""
  146. model_type = "t5gemma2_encoder"
  147. attribute_map = {
  148. "image_token_id": "image_token_index",
  149. "boi_token_id": "boi_token_index",
  150. "eoi_token_id": "eoi_token_index",
  151. }
  152. sub_configs = {
  153. "text_config": T5Gemma2TextConfig,
  154. "vision_config": SiglipVisionConfig,
  155. }
  156. text_config: T5Gemma2TextConfig | dict[str, Any] | None = None
  157. vision_config: SiglipVisionConfig | dict[str, Any] | None = None
  158. mm_tokens_per_image: int | None = 256
  159. boi_token_index: int | None = 255_999
  160. eoi_token_index: int | None = 256_000
  161. image_token_index: int | None = 262_144
  162. initializer_range: float | None = 0.02
  163. tie_word_embeddings: bool | None = True
  164. def __post_init__(self, **kwargs):
  165. if self.text_config is None:
  166. self.text_config = T5Gemma2TextConfig()
  167. logger.info("text_config is None, using default T5Gemma2EncoderTextConfig text config.")
  168. elif isinstance(self.text_config, dict):
  169. self.text_config = T5Gemma2TextConfig(**self.text_config)
  170. if isinstance(self.vision_config, dict):
  171. self.vision_config = SiglipVisionConfig(**self.vision_config)
  172. elif self.vision_config is None:
  173. self.vision_config = SiglipVisionConfig()
  174. logger.info("vision_config is None, using default SiglipVisionConfig vision config.")
  175. super().__post_init__(**kwargs)
  176. @auto_docstring(checkpoint="google/t5gemma-2-270m-270m")
  177. @strict
  178. class T5Gemma2DecoderConfig(PreTrainedConfig):
  179. r"""
  180. query_pre_attn_scalar (`float`, *optional*, defaults to 256):
  181. Scaling factor used on the attention scores
  182. final_logit_softcapping (`float`, *optional*):
  183. Scaling factor when applying tanh softcapping on the logits.
  184. attn_logit_softcapping (`float`, *optional*):
  185. Scaling factor when applying tanh softcapping on the attention scores.
  186. """
  187. model_type = "t5gemma2_decoder"
  188. keys_to_ignore_at_inference = ["past_key_values"]
  189. base_model_tp_plan = {
  190. "layers.*.self_attn.q_proj": "colwise",
  191. "layers.*.self_attn.k_proj": "colwise",
  192. "layers.*.self_attn.v_proj": "colwise",
  193. "layers.*.self_attn.q_norm": "replicated_with_grad_allreduce",
  194. "layers.*.self_attn.k_norm": "replicated_with_grad_allreduce",
  195. "layers.*.self_attn.o_proj": "rowwise",
  196. "layers.*.mlp.gate_proj": "colwise",
  197. "layers.*.mlp.up_proj": "colwise",
  198. "layers.*.mlp.down_proj": "rowwise",
  199. }
  200. base_model_pp_plan = {
  201. "embed_tokens": (["input_ids"], ["inputs_embeds"]),
  202. "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
  203. "norm": (["hidden_states"], ["hidden_states"]),
  204. }
  205. vocab_size: int = 262_208
  206. hidden_size: int = 2304
  207. intermediate_size: int = 9216
  208. num_hidden_layers: int = 26
  209. num_attention_heads: int = 8
  210. num_key_value_heads: int = 4
  211. head_dim: int = 256
  212. hidden_activation: str = "gelu_pytorch_tanh"
  213. max_position_embeddings: int = 131_072
  214. initializer_range: float = 0.02
  215. rms_norm_eps: float = 1e-6
  216. use_cache: bool = True
  217. pad_token_id: int | None = 0
  218. eos_token_id: int | list[int] | None = 1
  219. bos_token_id: int | None = 2
  220. tie_word_embeddings: bool = True
  221. rope_parameters: dict | None = None
  222. attention_bias: bool = False
  223. attention_dropout: int | float | None = 0.0
  224. query_pre_attn_scalar: int = 256
  225. sliding_window: int | None = 4096
  226. layer_types: list[str] | None = None
  227. final_logit_softcapping: float | None = None
  228. attn_logit_softcapping: float | None = None
  229. default_theta = {"global": 1_000_000.0, "local": 10_000.0}
  230. def __post_init__(self, **kwargs):
  231. # BC -> the pattern used to be a simple int, and it's still present in configs on the Hub
  232. _sliding_window_pattern = kwargs.pop("sliding_window_pattern", 6)
  233. if self.layer_types is None:
  234. self.layer_types = [
  235. "sliding_attention" if bool((i + 1) % _sliding_window_pattern) else "full_attention"
  236. for i in range(self.num_hidden_layers)
  237. ]
  238. super().__post_init__(**kwargs)
  239. def validate_architecture(self):
  240. """Part of `@strict`-powered validation. Validates the architecture of the config."""
  241. if self.hidden_size % self.num_attention_heads != 0:
  242. raise ValueError(
  243. f"The hidden size ({self.hidden_size}) is not a multiple of the number of attention "
  244. f"heads ({self.num_attention_heads})."
  245. )
  246. def convert_rope_params_to_dict(self, **kwargs):
  247. rope_scaling = kwargs.pop("rope_scaling", None)
  248. # Try to set `rope_scaling` if available, otherwise use `rope_parameters`. If we find `rope_parameters`
  249. # as arg in the inputs, we can safely assume that it is in the new format. New naming used -> new format
  250. default_rope_params = {
  251. "sliding_attention": {"rope_type": "default"},
  252. "full_attention": {"rope_type": "default"},
  253. }
  254. self.rope_parameters = self.rope_parameters if self.rope_parameters is not None else default_rope_params
  255. if rope_scaling is not None:
  256. self.rope_parameters["full_attention"].update(rope_scaling)
  257. # Set default values if not present
  258. if self.rope_parameters.get("full_attention") is None:
  259. self.rope_parameters["full_attention"] = {"rope_type": "default"}
  260. self.rope_parameters["full_attention"].setdefault(
  261. "rope_theta", kwargs.pop("rope_theta", self.default_theta["global"])
  262. )
  263. if self.rope_parameters.get("sliding_attention") is None:
  264. self.rope_parameters["sliding_attention"] = {"rope_type": "default"}
  265. self.rope_parameters["sliding_attention"].setdefault(
  266. "rope_theta", kwargs.pop("rope_local_base_freq", self.default_theta["local"])
  267. )
  268. # Standardize and validate the correctness of rotary position embeddings parameters
  269. self.standardize_rope_params()
  270. return kwargs
  271. @auto_docstring(checkpoint="google/t5gemma-2-270m-270m")
  272. @strict
  273. class T5Gemma2Config(PreTrainedConfig):
  274. r"""
  275. encoder (`Union[T5Gemma2EncoderConfig, dict]`, optional, *optional*):
  276. Configuration for the encoder.
  277. decoder (`Union[T5Gemma2DecoderConfig, dict]`, optional, *optional*):
  278. Configuration for the decoder.
  279. eoi_token_index (`int`, *optional*):
  280. The end-of-image token index to wrap the image prompt. Will be same as
  281. `self.encoder.eoi_token_index`
  282. ```python
  283. >>> from transformers import T5Gemma2Config, T5Gemma2Model
  284. >>> t5gemma2_config = T5Gemma2Config.from_pretrained("google/t5gemma-270m-270m")
  285. >>> model = T5Gemma2Model(t5gemma2_config)
  286. ```
  287. """
  288. model_type = "t5gemma2"
  289. keys_to_ignore_at_inference = ["past_key_values"]
  290. sub_configs = {
  291. "encoder": T5Gemma2EncoderConfig,
  292. "decoder": T5Gemma2DecoderConfig,
  293. }
  294. attribute_map = {
  295. "image_token_id": "image_token_index",
  296. "eoi_token_id": "eoi_token_index",
  297. }
  298. encoder: T5Gemma2EncoderConfig | dict[str, Any] | None = None
  299. decoder: T5Gemma2DecoderConfig | dict[str, Any] | None = None
  300. is_encoder_decoder: bool = True
  301. dropout_rate: float | int = 0.0
  302. attention_dropout: float | int = 0.0
  303. classifier_dropout_rate: float | int = 0.0
  304. initializer_range: float = 0.02
  305. image_token_index: int = 256_001
  306. eoi_token_index: int | None = None
  307. tie_word_embeddings: bool = True
  308. def __post_init__(self, **kwargs):
  309. if isinstance(self.encoder, dict):
  310. self.encoder = T5Gemma2EncoderConfig(**self.encoder)
  311. elif self.encoder is None:
  312. self.encoder = T5Gemma2EncoderConfig()
  313. logger.info("encoder is None, using default T5Gemma2EncoderConfig encoder config.")
  314. if isinstance(self.decoder, dict):
  315. self.decoder = T5Gemma2DecoderConfig(**self.decoder)
  316. elif self.decoder is None:
  317. self.decoder = T5Gemma2DecoderConfig()
  318. logger.info("decoder is None, using default T5Gemma2DecoderConfig decoder config.")
  319. self.encoder.text_config.dropout_rate = self.dropout_rate
  320. self.encoder.text_config.attention_dropout = self.attention_dropout
  321. self.encoder.vision_config.attention_dropout = self.attention_dropout
  322. self.encoder.image_token_index = self.image_token_index
  323. self.decoder.dropout_rate = self.dropout_rate
  324. self.decoder.attention_dropout = self.attention_dropout
  325. self.eoi_token_index = self.encoder.eoi_token_index
  326. for special_token_key in ["bos_token_id", "pad_token_id", "eos_token_id", "vocab_size"]:
  327. if special_token_key not in kwargs:
  328. kwargs[special_token_key] = getattr(self.decoder, special_token_key)
  329. super().__post_init__(**kwargs)
  330. def validate_architecture(self):
  331. """Part of `@strict`-powered validation. Validates the architecture of the config."""
  332. if self.encoder.text_config.hidden_size != self.decoder.hidden_size:
  333. raise ValueError(
  334. "Imbalanced encoder-decoder is not supported in T5Gemma2: "
  335. f"encoder ({self.encoder.text_config.hidden_size}) vs decoder ({self.decoder.hidden_size})."
  336. )
  337. if not self.is_encoder_decoder:
  338. raise ValueError("T5Gemma2Model only support encoder-decoder modeling.")
  339. if self.encoder.text_config.vocab_size != self.decoder.vocab_size:
  340. raise ValueError(
  341. "Imbalanced encoder-decoder vocabulary size is not supported in T5Gemma2: "
  342. f"encoder ({self.encoder.text_config.vocab_size}) vs decoder ({self.decoder.vocab_size})."
  343. )
  344. __all__ = ["T5Gemma2Config", "T5Gemma2TextConfig", "T5Gemma2EncoderConfig", "T5Gemma2DecoderConfig"]