Crystalcareai commited on
Commit
6273a49
1 Parent(s): 4607189

Upload 3 files

Browse files
Files changed (3) hide show
  1. config.json +2 -3
  2. configuration_gemmoe.py +167 -0
  3. modeling_gemmoe.py +1507 -0
config.json CHANGED
@@ -1,5 +1,5 @@
1
  {
2
- "_name_or_path": "Crystalcareai/GemMoE-Medium-Base",
3
  "architectures": [
4
  "GemmoeForCausalLM"
5
  ],
@@ -13,7 +13,6 @@
13
  "eos_token_id": 1,
14
  "head_dim": 256,
15
  "hidden_act": "gelu",
16
- "hidden_activation": null,
17
  "hidden_size": 3072,
18
  "initializer_range": 0.02,
19
  "intermediate_size": 24576,
@@ -32,7 +31,7 @@
32
  "router_aux_loss_coef": 0.02,
33
  "sliding_window": null,
34
  "torch_dtype": "bfloat16",
35
- "transformers_version": "4.39.0",
36
  "use_cache": false,
37
  "vocab_size": 256000
38
  }
 
1
  {
2
+ "_name_or_path": "Crystalcareai/GemMoE-Beta-1",
3
  "architectures": [
4
  "GemmoeForCausalLM"
5
  ],
 
13
  "eos_token_id": 1,
14
  "head_dim": 256,
15
  "hidden_act": "gelu",
 
16
  "hidden_size": 3072,
17
  "initializer_range": 0.02,
18
  "intermediate_size": 24576,
 
31
  "router_aux_loss_coef": 0.02,
32
  "sliding_window": null,
33
  "torch_dtype": "bfloat16",
34
+ "transformers_version": "4.38.2",
35
  "use_cache": false,
36
  "vocab_size": 256000
37
  }
