OrionZheng commited on
Commit
968fc4d
1 Parent(s): b8c2f09

Upload modeling_openmoe.py

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