modular_helium.py 5.1 KB

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