configuration_gemmoe.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The HuggingFace Inc. team. All rights reserved.
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
+ """ Gemmoe model configuration"""
16
+
17
+ from transformers.configuration_utils import PretrainedConfig
18
+ from transformers.utils import logging
19
+
20
+
21
+ logger = logging.get_logger(__name__)
22
+
23
+ GEMMOE_PRETRAINED_CONFIG_ARCHIVE_MAP = {
24
+ "Crystalcareai/GemMoE-Beta-1": "https://huggingface.co/Crystalcareai/GemMoE-Beta-1/resolve/main/config.json",
25
+ }
26
+
27
+
28
+ class GemmoeConfig(PretrainedConfig):
29
+ r"""
30
+ This is the configuration class to store the configuration of a [`GemmoeModel`]. It is used to instantiate a Gemmoe
31
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
32
+ defaults will yield a similar configuration to that of the Gemmoe-7B.
33
+
34
+ e.g. [mhenrichsen/gemmoe-7b](https://huggingface.co/mhenrichsen/gemmoe-7b)
35
+
36
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
37
+ documentation from [`PretrainedConfig`] for more information.
38
+
39
+ Args:
40
+ vocab_size (`int`, *optional*, defaults to 256000):
41
+ Vocabulary size of the Gemmoe model. Defines the number of different tokens that can be represented by the
42
+ `inputs_ids` passed when calling [`GemmoeModel`]
43
+ hidden_size (`int`, *optional*, defaults to 3072):
44
+ Dimension of the hidden representations.
45
+ intermediate_size (`int`, *optional*, defaults to 24576):
46
+ Dimension of the MLP representations.
47
+ num_hidden_layers (`int`, *optional*, defaults to 28):
48
+ Number of hidden layers in the Transformer decoder.
49
+ num_attention_heads (`int`, *optional*, defaults to 16):
50
+ Number of attention heads for each attention layer in the Transformer decoder.
51
+ num_key_value_heads (`int`, *optional*, defaults to 16):
52
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
53
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
54
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
55
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
56
+ by meanpooling all the original heads within that group. For more details checkout [this
57
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
58
+ `num_attention_heads`.
59
+ head_dim (`int`, *optional*, defaults to 256):
60
+ The attention head dimension.
61
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
62
+ The non-linear activation function (function or string) in the decoder.
63
+ max_position_embeddings (`int`, *optional*, defaults to 8192):
64
+ The maximum sequence length that this model might ever be used with.
65
+ initializer_range (`float`, *optional*, defaults to 0.02):
66
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
67
+ rms_norm_eps (`float`, *optional*, defaults to 1e-6):
68
+ The epsilon used by the rms normalization layers.
69
+ use_cache (`bool`, *optional*, defaults to `True`):
70
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
71
+ relevant if `config.is_decoder=True`.
72
+ pad_token_id (`int`, *optional*, defaults to 0):
73
+ Padding token id.
74
+ eos_token_id (`int`, *optional*, defaults to 1):
75
+ End of stream token id.
76
+ bos_token_id (`int`, *optional*, defaults to 2):
77
+ Beginning of stream token id.
78
+ tie_word_embeddings (`bool`, *optional*, defaults to `True`):
79
+ Whether to tie weight embeddings
80
+ rope_theta (`float`, *optional*, defaults to 10000.0):
81
+ The base period of the RoPE embeddings.
82
+ attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
83
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
84
+ attention_dropout (`float`, *optional*, defaults to 0.0):
85
+ The dropout ratio for the attention probabilities.
86
+ num_experts_per_tok (`int`, *optional*, defaults to 2):
87
+ The number of experts used in the sparse mixture of experts layer.
88
+ num_local_experts (`int`, *optional*, defaults to 8):
89
+ The number of local experts used in the sparse mixture of experts layer.
90
+ router_aux_loss_coef (`float`, *optional*, defaults to 0.01):
91
+ The coefficient for the auxiliary loss of the router.
92
+ output_router_logits (`bool`, *optional*, defaults to `False`):
93
+ Whether or not to output the logits of the routers. They are useful for computing the router loss, and
94
+ should not be returned during inference.
95
+
96
+ ```python
97
+ >>> from transformers import GemmoeModel, GemmoeConfig
98
+
99
+ >>> # Initializing a Gemmoe gemmoe-7b style configuration
100
+ >>> configuration = GemmoeConfig()
101
+
102
+ >>> # Initializing a model from the gemmoe-7b style configuration
103
+ >>> model = GemmoeModel(configuration)
104
+
105
+ >>> # Accessing the model configuration
106
+ >>> configuration = model.config
107
+ ```"""
108
+
109
+ model_type = "gemmoe"
110
+ keys_to_ignore_at_inference = ["past_key_values"]
111
+
112
+ def __init__(
113
+ self,
114
+ vocab_size=256000,
115
+ hidden_size=3072,
116
+ intermediate_size=24576,
117
+ num_hidden_layers=28,
118
+ num_attention_heads=16,
119
+ num_key_value_heads=16,
120
+ head_dim=256,
121
+ hidden_act="gelu_pytorch_tanh",
122
+ max_position_embeddings=8192,
123
+ initializer_range=0.02,
124
+ rms_norm_eps=1e-6,
125
+ use_cache=True,
126
+ pad_token_id=0,
127
+ eos_token_id=1,
128
+ bos_token_id=2,
129
+ hidden_activation=None,
130
+ tie_word_embeddings=True,
131
+ rope_theta=10000.0,
132
+ attention_bias=False,
133
+ attention_dropout=0.0,
134
+ num_experts_per_tok=2,
135
+ num_local_experts=4,
136
+ router_aux_loss_coef=0.02,
137
+ output_router_logits=False,
138
+ **kwargs,
139
+ ):
140
+ self.vocab_size = vocab_size
141
+ self.max_position_embeddings = max_position_embeddings
142
+ self.hidden_size = hidden_size
143
+ self.intermediate_size = intermediate_size
144
+ self.num_hidden_layers = num_hidden_layers
145
+ self.num_attention_heads = num_attention_heads
146
+ self.head_dim = head_dim
147
+ self.hidden_act = hidden_act
148
+ self.hidden_activation = hidden_activation
149
+ self.num_key_value_heads = num_key_value_heads
150
+ self.initializer_range = initializer_range
151
+ self.rms_norm_eps = rms_norm_eps
152
+ self.use_cache = use_cache
153
+ self.rope_theta = rope_theta
154
+ self.attention_bias = attention_bias
155
+ self.attention_dropout = attention_dropout
156
+ self.num_experts_per_tok = num_experts_per_tok
157
+ self.num_local_experts = num_local_experts
158
+ self.router_aux_loss_coef = router_aux_loss_coef
159
+ self.output_router_logits = output_router_logits
160
+
161
+ super().__init__(
162
+ pad_token_id=pad_token_id,
163
+ bos_token_id=bos_token_id,
164
+ eos_token_id=eos_token_id,
165
+ tie_word_embeddings=tie_word_embeddings,
166
+ **kwargs,
167
+ )
modeling_gemmoe.py ADDED
@@ -0,0 +1,1507 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 Google Inc. HuggingFace Inc. team. 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
+ """ PyTorch Gemmoe model."""
17
+
18
+ import math
19
+ import warnings
20
+ from typing import List, Optional, Tuple, Union
21
+
22
+ import torch
23
+ import torch.nn.functional as F
24
+ import torch.utils.checkpoint
25
+ from torch import nn
26
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
27
+
28
+ from transformers.activations import ACT2FN
29
+ from transformers.cache_utils import Cache, DynamicCache, StaticCache
30
+ from transformers.modeling_attn_mask_utils import (
31
+ AttentionMaskConverter,
32
+ _prepare_4d_causal_attention_mask,
33
+ )
34
+ from transformers.modeling_outputs import MoeModelOutputWithPast, MoeCausalLMOutputWithPast, SequenceClassifierOutputWithPast
35
+ from transformers.modeling_utils import PreTrainedModel
36
+ from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS, is_torch_greater_or_equal_than_1_13
37
+ from transformers.utils import (
38
+ add_start_docstrings,
39
+ add_start_docstrings_to_model_forward,
40
+ is_flash_attn_2_available,
41
+ is_flash_attn_greater_or_equal_2_10,
42
+ logging,
43
+ replace_return_docstrings,
44
+ )
45
+ from transformers.utils.import_utils import is_torch_fx_available
46
+ from .configuration_gemmoe import GemmoeConfig
47
+
48
+
49
+ if is_flash_attn_2_available():
50
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
51
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
52
+
53
+
54
+ # This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.
55
+ # It means that the function will not be traced through and simply appear as a node in the graph.
56
+ if is_torch_fx_available():
57
+ if not is_torch_greater_or_equal_than_1_13:
58
+ import torch.fx
59
+
60
+ _prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask)
61
+
62
+
63
+ logger = logging.get_logger(__name__)
64
+
65
+ _CONFIG_FOR_DOC = "GemmoeConfig"
66
+
67
+ def load_balancing_loss_func(gate_logits: torch.Tensor, num_experts: torch.Tensor = None, top_k=2) -> float:
68
+ r"""
69
+ Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.
70
+
71
+ See Switch Transformer (https://arxiv.org/abs/2101.03961) for more details. This function implements the loss
72
+ function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
73
+ experts is too unbalanced.
74
+
75
+ Args:
76
+ gate_logits (Union[`torch.Tensor`, Tuple[torch.Tensor]):
77
+ Logits from the `gate`, should be a tuple of tensors. Shape: [batch_size, seqeunce_length, num_experts].
78
+ num_experts (`int`, *optional*):
79
+ Number of experts
80
+
81
+ Returns:
82
+ The auxiliary loss.
83
+ """
84
+ if gate_logits is None:
85
+ return 0
86
+
87
+ if isinstance(gate_logits, tuple):
88
+ # cat along the layers?
89
+ gate_logits = torch.cat(gate_logits, dim=0)
90
+
91
+ routing_weights, selected_experts = torch.topk(gate_logits, top_k, dim=-1)
92
+ routing_weights = routing_weights.softmax(dim=-1)
93
+
94
+ # cast the expert indices to int64, otherwise one-hot encoding will fail
95
+ if selected_experts.dtype != torch.int64:
96
+ selected_experts = selected_experts.to(torch.int64)
97
+
98
+ if len(selected_experts.shape) == 2:
99
+ selected_experts = selected_experts.unsqueeze(2)
100
+
101
+ expert_mask = torch.nn.functional.one_hot(selected_experts, num_experts)
102
+
103
+ # For a given token, determine if it was routed to a given expert.
104
+ expert_mask = torch.max(expert_mask, axis=-2).values
105
+
106
+ # cast to float32 otherwise mean will fail
107
+ expert_mask = expert_mask.to(torch.float32)
108
+ tokens_per_group_and_expert = torch.mean(expert_mask, axis=-2)
109
+
110
+ router_prob_per_group_and_expert = torch.mean(routing_weights, axis=-1)
111
+ return torch.mean(tokens_per_group_and_expert * router_prob_per_group_and_expert.unsqueeze(-1)) * (num_experts**2)
112
+
113
+
114
+ def _get_unpad_data(attention_mask):
115
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
116
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
117
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
118
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
119
+ return (
120
+ indices,
121
+ cu_seqlens,
122
+ max_seqlen_in_batch,
123
+ )
124
+
125
+
126
+ class GemmoeRMSNorm(nn.Module):
127
+ def __init__(self, dim: int, eps: float = 1e-6):
128
+ super().__init__()
129
+ self.eps = eps
130
+ self.weight = nn.Parameter(torch.zeros(dim))
131
+
132
+ def _norm(self, x):
133
+ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
134
+
135
+ def forward(self, x):
136
+ output = self._norm(x.float())
137
+ # Llama does x.to(float16) * w whilst Gemmoe is (x * w).to(float16)
138
+ # See https://github.com/huggingface/transformers/pull/29402
139
+ output = output * (1.0 + self.weight.float())
140
+ return output.type_as(x)
141
+
142
+
143
+ ALL_LAYERNORM_LAYERS.append(GemmoeRMSNorm)
144
+
145
+
146
+ class GemmoeRotaryEmbedding(nn.Module):
147
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
148
+ super().__init__()
149
+
150
+ self.dim = dim
151
+ self.max_position_embeddings = max_position_embeddings
152
+ self.base = base
153
+ self.register_buffer("inv_freq", None, persistent=False)
154
+
155
+ @torch.no_grad()
156
+ def forward(self, x, position_ids, seq_len=None):
157
+ # x: [bs, num_attention_heads, seq_len, head_size]
158
+ if self.inv_freq is None:
159
+ self.inv_freq = 1.0 / (
160
+ self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64, device=x.device).float() / self.dim)
161
+ )
162
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
163
+ position_ids_expanded = position_ids[:, None, :].float()
164
+ # Force float32 since bfloat16 loses precision on long contexts
165
+ # See https://github.com/huggingface/transformers/pull/29285
166
+ device_type = x.device.type
167
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
168
+ with torch.autocast(device_type=device_type, enabled=False):
169
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
170
+ emb = torch.cat((freqs, freqs), dim=-1)
171
+ cos = emb.cos()
172
+ sin = emb.sin()
173
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
174
+
175
+
176
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
177
+ def rotate_half(x):
178
+ """Rotates half the hidden dims of the input."""
179
+ x1 = x[..., : x.shape[-1] // 2]
180
+ x2 = x[..., x.shape[-1] // 2 :]
181
+ return torch.cat((-x2, x1), dim=-1)
182
+
183
+
184
+ # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
185
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
186
+ """Applies Rotary Position Embedding to the query and key tensors.
187
+
188
+ Args:
189
+ q (`torch.Tensor`): The query tensor.
190
+ k (`torch.Tensor`): The key tensor.
191
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
192
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
193
+ position_ids (`torch.Tensor`, *optional*):
194
+ Deprecated and unused.
195
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
196
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
197
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
198
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
199
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
200
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
201
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
202
+ Returns:
203
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
204
+ """
205
+ cos = cos.unsqueeze(unsqueeze_dim)
206
+ sin = sin.unsqueeze(unsqueeze_dim)
207
+ q_embed = (q * cos) + (rotate_half(q) * sin)
208
+ k_embed = (k * cos) + (rotate_half(k) * sin)
209
+ return q_embed, k_embed
210
+
211
+
212
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
213
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
214
+ """
215
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
216
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
217
+ """
218
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
219
+ if n_rep == 1:
220
+ return hidden_states
221
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
222
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
223
+
224
+
225
+ class GemmoeAttention(nn.Module):
226
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
227
+
228
+ # Ignore copy
229
+ def __init__(self, config: GemmoeConfig, layer_idx: Optional[int] = None):
230
+ super().__init__()
231
+ self.config = config
232
+ self.layer_idx = layer_idx
233
+ if layer_idx is None:
234
+ logger.warning_once(
235
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
236
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
237
+ "when creating this class."
238
+ )
239
+
240
+ self.attention_dropout = config.attention_dropout
241
+ self.hidden_size = config.hidden_size
242
+ self.num_heads = config.num_attention_heads
243
+ self.head_dim = config.head_dim
244
+ self.num_key_value_heads = config.num_key_value_heads
245
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
246
+ self.max_position_embeddings = config.max_position_embeddings
247
+ self.rope_theta = config.rope_theta
248
+ self.is_causal = True
249
+
250
+ if self.hidden_size % self.num_heads != 0:
251
+ raise ValueError(
252
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
253
+ f" and `num_heads`: {self.num_heads})."
254
+ )
255
+
256
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
257
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
258
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
259
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.attention_bias)
260
+ self.rotary_emb = GemmoeRotaryEmbedding(
261
+ self.head_dim,
262
+ max_position_embeddings=self.max_position_embeddings,
263
+ base=self.rope_theta,
264
+ )
265
+
266
+ def forward(
267
+ self,
268
+ hidden_states: torch.Tensor,
269
+ attention_mask: Optional[torch.Tensor] = None,
270
+ position_ids: Optional[torch.LongTensor] = None,
271
+ past_key_value: Optional[Cache] = None,
272
+ output_attentions: bool = False,
273
+ use_cache: bool = False,
274
+ cache_position: Optional[torch.LongTensor] = None,
275
+ **kwargs,
276
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
277
+ bsz, q_len, _ = hidden_states.size()
278
+
279
+ query_states = self.q_proj(hidden_states)
280
+ key_states = self.k_proj(hidden_states)
281
+ value_states = self.v_proj(hidden_states)
282
+
283
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
284
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
285
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
286
+
287
+ past_key_value = getattr(self, "past_key_value", past_key_value)
288
+ cos, sin = self.rotary_emb(value_states, position_ids, seq_len=None)
289
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, None)
290
+
291
+ if past_key_value is not None:
292
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
293
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
294
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
295
+
296
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
297
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
298
+
299
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
300
+
301
+ if attention_mask is not None: # no matter the length, we just slice it
302
+ if cache_position is not None:
303
+ causal_mask = attention_mask[:, :, cache_position, : key_states.shape[-2]]
304
+ else:
305
+ causal_mask = attention_mask
306
+ attn_weights = attn_weights + causal_mask
307
+
308
+ # upcast attention to fp32
309
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
310
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
311
+ attn_output = torch.matmul(attn_weights, value_states)
312
+
313
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
314
+ raise ValueError(
315
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
316
+ f" {attn_output.size()}"
317
+ )
318
+
319
+ attn_output = attn_output.transpose(1, 2).contiguous()
320
+
321
+ attn_output = attn_output.view(bsz, q_len, -1)
322
+ attn_output = self.o_proj(attn_output)
323
+
324
+ if not output_attentions:
325
+ attn_weights = None
326
+
327
+ return attn_output, attn_weights, past_key_value
328
+
329
+
330
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2 with Llama->Gemmoe
331
+ class GemmoeFlashAttention2(GemmoeAttention):
332
+ """
333
+ Gemmoe flash attention module. This module inherits from `GemmoeAttention` as the weights of the module stays
334
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
335
+ flash attention and deal with padding tokens in case the input contains any of them.
336
+ """
337
+
338
+ def __init__(self, *args, **kwargs):
339
+ super().__init__(*args, **kwargs)
340
+
341
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
342
+ # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
343
+ # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
344
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
345
+
346
+ # Ignore copy
347
+ def forward(
348
+ self,
349
+ hidden_states: torch.Tensor,
350
+ attention_mask: Optional[torch.LongTensor] = None,
351
+ position_ids: Optional[torch.LongTensor] = None,
352
+ past_key_value: Optional[Cache] = None,
353
+ output_attentions: bool = False,
354
+ use_cache: bool = False,
355
+ cache_position: Optional[torch.LongTensor] = None,
356
+ **kwargs,
357
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
358
+ output_attentions = False
359
+
360
+ bsz, q_len, _ = hidden_states.size()
361
+
362
+ query_states = self.q_proj(hidden_states)
363
+ key_states = self.k_proj(hidden_states)
364
+ value_states = self.v_proj(hidden_states)
365
+
366
+ # Flash attention requires the input to have the shape
367
+ # batch_size x seq_length x head_dim x hidden_dim
368
+ # therefore we just need to keep the original shape
369
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
370
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
371
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
372
+
373
+ cos, sin = self.rotary_emb(value_states, position_ids, seq_len=None)
374
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, None)
375
+
376
+ past_key_value = getattr(self, "past_key_value", past_key_value)
377
+
378
+ if past_key_value is not None:
379
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
380
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
381
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
382
+
383
+ # TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
384
+ # to be able to avoid many of these transpose/reshape/view.
385
+ query_states = query_states.transpose(1, 2)
386
+ key_states = key_states.transpose(1, 2)
387
+ value_states = value_states.transpose(1, 2)
388
+
389
+ dropout_rate = self.attention_dropout if self.training else 0.0
390
+
391
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
392
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
393
+ # cast them back in the correct dtype just to be sure everything works as expected.
394
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
395
+ # in fp32. (GemmoeRMSNorm handles it correctly)
396
+
397
+ input_dtype = query_states.dtype
398
+ if input_dtype == torch.float32:
399
+ if torch.is_autocast_enabled():
400
+ target_dtype = torch.get_autocast_gpu_dtype()
401
+ # Handle the case where the model is quantized
402
+ elif hasattr(self.config, "_pre_quantization_dtype"):
403
+ target_dtype = self.config._pre_quantization_dtype
404
+ else:
405
+ target_dtype = self.q_proj.weight.dtype
406
+
407
+ logger.warning_once(
408
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
409
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
410
+ f" {target_dtype}."
411
+ )
412
+
413
+ query_states = query_states.to(target_dtype)
414
+ key_states = key_states.to(target_dtype)
415
+ value_states = value_states.to(target_dtype)
416
+
417
+ attn_output = self._flash_attention_forward(
418
+ query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate
419
+ )
420
+
421
+ attn_output = attn_output.reshape(bsz, q_len, -1).contiguous()
422
+ attn_output = self.o_proj(attn_output)
423
+
424
+ if not output_attentions:
425
+ attn_weights = None
426
+
427
+ return attn_output, attn_weights, past_key_value
428
+
429
+ def _flash_attention_forward(
430
+ self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
431
+ ):
432
+ """
433
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
434
+ first unpad the input, then computes the attention scores and pad the final attention scores.
435
+
436
+ Args:
437
+ query_states (`torch.Tensor`):
438
+ Input query states to be passed to Flash Attention API
439
+ key_states (`torch.Tensor`):
440
+ Input key states to be passed to Flash Attention API
441
+ value_states (`torch.Tensor`):
442
+ Input value states to be passed to Flash Attention API
443
+ attention_mask (`torch.Tensor`):
444
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
445
+ position of padding tokens and 1 for the position of non-padding tokens.
446
+ dropout (`float`):
447
+ Attention dropout
448
+ softmax_scale (`float`, *optional*):
449
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
450
+ """
451
+ if not self._flash_attn_uses_top_left_mask:
452
+ causal = self.is_causal
453
+ else:
454
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in GemmoeFlashAttention2 __init__.
455
+ causal = self.is_causal and query_length != 1
456
+
457
+ # Contains at least one padding token in the sequence
458
+ if attention_mask is not None:
459
+ batch_size = query_states.shape[0]
460
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
461
+ query_states, key_states, value_states, attention_mask, query_length
462
+ )
463
+
464
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
465
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
466
+
467
+ attn_output_unpad = flash_attn_varlen_func(
468
+ query_states,
469
+ key_states,
470
+ value_states,
471
+ cu_seqlens_q=cu_seqlens_q,
472
+ cu_seqlens_k=cu_seqlens_k,
473
+ max_seqlen_q=max_seqlen_in_batch_q,
474
+ max_seqlen_k=max_seqlen_in_batch_k,
475
+ dropout_p=dropout,
476
+ softmax_scale=softmax_scale,
477
+ causal=causal,
478
+ )
479
+
480
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
481
+ else:
482
+ attn_output = flash_attn_func(
483
+ query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
484
+ )
485
+
486
+ return attn_output
487
+
488
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
489
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
490
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
491
+
492
+ key_layer = index_first_axis(
493
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
494
+ )
495
+ value_layer = index_first_axis(
496
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
497
+ )
498
+ if query_length == kv_seq_len:
499
+ query_layer = index_first_axis(
500
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
501
+ )
502
+ cu_seqlens_q = cu_seqlens_k
503
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
504
+ indices_q = indices_k
505
+ elif query_length == 1:
506
+ max_seqlen_in_batch_q = 1
507
+ cu_seqlens_q = torch.arange(
508
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
509
+ ) # There is a memcpy here, that is very bad.
510
+ indices_q = cu_seqlens_q[:-1]
511
+ query_layer = query_layer.squeeze(1)
512
+ else:
513
+ # The -q_len: slice assumes left padding.
514
+ attention_mask = attention_mask[:, -query_length:]
515
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
516
+
517
+ return (
518
+ query_layer,
519
+ key_layer,
520
+ value_layer,
521
+ indices_q,
522
+ (cu_seqlens_q, cu_seqlens_k),
523
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
524
+ )
525
+
526
+
527
+ # Copied from transformers.models.llama.modeling_llama.LlamaSdpaAttention with Llama->Gemmoe
528
+ class GemmoeSdpaAttention(GemmoeAttention):
529
+ """
530
+ Gemmoe attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
531
+ `GemmoeAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
532
+ SDPA API.
533
+ """
534
+
535
+ # Ignore copy
536
+ def forward(
537
+ self,
538
+ hidden_states: torch.Tensor,
539
+ attention_mask: Optional[torch.Tensor] = None,
540
+ position_ids: Optional[torch.LongTensor] = None,
541
+ past_key_value: Optional[Cache] = None,
542
+ output_attentions: bool = False,
543
+ use_cache: bool = False,
544
+ cache_position: Optional[torch.LongTensor] = None,
545
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
546
+ if output_attentions:
547
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
548
+ logger.warning_once(
549
+ "GemmoeModel is using GemmoeSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
550
+ 'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
551
+ )
552
+ return super().forward(
553
+ hidden_states=hidden_states,
554
+ attention_mask=attention_mask,
555
+ position_ids=position_ids,
556
+ past_key_value=past_key_value,
557
+ output_attentions=output_attentions,
558
+ use_cache=use_cache,
559
+ cache_position=cache_position,
560
+ )
561
+
562
+ bsz, q_len, _ = hidden_states.size()
563
+
564
+ query_states = self.q_proj(hidden_states)
565
+ key_states = self.k_proj(hidden_states)
566
+ value_states = self.v_proj(hidden_states)
567
+
568
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
569
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
570
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
571
+
572
+ cos, sin = self.rotary_emb(value_states, position_ids, seq_len=None)
573
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, None)
574
+
575
+ past_key_value = getattr(self, "past_key_value", past_key_value)
576
+
577
+ if past_key_value is not None:
578
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
579
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
580
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
581
+
582
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
583
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
584
+
585
+ causal_mask = attention_mask
586
+ if attention_mask is not None and cache_position is not None:
587
+ causal_mask = causal_mask[:, :, cache_position, : key_states.shape[-2]]
588
+
589
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
590
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
591
+ if query_states.device.type == "cuda" and causal_mask is not None:
592
+ query_states = query_states.contiguous()
593
+ key_states = key_states.contiguous()
594
+ value_states = value_states.contiguous()
595
+
596
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
597
+ query_states,
598
+ key_states,
599
+ value_states,
600
+ attn_mask=causal_mask,
601
+ dropout_p=self.attention_dropout if self.training else 0.0,
602
+ )
603
+
604
+ attn_output = attn_output.transpose(1, 2).contiguous()
605
+ attn_output = attn_output.view(bsz, q_len, -1)
606
+
607
+ attn_output = self.o_proj(attn_output)
608
+
609
+ return attn_output, None, past_key_value
610
+
611
+
612
+ GEMMOE_ATTENTION_CLASSES = {
613
+ "eager": GemmoeAttention,
614
+ "flash_attention_2": GemmoeFlashAttention2,
615
+ "sdpa": GemmoeSdpaAttention,
616
+ }
617
+
618
+ class GemmoeBlockSparseTop2MLP(nn.Module):
619
+ def __init__(self, config: GemmoeConfig):
620
+ super().__init__()
621
+ self.ffn_dim = config.intermediate_size
622
+ self.hidden_dim = config.hidden_size
623
+
624
+ self.w1 = nn.Linear(self.hidden_dim, self.ffn_dim, bias=False)
625
+ self.w2 = nn.Linear(self.ffn_dim, self.hidden_dim, bias=False)
626
+ self.w3 = nn.Linear(self.hidden_dim, self.ffn_dim, bias=False)
627
+
628
+ if config.hidden_activation is None:
629
+ logger.warning_once(
630
+ "Gemmoe's activation function should be approximate GeLU and not exact GeLU.\n"
631
+ "Changing the activation function to `gelu_pytorch_tanh`."
632
+ f"if you want to use the legacy `{config.hidden_act}`, "
633
+ f"edit the `model.config` to set `hidden_activation={config.hidden_act}` "
634
+ " instead of `hidden_act`. See https://github.com/huggingface/transformers/pull/29402 for more details."
635
+ )
636
+ hidden_activation = "gelu_pytorch_tanh"
637
+ else:
638
+ hidden_activation = config.hidden_activation
639
+
640
+ self.act_fn = ACT2FN[hidden_activation]
641
+
642
+ def forward(self, hidden_states):
643
+ current_hidden_states = self.act_fn(self.w1(hidden_states)) * self.w3(hidden_states)
644
+ current_hidden_states = self.w2(current_hidden_states)
645
+ return current_hidden_states.to(hidden_states.dtype)
646
+
647
+
648
+ class GemmoeSparseMoeBlock(nn.Module):
649
+ def __init__(self, config):
650
+ super().__init__()
651
+ self.hidden_dim = config.hidden_size
652
+ self.ffn_dim = config.intermediate_size
653
+ self.num_experts = config.num_local_experts
654
+ self.top_k = 2
655
+
656
+ # gating
657
+ self.gate = nn.Linear(self.hidden_dim, self.num_experts, bias=False)
658
+
659
+ self.experts = nn.ModuleList([GemmoeBlockSparseTop2MLP(config) for _ in range(self.num_experts)])
660
+
661
+ def forward(self, hidden_states: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
662
+ batch_size, sequence_length, hidden_dim = hidden_states.shape
663
+ hidden_states = hidden_states.view(-1, hidden_dim)
664
+
665
+ # router_logits: (batch * sequence_length, n_experts)
666
+ router_logits = self.gate(hidden_states)
667
+ routing_weights = F.softmax(router_logits, dim=1)
668
+ topk_weight, topk_idx = torch.topk(routing_weights, self.top_k, dim=-1, sorted=False)
669
+ topk_weight /= topk_weight.sum(dim=-1, keepdim=True)
670
+
671
+ hidden_states = hidden_states.repeat_interleave(self.top_k, dim=0)
672
+
673
+ y = torch.empty_like(hidden_states)
674
+
675
+ flat_topk_idx = topk_idx.view(-1)
676
+ for i in range(self.num_experts):
677
+ expert = self.experts[i]
678
+ expert_output = expert(hidden_states[flat_topk_idx == i])
679
+ y[flat_topk_idx == i] = expert_output
680
+
681
+ y = (y.view(*topk_weight.shape, -1) * topk_weight.unsqueeze(-1)).sum(dim=1)
682
+
683
+ final_hidden_states = y.reshape(batch_size, sequence_length, hidden_dim)
684
+ return final_hidden_states.to(hidden_states.dtype), router_logits.to(hidden_states.dtype)
685
+
686
+
687
+ # Copied from transformers.models.llama.modeling_llama.LlamaDecoderLayer with LLAMA->GEMMOE,Llama->Gemmoe
688
+ class GemmoeDecoderLayer(nn.Module):
689
+ def __init__(self, config: GemmoeConfig, layer_idx: int):
690
+ super().__init__()
691
+ self.hidden_size = config.hidden_size
692
+
693
+ self.self_attn = GEMMOE_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx)
694
+
695
+ self.block_sparse_moe = GemmoeSparseMoeBlock(config)
696
+ self.input_layernorm = GemmoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
697
+ self.post_attention_layernorm = GemmoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
698
+
699
+ def forward(
700
+ self,
701
+ hidden_states: torch.Tensor,
702
+ attention_mask: Optional[torch.Tensor] = None,
703
+ position_ids: Optional[torch.LongTensor] = None,
704
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
705
+ output_attentions: Optional[bool] = False,
706
+ output_router_logits: Optional[bool] = False,
707
+ use_cache: Optional[bool] = False,
708
+ cache_position: Optional[torch.LongTensor] = None,
709
+ **kwargs,
710
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
711
+ # ... (rest of the code remains the same)
712
+ if "padding_mask" in kwargs:
713
+ warnings.warn(
714
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
715
+ )
716
+ """
717
+ Args:
718
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
719
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
720
+ `(batch, sequence_length)` where padding elements are indicated by 0.
721
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
722
+ output_attentions (`bool`, *optional*):
723
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
724
+ returned tensors for more detail.
725
+ output_router_logits (`bool`, *optional*):
726
+ Whether or not to return the logits of all the routers. They are useful for computing the router loss, and
727
+ should not be returned during inference.
728
+ use_cache (`bool`, *optional*):
729
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
730
+ (see `past_key_values`).
731
+ """
732
+
733
+ residual = hidden_states
734
+
735
+ hidden_states = self.input_layernorm(hidden_states)
736
+
737
+ # Self Attention
738
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
739
+ hidden_states=hidden_states,
740
+ attention_mask=attention_mask,
741
+ position_ids=position_ids,
742
+ past_key_value=past_key_value,
743
+ output_attentions=output_attentions,
744
+ use_cache=use_cache,
745
+ )
746
+ hidden_states = residual + hidden_states
747
+
748
+ # Fully Connected
749
+ residual = hidden_states
750
+ hidden_states = self.post_attention_layernorm(hidden_states)
751
+ hidden_states, router_logits = self.block_sparse_moe(hidden_states)
752
+ hidden_states = residual + hidden_states
753
+
754
+ outputs = (hidden_states,)
755
+
756
+ if output_attentions:
757
+ outputs += (self_attn_weights,)
758
+
759
+ if use_cache:
760
+ outputs += (present_key_value,)
761
+
762
+ if output_router_logits:
763
+ outputs += (router_logits,)
764
+
765
+ return outputs
766
+
767
+
768
+ GEMMOE_START_DOCSTRING = r"""
769
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
770
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
771
+ etc.)
772
+
773
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
774
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
775
+ and behavior.
776
+
777
+ Parameters:
778
+ config ([`GemmoeConfig`]):
779
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
780
+ load the weights associated with the model, only the configuration. Check out the
781
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
782
+ """
783
+
784
+
785
+ @add_start_docstrings(
786
+ "The bare Gemmoe Model outputting raw hidden-states without any specific head on top.",
787
+ GEMMOE_START_DOCSTRING,
788
+ )
789
+ class GemmoePreTrainedModel(PreTrainedModel):
790
+ config_class = GemmoeConfig
791
+ base_model_prefix = "model"
792
+ supports_gradient_checkpointing = True
793
+ _keep_in_fp32_modules = ["inv_freq", "rotary_emb", "cos_cached", "sin_cached"]
794
+ _no_split_modules = ["GemmoeDecoderLayer"]
795
+ _skip_keys_device_placement = ["past_key_values", "causal_mask"]
796
+ _supports_flash_attn_2 = True
797
+ _supports_sdpa = True
798
+ _supports_cache_class = True
799
+
800
+ def _init_weights(self, module):
801
+ std = self.config.initializer_range
802
+ if isinstance(module, nn.Linear):
803
+ module.weight.data.normal_(mean=0.0, std=std)
804
+ if module.bias is not None:
805
+ module.bias.data.zero_()
806
+ elif isinstance(module, nn.Embedding):
807
+ module.weight.data.normal_(mean=0.0, std=std)
808
+ if module.padding_idx is not None:
809
+ module.weight.data[module.padding_idx].zero_()
810
+
811
+ def _setup_cache(self, cache_cls, max_batch_size, max_cache_len: Optional[int] = None):
812
+ if self.config._attn_implementation == "flash_attention_2" and cache_cls == StaticCache:
813
+ raise ValueError(
814
+ "`static` cache implementation is not compatible with `attn_implementation==flash_attention_2` "
815
+ "make sure to use `sdpa` in the mean time, and open an issue at https://github.com/huggingface/transformers"
816
+ )
817
+
818
+ if max_cache_len > self.model.causal_mask.shape[-1] or self.device != self.model.causal_mask.device:
819
+ causal_mask = torch.full((max_cache_len, max_cache_len), fill_value=1, device=self.device)
820
+ self.register_buffer("causal_mask", torch.triu(causal_mask, diagonal=1), persistent=False)
821
+
822
+ for layer in self.model.layers:
823
+ weights = layer.self_attn.o_proj.weight
824
+ layer.self_attn.past_key_value = cache_cls(
825
+ self.config, max_batch_size, max_cache_len, device=weights.device, dtype=weights.dtype
826
+ )
827
+
828
+ def _reset_cache(self):
829
+ for layer in self.model.layers:
830
+ layer.self_attn.past_key_value = None
831
+
832
+
833
+ GEMMOE_INPUTS_DOCSTRING = r"""
834
+ Args:
835
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
836
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
837
+ it.
838
+
839
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
840
+ [`PreTrainedTokenizer.__call__`] for details.
841
+
842
+ [What are input IDs?](../glossary#input-ids)
843
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
844
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
845
+
846
+ - 1 for tokens that are **not masked**,
847
+ - 0 for tokens that are **masked**.
848
+
849
+ [What are attention masks?](../glossary#attention-mask)
850
+
851
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
852
+ [`PreTrainedTokenizer.__call__`] for details.
853
+
854
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
855
+ `past_key_values`).
856
+
857
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
858
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
859
+ information on the default strategy.
860
+
861
+ - 1 indicates the head is **not masked**,
862
+ - 0 indicates the head is **masked**.
863
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
864
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
865
+ config.n_positions - 1]`.
866
+
867
+ [What are position IDs?](../glossary#position-ids)
868
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
869
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
870
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
871
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
872
+
873
+ Two formats are allowed:
874
+ - a [`~cache_utils.Cache`] instance;
875
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
876
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
877
+ cache format.
878
+
879
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
880
+ legacy cache format will be returned.
881
+
882
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
883
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
884
+ of shape `(batch_size, sequence_length)`.
885
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
886
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
887
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
888
+ model's internal embedding lookup matrix.
889
+ use_cache (`bool`, *optional*):
890
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
891
+ `past_key_values`).
892
+ output_attentions (`bool`, *optional*):
893
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
894
+ tensors for more detail.
895
+ output_hidden_states (`bool`, *optional*):
896
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
897
+ more detail.
898
+ return_dict (`bool`, *optional*):
899
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
900
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
901
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
902
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
903
+ the complete sequence length.
904
+ """
905
+
906
+
907
+ @add_start_docstrings(
908
+ "The bare Gemmoe Model outputting raw hidden-states without any specific head on top.",
909
+ GEMMOE_START_DOCSTRING,
910
+ )
911
+ # Copied from transformers.models.llama.modeling_llama.LlamaModel with LLAMA->GEMMOE,Llama->Gemmoe
912
+ class GemmoeModel(GemmoePreTrainedModel):
913
+ """
914
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`GemmoeDecoderLayer`]
915
+
916
+ Args:
917
+ config: GemmoeConfig
918
+ """
919
+
920
+ def __init__(self, config: GemmoeConfig):
921
+ super().__init__(config)
922
+ self.padding_idx = config.pad_token_id
923
+ self.vocab_size = config.vocab_size
924
+
925
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
926
+ self.layers = nn.ModuleList(
927
+ [GemmoeDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
928
+ )
929
+ self.norm = GemmoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
930
+ self.gradient_checkpointing = False
931
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
932
+
933
+ # Register a causal mask to separate causal and padding mask creation. Merging happens in the attention class.
934
+ # NOTE: This is not friendly with TorchScript, ONNX, ExportedProgram serialization for very large `max_position_embeddings`.
935
+ causal_mask = torch.full(
936
+ (config.max_position_embeddings, config.max_position_embeddings), fill_value=True, dtype=torch.bool
937
+ )
938
+ self.register_buffer("causal_mask", torch.triu(causal_mask, diagonal=1), persistent=False)
939
+ # Initialize weights and apply final processing
940
+ self.post_init()
941
+
942
+ def get_input_embeddings(self):
943
+ return self.embed_tokens
944
+
945
+ def set_input_embeddings(self, value):
946
+ self.embed_tokens = value
947
+
948
+ @add_start_docstrings_to_model_forward(GEMMOE_INPUTS_DOCSTRING)
949
+ def forward(
950
+ self,
951
+ input_ids: torch.LongTensor = None,
952
+ attention_mask: Optional[torch.Tensor] = None,
953
+ position_ids: Optional[torch.LongTensor] = None,
954
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
955
+ inputs_embeds: Optional[torch.FloatTensor] = None,
956
+ use_cache: Optional[bool] = None,
957
+ output_attentions: Optional[bool] = None,
958
+ output_hidden_states: Optional[bool] = None,
959
+ output_router_logits: Optional[bool] = None,
960
+ return_dict: Optional[bool] = None,
961
+ cache_position: Optional[torch.LongTensor] = None,
962
+ ) -> Union[Tuple, MoeModelOutputWithPast]:
963
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
964
+ output_router_logits = (
965
+ output_router_logits if output_router_logits is not None else self.config.output_router_logits
966
+ )
967
+ output_hidden_states = (
968
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
969
+ )
970
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
971
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
972
+
973
+ if (input_ids is None) ^ (inputs_embeds is not None):
974
+ raise ValueError(
975
+ "You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
976
+ )
977
+
978
+ if self.gradient_checkpointing and self.training and use_cache:
979
+ logger.warning_once(
980
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
981
+ )
982
+ use_cache = False
983
+
984
+ if inputs_embeds is None:
985
+ inputs_embeds = self.embed_tokens(input_ids)
986
+
987
+ past_seen_tokens = 0
988
+ if use_cache: # kept for BC (cache positions)
989
+ if not isinstance(past_key_values, StaticCache):
990
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
991
+ past_seen_tokens = past_key_values.get_seq_length()
992
+
993
+ if cache_position is None:
994
+ cache_position = torch.arange(
995
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
996
+ )
997
+
998
+ if position_ids is None:
999
+ position_ids = cache_position.unsqueeze(0)
1000
+
1001
+ if attention_mask is not None and self._use_flash_attention_2 and use_cache:
1002
+ is_padding_right = attention_mask[:, -1].sum().item() != inputs_embeds.shape[0]
1003
+ if is_padding_right:
1004
+ raise ValueError(
1005
+ "You are attempting to perform batched generation with padding_side='right'"
1006
+ " this may lead to unexpected behaviour for Flash Attention version of Gemmoe. Make sure to "
1007
+ " call `tokenizer.padding_side = 'left'` before tokenizing the input. "
1008
+ )
1009
+
1010
+ if self._use_flash_attention_2:
1011
+ # 2d mask is passed through the layers
1012
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1013
+ else:
1014
+ causal_mask = self._update_causal_mask(attention_mask, inputs_embeds, past_seen_tokens)
1015
+
1016
+ # normalized
1017
+ # Gemmoe downcasts the below to float16, causing sqrt(3072)=55.4256 to become 55.5
1018
+ # See https://github.com/huggingface/transformers/pull/29402
1019
+ normalizer = torch.tensor(self.config.hidden_size**0.5, dtype=inputs_embeds.dtype)
1020
+ hidden_states = inputs_embeds * normalizer
1021
+
1022
+ # decoder layers
1023
+ all_hidden_states = () if output_hidden_states else None
1024
+ all_self_attns = () if output_attentions else None
1025
+ all_router_logits = () if output_router_logits else None
1026
+ next_decoder_cache = None
1027
+
1028
+ for decoder_layer in self.layers:
1029
+ if output_hidden_states:
1030
+ all_hidden_states += (hidden_states,)
1031
+
1032
+ if self.gradient_checkpointing and self.training:
1033
+ layer_outputs = self._gradient_checkpointing_func(
1034
+ decoder_layer.__call__,
1035
+ hidden_states,
1036
+ causal_mask if not self._use_flash_attention_2 else attention_mask,
1037
+ position_ids,
1038
+ past_key_values,
1039
+ output_attentions,
1040
+ output_router_logits,
1041
+ use_cache,
1042
+ cache_position,
1043
+ )
1044
+ else:
1045
+ layer_outputs = decoder_layer(
1046
+ hidden_states,
1047
+ attention_mask=causal_mask if not self._use_flash_attention_2 else attention_mask,
1048
+ position_ids=position_ids,
1049
+ past_key_value=past_key_values,
1050
+ output_attentions=output_attentions,
1051
+ output_router_logits=output_router_logits,
1052
+ use_cache=use_cache,
1053
+ cache_position=cache_position,
1054
+ )
1055
+
1056
+ hidden_states = layer_outputs[0]
1057
+
1058
+ if use_cache:
1059
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1060
+
1061
+ if output_attentions:
1062
+ all_self_attns += (layer_outputs[1],)
1063
+
1064
+ if output_router_logits:
1065
+ all_router_logits += (layer_outputs[-1],)
1066
+
1067
+ hidden_states = self.norm(hidden_states)
1068
+
1069
+ # add hidden states from the last decoder layer
1070
+ if output_hidden_states:
1071
+ all_hidden_states += (hidden_states,)
1072
+
1073
+ next_cache = None
1074
+ if use_cache:
1075
+ next_cache = (
1076
+ next_decoder_cache.to_legacy_cache() if isinstance(next_decoder_cache, Cache) else next_decoder_cache
1077
+ )
1078
+ if not return_dict:
1079
+ return tuple(
1080
+ v
1081
+ for v in [hidden_states, next_cache, all_hidden_states, all_self_attns, all_router_logits]
1082
+ if v is not None
1083
+ )
1084
+ return MoeModelOutputWithPast(
1085
+ last_hidden_state=hidden_states,
1086
+ past_key_values=next_cache,
1087
+ hidden_states=all_hidden_states,
1088
+ attentions=all_self_attns,
1089
+ router_logits=all_router_logits,
1090
+ )
1091
+
1092
+ # TODO: As of torch==2.2.0, the `attention_mask` passed to the model in `generate` is 2D and of dynamic length even when the static
1093
+ # KV cache is used. This is an issue for torch.compile which then recaptures cudagraphs at each decode steps due to the dynamic shapes.
1094
+ # (`recording cudagraph tree for symint key 13`, etc.), which is VERY slow. A workaround is `@torch.compiler.disable`, but this prevents using
1095
+ # `fullgraph=True`. See more context in https://github.com/huggingface/transformers/pull/29114
1096
+ def _update_causal_mask(self, attention_mask, input_tensor, past_seen_tokens):
1097
+ if self.config._attn_implementation == "flash_attention_2":
1098
+ if attention_mask is not None and 0.0 in attention_mask:
1099
+ return attention_mask
1100
+ return None
1101
+
1102
+ batch_size, seq_length = input_tensor.shape[:2]
1103
+ dtype = input_tensor.dtype
1104
+ device = input_tensor.device
1105
+
1106
+ # support going beyond cached `max_position_embedding`
1107
+ if seq_length > self.causal_mask.shape[-1]:
1108
+ causal_mask = torch.full((2 * self.causal_mask.shape[-1], 2 * self.causal_mask.shape[-1]), fill_value=1)
1109
+ self.register_buffer("causal_mask", torch.triu(causal_mask, diagonal=1), persistent=False)
1110
+
1111
+ # We use the current dtype to avoid any overflows
1112
+ min_dtype = torch.finfo(dtype).min
1113
+
1114
+ causal_mask = self.causal_mask[None, None, :, :].to(dtype=dtype, device=device) * min_dtype
1115
+ causal_mask = causal_mask.expand(batch_size, 1, -1, -1)
1116
+ if attention_mask is not None:
1117
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
1118
+ if attention_mask.dim() == 2:
1119
+ mask_length = attention_mask.shape[-1]
1120
+ padding_mask = causal_mask[..., :mask_length].eq(0.0) * attention_mask[:, None, None, :].eq(0.0)
1121
+ causal_mask[..., :mask_length] = causal_mask[..., :mask_length].masked_fill(padding_mask, min_dtype)
1122
+ elif attention_mask.dim() == 4:
1123
+ # backwards compatibility: we allow passing a 4D attention mask shorter than the input length with
1124
+ # cache. In that case, the 4D attention mask attends to the newest tokens only.
1125
+ if attention_mask.shape[-2] < past_seen_tokens + input_tensor.shape[1]:
1126
+ offset = past_seen_tokens
1127
+ else:
1128
+ offset = 0
1129
+ mask_shape = attention_mask.shape
1130
+ mask_slice = (attention_mask.eq(0.0)).to(dtype=dtype) * min_dtype
1131
+ causal_mask[
1132
+ : mask_shape[0], : mask_shape[1], offset : mask_shape[2] + offset, : mask_shape[3]
1133
+ ] = mask_slice
1134
+
1135
+ if (
1136
+ self.config._attn_implementation == "sdpa"
1137
+ and attention_mask is not None
1138
+ and attention_mask.device.type == "cuda"
1139
+ ):
1140
+ # TODO: For dynamo, rather use a check on fullgraph=True once this is possible (https://github.com/pytorch/pytorch/pull/120400).
1141
+ is_tracing = (
1142
+ torch.jit.is_tracing()
1143
+ or isinstance(input_tensor, torch.fx.Proxy)
1144
+ or (hasattr(torch, "_dynamo") and torch._dynamo.is_compiling())
1145
+ )
1146
+ if not is_tracing and torch.any(attention_mask != 1):
1147
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
1148
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
1149
+ # Details: https://github.com/pytorch/pytorch/issues/110213
1150
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
1151
+
1152
+ return causal_mask
1153
+
1154
+
1155
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM with LLAMA->GEMMOE,Llama->Gemmoe,llama->GEMMA
1156
+ class GemmoeForCausalLM(GemmoePreTrainedModel):
1157
+ _tied_weights_keys = ["lm_head.weight"]
1158
+
1159
+ def __init__(self, config):
1160
+ super().__init__(config)
1161
+ self.model = GemmoeModel(config)
1162
+ self.vocab_size = config.vocab_size
1163
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1164
+ self.router_aux_loss_coef = config.router_aux_loss_coef
1165
+ self.num_experts = config.num_local_experts
1166
+ self.num_experts_per_tok = config.num_experts_per_tok
1167
+ # Initialize weights and apply final processing
1168
+ self.post_init()
1169
+
1170
+ def get_input_embeddings(self):
1171
+ return self.model.embed_tokens
1172
+
1173
+ def set_input_embeddings(self, value):
1174
+ self.model.embed_tokens = value
1175
+
1176
+ def get_output_embeddings(self):
1177
+ return self.lm_head
1178
+
1179
+ def set_output_embeddings(self, new_embeddings):
1180
+ self.lm_head = new_embeddings
1181
+
1182
+ def set_decoder(self, decoder):
1183
+ self.model = decoder
1184
+
1185
+ def get_decoder(self):
1186
+ return self.model
1187
+
1188
+ @add_start_docstrings_to_model_forward(GEMMOE_INPUTS_DOCSTRING)
1189
+ @replace_return_docstrings(output_type=MoeCausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1190
+ def forward(
1191
+ self,
1192
+ input_ids: torch.LongTensor = None,
1193
+ attention_mask: Optional[torch.Tensor] = None,
1194
+ position_ids: Optional[torch.LongTensor] = None,
1195
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1196
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1197
+ labels: Optional[torch.LongTensor] = None,
1198
+ use_cache: Optional[bool] = None,
1199
+ output_attentions: Optional[bool] = None,
1200
+ output_hidden_states: Optional[bool] = None,
1201
+ output_router_logits: Optional[bool] = None,
1202
+ return_dict: Optional[bool] = None,
1203
+ cache_position: Optional[torch.LongTensor] = None,
1204
+ ) -> Union[Tuple, MoeCausalLMOutputWithPast]:
1205
+ r"""
1206
+ Args:
1207
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1208
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1209
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1210
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1211
+
1212
+ Returns:
1213
+
1214
+ Example:
1215
+
1216
+ ```python
1217
+ >>> from transformers import AutoTokenizer, GemmoeForCausalLM
1218
+
1219
+ >>> model= GemmoeForCausalLM.from_pretrained("google/GEMMA-7b")
1220
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/GEMMA-7b")
1221
+ >>> prompt = "What is your favorite condiment?"
1222
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1223
+
1224
+ >>> # Generate
1225
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1226
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1227
+ "What is your favorite condiment?"
1228
+ ```"""
1229
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1230
+ output_router_logits = (
1231
+ output_router_logits if output_router_logits is not None else self.config.output_router_logits
1232
+ )
1233
+ output_hidden_states = (
1234
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1235
+ )
1236
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1237
+
1238
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1239
+ outputs = self.model(
1240
+ input_ids=input_ids,
1241
+ attention_mask=attention_mask,
1242
+ position_ids=position_ids,
1243
+ past_key_values=past_key_values,
1244
+ inputs_embeds=inputs_embeds,
1245
+ use_cache=use_cache,
1246
+ output_attentions=output_attentions,
1247
+ output_hidden_states=output_hidden_states,
1248
+ output_router_logits=output_router_logits,
1249
+ return_dict=return_dict,
1250
+ cache_position=cache_position,
1251
+ )
1252
+
1253
+ hidden_states = outputs[0]
1254
+ logits = self.lm_head(hidden_states)
1255
+ logits = logits.float()
1256
+
1257
+ loss = None
1258
+ if labels is not None:
1259
+ # Shift so that tokens < n predict n
1260
+ shift_logits = logits[..., :-1, :].contiguous()
1261
+ shift_labels = labels[..., 1:].contiguous()
1262
+ # Flatten the tokens
1263
+ loss_fct = CrossEntropyLoss()
1264
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1265
+ shift_labels = shift_labels.view(-1)
1266
+ # Enable model parallelism
1267
+ shift_labels = shift_labels.to(shift_logits.device)
1268
+ loss = loss_fct(shift_logits, shift_labels)
1269
+
1270
+ aux_loss = None
1271
+ if output_router_logits:
1272
+ aux_loss = load_balancing_loss_func(
1273
+ outputs.router_logits if return_dict else outputs[-1], self.num_experts, self.num_experts_per_tok
1274
+ )
1275
+ if labels is not None:
1276
+ loss += self.router_aux_loss_coef * aux_loss
1277
+
1278
+ if not return_dict:
1279
+ output = (logits,) + outputs[1:]
1280
+ if output_router_logits:
1281
+ output = (aux_loss,) + output
1282
+ return (loss,) + output if loss is not None else output
1283
+
1284
+ return MoeCausalLMOutputWithPast(
1285
+ loss=loss,
1286
+ aux_loss=aux_loss,
1287
+ logits=logits,
1288
+ past_key_values=outputs.past_key_values,
1289
+ hidden_states=outputs.hidden_states,
1290
+ attentions=outputs.attentions,
1291
+ router_logits=outputs.router_logits,
1292
+ )
1293
+
1294
+ def prepare_inputs_for_generation(
1295
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, cache_position=None, **kwargs
1296
+ ):
1297
+ # With static cache, the `past_key_values` is None
1298
+ # TODO joao: standardize interface for the different Cache classes and remove of this if
1299
+ has_static_cache = False
1300
+ if past_key_values is None:
1301
+ past_key_values = getattr(self.model.layers[0].self_attn, "past_key_value", None)
1302
+ has_static_cache = past_key_values is not None
1303
+
1304
+ past_length = 0
1305
+ if past_key_values is not None:
1306
+ if isinstance(past_key_values, Cache):
1307
+ past_length = cache_position[0] if cache_position is not None else past_key_values.get_seq_length()
1308
+ max_cache_length = (
1309
+ torch.tensor(past_key_values.get_max_length(), device=input_ids.device)
1310
+ if past_key_values.get_max_length() is not None
1311
+ else None
1312
+ )
1313
+ cache_length = past_length if max_cache_length is None else torch.min(max_cache_length, past_length)
1314
+ # TODO joao: remove this `else` after `generate` prioritizes `Cache` objects
1315
+ else:
1316
+ cache_length = past_length = past_key_values[0][0].shape[2]
1317
+ max_cache_length = None
1318
+
1319
+ # Keep only the unprocessed tokens:
1320
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1321
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
1322
+ # input)
1323
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1324
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1325
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1326
+ # input_ids based on the past_length.
1327
+ elif past_length < input_ids.shape[1]:
1328
+ input_ids = input_ids[:, past_length:]
1329
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1330
+
1331
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1332
+ if (
1333
+ max_cache_length is not None
1334
+ and attention_mask is not None
1335
+ and cache_length + input_ids.shape[1] > max_cache_length
1336
+ ):
1337
+ attention_mask = attention_mask[:, -max_cache_length:]
1338
+
1339
+ position_ids = kwargs.get("position_ids", None)
1340
+ if attention_mask is not None and position_ids is None:
1341
+ # create position_ids on the fly for batch generation
1342
+ position_ids = attention_mask.long().cumsum(-1) - 1
1343
+ position_ids.masked_fill_(attention_mask == 0, 1)
1344
+ if past_key_values:
1345
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1346
+
1347
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1348
+ if inputs_embeds is not None and past_key_values is None:
1349
+ model_inputs = {"inputs_embeds": inputs_embeds}
1350
+ else:
1351
+ # The `contiguous()` here is necessary to have a static stride during decoding. torchdynamo otherwise
1352
+ # recompiles graphs as the stride of the inputs is a guard. Ref: https://github.com/huggingface/transformers/pull/29114
1353
+ # TODO: use `next_tokens` directly instead.
1354
+ model_inputs = {"input_ids": input_ids.contiguous()}
1355
+
1356
+ input_length = position_ids.shape[-1] if position_ids is not None else input_ids.shape[-1]
1357
+ if cache_position is None:
1358
+ cache_position = torch.arange(past_length, past_length + input_length, device=input_ids.device)
1359
+ else:
1360
+ cache_position = cache_position[-input_length:]
1361
+
1362
+ if has_static_cache:
1363
+ past_key_values = None
1364
+
1365
+ model_inputs.update(
1366
+ {
1367
+ "position_ids": position_ids,
1368
+ "cache_position": cache_position,
1369
+ "past_key_values": past_key_values,
1370
+ "use_cache": kwargs.get("use_cache"),
1371
+ "attention_mask": attention_mask,
1372
+ }
1373
+ )
1374
+ return model_inputs
1375
+
1376
+ @staticmethod
1377
+ def _reorder_cache(past_key_values, beam_idx):
1378
+ reordered_past = ()
1379
+ for layer_past in past_key_values:
1380
+ reordered_past += (
1381
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1382
+ )
1383
+ return reordered_past
1384
+
1385
+ @add_start_docstrings(
1386
+ """
1387
+ The Gemmoe Model transformer with a sequence classification head on top (linear layer).
1388
+
1389
+ [`GemmoeForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1390
+ (e.g. GPT-2) do.
1391
+
1392
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1393
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1394
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1395
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1396
+ each row of the batch).
1397
+ """,
1398
+ GEMMOE_START_DOCSTRING,
1399
+ )
1400
+ # Copied from transformers.models.llama.modeling_llama.LlamaForSequenceClassification with LLAMA->GEMMOE,Llama->Gemmoe
1401
+ class GemmoeForSequenceClassification(GemmoePreTrainedModel):
1402
+ def __init__(self, config):
1403
+ super().__init__(config)
1404
+ self.num_labels = config.num_labels
1405
+ self.model = GemmoeModel(config)
1406
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1407
+
1408
+ # Initialize weights and apply final processing
1409
+ self.post_init()
1410
+
1411
+ def get_input_embeddings(self):
1412
+ return self.model.embed_tokens
1413
+
1414
+ def set_input_embeddings(self, value):
1415
+ self.model.embed_tokens = value
1416
+
1417
+ @add_start_docstrings_to_model_forward(GEMMOE_INPUTS_DOCSTRING)
1418
+ def forward(
1419
+ self,
1420
+ input_ids: torch.LongTensor = None,
1421
+ attention_mask: Optional[torch.Tensor] = None,
1422
+ position_ids: Optional[torch.LongTensor] = None,
1423
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1424
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1425
+ labels: Optional[torch.LongTensor] = None,
1426
+ use_cache: Optional[bool] = None,
1427
+ output_attentions: Optional[bool] = None,
1428
+ output_hidden_states: Optional[bool] = None,
1429
+ return_dict: Optional[bool] = None,
1430
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1431
+ r"""
1432
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1433
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1434
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1435
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1436
+ """
1437
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1438
+
1439
+ transformer_outputs = self.model(
1440
+ input_ids,
1441
+ attention_mask=attention_mask,
1442
+ position_ids=position_ids,
1443
+ past_key_values=past_key_values,
1444
+ inputs_embeds=inputs_embeds,
1445
+ use_cache=use_cache,
1446
+ output_attentions=output_attentions,
1447
+ output_hidden_states=output_hidden_states,
1448
+ return_dict=return_dict,
1449
+ cache_position=None,
1450
+ )
1451
+ hidden_states = transformer_outputs[0]
1452
+ logits = self.score(hidden_states)
1453
+
1454
+ if input_ids is not None:
1455
+ batch_size = input_ids.shape[0]
1456
+ else:
1457
+ batch_size = inputs_embeds.shape[0]
1458
+
1459
+ if self.config.pad_token_id is None and batch_size != 1:
1460
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1461
+ if self.config.pad_token_id is None:
1462
+ sequence_lengths = -1
1463
+ else:
1464
+ if input_ids is not None:
1465
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1466
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1467
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1468
+ sequence_lengths = sequence_lengths.to(logits.device)
1469
+ else:
1470
+ sequence_lengths = -1
1471
+
1472
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1473
+
1474
+ loss = None
1475
+ if labels is not None:
1476
+ labels = labels.to(logits.device)
1477
+ if self.config.problem_type is None:
1478
+ if self.num_labels == 1:
1479
+ self.config.problem_type = "regression"
1480
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1481
+ self.config.problem_type = "single_label_classification"
1482
+ else:
1483
+ self.config.problem_type = "multi_label_classification"
1484
+
1485
+ if self.config.problem_type == "regression":
1486
+ loss_fct = MSELoss()
1487
+ if self.num_labels == 1:
1488
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1489
+ else:
1490
+ loss = loss_fct(pooled_logits, labels)
1491
+ elif self.config.problem_type == "single_label_classification":
1492
+ loss_fct = CrossEntropyLoss()
1493
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1494
+ elif self.config.problem_type == "multi_label_classification":
1495
+ loss_fct = BCEWithLogitsLoss()
1496
+ loss = loss_fct(pooled_logits, labels)
1497
+ if not return_dict:
1498
+ output = (pooled_logits,) + transformer_outputs[1:]
1499
+ return ((loss,) + output) if loss is not None else output
1500
+
1501
+ return SequenceClassifierOutputWithPast(
1502
+ loss=loss,
1503
+ logits=pooled_logits,
1504
+ past_key_values=transformer_outputs.past_key_values,
1505
+ hidden_states=transformer_outputs.hidden_states,
1506
+ attentions=transformer_outputs.attentions,
1507
+ )