Crystalcareai
commited on
Commit
•
008f139
1
Parent(s):
7014657
Upload 3 files
Browse files- configuration_gemmoe.py +165 -0
- modeling_gemmoe.py +1477 -0
- tokenization_gemmoe.py +311 -0
configuration_gemmoe.py
ADDED
@@ -0,0 +1,165 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 ...configuration_utils import PretrainedConfig
|
18 |
+
from ...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",
|
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 |
+
tie_word_embeddings=True,
|
130 |
+
rope_theta=10000.0,
|
131 |
+
attention_bias=False,
|
132 |
+
attention_dropout=0.0,
|
133 |
+
num_experts_per_tok=2,
|
134 |
+
num_local_experts=8,
|
135 |
+
router_aux_loss_coef=0.01,
|
136 |
+
output_router_logits=False,
|
137 |
+
**kwargs,
|
138 |
+
):
|
139 |
+
self.vocab_size = vocab_size
|
140 |
+
self.max_position_embeddings = max_position_embeddings
|
141 |
+
self.hidden_size = hidden_size
|
142 |
+
self.intermediate_size = intermediate_size
|
143 |
+
self.num_hidden_layers = num_hidden_layers
|
144 |
+
self.num_attention_heads = num_attention_heads
|
145 |
+
self.head_dim = head_dim
|
146 |
+
self.num_key_value_heads = num_key_value_heads
|
147 |
+
self.hidden_act = hidden_act
|
148 |
+
self.initializer_range = initializer_range
|
149 |
+
self.rms_norm_eps = rms_norm_eps
|
150 |
+
self.use_cache = use_cache
|
151 |
+
self.rope_theta = rope_theta
|
152 |
+
self.attention_bias = attention_bias
|
153 |
+
self.attention_dropout = attention_dropout
|
154 |
+
self.num_experts_per_tok = num_experts_per_tok
|
155 |
+
self.num_local_experts = num_local_experts
|
156 |
+
self.router_aux_loss_coef = router_aux_loss_coef
|
157 |
+
self.output_router_logits = output_router_logits
|
158 |
+
|
159 |
+
super().__init__(
|
160 |
+
pad_token_id=pad_token_id,
|
161 |
+
bos_token_id=bos_token_id,
|
162 |
+
eos_token_id=eos_token_id,
|
163 |
+
tie_word_embeddings=tie_word_embeddings,
|
164 |
+
**kwargs,
|
165 |
+
)
|
modeling_gemmoe.py
ADDED
@@ -0,0 +1,1477 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 ...activations import ACT2FN
|
29 |
+
from ...cache_utils import Cache, DynamicCache, StaticCache
|
30 |
+
from ...modeling_attn_mask_utils import (
|
31 |
+
_prepare_4d_causal_attention_mask,
|
32 |
+
)
|
33 |
+
from ...modeling_outputs import SequenceClassifierOutputWithPast, MoeModelOutputWithPast, MoeCausalLMOutputWithPast
|
34 |
+
from ...modeling_utils import PreTrainedModel
|
35 |
+
from ...pytorch_utils import ALL_LAYERNORM_LAYERS, is_torch_greater_or_equal_than_1_13
|
36 |
+
from ...utils import (
|
37 |
+
add_start_docstrings,
|
38 |
+
add_start_docstrings_to_model_forward,
|
39 |
+
is_flash_attn_2_available,
|
40 |
+
is_flash_attn_greater_or_equal_2_10,
|
41 |
+
logging,
|
42 |
+
replace_return_docstrings,
|
43 |
+
)
|
44 |
+
from ...utils.import_utils import is_torch_fx_available
|
45 |
+
from .configuration_gemmoe import GemmoeConfig
|
46 |
+
|
47 |
+
from math import sqrt as math_sqrt
|
48 |
+
|
49 |
+
|
50 |
+
if is_flash_attn_2_available():
|
51 |
+
from flash_attn import flash_attn_func, flash_attn_varlen_func
|
52 |
+
from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
|
53 |
+
|
54 |
+
|
55 |
+
# This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.
|
56 |
+
# It means that the function will not be traced through and simply appear as a node in the graph.
|
57 |
+
if is_torch_fx_available():
|
58 |
+
if not is_torch_greater_or_equal_than_1_13:
|
59 |
+
import torch.fx
|
60 |
+
|
61 |
+
_prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask)
|
62 |
+
|
63 |
+
|
64 |
+
logger = logging.get_logger(__name__)
|
65 |
+
|
66 |
+
_CONFIG_FOR_DOC = "GemmoeConfig"
|
67 |
+
|
68 |
+
def approx_gelu(x):
|
69 |
+
return 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * x**3)))
|
70 |
+
|
71 |
+
def _get_unpad_data(attention_mask):
|
72 |
+
seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
|
73 |
+
indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
|
74 |
+
max_seqlen_in_batch = seqlens_in_batch.max().item()
|
75 |
+
cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
|
76 |
+
return (
|
77 |
+
indices,
|
78 |
+
cu_seqlens,
|
79 |
+
max_seqlen_in_batch,
|
80 |
+
)
|
81 |
+
|
82 |
+
|
83 |
+
class GemmoeRMSNorm(nn.Module):
|
84 |
+
def __init__(self, dim: int, eps: float = 1e-6):
|
85 |
+
super().__init__()
|
86 |
+
self.eps = eps
|
87 |
+
self.weight = nn.Parameter(torch.zeros(dim))
|
88 |
+
|
89 |
+
def _norm(self, x):
|
90 |
+
return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
|
91 |
+
|
92 |
+
def forward(self, x):
|
93 |
+
output = self._norm(x.float()).type_as(x)
|
94 |
+
return output * (self.weight + 1)
|
95 |
+
|
96 |
+
ALL_LAYERNORM_LAYERS.append(GemmoeRMSNorm)
|
97 |
+
|
98 |
+
class GemmoeRotaryEmbedding(nn.Module):
|
99 |
+
def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
|
100 |
+
super().__init__()
|
101 |
+
self.dim = dim
|
102 |
+
self.max_position_embeddings = max_position_embeddings
|
103 |
+
self.base = base
|
104 |
+
self._set_cos_sin_cache(seq_len=max_position_embeddings, device=device, dtype=torch.get_default_dtype())
|
105 |
+
|
106 |
+
def _set_cos_sin_cache(self, seq_len, device, dtype):
|
107 |
+
self.max_seq_len_cached = seq_len
|
108 |
+
freq_exponents = (2.0 / self.dim) * (
|
109 |
+
torch.arange(self.dim // 2, dtype=torch.int64, device="cpu").float()
|
110 |
+
)
|
111 |
+
timescale = self.base ** freq_exponents
|
112 |
+
positions = torch.arange(self.max_seq_len_cached, device="cpu", dtype=torch.int64).float()
|
113 |
+
radians_new = positions[..., None] / timescale[None, None, :]
|
114 |
+
radians_new = radians_new.squeeze(0)
|
115 |
+
emb = torch.cat((radians_new, radians_new), dim=-1)
|
116 |
+
cos = emb.cos().to(device=device, non_blocking=True)
|
117 |
+
sin = emb.sin().to(device=device, non_blocking=True)
|
118 |
+
self.register_buffer("cos_cached", cos, persistent=False)
|
119 |
+
self.register_buffer("sin_cached", sin, persistent=False)
|
120 |
+
|
121 |
+
def forward(self, x, position_ids=None, seq_len=None):
|
122 |
+
if seq_len is None:
|
123 |
+
seq_len = x.size(2)
|
124 |
+
if seq_len > self.max_seq_len_cached:
|
125 |
+
self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
|
126 |
+
return (
|
127 |
+
self.cos_cached[:seq_len],
|
128 |
+
self.sin_cached[:seq_len],
|
129 |
+
)
|
130 |
+
|
131 |
+
def rotate_half(x):
|
132 |
+
"""Rotates half the hidden dims of the input."""
|
133 |
+
x1 = x[..., : x.shape[-1] // 2]
|
134 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
135 |
+
return torch.cat((-x2, x1), dim=-1)
|
136 |
+
|
137 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None):
|
138 |
+
"""Applies Rotary Position Embedding to the query and key tensors."""
|
139 |
+
seq_len, dim = q.shape[-2], q.shape[-1]
|
140 |
+
cos = cos[:seq_len].view(1, 1, seq_len, dim)
|
141 |
+
sin = sin[:seq_len].view(1, 1, seq_len, dim)
|
142 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
143 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
144 |
+
return q_embed, k_embed
|
145 |
+
|
146 |
+
class GemmoeMLP(nn.Module):
|
147 |
+
def __init__(self, config):
|
148 |
+
super().__init__()
|
149 |
+
self.config = config
|
150 |
+
self.hidden_size = config.hidden_size
|
151 |
+
self.intermediate_size = config.intermediate_size
|
152 |
+
|
153 |
+
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
154 |
+
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
155 |
+
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
|
156 |
+
|
157 |
+
self.act_fn = approx_gelu
|
158 |
+
|
159 |
+
def forward(self, x):
|
160 |
+
return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
161 |
+
|
162 |
+
def load_balancing_loss_func(
|
163 |
+
self,
|
164 |
+
gate_logits: torch.Tensor, num_experts: torch.Tensor = None, top_k=2, attention_mask: Optional[torch.Tensor] = None
|
165 |
+
) -> float:
|
166 |
+
r"""
|
167 |
+
Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.
|
168 |
+
|
169 |
+
See Switch Transformer (https://arxiv.org/abs/2101.03961) for more details. This function implements the loss
|
170 |
+
function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
|
171 |
+
experts is too unbalanced.
|
172 |
+
|
173 |
+
Args:
|
174 |
+
gate_logits (Union[`torch.Tensor`, Tuple[torch.Tensor]):
|
175 |
+
Logits from the `gate`, should be a tuple of model.config.num_hidden_layers tensors of
|
176 |
+
shape [batch_size X sequence_length, num_experts].
|
177 |
+
attention_mask (`torch.Tensor`, None):
|
178 |
+
The attention_mask used in forward function
|
179 |
+
shape [batch_size X sequence_length] if not None.
|
180 |
+
num_experts (`int`, *optional*):
|
181 |
+
Number of experts
|
182 |
+
|
183 |
+
Returns:
|
184 |
+
The auxiliary loss.
|
185 |
+
"""
|
186 |
+
if gate_logits is None or not isinstance(gate_logits, tuple):
|
187 |
+
return 0
|
188 |
+
|
189 |
+
if isinstance(gate_logits, tuple):
|
190 |
+
compute_device = gate_logits[0].device
|
191 |
+
concatenated_gate_logits = torch.cat([layer_gate.to(compute_device) for layer_gate in gate_logits], dim=0)
|
192 |
+
|
193 |
+
routing_weights = torch.nn.functional.softmax(concatenated_gate_logits, dim=-1)
|
194 |
+
_, selected_experts = torch.topk(routing_weights, top_k, dim=-1)
|
195 |
+
expert_mask = torch.nn.functional.one_hot(selected_experts, num_experts)
|
196 |
+
|
197 |
+
if attention_mask is None:
|
198 |
+
# Compute the percentage of tokens routed to each experts
|
199 |
+
tokens_per_expert = torch.mean(expert_mask.float(), dim=0)
|
200 |
+
# Compute the average probability of routing to these experts
|
201 |
+
router_prob_per_expert = torch.mean(routing_weights, dim=0)
|
202 |
+
else:
|
203 |
+
batch_size, sequence_length = attention_mask.shape
|
204 |
+
num_hidden_layers = concatenated_gate_logits.shape[0] // (batch_size * sequence_length)
|
205 |
+
|
206 |
+
# Compute the mask that masks all padding tokens as 0 with the same shape of expert_mask
|
207 |
+
expert_attention_mask = (
|
208 |
+
attention_mask[None, :, :, None, None]
|
209 |
+
.expand((num_hidden_layers, batch_size, sequence_length, 2, num_experts))
|
210 |
+
.reshape(-1, 2, num_experts)
|
211 |
+
.to(compute_device)
|
212 |
+
)
|
213 |
+
# Compute the percentage of tokens routed to each experts
|
214 |
+
tokens_per_expert = torch.sum(expert_mask.float() * expert_attention_mask, dim=0) / torch.sum(
|
215 |
+
expert_attention_mask, dim=0
|
216 |
+
)
|
217 |
+
|
218 |
+
# Compute the mask that masks all padding tokens as 0 with the same shape of tokens_per_expert
|
219 |
+
router_per_expert_attention_mask = (
|
220 |
+
attention_mask[None, :, :, None]
|
221 |
+
.expand((num_hidden_layers, batch_size, sequence_length, num_experts))
|
222 |
+
.reshape(-1, num_experts)
|
223 |
+
.to(compute_device)
|
224 |
+
)
|
225 |
+
# Compute the average probability of routing to these experts
|
226 |
+
router_prob_per_expert = torch.sum(routing_weights * router_per_expert_attention_mask, dim=0) / torch.sum(
|
227 |
+
router_per_expert_attention_mask, dim=0
|
228 |
+
)
|
229 |
+
|
230 |
+
overall_loss = torch.sum(tokens_per_expert * router_prob_per_expert.unsqueeze(0))
|
231 |
+
return overall_loss * num_experts
|
232 |
+
|
233 |
+
def repeat_kv(self, hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
234 |
+
"""
|
235 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
236 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
237 |
+
"""
|
238 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
239 |
+
if n_rep == 1:
|
240 |
+
return hidden_states
|
241 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
242 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
243 |
+
|
244 |
+
class GemmoeAttention(nn.Module):
|
245 |
+
"""
|
246 |
+
Multi-headed attention module for Gemmoe model.
|
247 |
+
|
248 |
+
Args:
|
249 |
+
config (GemmoeConfig): The configuration object for the Gemmoe model.
|
250 |
+
layer_idx (Optional[int]): The index of the layer. Default is None.
|
251 |
+
"""
|
252 |
+
|
253 |
+
def __init__(self, config: GemmoeConfig, layer_idx: Optional[int] = None):
|
254 |
+
super().__init__()
|
255 |
+
self.config = config
|
256 |
+
self.layer_idx = layer_idx
|
257 |
+
if layer_idx is None:
|
258 |
+
logger.warning_once(
|
259 |
+
f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
|
260 |
+
"lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
|
261 |
+
"when creating this class."
|
262 |
+
)
|
263 |
+
self.attention_dropout = config.attention_dropout
|
264 |
+
self.hidden_size = config.hidden_size
|
265 |
+
self.num_heads = config.num_attention_heads
|
266 |
+
self.head_dim = config.head_dim
|
267 |
+
self.num_key_value_heads = config.num_key_value_heads
|
268 |
+
self.num_key_value_groups = self.num_heads // self.num_key_value_heads
|
269 |
+
self.max_position_embeddings = config.max_position_embeddings
|
270 |
+
self.rope_theta = config.rope_theta
|
271 |
+
self.is_causal = True
|
272 |
+
|
273 |
+
if self.hidden_size % self.num_heads != 0:
|
274 |
+
raise ValueError(
|
275 |
+
f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
|
276 |
+
f" and `num_heads`: {self.num_heads})."
|
277 |
+
)
|
278 |
+
self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
|
279 |
+
self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
|
280 |
+
self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
|
281 |
+
self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
|
282 |
+
self.rotary_emb = GemmoeRotaryEmbedding(
|
283 |
+
self.head_dim,
|
284 |
+
max_position_embeddings=self.max_position_embeddings,
|
285 |
+
base=self.rope_theta,
|
286 |
+
)
|
287 |
+
|
288 |
+
def forward(
|
289 |
+
self,
|
290 |
+
hidden_states: torch.Tensor,
|
291 |
+
attention_mask: Optional[torch.Tensor] = None,
|
292 |
+
position_ids: Optional[torch.LongTensor] = None,
|
293 |
+
past_key_value: Optional[Cache] = None,
|
294 |
+
output_attentions: bool = False,
|
295 |
+
use_cache: bool = False,
|
296 |
+
cache_position: Optional[torch.LongTensor] = None,
|
297 |
+
**kwargs,
|
298 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
299 |
+
"""
|
300 |
+
Forward pass of the attention module.
|
301 |
+
|
302 |
+
Args:
|
303 |
+
hidden_states (torch.Tensor): The input hidden states.
|
304 |
+
attention_mask (Optional[torch.Tensor]): The attention mask. Default is None.
|
305 |
+
position_ids (Optional[torch.LongTensor]): The position IDs. Default is None.
|
306 |
+
past_key_value (Optional[Cache]): The past key-value cache. Default is None.
|
307 |
+
output_attentions (bool): Whether to output the attention weights. Default is False.
|
308 |
+
use_cache (bool): Whether to use caching. Default is False.
|
309 |
+
cache_position (Optional[torch.LongTensor]): The cache position. Default is None.
|
310 |
+
**kwargs: Additional keyword arguments.
|
311 |
+
|
312 |
+
Returns:
|
313 |
+
Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
314 |
+
- The output hidden states.
|
315 |
+
- The attention weights (if `output_attentions=True`).
|
316 |
+
- The past key-value cache (if `use_cache=True`).
|
317 |
+
"""
|
318 |
+
bsz, q_len, _ = hidden_states.size()
|
319 |
+
|
320 |
+
query_states = self.q_proj(hidden_states)
|
321 |
+
key_states = self.k_proj(hidden_states)
|
322 |
+
value_states = self.v_proj(hidden_states)
|
323 |
+
|
324 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
325 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
326 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
327 |
+
|
328 |
+
past_key_value = getattr(self, "past_key_value", past_key_value)
|
329 |
+
|
330 |
+
cos, sin = self.rotary_emb(value_states, position_ids, seq_len=None)
|
331 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, None)
|
332 |
+
|
333 |
+
if past_key_value is not None:
|
334 |
+
# sin and cos are specific to RoPE models; position_ids needed for the static cache
|
335 |
+
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
|
336 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
337 |
+
|
338 |
+
key_states = self.repeat_kv(key_states, self.num_key_value_groups)
|
339 |
+
value_states = self.repeat_kv(value_states, self.num_key_value_groups)
|
340 |
+
|
341 |
+
attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
|
342 |
+
|
343 |
+
if attention_mask is not None: # no matter the length, we just slice it
|
344 |
+
if cache_position is not None:
|
345 |
+
causal_mask = attention_mask[:, :, cache_position, : key_states.shape[-2]]
|
346 |
+
else:
|
347 |
+
causal_mask = attention_mask
|
348 |
+
attn_weights = attn_weights + causal_mask
|
349 |
+
|
350 |
+
# upcast attention to fp32
|
351 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
|
352 |
+
attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
|
353 |
+
|
354 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
355 |
+
|
356 |
+
if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
|
357 |
+
raise ValueError(
|
358 |
+
f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
|
359 |
+
f" {attn_output.size()}"
|
360 |
+
)
|
361 |
+
|
362 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
363 |
+
attn_output = attn_output.view(bsz, q_len, -1)
|
364 |
+
|
365 |
+
attn_output = self.o_proj(attn_output)
|
366 |
+
|
367 |
+
if not output_attentions:
|
368 |
+
attn_weights = None
|
369 |
+
|
370 |
+
return attn_output, attn_weights, past_key_value
|
371 |
+
|
372 |
+
class GemmoeFlashAttention2(GemmoeAttention):
|
373 |
+
"""
|
374 |
+
Gemmoe flash attention module. This module inherits from `GemmoeAttention` as the weights of the module stays
|
375 |
+
untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
|
376 |
+
flash attention and deal with padding tokens in case the input contains any of them.
|
377 |
+
"""
|
378 |
+
def __init__(self, *args, **kwargs):
|
379 |
+
super().__init__(*args, **kwargs)
|
380 |
+
# TODO: Remove this attribute once Flash Attention for RoCm is bumped to 2.1.
|
381 |
+
self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
|
382 |
+
|
383 |
+
def forward(
|
384 |
+
self,
|
385 |
+
hidden_states: torch.Tensor,
|
386 |
+
attention_mask: Optional[torch.LongTensor] = None,
|
387 |
+
position_ids: Optional[torch.LongTensor] = None,
|
388 |
+
past_key_value: Optional[Cache] = None,
|
389 |
+
output_attentions: bool = False,
|
390 |
+
use_cache: bool = False,
|
391 |
+
cache_position: Optional[torch.LongTensor] = None,
|
392 |
+
**kwargs,
|
393 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
394 |
+
output_attentions = False
|
395 |
+
|
396 |
+
bsz, q_len, _ = hidden_states.size()
|
397 |
+
|
398 |
+
query_states = self.q_proj(hidden_states)
|
399 |
+
key_states = self.k_proj(hidden_states)
|
400 |
+
value_states = self.v_proj(hidden_states)
|
401 |
+
|
402 |
+
# Flash attention requires the input to have the shape
|
403 |
+
# batch_size x seq_length x head_dim x hidden_dim
|
404 |
+
# therefore we just need to keep the original shape
|
405 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
406 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
407 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
408 |
+
|
409 |
+
cos, sin = self.rotary_emb(value_states, position_ids, seq_len=None)
|
410 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, None)
|
411 |
+
|
412 |
+
past_key_value = getattr(self, "past_key_value", past_key_value)
|
413 |
+
if past_key_value is not None:
|
414 |
+
# sin and cos are specific to RoPE models; position_ids needed for the static cache
|
415 |
+
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
|
416 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
417 |
+
|
418 |
+
# 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
|
419 |
+
# to be able to avoid many of these transpose/reshape/view.
|
420 |
+
query_states = query_states.transpose(1, 2)
|
421 |
+
key_states = key_states.transpose(1, 2)
|
422 |
+
value_states = value_states.transpose(1, 2)
|
423 |
+
|
424 |
+
dropout_rate = self.attention_dropout if self.training else 0.0
|
425 |
+
|
426 |
+
# In PEFT, usually we cast the layer norms in float32 for training stability reasons
|
427 |
+
# therefore the input hidden states gets silently casted in float32. Hence, we need
|
428 |
+
# cast them back in the correct dtype just to be sure everything works as expected.
|
429 |
+
# This might slowdown training & inference so it is recommended to not cast the LayerNorms
|
430 |
+
# in fp32. (GemmoeRMSNorm handles it correctly)
|
431 |
+
input_dtype = query_states.dtype
|
432 |
+
if input_dtype == torch.float32:
|
433 |
+
if torch.is_autocast_enabled():
|
434 |
+
target_dtype = torch.get_autocast_gpu_dtype()
|
435 |
+
# Handle the case where the model is quantized
|
436 |
+
elif hasattr(self.config, "_pre_quantization_dtype"):
|
437 |
+
target_dtype = self.config._pre_quantization_dtype
|
438 |
+
else:
|
439 |
+
target_dtype = self.q_proj.weight.dtype
|
440 |
+
|
441 |
+
logger.warning_once(
|
442 |
+
f"The input hidden states seems to be silently casted in float32, this might be related to"
|
443 |
+
f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
|
444 |
+
f" {target_dtype}."
|
445 |
+
)
|
446 |
+
query_states = query_states.to(target_dtype)
|
447 |
+
key_states = key_states.to(target_dtype)
|
448 |
+
value_states = value_states.to(target_dtype)
|
449 |
+
|
450 |
+
attn_output = self._flash_attention_forward(
|
451 |
+
query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate
|
452 |
+
)
|
453 |
+
|
454 |
+
attn_output = attn_output.reshape(bsz, q_len, -1).contiguous()
|
455 |
+
attn_output = self.o_proj(attn_output)
|
456 |
+
|
457 |
+
if not output_attentions:
|
458 |
+
attn_weights = None
|
459 |
+
|
460 |
+
return attn_output, attn_weights, past_key_value
|
461 |
+
|
462 |
+
def _flash_attention_forward(
|
463 |
+
self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
|
464 |
+
):
|
465 |
+
"""
|
466 |
+
Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
|
467 |
+
first unpad the input, then computes the attention scores and pad the final attention scores.
|
468 |
+
|
469 |
+
Args:
|
470 |
+
query_states (`torch.Tensor`):
|
471 |
+
Input query states to be passed to Flash Attention API
|
472 |
+
key_states (`torch.Tensor`):
|
473 |
+
Input key states to be passed to Flash Attention API
|
474 |
+
value_states (`torch.Tensor`):
|
475 |
+
Input value states to be passed to Flash Attention API
|
476 |
+
attention_mask (`torch.Tensor`):
|
477 |
+
The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
|
478 |
+
position of padding tokens and 1 for the position of non-padding tokens.
|
479 |
+
dropout (`int`, *optional*):
|
480 |
+
Attention dropout
|
481 |
+
softmax_scale (`float`, *optional*):
|
482 |
+
The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
|
483 |
+
"""
|
484 |
+
if not self._flash_attn_uses_top_left_mask:
|
485 |
+
causal = self.is_causal
|
486 |
+
else:
|
487 |
+
# 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__.
|
488 |
+
causal = self.is_causal and query_length != 1
|
489 |
+
|
490 |
+
# Contains at least one padding token in the sequence
|
491 |
+
if attention_mask is not None:
|
492 |
+
batch_size = query_states.shape[0]
|
493 |
+
query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
|
494 |
+
query_states, key_states, value_states, attention_mask, query_length
|
495 |
+
)
|
496 |
+
cu_seqlens_q, cu_seqlens_k = cu_seq_lens
|
497 |
+
max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
|
498 |
+
|
499 |
+
attn_output_unpad = flash_attn_varlen_func(
|
500 |
+
query_states,
|
501 |
+
key_states,
|
502 |
+
value_states,
|
503 |
+
cu_seqlens_q=cu_seqlens_q,
|
504 |
+
cu_seqlens_k=cu_seqlens_k,
|
505 |
+
max_seqlen_q=max_seqlen_in_batch_q,
|
506 |
+
max_seqlen_k=max_seqlen_in_batch_k,
|
507 |
+
dropout_p=dropout,
|
508 |
+
softmax_scale=softmax_scale,
|
509 |
+
causal=causal,
|
510 |
+
)
|
511 |
+
attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
|
512 |
+
else:
|
513 |
+
attn_output = flash_attn_func(
|
514 |
+
query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
|
515 |
+
)
|
516 |
+
|
517 |
+
return attn_output
|
518 |
+
|
519 |
+
def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
|
520 |
+
indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
|
521 |
+
|
522 |
+
batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
|
523 |
+
key_layer = index_first_axis(
|
524 |
+
key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
|
525 |
+
)
|
526 |
+
value_layer = index_first_axis(
|
527 |
+
value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
|
528 |
+
)
|
529 |
+
|
530 |
+
if query_length == kv_seq_len:
|
531 |
+
query_layer = index_first_axis(
|
532 |
+
query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
|
533 |
+
)
|
534 |
+
cu_seqlens_q = cu_seqlens_k
|
535 |
+
max_seqlen_in_batch_q = max_seqlen_in_batch_k
|
536 |
+
indices_q = indices_k
|
537 |
+
elif query_length == 1:
|
538 |
+
max_seqlen_in_batch_q = 1
|
539 |
+
cu_seqlens_q = torch.arange(
|
540 |
+
batch_size + 1, dtype=torch.int32, device=query_layer.device
|
541 |
+
) # There is a memcpy here, that is very bad.
|
542 |
+
indices_q = cu_seqlens_q[:-1]
|
543 |
+
query_layer = query_layer.squeeze(1)
|
544 |
+
else:
|
545 |
+
# The -q_len: slice assumes left padding.
|
546 |
+
attention_mask = attention_mask[:, -query_length:]
|
547 |
+
query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
|
548 |
+
|
549 |
+
return (
|
550 |
+
query_layer,
|
551 |
+
key_layer,
|
552 |
+
value_layer,
|
553 |
+
indices_q,
|
554 |
+
(cu_seqlens_q, cu_seqlens_k),
|
555 |
+
(max_seqlen_in_batch_q, max_seqlen_in_batch_k),
|
556 |
+
)
|
557 |
+
|
558 |
+
class GemmoeSdpaAttention(GemmoeAttention):
|
559 |
+
"""
|
560 |
+
Gemmoe attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
|
561 |
+
GemmoeAttention as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
|
562 |
+
SDPA API.
|
563 |
+
"""
|
564 |
+
def repeat_kv(self, hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
565 |
+
"""
|
566 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
567 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
568 |
+
"""
|
569 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
570 |
+
if n_rep == 1:
|
571 |
+
return hidden_states
|
572 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
573 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
574 |
+
|
575 |
+
def forward(
|
576 |
+
self,
|
577 |
+
hidden_states: torch.Tensor,
|
578 |
+
attention_mask: Optional[torch.Tensor] = None,
|
579 |
+
position_ids: Optional[torch.LongTensor] = None,
|
580 |
+
past_key_value: Optional[Cache] = None,
|
581 |
+
output_attentions: bool = False,
|
582 |
+
use_cache: bool = False,
|
583 |
+
cache_position: Optional[torch.LongTensor] = None,
|
584 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
585 |
+
if output_attentions:
|
586 |
+
# TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
|
587 |
+
# logger.warning_once(
|
588 |
+
"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, "
|
589 |
+
'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.'
|
590 |
+
# )
|
591 |
+
|
592 |
+
return super().forward(
|
593 |
+
hidden_states=hidden_states,
|
594 |
+
attention_mask=attention_mask,
|
595 |
+
position_ids=position_ids,
|
596 |
+
past_key_value=past_key_value,
|
597 |
+
output_attentions=output_attentions,
|
598 |
+
use_cache=use_cache,
|
599 |
+
cache_position=cache_position,
|
600 |
+
),
|
601 |
+
|
602 |
+
bsz, q_len, _ = hidden_states.size()
|
603 |
+
|
604 |
+
query_states = self.q_proj(hidden_states)
|
605 |
+
key_states = self.k_proj(hidden_states)
|
606 |
+
value_states = self.v_proj(hidden_states)
|
607 |
+
|
608 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
609 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
610 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
611 |
+
|
612 |
+
cos, sin = self.rotary_emb(value_states, position_ids, seq_len=None)
|
613 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, None)
|
614 |
+
|
615 |
+
past_key_value = getattr(self, "past_key_value", past_key_value)
|
616 |
+
if past_key_value is not None:
|
617 |
+
# sin and cos are specific to RoPE models; position_ids needed for the static cache
|
618 |
+
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
|
619 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
620 |
+
|
621 |
+
key_states = self.repeat_kv(key_states, self.num_key_value_groups)
|
622 |
+
value_states = self.repeat_kv(value_states, self.num_key_value_groups)
|
623 |
+
|
624 |
+
causal_mask = attention_mask
|
625 |
+
if attention_mask is not None and cache_position is not None:
|
626 |
+
causal_mask = causal_mask[:, :, cache_position, : key_states.shape[-2]]
|
627 |
+
|
628 |
+
# Cast query, key, and value states to the same dtype (bf16)
|
629 |
+
query_states = query_states.to(dtype=torch.bfloat16)
|
630 |
+
key_states = key_states.to(dtype=torch.bfloat16)
|
631 |
+
value_states = value_states.to(dtype=torch.bfloat16)
|
632 |
+
|
633 |
+
# SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
|
634 |
+
# Reference: https://github.com/pytorch/pytorch/issues/112577.
|
635 |
+
if query_states.device.type == "cuda" and causal_mask is not None:
|
636 |
+
query_states = query_states.contiguous()
|
637 |
+
key_states = key_states.contiguous()
|
638 |
+
value_states = value_states.contiguous()
|
639 |
+
|
640 |
+
attn_output = torch.nn.functional.scaled_dot_product_attention(
|
641 |
+
query_states,
|
642 |
+
key_states,
|
643 |
+
value_states,
|
644 |
+
attn_mask=causal_mask,
|
645 |
+
dropout_p=self.attention_dropout if self.training else 0.0,
|
646 |
+
)
|
647 |
+
|
648 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
649 |
+
attn_output = attn_output.view(bsz, q_len, -1)
|
650 |
+
attn_output = self.o_proj(attn_output)
|
651 |
+
|
652 |
+
return attn_output, None, past_key_value
|
653 |
+
|
654 |
+
GEMMOE_ATTENTION_CLASSES = {
|
655 |
+
"eager": GemmoeAttention,
|
656 |
+
"flash_attention_2": GemmoeFlashAttention2,
|
657 |
+
"sdpa": GemmoeSdpaAttention,
|
658 |
+
}
|
659 |
+
|
660 |
+
class GemmoeBlockSparseTop2MLP(nn.Module):
|
661 |
+
def __init__(self, config: GemmoeConfig):
|
662 |
+
super().__init__()
|
663 |
+
self.ffn_dim = config.intermediate_size
|
664 |
+
self.hidden_dim = config.hidden_size
|
665 |
+
self.w1 = nn.Linear(self.hidden_dim, self.ffn_dim, bias=False)
|
666 |
+
self.w2 = nn.Linear(self.ffn_dim, self.hidden_dim, bias=False)
|
667 |
+
self.w3 = nn.Linear(self.hidden_dim, self.ffn_dim, bias=False)
|
668 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
669 |
+
|
670 |
+
def forward(self, hidden_states):
|
671 |
+
current_hidden_states = self.act_fn(self.w1(hidden_states)) * self.w3(hidden_states)
|
672 |
+
current_hidden_states = self.w2(current_hidden_states)
|
673 |
+
return current_hidden_states
|
674 |
+
|
675 |
+
|
676 |
+
class GemmoeSparseMoeBlock(nn.Module):
|
677 |
+
def __init__(self, config):
|
678 |
+
super().__init__()
|
679 |
+
self.hidden_dim = config.hidden_size
|
680 |
+
self.ffn_dim = config.intermediate_size
|
681 |
+
self.num_experts = config.num_local_experts
|
682 |
+
self.top_k = 2
|
683 |
+
|
684 |
+
# gating
|
685 |
+
self.gate = nn.Linear(self.hidden_dim, self.num_experts, bias=False)
|
686 |
+
|
687 |
+
self.experts = nn.ModuleList([GemmoeBlockSparseTop2MLP(config) for _ in range(self.num_experts)])
|
688 |
+
|
689 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
690 |
+
hidden_states = hidden_states.to(self.gate.weight.device)
|
691 |
+
batch_size, sequence_length, hidden_dim = hidden_states.shape
|
692 |
+
hidden_states = hidden_states.view(-1, hidden_dim)
|
693 |
+
|
694 |
+
# router_logits: (batch * sequence_length, n_experts)
|
695 |
+
router_logits = self.gate(hidden_states)
|
696 |
+
routing_weights = F.softmax(router_logits, dim=1, dtype=torch.float32)
|
697 |
+
top_routing_weights, selected_experts = torch.topk(routing_weights, self.top_k, dim=-1)
|
698 |
+
top_routing_weights /= top_routing_weights.sum(dim=-1, keepdim=True)
|
699 |
+
|
700 |
+
# we cast back to the input dtype
|
701 |
+
top_routing_weights = top_routing_weights.to(hidden_states.dtype)
|
702 |
+
|
703 |
+
final_hidden_states = torch.zeros(
|
704 |
+
(batch_size * sequence_length, hidden_dim), dtype=hidden_states.dtype, device=hidden_states.device
|
705 |
+
)
|
706 |
+
|
707 |
+
# Loop over all available experts in the model and perform the computation on each expert
|
708 |
+
for expert_idx in range(self.num_experts):
|
709 |
+
expert_layer = self.experts[expert_idx]
|
710 |
+
token_indices = (selected_experts == expert_idx).any(dim=-1).nonzero(as_tuple=True)[0]
|
711 |
+
|
712 |
+
if token_indices.numel() == 0:
|
713 |
+
continue
|
714 |
+
|
715 |
+
current_state = hidden_states[token_indices]
|
716 |
+
current_hidden_states = expert_layer(current_state)
|
717 |
+
|
718 |
+
# Multiply the output hidden states by `top_routing_weights` on the corresponding tokens
|
719 |
+
expert_indices = (selected_experts[token_indices] == expert_idx).nonzero(as_tuple=True)[1]
|
720 |
+
current_hidden_states *= top_routing_weights[token_indices, expert_indices, None]
|
721 |
+
|
722 |
+
final_hidden_states.index_add_(0, token_indices, current_hidden_states)
|
723 |
+
|
724 |
+
final_hidden_states = final_hidden_states.reshape(batch_size, sequence_length, hidden_dim)
|
725 |
+
return final_hidden_states, router_logits
|
726 |
+
|
727 |
+
|
728 |
+
class GemmoeDecoderLayer(nn.Module):
|
729 |
+
"""
|
730 |
+
Decoder layer for the Gemmoe model.
|
731 |
+
|
732 |
+
Args:
|
733 |
+
config (GemmoeConfig): The configuration object for the Gemmoe model.
|
734 |
+
layer_idx (int): The index of the layer.
|
735 |
+
"""
|
736 |
+
def __init__(self, config: GemmoeConfig, layer_idx: int):
|
737 |
+
super().__init__()
|
738 |
+
self.hidden_size = config.hidden_size
|
739 |
+
self.self_attn = GEMMOE_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
|
740 |
+
self.mlp = GemmoeMLP(config)
|
741 |
+
self.block_sparse_moe = GemmoeSparseMoeBlock(config)
|
742 |
+
self.input_layernorm = GemmoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
743 |
+
self.post_attention_layernorm = GemmoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
744 |
+
|
745 |
+
def forward(
|
746 |
+
self,
|
747 |
+
hidden_states: torch.Tensor,
|
748 |
+
attention_mask: Optional[torch.Tensor] = None,
|
749 |
+
position_ids: Optional[torch.LongTensor] = None,
|
750 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
751 |
+
output_attentions: Optional[bool] = False,
|
752 |
+
output_router_logits: Optional[bool] = False,
|
753 |
+
use_cache: Optional[bool] = False,
|
754 |
+
cache_position: Optional[torch.LongTensor] = None,
|
755 |
+
**kwargs,
|
756 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
757 |
+
"""
|
758 |
+
Args:
|
759 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
760 |
+
attention_mask (`torch.FloatTensor`, *optional*):
|
761 |
+
attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
|
762 |
+
query_sequence_length, key_sequence_length)` if default attention is used.
|
763 |
+
output_attentions (`bool`, *optional*):
|
764 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
765 |
+
returned tensors for more detail.
|
766 |
+
use_cache (`bool`, *optional*):
|
767 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
|
768 |
+
(see `past_key_values`).
|
769 |
+
past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
|
770 |
+
output_router_logits (`bool`, *optional*):
|
771 |
+
Whether or not to return the logits of all the routers. They are useful for computing the router loss, and
|
772 |
+
should not be returned during inference.
|
773 |
+
"""
|
774 |
+
if "padding_mask" in kwargs:
|
775 |
+
warnings.warn(
|
776 |
+
"Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
|
777 |
+
)
|
778 |
+
|
779 |
+
residual = hidden_states
|
780 |
+
hidden_states = self.input_layernorm(hidden_states)
|
781 |
+
|
782 |
+
# Self Attention
|
783 |
+
hidden_states, self_attn_weights, present_key_value = self.self_attn(
|
784 |
+
hidden_states=hidden_states,
|
785 |
+
attention_mask=attention_mask,
|
786 |
+
position_ids=position_ids,
|
787 |
+
past_key_value=past_key_value,
|
788 |
+
output_attentions=output_attentions,
|
789 |
+
use_cache=use_cache,
|
790 |
+
cache_position=cache_position,
|
791 |
+
**kwargs,
|
792 |
+
)
|
793 |
+
hidden_states = residual + hidden_states
|
794 |
+
|
795 |
+
# Fully Connected
|
796 |
+
residual = hidden_states
|
797 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
798 |
+
hidden_states, router_logits = self.block_sparse_moe(hidden_states)
|
799 |
+
hidden_states = residual + hidden_states
|
800 |
+
|
801 |
+
|
802 |
+
outputs = (hidden_states,)
|
803 |
+
|
804 |
+
if output_attentions:
|
805 |
+
outputs += (self_attn_weights,)
|
806 |
+
|
807 |
+
if use_cache:
|
808 |
+
outputs += (present_key_value,)
|
809 |
+
|
810 |
+
if output_router_logits:
|
811 |
+
outputs += (router_logits,)
|
812 |
+
|
813 |
+
return outputs
|
814 |
+
|
815 |
+
GEMMOE_START_DOCSTRING = r"""
|
816 |
+
This model inherits from [PreTrainedModel]. Check the superclass documentation for the generic methods the
|
817 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
818 |
+
etc.)
|
819 |
+
"""
|
820 |
+
|
821 |
+
@add_start_docstrings(
|
822 |
+
"The bare Gemmoe Model outputting raw hidden-states without any specific head on top.",
|
823 |
+
GEMMOE_START_DOCSTRING,
|
824 |
+
)
|
825 |
+
|
826 |
+
class GemmoePreTrainedModel(PreTrainedModel):
|
827 |
+
config_class = GemmoeConfig
|
828 |
+
base_model_prefix = "model"
|
829 |
+
supports_gradient_checkpointing = True
|
830 |
+
_keep_in_fp32_modules = ["inv_freq", "rotary_emb", "cos_cached", "sin_cached"]
|
831 |
+
_no_split_modules = ["GemmoeDecoderLayer"]
|
832 |
+
_skip_keys_device_placement = ["past_key_values", "causal_mask"]
|
833 |
+
_supports_flash_attn_2 = True
|
834 |
+
_supports_sdpa = True
|
835 |
+
_supports_cache_class = True
|
836 |
+
|
837 |
+
def _init_weights(self, module):
|
838 |
+
std = self.config.initializer_range
|
839 |
+
if isinstance(module, nn.Linear):
|
840 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
841 |
+
if module.bias is not None:
|
842 |
+
module.bias.data.zero_()
|
843 |
+
elif isinstance(module, nn.Embedding):
|
844 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
845 |
+
if module.padding_idx is not None:
|
846 |
+
module.weight.data[module.padding_idx].zero_()
|
847 |
+
|
848 |
+
def _setup_cache(self, cache_cls, max_batch_size, max_cache_len: Optional[int] = None):
|
849 |
+
if self.config._attn_implementation == "flash_attention_2" and cache_cls == StaticCache:
|
850 |
+
raise ValueError(
|
851 |
+
"`static` cache implementation is not compatible with `attn_implementation==flash_attention_2` "
|
852 |
+
"make sure to use `sdpa` in the mean time, and open an issue at https://github.com/huggingface/transformers"
|
853 |
+
)
|
854 |
+
if max_cache_len > self.model.causal_mask.shape[-1] or self.device != self.model.causal_mask.device:
|
855 |
+
causal_mask = torch.full((max_cache_len, max_cache_len), fill_value=1, device=self.device)
|
856 |
+
self.register_buffer("causal_mask", torch.triu(causal_mask, diagonal=1), persistent=False)
|
857 |
+
|
858 |
+
for layer in self.model.layers:
|
859 |
+
weights = layer.self_attn.o_proj.weight
|
860 |
+
layer.self_attn.past_key_value = cache_cls(
|
861 |
+
self.config, max_batch_size, max_cache_len, device=weights.device, dtype=weights.dtype
|
862 |
+
)
|
863 |
+
|
864 |
+
def _reset_cache(self):
|
865 |
+
for layer in self.model.layers:
|
866 |
+
layer.self_attn.past_key_value = None
|
867 |
+
|
868 |
+
GEMMOE_INPUTS_DOCSTRING = r"""
|
869 |
+
Args:
|
870 |
+
input_ids (torch.LongTensor of shape (batch_size, sequence_length)):
|
871 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
872 |
+
it.
|
873 |
+
"""
|
874 |
+
|
875 |
+
@add_start_docstrings(
|
876 |
+
"The bare Gemmoe Model outputting raw hidden-states without any specific head on top.",
|
877 |
+
GEMMOE_START_DOCSTRING,
|
878 |
+
)
|
879 |
+
|
880 |
+
class GemmoeModel(GemmoePreTrainedModel):
|
881 |
+
"""
|
882 |
+
Transformer decoder consisting of config.num_hidden_layers layers. Each layer is a [GemmoeDecoderLayer]Args:
|
883 |
+
config: GemmoeConfig
|
884 |
+
"""
|
885 |
+
|
886 |
+
|
887 |
+
def __init__(self, config: GemmoeConfig):
|
888 |
+
super().__init__(config)
|
889 |
+
self.padding_idx = config.pad_token_id
|
890 |
+
self.vocab_size = config.vocab_size
|
891 |
+
|
892 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
893 |
+
self.layers = nn.ModuleList(
|
894 |
+
[GemmoeDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
895 |
+
)
|
896 |
+
self.norm = GemmoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
897 |
+
|
898 |
+
self.gradient_checkpointing = False
|
899 |
+
|
900 |
+
# Register a causal mask to separate causal and padding mask creation. Merging happens in the attention class.
|
901 |
+
# NOTE: This is not friendly with TorchScript, ONNX, ExportedProgram serialization for very large `max_position_embeddings`.
|
902 |
+
causal_mask = torch.full(
|
903 |
+
(config.max_position_embeddings, config.max_position_embeddings), fill_value=True, dtype=torch.bool
|
904 |
+
)
|
905 |
+
self.register_buffer("causal_mask", torch.triu(causal_mask, diagonal=1), persistent=False)
|
906 |
+
|
907 |
+
# Initialize weights and apply final processing
|
908 |
+
self.post_init()
|
909 |
+
|
910 |
+
def get_input_embeddings(self):
|
911 |
+
return self.embed_tokens
|
912 |
+
|
913 |
+
def set_input_embeddings(self, value):
|
914 |
+
self.embed_tokens = value
|
915 |
+
|
916 |
+
@add_start_docstrings_to_model_forward(GEMMOE_INPUTS_DOCSTRING)
|
917 |
+
@replace_return_docstrings(output_type=MoeModelOutputWithPast, config_class=_CONFIG_FOR_DOC)
|
918 |
+
def forward(
|
919 |
+
self,
|
920 |
+
input_ids: torch.LongTensor = None,
|
921 |
+
attention_mask: Optional[torch.Tensor] = None,
|
922 |
+
position_ids: Optional[torch.LongTensor] = None,
|
923 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
924 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
925 |
+
use_cache: Optional[bool] = None,
|
926 |
+
output_attentions: Optional[bool] = None,
|
927 |
+
output_hidden_states: Optional[bool] = None,
|
928 |
+
output_router_logits: Optional[bool] = None,
|
929 |
+
return_dict: Optional[bool] = None,
|
930 |
+
cache_position: Optional[torch.LongTensor] = None,
|
931 |
+
) -> Union[Tuple, MoeModelOutputWithPast]:
|
932 |
+
"""
|
933 |
+
Forward pass of the sequence classification model.
|
934 |
+
|
935 |
+
Args:
|
936 |
+
input_ids: Input token IDs.
|
937 |
+
attention_mask: Attention mask.
|
938 |
+
position_ids: Position IDs.
|
939 |
+
past_key_values: Past key-value pairs.
|
940 |
+
inputs_embeds: Input embeddings.
|
941 |
+
labels: Labels for sequence classification.
|
942 |
+
use_cache: Whether to use cache.
|
943 |
+
output_attentions: Whether to output attentions.
|
944 |
+
output_hidden_states: Whether to output hidden states.
|
945 |
+
return_dict: Whether to return a dictionary or tuple.
|
946 |
+
|
947 |
+
Returns:
|
948 |
+
Output of the sequence classification model.
|
949 |
+
"""
|
950 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
951 |
+
output_hidden_states = (
|
952 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
953 |
+
)
|
954 |
+
output_router_logits = (
|
955 |
+
output_router_logits if output_router_logits is not None else self.config.output_router_logits
|
956 |
+
)
|
957 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
958 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
959 |
+
|
960 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
961 |
+
raise ValueError(
|
962 |
+
"You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
|
963 |
+
)
|
964 |
+
|
965 |
+
if self.gradient_checkpointing and self.training and use_cache:
|
966 |
+
logger.warning_once(
|
967 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
|
968 |
+
)
|
969 |
+
use_cache = False
|
970 |
+
|
971 |
+
if inputs_embeds is None:
|
972 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
973 |
+
|
974 |
+
past_seen_tokens = 0
|
975 |
+
if use_cache: # kept for BC (cache positions)
|
976 |
+
if not isinstance(past_key_values, StaticCache):
|
977 |
+
past_key_values = DynamicCache.from_legacy_cache(past_key_values)
|
978 |
+
past_seen_tokens = past_key_values.get_seq_length()
|
979 |
+
|
980 |
+
if cache_position is None:
|
981 |
+
cache_position = torch.arange(
|
982 |
+
past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
|
983 |
+
)
|
984 |
+
|
985 |
+
if position_ids is None:
|
986 |
+
position_ids = cache_position.unsqueeze(0)
|
987 |
+
|
988 |
+
causal_mask = self._update_causal_mask(attention_mask, inputs_embeds)
|
989 |
+
|
990 |
+
hidden_states = inputs_embeds
|
991 |
+
|
992 |
+
# Normalize
|
993 |
+
scale_factor = torch.tensor(math_sqrt(self.config.hidden_size), dtype=hidden_states.dtype)
|
994 |
+
hidden_states = hidden_states * scale_factor
|
995 |
+
# Decoder layers
|
996 |
+
all_hidden_states = () if output_hidden_states else None
|
997 |
+
all_self_attns = () if output_attentions else None
|
998 |
+
all_router_logits = () if output_router_logits else None
|
999 |
+
next_decoder_cache = None
|
1000 |
+
|
1001 |
+
for decoder_layer in self.layers:
|
1002 |
+
if output_hidden_states:
|
1003 |
+
all_hidden_states += (hidden_states,)
|
1004 |
+
|
1005 |
+
if self.gradient_checkpointing and self.training:
|
1006 |
+
layer_outputs = self._gradient_checkpointing_func(
|
1007 |
+
decoder_layer.__call__,
|
1008 |
+
hidden_states,
|
1009 |
+
causal_mask,
|
1010 |
+
position_ids,
|
1011 |
+
past_key_values,
|
1012 |
+
output_attentions,
|
1013 |
+
output_router_logits,
|
1014 |
+
use_cache,
|
1015 |
+
cache_position,
|
1016 |
+
)
|
1017 |
+
else:
|
1018 |
+
layer_outputs = decoder_layer(
|
1019 |
+
hidden_states,
|
1020 |
+
attention_mask=causal_mask,
|
1021 |
+
position_ids=position_ids,
|
1022 |
+
past_key_value=past_key_values,
|
1023 |
+
output_attentions=output_attentions,
|
1024 |
+
output_router_logits=output_router_logits,
|
1025 |
+
use_cache=use_cache,
|
1026 |
+
cache_position=cache_position,
|
1027 |
+
)
|
1028 |
+
|
1029 |
+
hidden_states = layer_outputs[0]
|
1030 |
+
if use_cache:
|
1031 |
+
next_decoder_cache = layer_outputs[2 if output_attentions else 1]
|
1032 |
+
if output_attentions:
|
1033 |
+
all_self_attns += (layer_outputs[1],)
|
1034 |
+
if output_router_logits:
|
1035 |
+
all_router_logits += (layer_outputs[-1],)
|
1036 |
+
|
1037 |
+
hidden_states = self.norm(hidden_states)
|
1038 |
+
|
1039 |
+
# Add hidden states from the last decoder layer
|
1040 |
+
if output_hidden_states:
|
1041 |
+
all_hidden_states += (hidden_states,)
|
1042 |
+
|
1043 |
+
next_cache = None
|
1044 |
+
if use_cache:
|
1045 |
+
next_cache = (
|
1046 |
+
next_decoder_cache.to_legacy_cache() if isinstance(next_decoder_cache, Cache) else next_decoder_cache
|
1047 |
+
)
|
1048 |
+
|
1049 |
+
if not return_dict:
|
1050 |
+
return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns, all_router_logits] if v is not None)
|
1051 |
+
|
1052 |
+
return MoeModelOutputWithPast(
|
1053 |
+
last_hidden_state=hidden_states,
|
1054 |
+
past_key_values=next_cache,
|
1055 |
+
hidden_states=all_hidden_states,
|
1056 |
+
attentions=all_self_attns,
|
1057 |
+
router_logits=all_router_logits
|
1058 |
+
)
|
1059 |
+
|
1060 |
+
def _update_causal_mask(self, attention_mask, input_tensor):
|
1061 |
+
"""
|
1062 |
+
Update the causal mask based on the attention mask and input tensor.
|
1063 |
+
|
1064 |
+
Args:
|
1065 |
+
attention_mask (torch.Tensor): The attention mask.
|
1066 |
+
input_tensor (torch.Tensor): The input tensor.
|
1067 |
+
|
1068 |
+
Returns:
|
1069 |
+
torch.Tensor: The updated causal mask.
|
1070 |
+
"""
|
1071 |
+
|
1072 |
+
if self.config._attn_implementation == "flash_attention_2":
|
1073 |
+
if attention_mask is not None and 0.0 in attention_mask:
|
1074 |
+
return attention_mask
|
1075 |
+
return None
|
1076 |
+
|
1077 |
+
batch_size, seq_length = input_tensor.shape[:2]
|
1078 |
+
dtype = input_tensor.dtype
|
1079 |
+
device = input_tensor.device
|
1080 |
+
|
1081 |
+
# support going beyond cached `max_position_embedding`
|
1082 |
+
if seq_length > self.causal_mask.shape[-1]:
|
1083 |
+
logger.info(f"Resizing causal mask buffer from {self.causal_mask.shape[-1]} to {2 * self.causal_mask.shape[-1]}")
|
1084 |
+
causal_mask = torch.full((2 * self.causal_mask.shape[-1], 2 * self.causal_mask.shape[-1]), fill_value=1)
|
1085 |
+
self.register_buffer("causal_mask", torch.triu(causal_mask, diagonal=1), persistent=False)
|
1086 |
+
|
1087 |
+
# We use the current dtype to avoid any overflows
|
1088 |
+
min_dtype = torch.finfo(dtype).min
|
1089 |
+
causal_mask = self.causal_mask[None, None, :, :].repeat(batch_size, 1, 1, 1).to(dtype) * min_dtype
|
1090 |
+
causal_mask = causal_mask.to(dtype=dtype, device=device)
|
1091 |
+
|
1092 |
+
if attention_mask is not None and attention_mask.dim() == 2:
|
1093 |
+
mask_length = attention_mask.shape[-1]
|
1094 |
+
padding_mask = causal_mask[..., :mask_length].eq(0.0) * attention_mask[:, None, None, :].eq(0.0)
|
1095 |
+
causal_mask[..., :mask_length] = causal_mask[..., :mask_length].masked_fill(padding_mask, min_dtype)
|
1096 |
+
|
1097 |
+
if self.config._attn_implementation == "sdpa" and attention_mask is not None:
|
1098 |
+
# TODO: For dynamo, rather use a check on fullgraph=True once this is possible (https://github.com/pytorch/pytorch/pull/120400).
|
1099 |
+
is_tracing = (
|
1100 |
+
torch.jit.is_tracing()
|
1101 |
+
or isinstance(input_tensor, torch.fx.Proxy)
|
1102 |
+
or (hasattr(torch, "_dynamo") and torch._dynamo.is_compiling())
|
1103 |
+
)
|
1104 |
+
|
1105 |
+
if not is_tracing and torch.any(attention_mask != 1):
|
1106 |
+
# Attend to all tokens in masked rows from the causal_mask, for example the relevant first rows when
|
1107 |
+
# using left padding. This is required by
|
1108 |
+
# F.scaled_dot_product_attention memory-efficient attention path.
|
1109 |
+
# Details: https://github.com/pytorch/pytorch/issues/110213
|
1110 |
+
causal_mask = causal_mask.mul(~torch.all(causal_mask == min_dtype, dim=-1, keepdim=True)).to(dtype)
|
1111 |
+
|
1112 |
+
return causal_mask
|
1113 |
+
|
1114 |
+
class GemmoeForCausalLM(GemmoePreTrainedModel):
|
1115 |
+
r"""
|
1116 |
+
The Gemmoe Model transformer with a language modeling head on top for causal language modeling (CLM).
|
1117 |
+
|
1118 |
+
Args:
|
1119 |
+
config (GemmoeConfig): The configuration object for the Gemmoe model.
|
1120 |
+
|
1121 |
+
Example usage:
|
1122 |
+
```python
|
1123 |
+
>>> from transformers import AutoTokenizer, GemmoeForCausalLM
|
1124 |
+
|
1125 |
+
>>> model = GemmoeForCausalLM.from_pretrained("google/gemmoe-7b")
|
1126 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("google/gemmoe-7b")
|
1127 |
+
|
1128 |
+
>>> prompt = "What is your favorite condiment?"
|
1129 |
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
1130 |
+
|
1131 |
+
>>> # Generate
|
1132 |
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
1133 |
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
1134 |
+
"What is your favorite condiment?"
|
1135 |
+
```
|
1136 |
+
"""
|
1137 |
+
_tied_weights_keys = ["lm_head.weight"]
|
1138 |
+
|
1139 |
+
def __init__(self, config):
|
1140 |
+
super().__init__(config)
|
1141 |
+
self.model = GemmoeModel(config)
|
1142 |
+
self.vocab_size = config.vocab_size
|
1143 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
1144 |
+
self.router_aux_loss_coef = config.router_aux_loss_coef
|
1145 |
+
self.num_experts = 8
|
1146 |
+
self.num_experts_per_tok = config.num_experts_per_tok
|
1147 |
+
|
1148 |
+
# Initialize weights and apply final processing
|
1149 |
+
self.post_init()
|
1150 |
+
|
1151 |
+
def get_input_embeddings(self):
|
1152 |
+
return self.model.embed_tokens
|
1153 |
+
|
1154 |
+
def set_input_embeddings(self, value):
|
1155 |
+
self.model.embed_tokens = value
|
1156 |
+
|
1157 |
+
def get_output_embeddings(self):
|
1158 |
+
return self.lm_head
|
1159 |
+
|
1160 |
+
def set_output_embeddings(self, new_embeddings):
|
1161 |
+
self.lm_head = new_embeddings
|
1162 |
+
|
1163 |
+
def set_decoder(self, decoder):
|
1164 |
+
self.model = decoder
|
1165 |
+
|
1166 |
+
def get_decoder(self):
|
1167 |
+
return self.model
|
1168 |
+
|
1169 |
+
@add_start_docstrings_to_model_forward(GEMMOE_INPUTS_DOCSTRING)
|
1170 |
+
@replace_return_docstrings(output_type=MoeCausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
|
1171 |
+
def forward(
|
1172 |
+
self,
|
1173 |
+
input_ids: torch.LongTensor = None,
|
1174 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1175 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1176 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
1177 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1178 |
+
labels: Optional[torch.LongTensor] = None,
|
1179 |
+
use_cache: Optional[bool] = None,
|
1180 |
+
output_attentions: Optional[bool] = None,
|
1181 |
+
output_hidden_states: Optional[bool] = None,
|
1182 |
+
output_router_logits: Optional[bool] = None,
|
1183 |
+
return_dict: Optional[bool] = None,
|
1184 |
+
cache_position: Optional[torch.LongTensor] = None,
|
1185 |
+
) -> Union[Tuple, MoeCausalLMOutputWithPast]:
|
1186 |
+
r"""
|
1187 |
+
Args:
|
1188 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
1189 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
1190 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
1191 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
1192 |
+
|
1193 |
+
Returns:
|
1194 |
+
|
1195 |
+
Example:
|
1196 |
+
|
1197 |
+
```python
|
1198 |
+
>>> from transformers import AutoTokenizer, GemmoeForCausalLM
|
1199 |
+
|
1200 |
+
>>> model = GemmoeForCausalLM.from_pretrained("google/gemmoe-7b")
|
1201 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("google/gemmoe-7b")
|
1202 |
+
|
1203 |
+
>>> prompt = "What is your favorite condiment?"
|
1204 |
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
1205 |
+
|
1206 |
+
>>> # Generate
|
1207 |
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
1208 |
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
1209 |
+
"What is your favorite condiment?"
|
1210 |
+
```"""
|
1211 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
1212 |
+
output_router_logits = (
|
1213 |
+
output_router_logits if output_router_logits is not None else getattr(self.config, "output_router_logits", False)
|
1214 |
+
)
|
1215 |
+
output_hidden_states = (
|
1216 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
1217 |
+
)
|
1218 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1219 |
+
|
1220 |
+
outputs = self.model(
|
1221 |
+
input_ids=input_ids,
|
1222 |
+
attention_mask=attention_mask,
|
1223 |
+
position_ids=position_ids,
|
1224 |
+
past_key_values=past_key_values,
|
1225 |
+
inputs_embeds=inputs_embeds,
|
1226 |
+
use_cache=use_cache,
|
1227 |
+
output_attentions=output_attentions,
|
1228 |
+
output_hidden_states=output_hidden_states,
|
1229 |
+
output_router_logits=output_router_logits,
|
1230 |
+
return_dict=return_dict,
|
1231 |
+
cache_position=cache_position,
|
1232 |
+
)
|
1233 |
+
|
1234 |
+
hidden_states = outputs[0]
|
1235 |
+
logits = self.lm_head(hidden_states)
|
1236 |
+
logits = logits.float()
|
1237 |
+
|
1238 |
+
loss = None
|
1239 |
+
if labels is not None:
|
1240 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
1241 |
+
shift_labels = labels[..., 1:].contiguous()
|
1242 |
+
loss_fct = CrossEntropyLoss()
|
1243 |
+
shift_logits = shift_logits.view(-1, self.config.vocab_size)
|
1244 |
+
shift_labels = shift_labels.view(-1)
|
1245 |
+
shift_labels = shift_labels.to(shift_logits.device)
|
1246 |
+
loss = loss_fct(shift_logits, shift_labels)
|
1247 |
+
|
1248 |
+
aux_loss = None
|
1249 |
+
if output_router_logits:
|
1250 |
+
router_logits = outputs.router_logits if return_dict else outputs[-1]
|
1251 |
+
if router_logits is not None:
|
1252 |
+
aux_loss = load_balancing_loss_func(
|
1253 |
+
router_logits,
|
1254 |
+
self.num_experts,
|
1255 |
+
self.num_experts_per_tok,
|
1256 |
+
attention_mask,
|
1257 |
+
)
|
1258 |
+
if labels is not None:
|
1259 |
+
loss += self.router_aux_loss_coef * aux_loss.to(loss.device)
|
1260 |
+
|
1261 |
+
if not return_dict:
|
1262 |
+
output = (logits,) + outputs[1:]
|
1263 |
+
if aux_loss is not None:
|
1264 |
+
output = (aux_loss,) + output
|
1265 |
+
return (loss,) + output if loss is not None else output
|
1266 |
+
|
1267 |
+
return MoeCausalLMOutputWithPast(
|
1268 |
+
loss=loss,
|
1269 |
+
aux_loss=aux_loss,
|
1270 |
+
logits=logits,
|
1271 |
+
past_key_values=outputs.past_key_values,
|
1272 |
+
hidden_states=outputs.hidden_states,
|
1273 |
+
attentions=outputs.attentions,
|
1274 |
+
router_logits=outputs.router_logits,
|
1275 |
+
)
|
1276 |
+
|
1277 |
+
def prepare_inputs_for_generation(
|
1278 |
+
self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
|
1279 |
+
):
|
1280 |
+
past_length = 0
|
1281 |
+
if past_key_values is not None:
|
1282 |
+
if isinstance(past_key_values, Cache):
|
1283 |
+
cache_length = past_key_values.get_seq_length()
|
1284 |
+
past_length = past_key_values.seen_tokens
|
1285 |
+
max_cache_length = past_key_values.get_max_length()
|
1286 |
+
else:
|
1287 |
+
cache_length = past_length = past_key_values[0][0].shape[2]
|
1288 |
+
max_cache_length = None
|
1289 |
+
|
1290 |
+
if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
|
1291 |
+
input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
|
1292 |
+
elif past_length < input_ids.shape[1]:
|
1293 |
+
input_ids = input_ids[:, past_length:]
|
1294 |
+
|
1295 |
+
if (
|
1296 |
+
max_cache_length is not None
|
1297 |
+
and attention_mask is not None
|
1298 |
+
and cache_length + input_ids.shape[1] > max_cache_length
|
1299 |
+
):
|
1300 |
+
attention_mask = attention_mask[:, -max_cache_length:]
|
1301 |
+
|
1302 |
+
position_ids = kwargs.get("position_ids", None)
|
1303 |
+
if attention_mask is not None and position_ids is None:
|
1304 |
+
position_ids = attention_mask.long().cumsum(-1) - 1
|
1305 |
+
position_ids.masked_fill_(attention_mask == 0, 1)
|
1306 |
+
if past_key_values:
|
1307 |
+
position_ids = position_ids[:, -input_ids.shape[1] :]
|
1308 |
+
|
1309 |
+
if self.generation_config.cache_implementation == "static":
|
1310 |
+
cache_position = kwargs.get("cache_position", None)
|
1311 |
+
if cache_position is None:
|
1312 |
+
past_length = 0
|
1313 |
+
else:
|
1314 |
+
past_length = cache_position[-1] + 1
|
1315 |
+
input_ids = input_ids[:, past_length:]
|
1316 |
+
position_ids = position_ids[:, past_length:]
|
1317 |
+
|
1318 |
+
cache_position = torch.arange(past_length, past_length + position_ids.shape[-1], device=position_ids.device)
|
1319 |
+
|
1320 |
+
if inputs_embeds is not None and past_key_values is None:
|
1321 |
+
model_inputs = {"inputs_embeds": inputs_embeds}
|
1322 |
+
else:
|
1323 |
+
model_inputs = {"input_ids": input_ids.contiguous()}
|
1324 |
+
|
1325 |
+
model_inputs.update(
|
1326 |
+
{
|
1327 |
+
"position_ids": position_ids.contiguous(),
|
1328 |
+
"cache_position": cache_position,
|
1329 |
+
"past_key_values": past_key_values,
|
1330 |
+
"use_cache": kwargs.get("use_cache"),
|
1331 |
+
"attention_mask": attention_mask,
|
1332 |
+
}
|
1333 |
+
)
|
1334 |
+
|
1335 |
+
return model_inputs
|
1336 |
+
|
1337 |
+
@staticmethod
|
1338 |
+
def _reorder_cache(past_key_values, beam_idx):
|
1339 |
+
reordered_past = ()
|
1340 |
+
for layer_past in past_key_values:
|
1341 |
+
reordered_past += (
|
1342 |
+
tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
|
1343 |
+
)
|
1344 |
+
return reordered_past
|
1345 |
+
@add_start_docstrings(
|
1346 |
+
"""
|
1347 |
+
The Gemmoe Model transformer with a sequence classification head on top (linear layer).
|
1348 |
+
[`GemmoeForSequenceClassification`] uses the last token in order to do the classification, as other causal models
|
1349 |
+
(e.g. GPT-2) do.
|
1350 |
+
|
1351 |
+
Since it does classification on the last token, it requires to know the position of the last token. If a
|
1352 |
+
`pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
|
1353 |
+
no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
|
1354 |
+
padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
|
1355 |
+
each row of the batch).
|
1356 |
+
""",
|
1357 |
+
GEMMOE_START_DOCSTRING,
|
1358 |
+
)
|
1359 |
+
|
1360 |
+
class GemmoeForSequenceClassification(GemmoePreTrainedModel):
|
1361 |
+
def __init__(self, config):
|
1362 |
+
super().__init__(config)
|
1363 |
+
self.num_labels = config.num_labels
|
1364 |
+
self.model = GemmoeModel(config)
|
1365 |
+
self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
|
1366 |
+
# Initialize weights and apply final processing
|
1367 |
+
self.post_init()
|
1368 |
+
|
1369 |
+
def get_input_embeddings(self):
|
1370 |
+
return self.model.embed_tokens
|
1371 |
+
|
1372 |
+
def set_input_embeddings(self, value):
|
1373 |
+
self.model.embed_tokens = value
|
1374 |
+
|
1375 |
+
@add_start_docstrings_to_model_forward(GEMMOE_INPUTS_DOCSTRING)
|
1376 |
+
@replace_return_docstrings(output_type=SequenceClassifierOutputWithPast, config_class=_CONFIG_FOR_DOC)
|
1377 |
+
def forward(
|
1378 |
+
self,
|
1379 |
+
input_ids: torch.LongTensor = None,
|
1380 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1381 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1382 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
1383 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1384 |
+
labels: Optional[torch.LongTensor] = None,
|
1385 |
+
use_cache: Optional[bool] = None,
|
1386 |
+
output_attentions: Optional[bool] = None,
|
1387 |
+
output_hidden_states: Optional[bool] = None,
|
1388 |
+
return_dict: Optional[bool] = None,
|
1389 |
+
) -> Union[Tuple, SequenceClassifierOutputWithPast]:
|
1390 |
+
"""
|
1391 |
+
Forward pass of the sequence classification model.
|
1392 |
+
|
1393 |
+
Args:
|
1394 |
+
input_ids (torch.LongTensor, optional): Input token IDs.
|
1395 |
+
attention_mask (torch.Tensor, optional): Attention mask.
|
1396 |
+
position_ids (torch.LongTensor, optional): Position IDs.
|
1397 |
+
past_key_values (List[torch.FloatTensor], optional): Past key-value pairs.
|
1398 |
+
inputs_embeds (torch.FloatTensor, optional): Input embeddings.
|
1399 |
+
labels (torch.LongTensor, optional): Labels for sequence classification.
|
1400 |
+
use_cache (bool, optional): Whether to use cache.
|
1401 |
+
output_attentions (bool, optional): Whether to output attentions.
|
1402 |
+
output_hidden_states (bool, optional): Whether to output hidden states.
|
1403 |
+
return_dict (bool, optional): Whether to return a dictionary or tuple.
|
1404 |
+
|
1405 |
+
Returns:
|
1406 |
+
Union[Tuple, SequenceClassifierOutputWithPast]: Output of the sequence classification model.
|
1407 |
+
"""
|
1408 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1409 |
+
transformer_outputs = self.model(
|
1410 |
+
input_ids,
|
1411 |
+
attention_mask=attention_mask,
|
1412 |
+
position_ids=position_ids,
|
1413 |
+
past_key_values=past_key_values,
|
1414 |
+
inputs_embeds=inputs_embeds,
|
1415 |
+
use_cache=use_cache,
|
1416 |
+
output_attentions=output_attentions,
|
1417 |
+
output_hidden_states=output_hidden_states,
|
1418 |
+
return_dict=return_dict,
|
1419 |
+
)
|
1420 |
+
hidden_states = transformer_outputs[0]
|
1421 |
+
logits = self.score(hidden_states)
|
1422 |
+
|
1423 |
+
if input_ids is not None:
|
1424 |
+
batch_size = input_ids.shape[0]
|
1425 |
+
else:
|
1426 |
+
batch_size = inputs_embeds.shape[0]
|
1427 |
+
|
1428 |
+
if self.config.pad_token_id is None and batch_size != 1:
|
1429 |
+
raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
|
1430 |
+
if self.config.pad_token_id is None:
|
1431 |
+
sequence_lengths = -1
|
1432 |
+
else:
|
1433 |
+
if input_ids is not None:
|
1434 |
+
# if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
|
1435 |
+
sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
|
1436 |
+
sequence_lengths = sequence_lengths % input_ids.shape[-1]
|
1437 |
+
sequence_lengths = sequence_lengths.to(logits.device)
|
1438 |
+
else:
|
1439 |
+
sequence_lengths = -1
|
1440 |
+
|
1441 |
+
pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
|
1442 |
+
|
1443 |
+
loss = None
|
1444 |
+
if labels is not None:
|
1445 |
+
labels = labels.to(logits.device)
|
1446 |
+
if self.config.problem_type is None:
|
1447 |
+
if self.num_labels == 1:
|
1448 |
+
self.config.problem_type = "regression"
|
1449 |
+
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
1450 |
+
self.config.problem_type = "single_label_classification"
|
1451 |
+
else:
|
1452 |
+
self.config.problem_type = "multi_label_classification"
|
1453 |
+
|
1454 |
+
if self.config.problem_type == "regression":
|
1455 |
+
loss_fct = MSELoss()
|
1456 |
+
if self.num_labels == 1:
|
1457 |
+
loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
|
1458 |
+
else:
|
1459 |
+
loss = loss_fct(pooled_logits, labels)
|
1460 |
+
elif self.config.problem_type == "single_label_classification":
|
1461 |
+
loss_fct = CrossEntropyLoss()
|
1462 |
+
loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
|
1463 |
+
elif self.config.problem_type == "multi_label_classification":
|
1464 |
+
loss_fct = BCEWithLogitsLoss()
|
1465 |
+
loss = loss_fct(pooled_logits, labels)
|
1466 |
+
|
1467 |
+
if not return_dict:
|
1468 |
+
output = (pooled_logits,) + transformer_outputs[1:]
|
1469 |
+
return ((loss,) + output) if loss is not None else output
|
1470 |
+
|
1471 |
+
return SequenceClassifierOutputWithPast(
|
1472 |
+
loss=loss,
|
1473 |
+
logits=pooled_logits,
|
1474 |
+
past_key_values=transformer_outputs.past_key_values,
|
1475 |
+
hidden_states=transformer_outputs.hidden_states,
|
1476 |
+
attentions=transformer_outputs.attentions,
|
1477 |
+
)
|
tokenization_gemmoe.py
ADDED
@@ -0,0 +1,311 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
"""Tokenization classes for Gemmoe."""
|
16 |
+
import os
|
17 |
+
from shutil import copyfile
|
18 |
+
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple
|
19 |
+
|
20 |
+
import sentencepiece as spm
|
21 |
+
|
22 |
+
from ...tokenization_utils import AddedToken, PreTrainedTokenizer
|
23 |
+
from ...utils import logging
|
24 |
+
|
25 |
+
if TYPE_CHECKING:
|
26 |
+
pass
|
27 |
+
|
28 |
+
logger = logging.get_logger(__name__)
|
29 |
+
|
30 |
+
VOCAB_FILES_NAMES = {"vocab_file": "tokenizer.model"}
|
31 |
+
|
32 |
+
SPIECE_UNDERLINE = "▁"
|
33 |
+
|
34 |
+
class GemmoeTokenizer(PreTrainedTokenizer):
|
35 |
+
"""
|
36 |
+
Construct a Gemmoe tokenizer. Based on byte-level Byte-Pair-Encoding. The default padding token is unset as there is
|
37 |
+
no padding token in the original model.
|
38 |
+
|
39 |
+
Args:
|
40 |
+
vocab_file (`str`):
|
41 |
+
Path to the vocabulary file.
|
42 |
+
unk_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"<unk>"`):
|
43 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
|
44 |
+
token instead.
|
45 |
+
bos_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"<bos>"`):
|
46 |
+
The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
|
47 |
+
eos_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"<eos>"`):
|
48 |
+
The end of sequence token.
|
49 |
+
pad_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"<pad>"`):
|
50 |
+
A special token used to make arrays of tokens the same size for batching purpose. Will then be ignored by
|
51 |
+
attention mechanisms or loss computation.
|
52 |
+
sp_model_kwargs (`Dict[str, Any]`, `Optional`, *optional*):
|
53 |
+
Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
|
54 |
+
SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
|
55 |
+
to set:
|
56 |
+
- `enable_sampling`: Enable subword regularization.
|
57 |
+
- `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.
|
58 |
+
- `nbest_size = {0,1}`: No sampling is performed.
|
59 |
+
- `nbest_size > 1`: samples from the nbest_size results.
|
60 |
+
- `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
|
61 |
+
using forward-filtering-and-backward-sampling algorithm.
|
62 |
+
- `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
|
63 |
+
BPE-dropout.
|
64 |
+
add_bos_token (`bool`, *optional*, defaults to `True`):
|
65 |
+
Whether or not to add an `bos_token` at the start of sequences.
|
66 |
+
add_eos_token (`bool`, *optional*, defaults to `False`):
|
67 |
+
Whether or not to add an `eos_token` at the end of sequences.
|
68 |
+
clean_up_tokenization_spaces (`bool`, *optional*, defaults to `False`):
|
69 |
+
Whether or not to cleanup spaces after decoding, cleanup consists in removing potential artifacts like
|
70 |
+
extra spaces.
|
71 |
+
use_default_system_prompt (`bool`, *optional*, defaults to `False`):
|
72 |
+
Whether or not the default system prompt for Gemmoe should be used.
|
73 |
+
spaces_between_special_tokens (`bool`, *optional*, defaults to `False`):
|
74 |
+
Whether or not to add spaces between special tokens.
|
75 |
+
"""
|
76 |
+
|
77 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
78 |
+
model_input_names = ["input_ids", "attention_mask"]
|
79 |
+
|
80 |
+
def __init__(
|
81 |
+
self,
|
82 |
+
vocab_file,
|
83 |
+
unk_token="<unk>",
|
84 |
+
bos_token="<bos>",
|
85 |
+
eos_token="<eos>",
|
86 |
+
pad_token="<pad>",
|
87 |
+
sp_model_kwargs: Optional[Dict[str, Any]] = None,
|
88 |
+
add_bos_token=True,
|
89 |
+
add_eos_token=False,
|
90 |
+
clean_up_tokenization_spaces=False,
|
91 |
+
use_default_system_prompt=False,
|
92 |
+
spaces_between_special_tokens=False,
|
93 |
+
**kwargs,
|
94 |
+
):
|
95 |
+
self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
|
96 |
+
bos_token = AddedToken(bos_token, normalized=False, special=True) if isinstance(bos_token, str) else bos_token
|
97 |
+
eos_token = AddedToken(eos_token, normalized=False, special=True) if isinstance(eos_token, str) else eos_token
|
98 |
+
unk_token = AddedToken(unk_token, normalized=False, special=True) if isinstance(unk_token, str) else unk_token
|
99 |
+
pad_token = AddedToken(pad_token, normalized=False, special=True) if isinstance(pad_token, str) else pad_token
|
100 |
+
|
101 |
+
self.vocab_file = vocab_file
|
102 |
+
self.add_bos_token = add_bos_token
|
103 |
+
self.add_eos_token = add_eos_token
|
104 |
+
self.use_default_system_prompt = use_default_system_prompt
|
105 |
+
|
106 |
+
self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
|
107 |
+
self.sp_model.Load(vocab_file)
|
108 |
+
|
109 |
+
super().__init__(
|
110 |
+
bos_token=bos_token,
|
111 |
+
eos_token=eos_token,
|
112 |
+
unk_token=unk_token,
|
113 |
+
pad_token=pad_token,
|
114 |
+
add_bos_token=add_bos_token,
|
115 |
+
add_eos_token=add_eos_token,
|
116 |
+
sp_model_kwargs=self.sp_model_kwargs,
|
117 |
+
clean_up_tokenization_spaces=clean_up_tokenization_spaces,
|
118 |
+
use_default_system_prompt=use_default_system_prompt,
|
119 |
+
spaces_between_special_tokens=spaces_between_special_tokens,
|
120 |
+
**kwargs,
|
121 |
+
)
|
122 |
+
|
123 |
+
def __getstate__(self):
|
124 |
+
state = self.__dict__.copy()
|
125 |
+
state["sp_model"] = None
|
126 |
+
state["sp_model_proto"] = self.sp_model.serialized_model_proto()
|
127 |
+
return state
|
128 |
+
|
129 |
+
def __setstate__(self, d):
|
130 |
+
self.__dict__ = d
|
131 |
+
self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
|
132 |
+
self.sp_model.LoadFromSerializedProto(self.sp_model_proto)
|
133 |
+
|
134 |
+
@property
|
135 |
+
def vocab_size(self):
|
136 |
+
"""Returns vocab size"""
|
137 |
+
return self.sp_model.get_piece_size()
|
138 |
+
|
139 |
+
def get_vocab(self):
|
140 |
+
"""Returns vocab as a dict"""
|
141 |
+
vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
|
142 |
+
vocab.update(self.added_tokens_encoder)
|
143 |
+
return vocab
|
144 |
+
|
145 |
+
def _tokenize(self, text, **kwargs):
|
146 |
+
"""
|
147 |
+
Returns a tokenized string. The Gemmoe tokenizer never adds a prefix space.
|
148 |
+
"""
|
149 |
+
return self.sp_model.encode(text, out_type=str)
|
150 |
+
|
151 |
+
def _convert_token_to_id(self, token):
|
152 |
+
"""Converts a token (str) in an id using the vocab."""
|
153 |
+
return self.sp_model.piece_to_id(token)
|
154 |
+
|
155 |
+
def _convert_id_to_token(self, index):
|
156 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
157 |
+
token = self.sp_model.IdToPiece(index)
|
158 |
+
return token
|
159 |
+
|
160 |
+
def _decode(
|
161 |
+
self,
|
162 |
+
token_ids: List[int],
|
163 |
+
skip_special_tokens: bool = False,
|
164 |
+
spaces_between_special_tokens: bool = False,
|
165 |
+
**kwargs,
|
166 |
+
) -> str:
|
167 |
+
sub_texts = []
|
168 |
+
current_sub_text = []
|
169 |
+
for ids in token_ids:
|
170 |
+
if skip_special_tokens and ids in self.all_special_ids:
|
171 |
+
continue
|
172 |
+
if ids in self._added_tokens_decoder:
|
173 |
+
if current_sub_text:
|
174 |
+
sub_texts.append(self.sp_model.decode(current_sub_text))
|
175 |
+
sub_texts.append(self._added_tokens_decoder[ids].content)
|
176 |
+
current_sub_text = []
|
177 |
+
else:
|
178 |
+
current_sub_text.append(ids)
|
179 |
+
if current_sub_text:
|
180 |
+
sub_texts.append(self.sp_model.decode(current_sub_text))
|
181 |
+
if spaces_between_special_tokens:
|
182 |
+
sub_texts = " ".join(sub_texts)
|
183 |
+
else:
|
184 |
+
sub_texts = "".join(sub_texts)
|
185 |
+
return sub_texts
|
186 |
+
|
187 |
+
def convert_tokens_to_string(self, tokens):
|
188 |
+
"""Converts a sequence of tokens (string) in a single string."""
|
189 |
+
current_sub_tokens = []
|
190 |
+
out_string = ""
|
191 |
+
for token in tokens:
|
192 |
+
# make sure that special tokens are not decoded using sentencepiece model
|
193 |
+
if token in self._added_tokens_encoder:
|
194 |
+
out_string += self.sp_model.decode(current_sub_tokens) + token
|
195 |
+
current_sub_tokens = []
|
196 |
+
else:
|
197 |
+
current_sub_tokens.append(token)
|
198 |
+
out_string += self.sp_model.decode(current_sub_tokens)
|
199 |
+
return out_string
|
200 |
+
|
201 |
+
def save_vocabulary(self, save_directory, filename_prefix: Optional[str] = None) -> Tuple[str]:
|
202 |
+
"""
|
203 |
+
Save the vocabulary and special tokens file to a directory.
|
204 |
+
|
205 |
+
Args:
|
206 |
+
save_directory (`str`):
|
207 |
+
The directory in which to save the vocabulary.
|
208 |
+
|
209 |
+
Returns:
|
210 |
+
`Tuple(str)`: Paths to the files saved.
|
211 |
+
"""
|
212 |
+
if not os.path.isdir(save_directory):
|
213 |
+
logger.error(f"Vocabulary path ({save_directory}) should be a directory")
|
214 |
+
return
|
215 |
+
out_vocab_file = os.path.join(
|
216 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
|
217 |
+
)
|
218 |
+
|
219 |
+
if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
|
220 |
+
copyfile(self.vocab_file, out_vocab_file)
|
221 |
+
elif not os.path.isfile(self.vocab_file):
|
222 |
+
with open(out_vocab_file, "wb") as fi:
|
223 |
+
content_spiece_model = self.sp_model.serialized_model_proto()
|
224 |
+
fi.write(content_spiece_model)
|
225 |
+
|
226 |
+
return (out_vocab_file,)
|
227 |
+
|
228 |
+
def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
|
229 |
+
bos_token_id = [self.bos_token_id] if self.add_bos_token else []
|
230 |
+
eos_token_id = [self.eos_token_id] if self.add_eos_token else []
|
231 |
+
output = bos_token_id + token_ids_0 + eos_token_id
|
232 |
+
if token_ids_1 is not None:
|
233 |
+
output = output + bos_token_id + token_ids_1 + eos_token_id
|
234 |
+
return output
|
235 |
+
|
236 |
+
def get_special_tokens_mask(
|
237 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
|
238 |
+
) -> List[int]:
|
239 |
+
"""
|
240 |
+
Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
|
241 |
+
special tokens using the tokenizer `prepare_for_model` method.
|
242 |
+
|
243 |
+
Args:
|
244 |
+
token_ids_0 (`List[int]`):
|
245 |
+
List of IDs.
|
246 |
+
token_ids_1 (`List[int]`, *optional*):
|
247 |
+
Optional second list of IDs for sequence pairs.
|
248 |
+
already_has_special_tokens (`bool`, *optional*, defaults to `False`):
|
249 |
+
Whether or not the token list is already formatted with special tokens for the model.
|
250 |
+
|
251 |
+
Returns:
|
252 |
+
`List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
|
253 |
+
"""
|
254 |
+
if already_has_special_tokens:
|
255 |
+
return super().get_special_tokens_mask(
|
256 |
+
token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
|
257 |
+
)
|
258 |
+
|
259 |
+
bos_token_id = [1] if self.add_bos_token else []
|
260 |
+
eos_token_id = [1] if self.add_eos_token else []
|
261 |
+
|
262 |
+
if token_ids_1 is None:
|
263 |
+
return bos_token_id + ([0] * len(token_ids_0)) + eos_token_id
|
264 |
+
return (
|
265 |
+
bos_token_id
|
266 |
+
+ ([0] * len(token_ids_0))
|
267 |
+
+ eos_token_id
|
268 |
+
+ bos_token_id
|
269 |
+
+ ([0] * len(token_ids_1))
|
270 |
+
+ eos_token_id
|
271 |
+
)
|
272 |
+
|
273 |
+
def create_token_type_ids_from_sequences(
|
274 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
|
275 |
+
) -> List[int]:
|
276 |
+
"""
|
277 |
+
Creates a mask from the two sequences passed to be used in a sequence-pair classification task. An ALBERT
|
278 |
+
sequence pair mask has the following format:
|
279 |
+
|
280 |
+
```
|
281 |
+
0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
|
282 |
+
| first sequence | second sequence |
|
283 |
+
```
|
284 |
+
|
285 |
+
if token_ids_1 is None, only returns the first portion of the mask (0s).
|
286 |
+
|
287 |
+
Args:
|
288 |
+
token_ids_0 (`List[int]`):
|
289 |
+
List of ids.
|
290 |
+
token_ids_1 (`List[int]`, *optional*):
|
291 |
+
Optional second list of IDs for sequence pairs.
|
292 |
+
|
293 |
+
Returns:
|
294 |
+
`List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
|
295 |
+
"""
|
296 |
+
bos_token_id = [self.bos_token_id] if self.add_bos_token else []
|
297 |
+
eos_token_id = [self.eos_token_id] if self.add_eos_token else []
|
298 |
+
output = [0] * len(bos_token_id + token_ids_0 + eos_token_id)
|
299 |
+
if token_ids_1 is not None:
|
300 |
+
output += [1] * len(bos_token_id + token_ids_1 + eos_token_id)
|
301 |
+
return output
|
302 |
+
|
303 |
+
def _build_conversation_input_ids(self, conversation: List[List[int]]) -> List[int]:
|
304 |
+
input_ids = []
|
305 |
+
for i, history in enumerate(conversation):
|
306 |
+
if i % 2 == 0:
|
307 |
+
input_ids.extend([self.bos_token_id, self.convert_tokens_to_ids("<start_of_turn>")] + history + [self.convert_tokens_to_ids("<end_of_turn>")])
|
308 |
+
else:
|
309 |
+
input_ids.extend([self.bos_token_id, self.convert_tokens_to_ids("<start_of_turn>"), self.convert_tokens_to_ids("model")] + history + [self.convert_tokens_to_ids("<end_of_turn>\n")])
|
310 |
+
input_ids.append(self.eos_token_id)
|
311 |
+
return input_ids
|