modeling_vaultgemma.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  1. # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
  2. # This file was automatically generated from src/transformers/models/vaultgemma/modular_vaultgemma.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_vaultgemma.py file directly. One of our CI enforces this.
  6. # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
  7. # coding=utf-8
  8. # Copyright 2025 the HuggingFace Team. All rights reserved.
  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 Callable, Optional, Union
  22. import torch
  23. import torch.nn as nn
  24. from ...activations import ACT2FN
  25. from ...cache_utils import Cache, DynamicCache
  26. from ...generation import GenerationMixin
  27. from ...masking_utils import create_causal_mask, create_sliding_window_causal_mask
  28. from ...modeling_flash_attention_utils import FlashAttentionKwargs
  29. from ...modeling_layers import GradientCheckpointingLayer
  30. from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
  31. from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
  32. from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
  33. from ...processing_utils import Unpack
  34. from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, logging
  35. from ...utils.deprecation import deprecate_kwarg
  36. from ...utils.generic import check_model_inputs
  37. from .configuration_vaultgemma import VaultGemmaConfig
  38. logger = logging.get_logger(__name__)
  39. class VaultGemmaRMSNorm(nn.Module):
  40. def __init__(self, dim: int, eps: float = 1e-6):
  41. super().__init__()
  42. self.eps = eps
  43. self.weight = nn.Parameter(torch.zeros(dim))
  44. def _norm(self, x):
  45. return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
  46. def forward(self, x):
  47. output = self._norm(x.float())
  48. # Llama does x.to(float16) * w whilst VaultGemma is (x * w).to(float16)
  49. # See https://github.com/huggingface/transformers/pull/29402
  50. output = output * (1.0 + self.weight.float())
  51. return output.type_as(x)
  52. def extra_repr(self):
  53. return f"{tuple(self.weight.shape)}, eps={self.eps}"
  54. class VaultGemmaMLP(nn.Module):
  55. def __init__(self, config):
  56. super().__init__()
  57. self.config = config
  58. self.hidden_size = config.hidden_size
  59. self.intermediate_size = config.intermediate_size
  60. self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
  61. self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
  62. self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
  63. self.act_fn = ACT2FN[config.hidden_activation]
  64. def forward(self, x):
  65. down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
  66. return down_proj
  67. def rotate_half(x):
  68. """Rotates half the hidden dims of the input."""
  69. x1 = x[..., : x.shape[-1] // 2]
  70. x2 = x[..., x.shape[-1] // 2 :]
  71. return torch.cat((-x2, x1), dim=-1)
  72. def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
  73. """Applies Rotary Position Embedding to the query and key tensors.
  74. Args:
  75. q (`torch.Tensor`): The query tensor.
  76. k (`torch.Tensor`): The key tensor.
  77. cos (`torch.Tensor`): The cosine part of the rotary embedding.
  78. sin (`torch.Tensor`): The sine part of the rotary embedding.
  79. position_ids (`torch.Tensor`, *optional*):
  80. Deprecated and unused.
  81. unsqueeze_dim (`int`, *optional*, defaults to 1):
  82. The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
  83. sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
  84. that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
  85. k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
  86. cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
  87. the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
  88. Returns:
  89. `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
  90. """
  91. cos = cos.unsqueeze(unsqueeze_dim)
  92. sin = sin.unsqueeze(unsqueeze_dim)
  93. q_embed = (q * cos) + (rotate_half(q) * sin)
  94. k_embed = (k * cos) + (rotate_half(k) * sin)
  95. return q_embed, k_embed
  96. def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
  97. """
  98. This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
  99. num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
  100. """
  101. batch, num_key_value_heads, slen, head_dim = hidden_states.shape
  102. if n_rep == 1:
  103. return hidden_states
  104. hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
  105. return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
  106. def eager_attention_forward(
  107. module: nn.Module,
  108. query: torch.Tensor,
  109. key: torch.Tensor,
  110. value: torch.Tensor,
  111. attention_mask: Optional[torch.Tensor],
  112. dropout: float = 0.0,
  113. scaling: Optional[float] = None,
  114. softcap: Optional[float] = None,
  115. **kwargs,
  116. ) -> tuple[torch.Tensor, torch.Tensor]:
  117. if scaling is None:
  118. scaling = module.head_dim**-0.5
  119. key_states = repeat_kv(key, module.num_key_value_groups)
  120. value_states = repeat_kv(value, module.num_key_value_groups)
  121. attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
  122. if softcap is not None:
  123. attn_weights = attn_weights / softcap
  124. attn_weights = torch.tanh(attn_weights)
  125. attn_weights = attn_weights * softcap
  126. if attention_mask is not None: # no matter the length, we just slice it
  127. causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
  128. attn_weights = attn_weights + causal_mask
  129. # upcast attention to fp32
  130. attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
  131. attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
  132. attn_output = torch.matmul(attn_weights, value_states)
  133. attn_output = attn_output.transpose(1, 2).contiguous()
  134. return attn_output, attn_weights
  135. class VaultGemmaAttention(nn.Module):
  136. """Multi-headed attention from 'Attention Is All You Need' paper"""
  137. def __init__(self, config: VaultGemmaConfig, layer_idx: int):
  138. super().__init__()
  139. self.config = config
  140. self.layer_idx = layer_idx
  141. self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
  142. self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
  143. self.scaling = config.query_pre_attn_scalar**-0.5
  144. self.attention_dropout = self.config.attention_dropout
  145. self.is_causal = True
  146. self.q_proj = nn.Linear(
  147. config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
  148. )
  149. self.k_proj = nn.Linear(
  150. config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
  151. )
  152. self.v_proj = nn.Linear(
  153. config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
  154. )
  155. self.o_proj = nn.Linear(
  156. config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
  157. )
  158. self.attn_logit_softcapping = self.config.attn_logit_softcapping
  159. self.sliding_window = config.sliding_window if config.layer_types[layer_idx] == "sliding_attention" else None
  160. @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
  161. def forward(
  162. self,
  163. hidden_states: torch.Tensor,
  164. position_embeddings: tuple[torch.Tensor, torch.Tensor],
  165. attention_mask: Optional[torch.Tensor],
  166. past_key_values: Optional[Cache] = None,
  167. cache_position: Optional[torch.LongTensor] = None,
  168. **kwargs: Unpack[FlashAttentionKwargs],
  169. ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
  170. input_shape = hidden_states.shape[:-1]
  171. hidden_shape = (*input_shape, -1, self.head_dim)
  172. query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
  173. key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
  174. value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
  175. cos, sin = position_embeddings
  176. query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
  177. if past_key_values is not None:
  178. # sin and cos are specific to RoPE models; cache_position needed for the static cache
  179. cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
  180. key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
  181. attention_interface: Callable = eager_attention_forward
  182. if self.config._attn_implementation != "eager":
  183. attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
  184. attn_output, attn_weights = attention_interface(
  185. self,
  186. query_states,
  187. key_states,
  188. value_states,
  189. attention_mask,
  190. dropout=self.attention_dropout if self.training else 0.0,
  191. scaling=self.scaling,
  192. sliding_window=self.sliding_window,
  193. softcap=self.attn_logit_softcapping,
  194. **kwargs,
  195. )
  196. attn_output = attn_output.reshape(*input_shape, -1).contiguous()
  197. attn_output = self.o_proj(attn_output)
  198. return attn_output, attn_weights
  199. class VaultGemmaDecoderLayer(GradientCheckpointingLayer):
  200. def __init__(self, config: VaultGemmaConfig, layer_idx: int):
  201. super().__init__()
  202. self.hidden_size = config.hidden_size
  203. self.config = config
  204. self.attention_type = config.layer_types[layer_idx]
  205. self.self_attn = VaultGemmaAttention(config=config, layer_idx=layer_idx)
  206. self.mlp = VaultGemmaMLP(config)
  207. self.input_layernorm = VaultGemmaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  208. self.pre_feedforward_layernorm = VaultGemmaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  209. @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
  210. def forward(
  211. self,
  212. hidden_states: torch.Tensor,
  213. position_embeddings: tuple[torch.Tensor, torch.Tensor],
  214. attention_mask: Optional[torch.Tensor] = None,
  215. position_ids: Optional[torch.LongTensor] = None,
  216. past_key_values: Optional[Cache] = None,
  217. output_attentions: Optional[bool] = False,
  218. use_cache: Optional[bool] = False,
  219. cache_position: Optional[torch.LongTensor] = None,
  220. **kwargs,
  221. ) -> tuple[torch.FloatTensor, Optional[tuple[torch.FloatTensor, torch.FloatTensor]]]:
  222. residual = hidden_states
  223. hidden_states = self.input_layernorm(hidden_states)
  224. # Self Attention
  225. hidden_states, self_attn_weights = self.self_attn(
  226. hidden_states=hidden_states,
  227. position_embeddings=position_embeddings,
  228. attention_mask=attention_mask,
  229. position_ids=position_ids,
  230. past_key_values=past_key_values,
  231. output_attentions=output_attentions,
  232. use_cache=use_cache,
  233. cache_position=cache_position,
  234. **kwargs,
  235. )
  236. hidden_states = residual + hidden_states
  237. residual = hidden_states
  238. hidden_states = self.pre_feedforward_layernorm(hidden_states)
  239. hidden_states = self.mlp(hidden_states)
  240. hidden_states = residual + hidden_states
  241. outputs = (hidden_states,)
  242. if output_attentions:
  243. outputs += (self_attn_weights,)
  244. return outputs
  245. class VaultGemmaRotaryEmbedding(nn.Module):
  246. inv_freq: torch.Tensor # fix linting for `register_buffer`
  247. def __init__(self, config: VaultGemmaConfig, device=None):
  248. super().__init__()
  249. # BC: "rope_type" was originally "type"
  250. if hasattr(config, "rope_scaling") and isinstance(config.rope_scaling, dict):
  251. self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
  252. else:
  253. self.rope_type = "default"
  254. self.max_seq_len_cached = config.max_position_embeddings
  255. self.original_max_seq_len = config.max_position_embeddings
  256. self.config = config
  257. self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
  258. inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
  259. self.register_buffer("inv_freq", inv_freq, persistent=False)
  260. self.original_inv_freq = self.inv_freq
  261. @torch.no_grad()
  262. @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
  263. def forward(self, x, position_ids):
  264. inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
  265. position_ids_expanded = position_ids[:, None, :].float()
  266. device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
  267. with torch.autocast(device_type=device_type, enabled=False): # Force float32
  268. freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
  269. emb = torch.cat((freqs, freqs), dim=-1)
  270. cos = emb.cos() * self.attention_scaling
  271. sin = emb.sin() * self.attention_scaling
  272. return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
  273. @auto_docstring
  274. class VaultGemmaPreTrainedModel(PreTrainedModel):
  275. config: VaultGemmaConfig
  276. base_model_prefix = "model"
  277. supports_gradient_checkpointing = True
  278. _no_split_modules = ["VaultGemmaDecoderLayer"]
  279. _skip_keys_device_placement = ["past_key_values"]
  280. _supports_flash_attn = True
  281. _supports_sdpa = True
  282. _supports_flex_attn = True
  283. _can_compile_fullgraph = True
  284. _supports_attention_backend = True
  285. _can_record_outputs = {
  286. "hidden_states": VaultGemmaDecoderLayer,
  287. "attentions": VaultGemmaAttention,
  288. }
  289. def _init_weights(self, module):
  290. super()._init_weights(module)
  291. # We initialize with 0s to be 1 centered as the RMSNorm here does (1 + weight)
  292. if "RMSNorm" in module.__class__.__name__:
  293. module.weight.data.zero_()
  294. @auto_docstring
  295. class VaultGemmaModel(VaultGemmaPreTrainedModel):
  296. def __init__(self, config: VaultGemmaConfig):
  297. super().__init__(config)
  298. self.padding_idx = config.pad_token_id
  299. self.vocab_size = config.vocab_size
  300. self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
  301. self.layers = nn.ModuleList(
  302. [VaultGemmaDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
  303. )
  304. self.norm = VaultGemmaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  305. self.rotary_emb = VaultGemmaRotaryEmbedding(config=config)
  306. self.gradient_checkpointing = False
  307. # Initialize weights and apply final processing
  308. self.post_init()
  309. @check_model_inputs()
  310. @auto_docstring
  311. def forward(
  312. self,
  313. input_ids: Optional[torch.LongTensor] = None,
  314. attention_mask: Optional[torch.Tensor] = None,
  315. position_ids: Optional[torch.LongTensor] = None,
  316. past_key_values: Optional[Cache] = None,
  317. inputs_embeds: Optional[torch.FloatTensor] = None,
  318. use_cache: Optional[bool] = None,
  319. output_attentions: Optional[bool] = None,
  320. output_hidden_states: Optional[bool] = None,
  321. cache_position: Optional[torch.LongTensor] = None,
  322. **kwargs: Unpack[TransformersKwargs],
  323. ) -> BaseModelOutputWithPast:
  324. output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
  325. output_hidden_states = (
  326. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  327. )
  328. use_cache = use_cache if use_cache is not None else self.config.use_cache
  329. if (input_ids is None) ^ (inputs_embeds is not None):
  330. raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
  331. if self.gradient_checkpointing and self.training and use_cache:
  332. logger.warning_once(
  333. "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
  334. )
  335. use_cache = False
  336. if inputs_embeds is None:
  337. inputs_embeds = self.embed_tokens(input_ids)
  338. if use_cache and past_key_values is None and not self.training:
  339. past_key_values = DynamicCache(config=self.config)
  340. if cache_position is None:
  341. past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
  342. cache_position = torch.arange(
  343. past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
  344. )
  345. if position_ids is None:
  346. position_ids = cache_position.unsqueeze(0)
  347. # It may already have been prepared by e.g. `generate`
  348. if not isinstance(causal_mask_mapping := attention_mask, dict):
  349. # Prepare mask arguments
  350. mask_kwargs = {
  351. "config": self.config,
  352. "input_embeds": inputs_embeds,
  353. "attention_mask": attention_mask,
  354. "cache_position": cache_position,
  355. "past_key_values": past_key_values,
  356. "position_ids": position_ids,
  357. }
  358. # Create the masks
  359. causal_mask_mapping = {
  360. "full_attention": create_causal_mask(**mask_kwargs),
  361. "sliding_attention": create_sliding_window_causal_mask(**mask_kwargs),
  362. }
  363. # embed positions
  364. hidden_states = inputs_embeds
  365. # create position embeddings to be shared across the decoder layers
  366. position_embeddings = self.rotary_emb(hidden_states, position_ids)
  367. # normalized
  368. # VaultGemma downcasts the below to float16, causing sqrt(3072)=55.4256 to become 55.5
  369. # See https://github.com/huggingface/transformers/pull/29402
  370. normalizer = torch.tensor(self.config.hidden_size**0.5, dtype=hidden_states.dtype)
  371. hidden_states = hidden_states * normalizer
  372. # decoder layers
  373. all_hidden_states = () if output_hidden_states else None
  374. all_self_attns = () if output_attentions else None
  375. for decoder_layer in self.layers[: self.config.num_hidden_layers]:
  376. if output_hidden_states:
  377. all_hidden_states += (hidden_states,)
  378. layer_outputs = decoder_layer(
  379. hidden_states,
  380. position_embeddings=position_embeddings,
  381. attention_mask=causal_mask_mapping[decoder_layer.attention_type],
  382. position_ids=position_ids,
  383. past_key_values=past_key_values,
  384. output_attentions=output_attentions,
  385. use_cache=use_cache,
  386. cache_position=cache_position,
  387. **kwargs,
  388. )
  389. hidden_states = layer_outputs[0]
  390. if output_attentions:
  391. all_self_attns += (layer_outputs[1],)
  392. hidden_states = self.norm(hidden_states)
  393. if output_hidden_states:
  394. all_hidden_states += (hidden_states,)
  395. return BaseModelOutputWithPast(
  396. last_hidden_state=hidden_states,
  397. past_key_values=past_key_values,
  398. hidden_states=all_hidden_states,
  399. attentions=all_self_attns,
  400. )
  401. @auto_docstring
  402. class VaultGemmaForCausalLM(VaultGemmaPreTrainedModel, GenerationMixin):
  403. _tied_weights_keys = ["lm_head.weight"]
  404. _tp_plan = {"lm_head": "colwise_rep"}
  405. _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
  406. def __init__(self, config):
  407. super().__init__(config)
  408. self.model = VaultGemmaModel(config)
  409. self.vocab_size = config.vocab_size
  410. self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
  411. # Initialize weights and apply final processing
  412. self.post_init()
  413. @can_return_tuple
  414. @auto_docstring
  415. def forward(
  416. self,
  417. input_ids: Optional[torch.LongTensor] = None,
  418. attention_mask: Optional[torch.Tensor] = None,
  419. position_ids: Optional[torch.LongTensor] = None,
  420. past_key_values: Optional[Cache] = None,
  421. inputs_embeds: Optional[torch.FloatTensor] = None,
  422. labels: Optional[torch.LongTensor] = None,
  423. use_cache: Optional[bool] = None,
  424. output_attentions: Optional[bool] = None,
  425. output_hidden_states: Optional[bool] = None,
  426. cache_position: Optional[torch.LongTensor] = None,
  427. logits_to_keep: Union[int, torch.Tensor] = 0,
  428. **kwargs,
  429. ) -> CausalLMOutputWithPast:
  430. r"""
  431. Example:
  432. ```python
  433. >>> from transformers import AutoTokenizer, VaultGemmaForCausalLM
  434. >>> model = VaultGemmaForCausalLM.from_pretrained("google/gemma-2-9b")
  435. >>> tokenizer = AutoTokenizer.from_pretrained("google/gemma-2-9b")
  436. >>> prompt = "What is your favorite condiment?"
  437. >>> inputs = tokenizer(prompt, return_tensors="pt")
  438. >>> # Generate
  439. >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
  440. >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
  441. "What is your favorite condiment?"
  442. ```"""
  443. output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
  444. output_hidden_states = (
  445. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  446. )
  447. # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
  448. outputs: BaseModelOutputWithPast = self.model(
  449. input_ids=input_ids,
  450. attention_mask=attention_mask,
  451. position_ids=position_ids,
  452. past_key_values=past_key_values,
  453. inputs_embeds=inputs_embeds,
  454. use_cache=use_cache,
  455. output_attentions=output_attentions,
  456. output_hidden_states=output_hidden_states,
  457. cache_position=cache_position,
  458. **kwargs,
  459. )
  460. hidden_states = outputs.last_hidden_state
  461. # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
  462. slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
  463. logits = self.lm_head(hidden_states[:, slice_indices, :])
  464. if self.config.final_logit_softcapping is not None:
  465. logits = logits / self.config.final_logit_softcapping
  466. logits = torch.tanh(logits)
  467. logits = logits * self.config.final_logit_softcapping
  468. loss = None
  469. if labels is not None:
  470. loss = self.loss_function(logits, labels, self.vocab_size, **kwargs)
  471. return CausalLMOutputWithPast(
  472. loss=loss,
  473. logits=logits,
  474. past_key_values=outputs.past_key_values,
  475. hidden_states=outputs.hidden_states,
  476. attentions=outputs.attentions,
  477. )
  478. __all__ = ["VaultGemmaForCausalLM", "VaultGemmaModel", "VaultGemmaPreTrainedModel"]