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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
|
3 |
+
#
|
4 |
+
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
|
5 |
+
# and OPT implementations in this library. It has been modified from its
|
6 |
+
# original forms to accommodate minor architectural differences compared
|
7 |
+
# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
|
8 |
+
#
|
9 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
10 |
+
# you may not use this file except in compliance with the License.
|
11 |
+
# You may obtain a copy of the License at
|
12 |
+
#
|
13 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
14 |
+
#
|
15 |
+
# Unless required by applicable law or agreed to in writing, software
|
16 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
17 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
18 |
+
# See the License for the specific language governing permissions and
|
19 |
+
# limitations under the License.
|
20 |
+
""" PyTorch OpenMoE model."""
|
21 |
+
import math
|
22 |
+
from typing import List, Optional, Tuple, Union
|
23 |
+
|
24 |
+
import torch
|
25 |
+
import torch.nn.functional as F
|
26 |
+
import torch.utils.checkpoint
|
27 |
+
from torch import nn
|
28 |
+
from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
|
29 |
+
from transformers.modeling_utils import PreTrainedModel
|
30 |
+
from transformers.models.llama.modeling_llama import LlamaConfig, LlamaRMSNorm
|
31 |
+
from transformers.utils import (
|
32 |
+
add_start_docstrings,
|
33 |
+
add_start_docstrings_to_model_forward,
|
34 |
+
logging,
|
35 |
+
replace_return_docstrings,
|
36 |
+
)
|
37 |
+
|
38 |
+
from colossalai.kernel.cuda_native.mha.flash_attn_2 import HAS_FLASH_ATTN
|
39 |
+
from colossalai.kernel.triton.llama_act_combine_kernel import HAS_TRITON
|
40 |
+
from colossalai.moe.layers import SparseMLP
|
41 |
+
from colossalai.moe.manager import MOE_MANAGER
|
42 |
+
from colossalai.moe.utils import get_activation, set_moe_args
|
43 |
+
|
44 |
+
if HAS_TRITON:
|
45 |
+
from colossalai.kernel.triton.llama_act_combine_kernel import LlamaActCombine
|
46 |
+
|
47 |
+
logger = logging.get_logger(__name__)
|
48 |
+
|
49 |
+
_CONFIG_FOR_DOC = "LlamaConfig"
|
50 |
+
|
51 |
+
class LlamaRotaryEmbedding(nn.Module):
|
52 |
+
def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
|
53 |
+
super().__init__()
|
54 |
+
|
55 |
+
self.dim = dim
|
56 |
+
self.max_position_embeddings = max_position_embeddings
|
57 |
+
self.base = base
|
58 |
+
inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
|
59 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
60 |
+
|
61 |
+
# Build here to make `torch.jit.trace` work.
|
62 |
+
self._set_cos_sin_cache(
|
63 |
+
seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
|
64 |
+
)
|
65 |
+
|
66 |
+
def _set_cos_sin_cache(self, seq_len, device, dtype):
|
67 |
+
self.max_seq_len_cached = seq_len
|
68 |
+
t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
|
69 |
+
|
70 |
+
freqs = torch.outer(t, self.inv_freq) # (seq_len, dim//2)
|
71 |
+
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
72 |
+
emb = torch.cat((freqs, freqs), dim=-1) # (seq_len, dim)
|
73 |
+
self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
|
74 |
+
self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
|
75 |
+
|
76 |
+
def forward(self, x, seq_len=None):
|
77 |
+
# x: [bs, num_attention_heads, seq_len, head_size]
|
78 |
+
if seq_len > self.max_seq_len_cached:
|
79 |
+
self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
|
80 |
+
|
81 |
+
return (
|
82 |
+
self.cos_cached[:seq_len].to(dtype=x.dtype),
|
83 |
+
self.sin_cached[:seq_len].to(dtype=x.dtype),
|
84 |
+
)
|
85 |
+
|
86 |
+
def set_openmoe_args(
|
87 |
+
config: LlamaConfig,
|
88 |
+
num_experts: int,
|
89 |
+
moe_layer_interval: int,
|
90 |
+
router_topk: int = 2,
|
91 |
+
router_capacity_factor_train: float = 1.25,
|
92 |
+
router_capacity_factor_eval: float = 2.0,
|
93 |
+
router_min_capacity: int = 4,
|
94 |
+
router_noisy_policy: str = None,
|
95 |
+
router_drop_tks: bool = True,
|
96 |
+
router_aux_loss_factor: float = 0.01,
|
97 |
+
router_z_loss_factor: float = 0.0001,
|
98 |
+
mlp_gated: bool = True,
|
99 |
+
label_smoothing: float = 0.001,
|
100 |
+
z_loss_factor: float = 0.01,
|
101 |
+
enable_load_balance: bool = False,
|
102 |
+
load_balance_tolerance: float = 0.1,
|
103 |
+
load_balance_beam_width: int = 8,
|
104 |
+
load_balance_group_swap_factor: float = 0.4,
|
105 |
+
enable_kernel: bool = False,
|
106 |
+
enable_comm_overlap: bool = False,
|
107 |
+
enable_hierarchical_alltoall: bool = False,
|
108 |
+
) -> None:
|
109 |
+
"""
|
110 |
+
MoE related arguments.
|
111 |
+
It inserts the MoE arguments into the Llama config.
|
112 |
+
|
113 |
+
Args:
|
114 |
+
config (LlamaConfig): Transformers Llama config.
|
115 |
+
num_experts (int, optional): Number of experts.
|
116 |
+
moe_layer_interval (int, optional): The interval moe layer.
|
117 |
+
router_topk (int, optional): Moe router top k. Defaults to 2.
|
118 |
+
router_capacity_factor_train (float, optional): Moe router max capacity for train. Defaults to 1.25.
|
119 |
+
router_capacity_factor_eval (float, optional): Moe router max capacity for eval. Defaults to 2.0.
|
120 |
+
router_min_capacity (int, optional): Moe router min capacity. Defaults to 4.
|
121 |
+
router_noisy_policy (str, optional): Moe router noisy policy. You can choose [Jitter, Gaussian, None]. Defaults to None.
|
122 |
+
router_drop_tks (bool, optional): Whether moe router drop tokens which exceed max capacity. Defaults to True.
|
123 |
+
router_aux_loss_factor (float, optional): Moe router aux loss. You can refer to STMoE for details. Defaults to 0.01.
|
124 |
+
router_z_loss_factor (float, optional): Moe router z loss. You can refer to STMoE for details. Defaults to 0.01.
|
125 |
+
mlp_gated (bool, optional): Use gate in mlp. Defaults to True.
|
126 |
+
label_smoothing (float, optional): Label smoothing. Defaults to 0.001.
|
127 |
+
z_loss_factor (float, optional): The final outputs' classification z loss factor. Defaults to 0.01.
|
128 |
+
enable_load_balance (bool, optional): Expert load balance. Defaults to False.
|
129 |
+
load_balance_tolerance (float, optional): Expert load balance search's difference tolerance. Defaults to 0.1.
|
130 |
+
load_balance_beam_width (int, optional): Expert load balance search's beam width. Defaults to 8.
|
131 |
+
load_balance_group_swap_factor (float, optional): Expert load balance group swap factor. Longer value encourages less swap. Defaults to 0.4.
|
132 |
+
enable_kernel (bool, optional): Use kernel optimization. Defaults to False.
|
133 |
+
enable_comm_overlap (bool, optional): Use communication overlap for MoE. Recommended to enable for muiti-node training. Defaults to False.
|
134 |
+
enable_hierarchical_alltoall (bool, optional): Use hierarchical alltoall for MoE. Defaults to False.
|
135 |
+
"""
|
136 |
+
moe_args = dict(
|
137 |
+
num_experts=num_experts,
|
138 |
+
moe_layer_interval=moe_layer_interval,
|
139 |
+
router_topk=router_topk,
|
140 |
+
router_capacity_factor_train=router_capacity_factor_train,
|
141 |
+
router_capacity_factor_eval=router_capacity_factor_eval,
|
142 |
+
router_min_capacity=router_min_capacity,
|
143 |
+
router_noisy_policy=router_noisy_policy,
|
144 |
+
router_drop_tks=router_drop_tks,
|
145 |
+
router_aux_loss_factor=router_aux_loss_factor,
|
146 |
+
router_z_loss_factor=router_z_loss_factor,
|
147 |
+
mlp_gated=mlp_gated,
|
148 |
+
label_smoothing=label_smoothing,
|
149 |
+
z_loss_factor=z_loss_factor,
|
150 |
+
enable_load_balance=enable_load_balance,
|
151 |
+
load_balance_tolerance=load_balance_tolerance,
|
152 |
+
load_balance_beam_width=load_balance_beam_width,
|
153 |
+
load_balance_group_swap_factor=load_balance_group_swap_factor,
|
154 |
+
enable_kernel=enable_kernel,
|
155 |
+
enable_comm_overlap=enable_comm_overlap,
|
156 |
+
enable_hierarchical_alltoall=enable_hierarchical_alltoall,
|
157 |
+
)
|
158 |
+
set_moe_args(config, moe_args)
|
159 |
+
|
160 |
+
|
161 |
+
# Copied from transformers.models.bart.modeling_bart._make_causal_mask
|
162 |
+
def _make_causal_mask(
|
163 |
+
input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
|
164 |
+
):
|
165 |
+
"""
|
166 |
+
Make causal mask used for bi-directional self-attention.
|
167 |
+
"""
|
168 |
+
bsz, tgt_len = input_ids_shape
|
169 |
+
mask = torch.full((tgt_len, tgt_len), torch.finfo(dtype).min, device=device)
|
170 |
+
mask_cond = torch.arange(mask.size(-1), device=device)
|
171 |
+
mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
|
172 |
+
mask = mask.to(dtype)
|
173 |
+
|
174 |
+
if past_key_values_length > 0:
|
175 |
+
mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
|
176 |
+
return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
|
177 |
+
|
178 |
+
|
179 |
+
# Copied from transformers.models.bart.modeling_bart._expand_mask
|
180 |
+
def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
|
181 |
+
"""
|
182 |
+
Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
|
183 |
+
"""
|
184 |
+
bsz, src_len = mask.size()
|
185 |
+
tgt_len = tgt_len if tgt_len is not None else src_len
|
186 |
+
|
187 |
+
expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
|
188 |
+
|
189 |
+
inverted_mask = 1.0 - expanded_mask
|
190 |
+
|
191 |
+
return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
|
192 |
+
|
193 |
+
|
194 |
+
def rotate_half(x):
|
195 |
+
"""Rotates half the hidden dims of the input."""
|
196 |
+
x1 = x[..., : x.shape[-1] // 2]
|
197 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
198 |
+
return torch.cat((-x2, x1), dim=-1)
|
199 |
+
|
200 |
+
|
201 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
|
202 |
+
"""Applies Rotary Position Embedding to the query and key tensors.
|
203 |
+
|
204 |
+
Args:
|
205 |
+
q (`torch.Tensor`): The query tensor.
|
206 |
+
k (`torch.Tensor`): The key tensor.
|
207 |
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
208 |
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
209 |
+
position_ids (`torch.Tensor`):
|
210 |
+
The position indices of the tokens corresponding to the query and key tensors. For example, this can be
|
211 |
+
used to pass offsetted position ids when working with a KV-cache.
|
212 |
+
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
213 |
+
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
214 |
+
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
215 |
+
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
216 |
+
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
217 |
+
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
218 |
+
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
219 |
+
Returns:
|
220 |
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
221 |
+
"""
|
222 |
+
cos = cos[position_ids].unsqueeze(unsqueeze_dim)
|
223 |
+
sin = sin[position_ids].unsqueeze(unsqueeze_dim)
|
224 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
225 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
226 |
+
return q_embed, k_embed
|
227 |
+
|
228 |
+
def SwiGLU(x):
|
229 |
+
"""Gated linear unit activation function.
|
230 |
+
Args:
|
231 |
+
x : input array
|
232 |
+
axis: the axis along which the split should be computed (default: -1)
|
233 |
+
"""
|
234 |
+
size = x.shape[-1]
|
235 |
+
assert size % 2 == 0, "axis size must be divisible by 2"
|
236 |
+
x1, x2 = torch.split(x, size // 2, -1)
|
237 |
+
return x1 * (x2 * torch.sigmoid(x2))
|
238 |
+
|
239 |
+
|
240 |
+
class OpenMoeMLP(nn.Module):
|
241 |
+
def __init__(self, config: LlamaConfig):
|
242 |
+
super().__init__()
|
243 |
+
self.pretraining_tp = config.pretraining_tp
|
244 |
+
self.hidden_size = config.hidden_size
|
245 |
+
self.intermediate_size = config.intermediate_size
|
246 |
+
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size * 2, bias=False)
|
247 |
+
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
248 |
+
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
|
249 |
+
self.hidden_act = config.hidden_act
|
250 |
+
self.act_fn = get_activation(self.hidden_act)
|
251 |
+
self.use_kernel = config.enable_kernel
|
252 |
+
|
253 |
+
def forward(self, x):
|
254 |
+
if self.pretraining_tp > 1:
|
255 |
+
slice = self.intermediate_size // self.pretraining_tp
|
256 |
+
gate_proj_slices = self.gate_proj.weight.split(slice, dim=0)
|
257 |
+
up_proj_slices = self.up_proj.weight.split(slice, dim=0)
|
258 |
+
down_proj_slices = self.down_proj.weight.split(slice, dim=1)
|
259 |
+
|
260 |
+
gate_proj = torch.cat([F.linear(x, gate_proj_slices[i]) for i in range(self.pretraining_tp)], dim=-1)
|
261 |
+
up_proj = torch.cat([F.linear(x, up_proj_slices[i]) for i in range(self.pretraining_tp)], dim=-1)
|
262 |
+
|
263 |
+
intermediate_states = (self.act_fn(gate_proj) * up_proj).split(slice, dim=2)
|
264 |
+
down_proj = [F.linear(intermediate_states[i], down_proj_slices[i]) for i in range(self.pretraining_tp)]
|
265 |
+
down_proj = sum(down_proj)
|
266 |
+
else:
|
267 |
+
if HAS_TRITON and self.use_kernel and self.hidden_act == "swiglu":
|
268 |
+
down_proj = self.down_proj(LlamaActCombine.apply(self.gate_proj(x), self.up_proj(x)))
|
269 |
+
else:
|
270 |
+
down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
271 |
+
|
272 |
+
return down_proj
|
273 |
+
|
274 |
+
|
275 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
276 |
+
"""
|
277 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
278 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
279 |
+
"""
|
280 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
281 |
+
if n_rep == 1:
|
282 |
+
return hidden_states
|
283 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
284 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
285 |
+
|
286 |
+
|
287 |
+
class OpenMoeAttention(nn.Module):
|
288 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
289 |
+
|
290 |
+
def __init__(self, config: LlamaConfig):
|
291 |
+
super().__init__()
|
292 |
+
self.config = config
|
293 |
+
self.hidden_size = config.hidden_size
|
294 |
+
self.num_heads = config.num_attention_heads
|
295 |
+
self.head_dim = config.head_dim
|
296 |
+
self.num_key_value_heads = config.num_key_value_heads
|
297 |
+
self.num_key_value_groups = self.num_heads // self.num_key_value_heads
|
298 |
+
self.pretraining_tp = config.pretraining_tp
|
299 |
+
self.max_position_embeddings = config.max_position_embeddings
|
300 |
+
self.rope_theta = config.rope_theta
|
301 |
+
|
302 |
+
self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
|
303 |
+
self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
|
304 |
+
self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
|
305 |
+
self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
|
306 |
+
self._init_rope()
|
307 |
+
|
308 |
+
def _init_rope(self):
|
309 |
+
if self.config.rope_scaling is None:
|
310 |
+
self.rotary_emb = LlamaRotaryEmbedding(
|
311 |
+
self.head_dim,
|
312 |
+
max_position_embeddings=self.max_position_embeddings,
|
313 |
+
base=self.rope_theta,
|
314 |
+
)
|
315 |
+
else:
|
316 |
+
raise ValueError(f"Only Original RotaryEmbedding is supported yet")
|
317 |
+
|
318 |
+
def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
|
319 |
+
return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
|
320 |
+
|
321 |
+
def forward(
|
322 |
+
self,
|
323 |
+
hidden_states: torch.Tensor,
|
324 |
+
attention_mask: Optional[torch.Tensor] = None,
|
325 |
+
position_ids: Optional[torch.LongTensor] = None,
|
326 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
327 |
+
output_attentions: bool = False,
|
328 |
+
use_cache: bool = False,
|
329 |
+
use_kernel: bool = True,
|
330 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
331 |
+
bsz, q_len, _ = hidden_states.size()
|
332 |
+
|
333 |
+
if self.pretraining_tp > 1:
|
334 |
+
key_value_slicing = (self.num_key_value_heads * self.head_dim) // self.pretraining_tp
|
335 |
+
query_slices = self.q_proj.weight.split((self.num_heads * self.head_dim) // self.pretraining_tp, dim=0)
|
336 |
+
key_slices = self.k_proj.weight.split(key_value_slicing, dim=0)
|
337 |
+
value_slices = self.v_proj.weight.split(key_value_slicing, dim=0)
|
338 |
+
|
339 |
+
query_states = [F.linear(hidden_states, query_slices[i]) for i in range(self.pretraining_tp)]
|
340 |
+
query_states = torch.cat(query_states, dim=-1)
|
341 |
+
|
342 |
+
key_states = [F.linear(hidden_states, key_slices[i]) for i in range(self.pretraining_tp)]
|
343 |
+
key_states = torch.cat(key_states, dim=-1)
|
344 |
+
|
345 |
+
value_states = [F.linear(hidden_states, value_slices[i]) for i in range(self.pretraining_tp)]
|
346 |
+
value_states = torch.cat(value_states, dim=-1)
|
347 |
+
|
348 |
+
else:
|
349 |
+
query_states = self.q_proj(hidden_states)
|
350 |
+
key_states = self.k_proj(hidden_states)
|
351 |
+
value_states = self.v_proj(hidden_states)
|
352 |
+
|
353 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2) # (bsz, num_heads, q_len, head_dim)
|
354 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2) # (bsz, num_heads, q_len, head_dim)
|
355 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2) # (bsz, num_heads, q_len, head_dim)
|
356 |
+
|
357 |
+
kv_seq_len = key_states.shape[-2]
|
358 |
+
if past_key_value is not None:
|
359 |
+
kv_seq_len += past_key_value[0].shape[-2]
|
360 |
+
# reuse k, v, self_attention
|
361 |
+
key_states = torch.cat([past_key_value[0], key_states], dim=2) # (bsz, num_heads, q_len+past_kv_len, head_dim)
|
362 |
+
value_states = torch.cat([past_key_value[1], value_states], dim=2) # (bsz, num_heads, q_len+past_kv_len, head_dim)
|
363 |
+
|
364 |
+
past_key_value = (key_states, value_states) if use_cache else None
|
365 |
+
|
366 |
+
cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
|
367 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
|
368 |
+
|
369 |
+
# repeat k/v heads if n_kv_heads < n_heads
|
370 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
371 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
372 |
+
|
373 |
+
if HAS_FLASH_ATTN and use_kernel:
|
374 |
+
from flash_attn import flash_attn_func
|
375 |
+
|
376 |
+
query_states = query_states.transpose(1, 2)
|
377 |
+
key_states = key_states.transpose(1, 2)
|
378 |
+
value_states = value_states.transpose(1, 2)
|
379 |
+
attn_output = flash_attn_func(query_states, key_states, value_states, softmax_scale=1.0, causal=True)
|
380 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
381 |
+
else:
|
382 |
+
attn_weights = torch.matmul(query_states, key_states.transpose(2, 3))
|
383 |
+
|
384 |
+
if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
|
385 |
+
raise ValueError(
|
386 |
+
f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
|
387 |
+
f" {attn_weights.size()}"
|
388 |
+
)
|
389 |
+
|
390 |
+
if attention_mask is not None:
|
391 |
+
if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
|
392 |
+
raise ValueError(
|
393 |
+
f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
|
394 |
+
)
|
395 |
+
if self.training:
|
396 |
+
attention_mask = attention_mask.clone().detach()
|
397 |
+
attention_mask[:, :, :, 0] = 0
|
398 |
+
attn_weights = attn_weights + attention_mask
|
399 |
+
|
400 |
+
# upcast attention to fp32
|
401 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
|
402 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
403 |
+
|
404 |
+
if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
|
405 |
+
raise ValueError(
|
406 |
+
f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
|
407 |
+
f" {attn_output.size()}"
|
408 |
+
)
|
409 |
+
|
410 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
411 |
+
attn_output = attn_output.reshape(bsz, q_len, self.num_heads * self.head_dim)
|
412 |
+
|
413 |
+
if self.pretraining_tp > 1:
|
414 |
+
attn_output = attn_output.split(self.hidden_size // self.pretraining_tp, dim=2)
|
415 |
+
o_proj_slices = self.o_proj.weight.split(self.hidden_size // self.pretraining_tp, dim=1)
|
416 |
+
attn_output = sum([F.linear(attn_output[i], o_proj_slices[i]) for i in range(self.pretraining_tp)])
|
417 |
+
else:
|
418 |
+
attn_output = self.o_proj(attn_output)
|
419 |
+
|
420 |
+
if not output_attentions:
|
421 |
+
attn_weights = None
|
422 |
+
|
423 |
+
return attn_output, attn_weights, past_key_value
|
424 |
+
|
425 |
+
|
426 |
+
class OpenMoeDecoderLayer(nn.Module):
|
427 |
+
def __init__(self, config: LlamaConfig, moe: bool):
|
428 |
+
super().__init__()
|
429 |
+
self.hidden_size = config.hidden_size
|
430 |
+
self.moe = moe
|
431 |
+
self.self_attn = OpenMoeAttention(config=config)
|
432 |
+
self.input_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
433 |
+
self.post_attention_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
434 |
+
if self.moe:
|
435 |
+
self.mlp = SparseMLP(
|
436 |
+
num_experts=config.num_experts,
|
437 |
+
hidden_size=config.hidden_size,
|
438 |
+
intermediate_size=config.intermediate_size,
|
439 |
+
router_top_k=config.router_topk,
|
440 |
+
router_capacity_factor_train=config.router_capacity_factor_train,
|
441 |
+
router_capacity_factor_eval=config.router_capacity_factor_eval,
|
442 |
+
router_min_capacity=config.router_min_capacity,
|
443 |
+
router_noisy_policy=config.router_noisy_policy,
|
444 |
+
router_drop_tks=config.router_drop_tks,
|
445 |
+
mlp_activation=config.hidden_act,
|
446 |
+
mlp_gated=config.mlp_gated,
|
447 |
+
enable_load_balance=config.enable_load_balance,
|
448 |
+
load_balance_tolerance=config.load_balance_tolerance,
|
449 |
+
load_balance_beam_width=config.load_balance_beam_width,
|
450 |
+
load_balance_group_swap_factor=config.load_balance_group_swap_factor,
|
451 |
+
enable_kernel=config.enable_kernel,
|
452 |
+
enable_comm_overlap=config.enable_comm_overlap,
|
453 |
+
)
|
454 |
+
self.pre_extra_mlp_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
455 |
+
self.extra_mlp = OpenMoeMLP(config)
|
456 |
+
else:
|
457 |
+
self.mlp = OpenMoeMLP(config)
|
458 |
+
|
459 |
+
def forward(
|
460 |
+
self,
|
461 |
+
hidden_states: torch.Tensor,
|
462 |
+
attention_mask: Optional[torch.Tensor] = None,
|
463 |
+
position_ids: Optional[torch.LongTensor] = None,
|
464 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
465 |
+
output_attentions: Optional[bool] = False,
|
466 |
+
use_cache: Optional[bool] = False,
|
467 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
468 |
+
"""
|
469 |
+
Args:
|
470 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
471 |
+
attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
|
472 |
+
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
|
473 |
+
output_attentions (`bool`, *optional*):
|
474 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
475 |
+
returned tensors for more detail.
|
476 |
+
use_cache (`bool`, *optional*):
|
477 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
|
478 |
+
(see `past_key_values`).
|
479 |
+
past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
|
480 |
+
"""
|
481 |
+
|
482 |
+
residual = hidden_states
|
483 |
+
|
484 |
+
hidden_states = self.input_layernorm(hidden_states)
|
485 |
+
|
486 |
+
# Self Attention
|
487 |
+
hidden_states, self_attn_weights, present_key_value = self.self_attn(
|
488 |
+
hidden_states=hidden_states,
|
489 |
+
attention_mask=attention_mask,
|
490 |
+
position_ids=position_ids,
|
491 |
+
past_key_value=past_key_value,
|
492 |
+
output_attentions=output_attentions,
|
493 |
+
use_cache=use_cache,
|
494 |
+
)
|
495 |
+
hidden_states = residual + hidden_states
|
496 |
+
|
497 |
+
# Fully Connected
|
498 |
+
residual = hidden_states
|
499 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
500 |
+
hidden_states = self.mlp(hidden_states)
|
501 |
+
hidden_states = residual + hidden_states
|
502 |
+
|
503 |
+
if self.moe:
|
504 |
+
residual = hidden_states
|
505 |
+
hidden_states = self.pre_extra_mlp_layernorm(hidden_states)
|
506 |
+
hidden_states = self.extra_mlp(hidden_states)
|
507 |
+
hidden_states = residual + hidden_states
|
508 |
+
|
509 |
+
outputs = (hidden_states,)
|
510 |
+
|
511 |
+
if output_attentions:
|
512 |
+
outputs += (self_attn_weights,)
|
513 |
+
|
514 |
+
if use_cache:
|
515 |
+
outputs += (present_key_value,)
|
516 |
+
|
517 |
+
return outputs
|
518 |
+
|
519 |
+
|
520 |
+
LLAMA_START_DOCSTRING = r"""
|
521 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
522 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
523 |
+
etc.)
|
524 |
+
|
525 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
526 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
527 |
+
and behavior.
|
528 |
+
|
529 |
+
Parameters:
|
530 |
+
config ([`LlamaConfig`]):
|
531 |
+
Model configuration class with all the parameters of the model. Initializing with a config file does not
|
532 |
+
load the weights associated with the model, only the configuration. Check out the
|
533 |
+
[`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
534 |
+
"""
|
535 |
+
|
536 |
+
|
537 |
+
@add_start_docstrings(
|
538 |
+
"The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
|
539 |
+
LLAMA_START_DOCSTRING,
|
540 |
+
)
|
541 |
+
class OpenMoePreTrainedModel(PreTrainedModel):
|
542 |
+
config_class = LlamaConfig
|
543 |
+
base_model_prefix = "model"
|
544 |
+
supports_gradient_checkpointing = True
|
545 |
+
_no_split_modules = ["LlamaDecoderLayer"]
|
546 |
+
_skip_keys_device_placement = "past_key_values"
|
547 |
+
|
548 |
+
def _init_weights(self, module):
|
549 |
+
std = self.config.initializer_range
|
550 |
+
if isinstance(module, nn.Linear):
|
551 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
552 |
+
if module.bias is not None:
|
553 |
+
module.bias.data.zero_()
|
554 |
+
elif isinstance(module, nn.Embedding):
|
555 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
556 |
+
if module.padding_idx is not None:
|
557 |
+
module.weight.data[module.padding_idx].zero_()
|
558 |
+
|
559 |
+
def _set_gradient_checkpointing(self, module, value=False):
|
560 |
+
if isinstance(module, OpenMoeModel):
|
561 |
+
module.gradient_checkpointing = value
|
562 |
+
|
563 |
+
|
564 |
+
LLAMA_INPUTS_DOCSTRING = r"""
|
565 |
+
Args:
|
566 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
567 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
568 |
+
it.
|
569 |
+
|
570 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
571 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
572 |
+
|
573 |
+
[What are input IDs?](../glossary#input-ids)
|
574 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
575 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
576 |
+
|
577 |
+
- 1 for tokens that are **not masked**,
|
578 |
+
- 0 for tokens that are **masked**.
|
579 |
+
|
580 |
+
[What are attention masks?](../glossary#attention-mask)
|
581 |
+
|
582 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
583 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
584 |
+
|
585 |
+
If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
|
586 |
+
`past_key_values`).
|
587 |
+
|
588 |
+
If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
|
589 |
+
and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
|
590 |
+
information on the default strategy.
|
591 |
+
|
592 |
+
- 1 indicates the head is **not masked**,
|
593 |
+
- 0 indicates the head is **masked**.
|
594 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
595 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
596 |
+
config.n_positions - 1]`.
|
597 |
+
|
598 |
+
[What are position IDs?](../glossary#position-ids)
|
599 |
+
past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
|
600 |
+
Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
|
601 |
+
`(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
|
602 |
+
`(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
|
603 |
+
|
604 |
+
Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
|
605 |
+
blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
|
606 |
+
|
607 |
+
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
|
608 |
+
don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
|
609 |
+
`decoder_input_ids` of shape `(batch_size, sequence_length)`.
|
610 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
611 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
612 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
613 |
+
model's internal embedding lookup matrix.
|
614 |
+
use_cache (`bool`, *optional*):
|
615 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
616 |
+
`past_key_values`).
|
617 |
+
output_attentions (`bool`, *optional*):
|
618 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
619 |
+
tensors for more detail.
|
620 |
+
output_hidden_states (`bool`, *optional*):
|
621 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
622 |
+
more detail.
|
623 |
+
return_dict (`bool`, *optional*):
|
624 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
625 |
+
"""
|
626 |
+
|
627 |
+
|
628 |
+
@add_start_docstrings(
|
629 |
+
"The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
|
630 |
+
LLAMA_START_DOCSTRING,
|
631 |
+
)
|
632 |
+
class OpenMoeModel(OpenMoePreTrainedModel):
|
633 |
+
"""
|
634 |
+
Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`LlamaDecoderLayer`]
|
635 |
+
|
636 |
+
Args:
|
637 |
+
config: LlamaConfig
|
638 |
+
"""
|
639 |
+
|
640 |
+
def __init__(self, config: LlamaConfig):
|
641 |
+
super().__init__(config)
|
642 |
+
self.padding_idx = config.pad_token_id
|
643 |
+
self.vocab_size = config.vocab_size
|
644 |
+
|
645 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
646 |
+
self.layers = nn.ModuleList(
|
647 |
+
[
|
648 |
+
OpenMoeDecoderLayer(config, moe=True if (i + 1) % config.moe_layer_interval == 0 else False)
|
649 |
+
for i in range(config.num_hidden_layers)
|
650 |
+
]
|
651 |
+
)
|
652 |
+
self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
653 |
+
|
654 |
+
self.gradient_checkpointing = False
|
655 |
+
# Initialize weights and apply final processing
|
656 |
+
self.post_init()
|
657 |
+
|
658 |
+
def get_input_embeddings(self):
|
659 |
+
return self.embed_tokens
|
660 |
+
|
661 |
+
def set_input_embeddings(self, value):
|
662 |
+
self.embed_tokens = value
|
663 |
+
|
664 |
+
# Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask
|
665 |
+
def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
|
666 |
+
# create causal mask
|
667 |
+
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
668 |
+
combined_attention_mask = None
|
669 |
+
if input_shape[-1] > 1:
|
670 |
+
combined_attention_mask = _make_causal_mask(
|
671 |
+
input_shape,
|
672 |
+
inputs_embeds.dtype,
|
673 |
+
device=inputs_embeds.device,
|
674 |
+
past_key_values_length=past_key_values_length,
|
675 |
+
)
|
676 |
+
|
677 |
+
if attention_mask is not None:
|
678 |
+
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
679 |
+
expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(
|
680 |
+
inputs_embeds.device
|
681 |
+
)
|
682 |
+
combined_attention_mask = (
|
683 |
+
expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
|
684 |
+
)
|
685 |
+
|
686 |
+
return combined_attention_mask
|
687 |
+
|
688 |
+
@add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
|
689 |
+
def forward(
|
690 |
+
self,
|
691 |
+
input_ids: torch.LongTensor = None,
|
692 |
+
attention_mask: Optional[torch.Tensor] = None,
|
693 |
+
position_ids: Optional[torch.LongTensor] = None,
|
694 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
695 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
696 |
+
use_cache: Optional[bool] = None,
|
697 |
+
output_attentions: Optional[bool] = None,
|
698 |
+
output_hidden_states: Optional[bool] = None,
|
699 |
+
return_dict: Optional[bool] = None,
|
700 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
701 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
702 |
+
output_hidden_states = (
|
703 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
704 |
+
)
|
705 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
706 |
+
|
707 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
708 |
+
|
709 |
+
# retrieve input_ids and inputs_embeds
|
710 |
+
if input_ids is not None and inputs_embeds is not None:
|
711 |
+
raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
|
712 |
+
elif input_ids is not None:
|
713 |
+
batch_size, seq_length = input_ids.shape
|
714 |
+
elif inputs_embeds is not None:
|
715 |
+
batch_size, seq_length, _ = inputs_embeds.shape
|
716 |
+
else:
|
717 |
+
raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
|
718 |
+
|
719 |
+
seq_length_with_past = seq_length
|
720 |
+
past_key_values_length = 0
|
721 |
+
|
722 |
+
if past_key_values is not None:
|
723 |
+
past_key_values_length = past_key_values[0][0].shape[2]
|
724 |
+
seq_length_with_past = seq_length_with_past + past_key_values_length
|
725 |
+
|
726 |
+
if position_ids is None:
|
727 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
728 |
+
position_ids = torch.arange(
|
729 |
+
past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
|
730 |
+
)
|
731 |
+
position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
|
732 |
+
else:
|
733 |
+
position_ids = position_ids.view(-1, seq_length).long()
|
734 |
+
|
735 |
+
if inputs_embeds is None:
|
736 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
737 |
+
# embed positions
|
738 |
+
if attention_mask is None:
|
739 |
+
attention_mask = torch.ones(
|
740 |
+
(batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device
|
741 |
+
)
|
742 |
+
attention_mask = self._prepare_decoder_attention_mask(
|
743 |
+
attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
|
744 |
+
)
|
745 |
+
|
746 |
+
hidden_states = inputs_embeds
|
747 |
+
|
748 |
+
if self.gradient_checkpointing and self.training:
|
749 |
+
if use_cache:
|
750 |
+
logger.warning_once(
|
751 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
752 |
+
)
|
753 |
+
use_cache = False
|
754 |
+
|
755 |
+
# decoder layers
|
756 |
+
all_hidden_states = () if output_hidden_states else None
|
757 |
+
all_self_attns = () if output_attentions else None
|
758 |
+
next_decoder_cache = () if use_cache else None
|
759 |
+
|
760 |
+
for idx, decoder_layer in enumerate(self.layers):
|
761 |
+
if output_hidden_states:
|
762 |
+
all_hidden_states += (hidden_states,)
|
763 |
+
|
764 |
+
past_key_value = past_key_values[idx] if past_key_values is not None else None
|
765 |
+
|
766 |
+
if self.gradient_checkpointing and self.training:
|
767 |
+
|
768 |
+
def create_custom_forward(module):
|
769 |
+
def custom_forward(*inputs):
|
770 |
+
# None for past_key_value
|
771 |
+
return module(*inputs, output_attentions, None)
|
772 |
+
|
773 |
+
return custom_forward
|
774 |
+
|
775 |
+
layer_outputs = torch.utils.checkpoint.checkpoint(
|
776 |
+
create_custom_forward(decoder_layer),
|
777 |
+
hidden_states,
|
778 |
+
attention_mask,
|
779 |
+
position_ids,
|
780 |
+
None,
|
781 |
+
)
|
782 |
+
else:
|
783 |
+
layer_outputs = decoder_layer(
|
784 |
+
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 |
+
)
|
791 |
+
|
792 |
+
hidden_states = layer_outputs[0]
|
793 |
+
|
794 |
+
if use_cache:
|
795 |
+
next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
|
796 |
+
|
797 |
+
if output_attentions:
|
798 |
+
all_self_attns += (layer_outputs[1],)
|
799 |
+
|
800 |
+
hidden_states = self.norm(hidden_states)
|
801 |
+
|
802 |
+
# add hidden states from the last decoder layer
|
803 |
+
if output_hidden_states:
|
804 |
+
all_hidden_states += (hidden_states,)
|
805 |
+
|
806 |
+
next_cache = next_decoder_cache if use_cache else None
|
807 |
+
if not return_dict:
|
808 |
+
return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
|
809 |
+
return BaseModelOutputWithPast(
|
810 |
+
last_hidden_state=hidden_states,
|
811 |
+
past_key_values=next_cache,
|
812 |
+
hidden_states=all_hidden_states,
|
813 |
+
attentions=all_self_attns,
|
814 |
+
)
|
815 |
+
|
816 |
+
|
817 |
+
class OpenMoeForCausalLM(OpenMoePreTrainedModel):
|
818 |
+
# _tied_weights_keys = ["lm_head.weight"]
|
819 |
+
|
820 |
+
def __init__(self, config):
|
821 |
+
super().__init__(config)
|
822 |
+
self.model = OpenMoeModel(config)
|
823 |
+
self.pretraining_tp = config.pretraining_tp
|
824 |
+
self.vocab_size = config.vocab_size
|
825 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
826 |
+
|
827 |
+
# Initialize weights and apply final processing
|
828 |
+
self.post_init()
|
829 |
+
|
830 |
+
def get_input_embeddings(self):
|
831 |
+
return self.model.embed_tokens
|
832 |
+
|
833 |
+
def set_input_embeddings(self, value):
|
834 |
+
self.model.embed_tokens = value
|
835 |
+
|
836 |
+
def get_output_embeddings(self):
|
837 |
+
return self.lm_head
|
838 |
+
|
839 |
+
def set_output_embeddings(self, new_embeddings):
|
840 |
+
self.lm_head = new_embeddings
|
841 |
+
|
842 |
+
def set_decoder(self, decoder):
|
843 |
+
self.model = decoder
|
844 |
+
|
845 |
+
def get_decoder(self):
|
846 |
+
return self.model
|
847 |
+
|
848 |
+
@add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
|
849 |
+
@replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
|
850 |
+
def forward(
|
851 |
+
self,
|
852 |
+
input_ids: torch.LongTensor = None,
|
853 |
+
attention_mask: Optional[torch.Tensor] = None,
|
854 |
+
position_ids: Optional[torch.LongTensor] = None,
|
855 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
856 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
857 |
+
labels: Optional[torch.LongTensor] = None,
|
858 |
+
use_cache: Optional[bool] = None,
|
859 |
+
output_attentions: Optional[bool] = None,
|
860 |
+
output_hidden_states: Optional[bool] = None,
|
861 |
+
return_dict: Optional[bool] = None,
|
862 |
+
chunk_head: Optional[bool] = True,
|
863 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
864 |
+
r"""
|
865 |
+
Args:
|
866 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
867 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
868 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
869 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
870 |
+
|
871 |
+
Returns:
|
872 |
+
|
873 |
+
Example:
|
874 |
+
|
875 |
+
```python
|
876 |
+
>>> from transformers import AutoTokenizer, LlamaForCausalLM
|
877 |
+
|
878 |
+
>>> model = LlamaForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
|
879 |
+
>>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
|
880 |
+
|
881 |
+
>>> prompt = "Hey, are you conscious? Can you talk to me?"
|
882 |
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
883 |
+
|
884 |
+
>>> # Generate
|
885 |
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
886 |
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
887 |
+
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
|
888 |
+
```"""
|
889 |
+
# reset moe loss
|
890 |
+
MOE_MANAGER.reset_loss()
|
891 |
+
|
892 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
893 |
+
output_hidden_states = (
|
894 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
895 |
+
)
|
896 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
897 |
+
|
898 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
899 |
+
outputs = self.model(
|
900 |
+
input_ids=input_ids,
|
901 |
+
attention_mask=attention_mask,
|
902 |
+
position_ids=position_ids,
|
903 |
+
past_key_values=past_key_values,
|
904 |
+
inputs_embeds=inputs_embeds,
|
905 |
+
use_cache=use_cache,
|
906 |
+
output_attentions=output_attentions,
|
907 |
+
output_hidden_states=output_hidden_states,
|
908 |
+
return_dict=return_dict,
|
909 |
+
)
|
910 |
+
|
911 |
+
hidden_states = outputs[0]
|
912 |
+
if self.pretraining_tp > 1:
|
913 |
+
lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.pretraining_tp, dim=0)
|
914 |
+
logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.pretraining_tp)]
|
915 |
+
logits = torch.cat(logits, dim=-1)
|
916 |
+
|
917 |
+
loss = None
|
918 |
+
# if no training, just do forward
|
919 |
+
if labels is None:
|
920 |
+
logits = self.lm_head(hidden_states)
|
921 |
+
logits = logits.float()
|
922 |
+
# the vocab size for openmoe is 30w+
|
923 |
+
# which causes great activation memory in training, up to 20G for one sequence
|
924 |
+
# so we use chunk and checkpoint to reduce memory
|
925 |
+
else:
|
926 |
+
if chunk_head == True:
|
927 |
+
|
928 |
+
def create_custom_forward(module):
|
929 |
+
def custom_forward(*inputs):
|
930 |
+
logits = module(inputs[0])
|
931 |
+
logits = logits.float()
|
932 |
+
# Shift so that tokens < n predict n
|
933 |
+
shift_logits = logits[..., :-1, :].contiguous().float()
|
934 |
+
shift_labels = inputs[1][..., 1:].contiguous()
|
935 |
+
# Flatten the tokens
|
936 |
+
loss = self._calculate_loss(shift_logits, shift_labels)
|
937 |
+
return loss
|
938 |
+
|
939 |
+
return custom_forward
|
940 |
+
|
941 |
+
aux_loss, z_loss = self._calculate_router_loss()
|
942 |
+
loss = aux_loss + z_loss
|
943 |
+
for batch_idx in range(hidden_states.shape[0]):
|
944 |
+
loss = loss + torch.utils.checkpoint.checkpoint(
|
945 |
+
create_custom_forward(self.lm_head),
|
946 |
+
hidden_states[batch_idx : batch_idx + 1, :],
|
947 |
+
labels[batch_idx : batch_idx + 1, :],
|
948 |
+
)
|
949 |
+
logits = None
|
950 |
+
else:
|
951 |
+
logits = self.lm_head(hidden_states)
|
952 |
+
logits = logits.float()
|
953 |
+
# Shift so that tokens < n predict n
|
954 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
955 |
+
shift_labels = labels[..., 1:].contiguous()
|
956 |
+
# Flatten the tokens
|
957 |
+
aux_loss, z_loss = self._calculate_router_loss()
|
958 |
+
loss = aux_loss + z_loss
|
959 |
+
loss = loss + self._calculate_loss(shift_logits, shift_labels)
|
960 |
+
|
961 |
+
if not return_dict:
|
962 |
+
output = (logits,) + outputs[1:]
|
963 |
+
return (loss,) + output if loss is not None else output
|
964 |
+
|
965 |
+
return CausalLMOutputWithPast(
|
966 |
+
loss=loss,
|
967 |
+
logits=logits,
|
968 |
+
past_key_values=outputs.past_key_values,
|
969 |
+
hidden_states=outputs.hidden_states,
|
970 |
+
attentions=outputs.attentions,
|
971 |
+
)
|
972 |
+
|
973 |
+
def prepare_inputs_for_generation(
|
974 |
+
self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
|
975 |
+
):
|
976 |
+
if past_key_values:
|
977 |
+
input_ids = input_ids[:, -1:]
|
978 |
+
|
979 |
+
position_ids = kwargs.get("position_ids", None)
|
980 |
+
if attention_mask is not None and position_ids is None:
|
981 |
+
# create position_ids on the fly for batch generation
|
982 |
+
position_ids = attention_mask.long().cumsum(-1) - 1
|
983 |
+
position_ids.masked_fill_(attention_mask == 0, 1)
|
984 |
+
if past_key_values:
|
985 |
+
position_ids = position_ids[:, -1].unsqueeze(-1)
|
986 |
+
|
987 |
+
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step
|
988 |
+
if inputs_embeds is not None and past_key_values is None:
|
989 |
+
model_inputs = {"inputs_embeds": inputs_embeds}
|
990 |
+
else:
|
991 |
+
model_inputs = {"input_ids": input_ids}
|
992 |
+
|
993 |
+
model_inputs.update(
|
994 |
+
{
|
995 |
+
"position_ids": position_ids,
|
996 |
+
"past_key_values": past_key_values,
|
997 |
+
"use_cache": kwargs.get("use_cache"),
|
998 |
+
"attention_mask": attention_mask,
|
999 |
+
}
|
1000 |
+
)
|
1001 |
+
return model_inputs
|
1002 |
+
|
1003 |
+
@staticmethod
|
1004 |
+
def _reorder_cache(past_key_values, beam_idx):
|
1005 |
+
reordered_past = ()
|
1006 |
+
for layer_past in past_key_values:
|
1007 |
+
reordered_past += (
|
1008 |
+
tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
|
1009 |
+
)
|
1010 |
+
return reordered_past
|
1011 |
+
|
1012 |
+
def _calculate_router_loss(self, aux_loss: list = None, z_loss: list = None):
|
1013 |
+
if aux_loss is None or z_loss is None:
|
1014 |
+
aux_loss, z_loss = MOE_MANAGER.get_loss()
|
1015 |
+
assert len(aux_loss) == len(z_loss) == self.config.num_hidden_layers // self.config.moe_layer_interval
|
1016 |
+
aux_loss = self.config.router_aux_loss_factor * sum(aux_loss) / len(aux_loss)
|
1017 |
+
z_loss = self.config.router_z_loss_factor * sum(z_loss) / len(z_loss)
|
1018 |
+
return aux_loss, z_loss
|
1019 |
+
|
1020 |
+
def _calculate_loss(self, logits: torch.Tensor, targets: torch.Tensor) -> torch.Tensor:
|
1021 |
+
"""Compute cross entropy and entropy for log probs and targets.
|
1022 |
+
|
1023 |
+
Args:
|
1024 |
+
logits: [batch, length, num_classes] float array.
|
1025 |
+
targets: categorical targets [batch, length] int array.
|
1026 |
+
|
1027 |
+
Returns:
|
1028 |
+
Tuple of scalar loss.
|
1029 |
+
"""
|
1030 |
+
if len(logits.shape) != len(targets.shape) + 1:
|
1031 |
+
raise ValueError(
|
1032 |
+
"Incorrect shapes. Got shape %s logits and %s targets" % (str(logits.shape), str(targets.shape))
|
1033 |
+
)
|
1034 |
+
vocab_size = logits.shape[-1]
|
1035 |
+
confidence = 1.0 - self.config.label_smoothing
|
1036 |
+
low_confidence = (1.0 - confidence) / (vocab_size - 1)
|
1037 |
+
normalizing_constant = -(
|
1038 |
+
confidence * math.log(confidence) + (vocab_size - 1) * low_confidence * math.log(low_confidence + 1e-20)
|
1039 |
+
)
|
1040 |
+
|
1041 |
+
# one hot
|
1042 |
+
soft_targets = targets[..., None] == torch.arange(vocab_size, device=targets.device).reshape(
|
1043 |
+
(1,) * len(targets.shape) + (-1,)
|
1044 |
+
)
|
1045 |
+
soft_targets = torch.where(
|
1046 |
+
soft_targets, torch.full_like(soft_targets, confidence), torch.full_like(soft_targets, low_confidence)
|
1047 |
+
)
|
1048 |
+
soft_targets = soft_targets.to(torch.float32)
|
1049 |
+
|
1050 |
+
# cross entropy
|
1051 |
+
total_loss = ZLossCrossEntropy.apply(logits, soft_targets, self.config.z_loss_factor)
|
1052 |
+
total_loss = total_loss - normalizing_constant
|
1053 |
+
total_loss = torch.mean(torch.sum(total_loss, dim=-1), dim=0)
|
1054 |
+
return total_loss
|
1055 |
+
|
1056 |
+
|
1057 |
+
class ZLossCrossEntropy(torch.autograd.Function):
|
1058 |
+
"""Computes cross entropy loss with stable custom gradient.
|
1059 |
+
|
1060 |
+
Computes a stabilized-gradient version of:
|
1061 |
+
-jnp.sum(targets * nn.log_softmax(logits), axis=-1)
|
1062 |
+
|
1063 |
+
If z_loss > 0, then an auxiliary loss equal to z_loss*log(z)^2
|
1064 |
+
will be added to the cross entropy loss (z = softmax normalization constant).
|
1065 |
+
The two uses of z_loss are:
|
1066 |
+
1. To keep the logits from drifting too far from zero, which can cause
|
1067 |
+
unacceptable roundoff errors in bfloat16.
|
1068 |
+
2. To encourage the logits to be normalized log-probabilities.
|
1069 |
+
|
1070 |
+
Args:
|
1071 |
+
logits: [batch, length, num_classes] float array.
|
1072 |
+
targets: categorical one-hot targets [batch, length, num_classes] float
|
1073 |
+
array.
|
1074 |
+
z_loss: coefficient for auxilliary z-loss loss term.
|
1075 |
+
|
1076 |
+
Returns:
|
1077 |
+
tuple with the total loss and the z_loss, both
|
1078 |
+
float arrays with shape [batch, length].
|
1079 |
+
"""
|
1080 |
+
|
1081 |
+
@staticmethod
|
1082 |
+
def forward(ctx, logits, targets, z_loss):
|
1083 |
+
max_logit = torch.max(logits, dim=-1, keepdim=True)[0]
|
1084 |
+
shifted = logits - max_logit
|
1085 |
+
exp_shifted = torch.exp(shifted)
|
1086 |
+
sum_exp = torch.sum(exp_shifted, axis=-1, keepdims=True)
|
1087 |
+
sum_exp_log = torch.log(sum_exp)
|
1088 |
+
log_softmax = shifted - sum_exp_log
|
1089 |
+
loss = -torch.sum(targets * log_softmax, axis=-1)
|
1090 |
+
# Add auxilliary z-loss term.
|
1091 |
+
log_z = torch.squeeze(sum_exp_log + max_logit, axis=-1)
|
1092 |
+
total_z_loss = z_loss * torch.square(log_z)
|
1093 |
+
loss += total_z_loss
|
1094 |
+
ctx.z_loss = z_loss
|
1095 |
+
ctx.save_for_backward(logits, targets, exp_shifted, sum_exp, log_softmax, log_z)
|
1096 |
+
return loss
|
1097 |
+
|
1098 |
+
@staticmethod
|
1099 |
+
def backward(ctx, *grad_outputs):
|
1100 |
+
assert len(grad_outputs) == 1
|
1101 |
+
g = grad_outputs[0]
|
1102 |
+
z_loss = ctx.z_loss
|
1103 |
+
logits, targets, exp_shifted, sum_exp, log_softmax, log_z = ctx.saved_tensors
|
1104 |
+
# z-loss term adds the (2 * z_loss * log_z) factor.
|
1105 |
+
deriv = (1 + 2 * z_loss * log_z).unsqueeze(-1) * exp_shifted / sum_exp - targets
|
1106 |
+
g_logits = g.unsqueeze(-1) * deriv
|
1107 |
+
g_targets = -g.unsqueeze(-1) * log_softmax
|
1108 |
+
|
1109 |
+
return (
|
1110 |
+
g_logits.to(logits.dtype),
|
1111 |
+
g_targets.to(targets.dtype),
|
1112 |
+
None,
|
1113 |
+
)
|