modular_helium.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. # coding=utf-8
  2. # Copyright 2024 The Kyutai and HuggingFace Inc. teams. All rights reserved.
  3. #
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. import math
  17. from typing import Optional
  18. import torch
  19. import torch.nn as nn
  20. from ...utils import logging
  21. from ..gemma.modeling_gemma import GemmaForCausalLM, GemmaForSequenceClassification, GemmaForTokenClassification
  22. from ..granite.modeling_granite import GraniteAttention
  23. from ..llama.modeling_llama import LlamaDecoderLayer, LlamaMLP, LlamaModel, LlamaPreTrainedModel, LlamaRotaryEmbedding
  24. from .configuration_helium import HeliumConfig
  25. logger = logging.get_logger(__name__)
  26. class HeliumRMSNorm(nn.Module):
  27. def __init__(self, hidden_size, eps=1e-6):
  28. super().__init__()
  29. self.weight = nn.Parameter(torch.ones(hidden_size))
  30. self.variance_epsilon = eps
  31. def forward(self, hidden_states):
  32. input_dtype = hidden_states.dtype
  33. hidden_states = hidden_states.to(torch.float32)
  34. variance = hidden_states.pow(2).mean(-1, keepdim=True)
  35. hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
  36. return (self.weight.to(torch.float32) * hidden_states).to(input_dtype)
  37. def extra_repr(self):
  38. return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
  39. class HeliumRotaryEmbedding(LlamaRotaryEmbedding):
  40. pass
  41. class HeliumMLP(LlamaMLP):
  42. pass
  43. def rotate_half(x):
  44. """Rotates half the hidden dims of the input."""
  45. x1 = x[..., 0::2]
  46. x2 = x[..., 1::2]
  47. return torch.stack((-x2, x1), dim=-1).flatten(-2)
  48. def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
  49. """Applies Rotary Position Embedding to the query and key tensors.
  50. Args:
  51. q (`torch.Tensor`): The query tensor.
  52. k (`torch.Tensor`): The key tensor.
  53. cos (`torch.Tensor`): The cosine part of the rotary embedding.
  54. sin (`torch.Tensor`): The sine part of the rotary embedding.
  55. position_ids (`torch.Tensor`, *optional*):
  56. Deprecated and unused.
  57. unsqueeze_dim (`int`, *optional*, defaults to 1):
  58. The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
  59. sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
  60. that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
  61. k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
  62. cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
  63. the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
  64. Returns:
  65. `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
  66. """
  67. cos = cos.unsqueeze(unsqueeze_dim)
  68. sin = sin.unsqueeze(unsqueeze_dim)
  69. # Interleave them instead of usual shape
  70. cos = cos[..., : cos.shape[-1] // 2].repeat_interleave(2, dim=-1)
  71. sin = sin[..., : sin.shape[-1] // 2].repeat_interleave(2, dim=-1)
  72. q_embed = (q * cos) + (rotate_half(q) * sin)
  73. k_embed = (k * cos) + (rotate_half(k) * sin)
  74. return q_embed, k_embed
  75. class HeliumAttention(GraniteAttention):
  76. def __init__(self, config: HeliumConfig, layer_idx: Optional[int] = None):
  77. super().__init__(config, layer_idx)
  78. self.o_proj = nn.Linear(config.hidden_size, config.hidden_size, bias=False)
  79. self.scaling = 1 / math.sqrt(self.head_dim)
  80. class HeliumDecoderLayer(LlamaDecoderLayer):
  81. def __init__(self, config: HeliumConfig, layer_idx: Optional[int] = None):
  82. super().__init__(config, layer_idx)
  83. self.mlp = HeliumMLP(config)
  84. self.input_layernorm = HeliumRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  85. self.post_attention_layernorm = HeliumRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  86. class HeliumPreTrainedModel(LlamaPreTrainedModel):
  87. pass
  88. class HeliumModel(HeliumPreTrainedModel, LlamaModel):
  89. def __init__(self, config: HeliumConfig):
  90. super().__init__(config)
  91. self.layers = nn.ModuleList(
  92. [HeliumDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
  93. )
  94. self.norm = HeliumRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  95. self.rotary_emb = HeliumRotaryEmbedding(config)
  96. self.gradient_checkpointing = False
  97. # Initialize weights and apply final processing
  98. self.post_init()
  99. class HeliumForCausalLM(GemmaForCausalLM):
  100. pass
  101. class HeliumForSequenceClassification(GemmaForSequenceClassification):
  102. pass
  103. class HeliumForTokenClassification(GemmaForTokenClassification):
  104. pass
  105. __all__ = [
  106. "HeliumPreTrainedModel",
  107. "HeliumModel",
  108. "HeliumForCausalLM",
  109. "HeliumForSequenceClassification",
  110. "HeliumForTokenClassification",
  111. ]