configuration_t5gemma.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
  2. # This file was automatically generated from src/transformers/models/t5gemma/modular_t5gemma.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_t5gemma.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. class T5GemmaModuleConfig(PretrainedConfig):
  25. r"""
  26. This is the configuration class to store the configuration of a [`T5GemmaModuleModel`]. It is used to instantiate an T5GemmaModule
  27. model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
  28. defaults will yield a similar configuration to that of the T5GemmaModule-7B.
  29. e.g. [google/t5_gemma_module-7b](https://huggingface.co/google/t5_gemma_module-7b)
  30. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  31. documentation from [`PretrainedConfig`] for more information.
  32. Args:
  33. vocab_size (`int`, *optional*, defaults to 256000):
  34. Vocabulary size of the T5GemmaModule model. Defines the number of different tokens that can be represented by the
  35. `inputs_ids` passed when calling [`T5GemmaModuleModel`]
  36. hidden_size (`int`, *optional*, defaults to 2304):
  37. Dimension of the hidden representations.
  38. intermediate_size (`int`, *optional*, defaults to 9216):
  39. Dimension of the MLP representations.
  40. num_hidden_layers (`int`, *optional*, defaults to 26):
  41. Number of hidden layers in the Transformer decoder.
  42. num_attention_heads (`int`, *optional*, defaults to 8):
  43. Number of attention heads for each attention layer in the Transformer decoder.
  44. num_key_value_heads (`int`, *optional*, defaults to 4):
  45. This is the number of key_value heads that should be used to implement Grouped Query Attention. If
  46. `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
  47. `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
  48. converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
  49. by meanpooling all the original heads within that group. For more details, check out [this
  50. paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to
  51. `num_attention_heads`.
  52. head_dim (`int`, *optional*, defaults to 256):
  53. The attention head dimension.
  54. hidden_activation (`str` or `function`, *optional*, defaults to `"gelu_pytorch_tanh"`):
  55. The non-linear activation function (function or string) in the decoder. Will default to `"gelu_pytorch_tanh"`
  56. if not specified. `"gelu_pytorch_tanh"` uses an approximation of the `"gelu"` activation function.
  57. max_position_embeddings (`int`, *optional*, defaults to 8192):
  58. The maximum sequence length that this model might ever be used with.
  59. initializer_range (`float`, *optional*, defaults to 0.02):
  60. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  61. rms_norm_eps (`float`, *optional*, defaults to 1e-06):
  62. The epsilon used by the rms normalization layers.
  63. use_cache (`bool`, *optional*, defaults to `True`):
  64. Whether or not the model should return the last key/values attentions (not used by all models). Only
  65. relevant if `config.is_decoder=True`.
  66. pad_token_id (`int`, *optional*, defaults to 0):
  67. Padding token id.
  68. eos_token_id (`int`, *optional*, defaults to 1):
  69. End of stream token id.
  70. bos_token_id (`int`, *optional*, defaults to 2):
  71. Beginning of stream token id.
  72. tie_word_embeddings (`bool`, *optional*, defaults to `True`):
  73. Whether to tie weight embeddings
  74. rope_theta (`float`, *optional*, defaults to 10000.0):
  75. The base period of the RoPE embeddings.
  76. attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
  77. Whether to use a bias in the query, key, value and output projection layers during self-attention.
  78. attention_dropout (`float`, *optional*, defaults to 0.0):
  79. The dropout ratio for the attention probabilities.
  80. query_pre_attn_scalar (`float`, *optional*, defaults to 256):
  81. scaling factor used on the attention scores
  82. sliding_window (`int`, *optional*, defaults to 4096):
  83. in T5GemmaModule, every other layer uses sliding window attention. This is the size of the sliding window.
  84. layer_types (`list`, *optional*):
  85. Attention pattern for each layer.
  86. final_logit_softcapping (`float`, *optional*, defaults to 30.0):
  87. scaling factor when applying tanh softcapping on the logits.
  88. attn_logit_softcapping (`float`, *optional*, defaults to 50.0):
  89. scaling factor when applying tanh softcapping on the attention scores.
  90. ```python
  91. >>> from transformers import T5GemmaModuleModel, T5GemmaModuleConfig
  92. >>> # Initializing a T5GemmaModule t5_gemma_module-7b style configuration
  93. >>> configuration = T5GemmaModuleConfig()
  94. >>> # Initializing a model from the t5_gemma_module-7b style configuration
  95. >>> model = T5GemmaModuleModel(configuration)
  96. >>> # Accessing the model configuration
  97. >>> configuration = model.config
  98. ```"""
  99. model_type = "t5_gemma_module"
  100. keys_to_ignore_at_inference = ["past_key_values"]
  101. base_model_tp_plan = {
  102. "layers.*.self_attn.q_proj": "colwise",
  103. "layers.*.self_attn.k_proj": "colwise",
  104. "layers.*.self_attn.v_proj": "colwise",
  105. "layers.*.self_attn.o_proj": "rowwise",
  106. "layers.*.mlp.gate_proj": "colwise",
  107. "layers.*.mlp.up_proj": "colwise",
  108. "layers.*.mlp.down_proj": "rowwise",
  109. }
  110. base_model_pp_plan = {
  111. "embed_tokens": (["input_ids"], ["inputs_embeds"]),
  112. "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
  113. "norm": (["hidden_states"], ["hidden_states"]),
  114. }
  115. def __init__(
  116. self,
  117. vocab_size=256000,
  118. hidden_size=2304,
  119. intermediate_size=9216,
  120. num_hidden_layers=26,
  121. num_attention_heads=8,
  122. num_key_value_heads=4,
  123. head_dim=256,
  124. hidden_activation="gelu_pytorch_tanh",
  125. max_position_embeddings=8192,
  126. initializer_range=0.02,
  127. rms_norm_eps=1e-6,
  128. use_cache=True,
  129. pad_token_id=0,
  130. eos_token_id=1,
  131. bos_token_id=2,
  132. tie_word_embeddings=True,
  133. rope_theta=10000.0,
  134. attention_bias=False,
  135. attention_dropout=0.0,
  136. query_pre_attn_scalar=256,
  137. sliding_window=4096,
  138. layer_types=None,
  139. final_logit_softcapping=30.0,
  140. attn_logit_softcapping=50.0,
  141. **kwargs,
  142. ):
  143. super().__init__(
  144. pad_token_id=pad_token_id,
  145. bos_token_id=bos_token_id,
  146. eos_token_id=eos_token_id,
  147. tie_word_embeddings=tie_word_embeddings,
  148. **kwargs,
  149. )
  150. self.vocab_size = vocab_size
  151. self.max_position_embeddings = max_position_embeddings
  152. self.hidden_size = hidden_size
  153. self.intermediate_size = intermediate_size
  154. self.num_hidden_layers = num_hidden_layers
  155. self.num_attention_heads = num_attention_heads
  156. self.head_dim = head_dim
  157. self.num_key_value_heads = num_key_value_heads
  158. self.initializer_range = initializer_range
  159. self.rms_norm_eps = rms_norm_eps
  160. self.use_cache = use_cache
  161. self.rope_theta = rope_theta
  162. self.attention_bias = attention_bias
  163. self.attention_dropout = attention_dropout
  164. self.hidden_activation = hidden_activation
  165. self.query_pre_attn_scalar = query_pre_attn_scalar
  166. self.sliding_window = sliding_window
  167. self.final_logit_softcapping = final_logit_softcapping
  168. self.attn_logit_softcapping = attn_logit_softcapping
  169. self.layer_types = layer_types
  170. if self.layer_types is None:
  171. self.layer_types = [
  172. "sliding_attention" if bool((i + 1) % 2) else "full_attention" for i in range(self.num_hidden_layers)
  173. ]
  174. layer_type_validation(self.layer_types, self.num_hidden_layers)
  175. class T5GemmaConfig(PretrainedConfig):
  176. r"""
  177. This is the configuration class to store the configuration of a [`T5GemmaModel`]. It is used to instantiate an T5Gemma
  178. model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
  179. defaults will yield a similar configuration to a hypothetical balanced Gemma2 encoder-decoder model.
  180. e.g. [google/t5gemma-2b-2b-prefixlm-it](https://huggingface.co/google/t5gemma-2b-2b-prefixlm-it)
  181. ```python
  182. >>> from transformers import T5GemmaConfig, T5GemmaModel
  183. >>> t5gemma_config = T5GemmaConfig.from_pretrained("google/t5gemma-2b-2b-prefixlm-it")
  184. >>> model = T5GemmaModel(t5gemma_config)
  185. ```
  186. Configuration objects inherit from [PretrainedConfig] and can be used to control the model outputs. Read the
  187. documentation from [PretrainedConfig] for more information.
  188. Args:
  189. encoder (`Union[T5GemmaModuleConfig, dict]`, optional, *optional*):
  190. Configuration for the encoder.
  191. decoder (`Union[T5GemmaModuleConfig, dict]`, optional, *optional*):
  192. Configuration for the decoder.
  193. is_encoder_decoder (bool, optional, *optional*, defaults to `True`):
  194. Whether the model is used as an encoder/decoder or not.
  195. dropout_rate (`float`, *optional*, defaults to 0.0):
  196. The ratio for all dropout layers (following T5).
  197. classifier_dropout_rate (`float`, *optional*, defaults to 0.0):
  198. The dropout ratio for classifier (following T5).
  199. attention_dropout (`float`, *optional*, defaults to 0.0):
  200. The dropout ratio for attention.
  201. tie_word_embeddings (`bool`, *optional*, defaults to `True`):
  202. Whether tie input and output embeddings.
  203. vocab_size (`int`, *optional*, defaults to 256000):
  204. Vocabulary size of the T5Gemma model (the same as Gemma 2).
  205. kwargs (additional keyword arguments, optional, *optional*):
  206. Will be passed to the PretrainedConfig base class.
  207. """
  208. model_type = "t5gemma"
  209. keys_to_ignore_at_inference = ["past_key_values"]
  210. base_model_tp_plan = {
  211. # encoder
  212. "encoder.layers.*.self_attn.q_proj": "colwise",
  213. "encoder.layers.*.self_attn.k_proj": "colwise",
  214. "encoder.layers.*.self_attn.v_proj": "colwise",
  215. "encoder.layers.*.self_attn.o_proj": "rowwise",
  216. "encoder.layers.*.mlp.gate_proj": "colwise",
  217. "encoder.layers.*.mlp.up_proj": "colwise",
  218. "encoder.layers.*.mlp.down_proj": "rowwise",
  219. # decoder
  220. "decoder.layers.*.self_attn.q_proj": "colwise",
  221. "decoder.layers.*.self_attn.k_proj": "colwise",
  222. "decoder.layers.*.self_attn.v_proj": "colwise",
  223. "decoder.layers.*.self_attn.o_proj": "rowwise",
  224. "decoder.layers.*.cross_attn.q_proj": "colwise",
  225. "decoder.layers.*.cross_attn.k_proj": "colwise",
  226. "decoder.layers.*.cross_attn.v_proj": "colwise",
  227. "decoder.layers.*.cross_attn.o_proj": "rowwise",
  228. "decoder.layers.*.mlp.gate_proj": "colwise",
  229. "decoder.layers.*.mlp.up_proj": "colwise",
  230. "decoder.layers.*.mlp.down_proj": "rowwise",
  231. }
  232. base_model_pp_plan = {
  233. # encoder
  234. "encoder.embed_tokens": (["input_ids"], ["inputs_embeds"]),
  235. "encoder.layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
  236. "encoder.norm": (["hidden_states"], ["hidden_states"]),
  237. # decoder
  238. "decoder.embed_tokens": (["input_ids"], ["inputs_embeds"]),
  239. "decoder.layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
  240. "decoder.norm": (["hidden_states"], ["hidden_states"]),
  241. }
  242. def __init__(
  243. self,
  244. encoder: Optional[Union[T5GemmaModuleConfig, dict[Any, Any]]] = None,
  245. decoder: Optional[Union[T5GemmaModuleConfig, dict[Any, Any]]] = None,
  246. is_encoder_decoder: bool = True,
  247. dropout_rate: float = 0.0,
  248. classifier_dropout_rate: float = 0.0,
  249. attention_dropout: float = 0.0,
  250. tie_word_embeddings: bool = True,
  251. vocab_size: int = 256000,
  252. **kwargs,
  253. ):
  254. if isinstance(encoder, dict):
  255. encoder = T5GemmaModuleConfig(**encoder)
  256. elif encoder is None:
  257. encoder = T5GemmaModuleConfig()
  258. else:
  259. assert isinstance(encoder, T5GemmaModuleConfig), f"{type(encoder)} is not supported."
  260. if isinstance(decoder, dict):
  261. decoder = T5GemmaModuleConfig(**decoder)
  262. elif decoder is None:
  263. decoder = encoder
  264. else:
  265. assert isinstance(decoder, T5GemmaModuleConfig), f"{type(decoder)} is not supported."
  266. encoder = T5GemmaModuleConfig(**encoder.to_dict())
  267. decoder = T5GemmaModuleConfig(**decoder.to_dict())
  268. encoder.is_decoder = False
  269. encoder.dropout_rate = dropout_rate
  270. encoder.attention_dropout = attention_dropout
  271. self.encoder = encoder
  272. decoder.is_decoder = True
  273. decoder.use_cache = True
  274. decoder.dropout_rate = dropout_rate
  275. decoder.attention_dropout = attention_dropout
  276. decoder.cross_attention_hidden_size = encoder.hidden_size
  277. self.decoder = decoder
  278. for special_token_key in ["bos_token_id", "pad_token_id", "eos_token_id"]:
  279. if special_token_key not in kwargs:
  280. kwargs[special_token_key] = getattr(decoder, special_token_key)
  281. super().__init__(**kwargs)
  282. self.is_encoder_decoder = is_encoder_decoder
  283. self.use_cache = kwargs.get("use_cache", decoder.use_cache)
  284. self.initializer_range = kwargs.get("initializer_range", decoder.initializer_range)
  285. self.dropout_rate = dropout_rate
  286. self.attention_dropout = attention_dropout
  287. self.classifier_dropout_rate = classifier_dropout_rate
  288. self.tie_word_embeddings = tie_word_embeddings
  289. # Used in pipeline generation.
  290. self.vocab_size = vocab_size
  291. def __setattr__(self, key, value):
  292. shared_attr_with_submodules = [
  293. "output_hidden_states",
  294. "output_attentions",
  295. "_attn_implementation",
  296. "dropout_rate",
  297. "attention_dropout",
  298. "vocab_size",
  299. ]
  300. if key in shared_attr_with_submodules:
  301. setattr(self.encoder, key, value)
  302. setattr(self.decoder, key, value)
  303. super().__setattr__(key, value)
  304. __all__ = ["T5GemmaConfig", "T5GemmaModuleConfig"]