OrionZheng commited on
Commit
0cd777f
1 Parent(s): 9c6b155

Delete .ipynb_checkpoints

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