modular_granitemoeshared.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. # Copyright 2024 IBM and the HuggingFace Inc. team. 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. from typing import TypedDict
  16. import torch
  17. from torch import nn
  18. from ...activations import ACT2FN
  19. from ...cache_utils import Cache
  20. from ...processing_utils import Unpack
  21. from ...utils import logging
  22. from ..granitemoe.modeling_granitemoe import (
  23. GraniteMoeDecoderLayer,
  24. GraniteMoeForCausalLM,
  25. GraniteMoeModel,
  26. GraniteMoePreTrainedModel,
  27. )
  28. from .configuration_granitemoeshared import GraniteMoeSharedConfig
  29. logger = logging.get_logger(__name__)
  30. class GraniteFlashAttentionKwargs(TypedDict, total=False):
  31. """
  32. Keyword arguments for advanced Flash Attention, causal-conv1d, and mamba_ssm kernel usage.
  33. Use cases include padding-free training and fewer `torch.compile` graph breaks.
  34. cu_seq_lens_q (`torch.LongTensor`):
  35. Gets cumulative sequence length for query state.
  36. cu_seq_lens_k (`torch.LongTensor`):
  37. Gets cumulative sequence length for key state.
  38. max_length_q (`int`):
  39. Maximum sequence length for query state.
  40. max_length_k (`int`):
  41. Maximum sequence length for key state.
  42. seq_idx (`torch.IntTensor):
  43. Index of each packed sequence.
  44. """
  45. cu_seq_lens_q: torch.LongTensor
  46. cu_seq_lens_k: torch.LongTensor
  47. max_length_q: int
  48. max_length_k: int
  49. seq_idx: torch.IntTensor
  50. class GraniteMoeSharedMLP(nn.Module):
  51. """
  52. MLP layer for shared experts
  53. Args:
  54. config:
  55. Configuration object with model hyperparameters.
  56. """
  57. def __init__(self, config: GraniteMoeSharedConfig):
  58. super().__init__()
  59. self.input_size = config.hidden_size
  60. self.hidden_size = config.shared_intermediate_size
  61. self.activation = ACT2FN[config.hidden_act]
  62. self.input_linear = nn.Linear(self.input_size, self.hidden_size * 2, bias=False)
  63. self.output_linear = nn.Linear(self.hidden_size, self.input_size, bias=False)
  64. def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
  65. hidden_states = self.input_linear(hidden_states)
  66. chunked_hidden_states = hidden_states.chunk(2, dim=-1)
  67. hidden_states = self.activation(chunked_hidden_states[0]) * chunked_hidden_states[1]
  68. hidden_states = self.output_linear(hidden_states)
  69. return hidden_states
  70. class GraniteMoeSharedDecoderLayer(GraniteMoeDecoderLayer):
  71. def __init__(self, config: GraniteMoeSharedConfig, layer_idx: int):
  72. super().__init__(config, layer_idx)
  73. self.shared_mlp = None if config.shared_intermediate_size == 0 else GraniteMoeSharedMLP(config)
  74. def forward(
  75. self,
  76. hidden_states: torch.Tensor,
  77. attention_mask: torch.Tensor | None = None,
  78. position_ids: torch.LongTensor | None = None,
  79. past_key_values: Cache | None = None,
  80. output_attentions: bool | None = False,
  81. use_cache: bool | None = False,
  82. position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
  83. **kwargs: Unpack[GraniteFlashAttentionKwargs],
  84. ) -> tuple[torch.FloatTensor, tuple[torch.FloatTensor, torch.FloatTensor] | None]:
  85. residual = hidden_states
  86. hidden_states = self.input_layernorm(hidden_states)
  87. # Self Attention
  88. hidden_states, _ = self.self_attn(
  89. hidden_states=hidden_states,
  90. attention_mask=attention_mask,
  91. position_ids=position_ids,
  92. past_key_values=past_key_values,
  93. output_attentions=output_attentions,
  94. use_cache=use_cache,
  95. position_embeddings=position_embeddings,
  96. **kwargs,
  97. )
  98. hidden_states = residual + hidden_states * self.residual_multiplier
  99. residual = hidden_states
  100. hidden_states = self.post_attention_layernorm(hidden_states)
  101. moe_hidden_states = self.block_sparse_moe(hidden_states)
  102. if self.shared_mlp is None:
  103. hidden_states = moe_hidden_states
  104. else:
  105. hidden_states = moe_hidden_states + self.shared_mlp(hidden_states)
  106. hidden_states = residual + hidden_states * self.residual_multiplier
  107. return hidden_states
  108. class GraniteMoeSharedPreTrainedModel(GraniteMoePreTrainedModel):
  109. config: GraniteMoeSharedConfig
  110. _no_split_modules = ["GraniteMoeSharedDecoderLayer"]
  111. class GraniteMoeSharedModel(GraniteMoeModel):
  112. def __init__(self, config: GraniteMoeSharedConfig):
  113. super().__init__(config)
  114. self.layers = nn.ModuleList(
  115. [GraniteMoeSharedDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
  116. )
  117. class GraniteMoeSharedForCausalLM(GraniteMoeForCausalLM):
  118. _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
  119. def __init__(self, config: GraniteMoeSharedConfig):
  120. super().__init__(config)
  121. self.model = GraniteMoeSharedModel(config)
  122. # Initialize weights and apply final processing
  123. self.post_init()
  124. __all__ = ["GraniteMoeSharedForCausalLM", "GraniteMoeSharedModel", "GraniteMoeSharedPreTrainedModel"]