-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
modeling.py
1544 lines (1313 loc) Β· 61.1 KB
/
modeling.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) 2023 PaddlePaddle Authors. All Rights Reserved.
# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Paddle Llama model"""
from __future__ import annotations
import math
import warnings
from functools import partial
from typing import Optional, Tuple
import paddle
import paddle.distributed.fleet.meta_parallel as mpu
import paddle.nn.functional as F
from paddle import Tensor, nn
from paddle.distributed import fleet
from paddle.distributed.fleet.utils import recompute
try:
from paddle.incubate.nn.functional import fused_rotary_position_embedding
except ImportError:
fused_rotary_position_embedding = None
from paddle.utils import try_import
from paddlenlp.transformers.conversion_utils import (
StateDictNameMapping,
init_name_mappings,
)
from paddlenlp.transformers.model_outputs import (
BaseModelOutputWithPastAndCrossAttentions,
CausalLMOutputWithCrossAttentions,
)
from paddlenlp.transformers.model_utils import PretrainedModel, register_base_model
from paddlenlp.utils.log import logger
from ..sequence_parallel_utils import (
ColumnSequenceParallelLinear,
GatherOp,
RowSequenceParallelLinear,
ScatterOp,
mark_as_sequence_parallel_parameter,
)
from .configuration import (
LLAMA_PRETRAINED_INIT_CONFIGURATION,
LLAMA_PRETRAINED_RESOURCE_FILES_MAP,
LlamaConfig,
)
try:
from paddle.nn.functional.flash_attention import flash_attention
except:
flash_attention = None
__all__ = [
"LlamaModel",
"LlamaPretrainedModel",
"LlamaForCausalLM",
"LlamaPretrainingCriterion",
]
def _get_interleave(n):
def _get_interleave_power_of_2(n):
start = 2 ** (-(2 ** -(math.log2(n) - 3)))
ratio = start
return [start * ratio**i for i in range(n)]
if math.log2(n).is_integer():
return _get_interleave_power_of_2(n)
else:
closest_power_of_2 = 2 ** math.floor(math.log2(n))
return (
_get_interleave_power_of_2(closest_power_of_2)
+ _get_interleave(2 * closest_power_of_2)[0::2][: n - closest_power_of_2]
)
def build_alibi_tensor(
bool_attention_mask: Tensor, num_heads: int, dtype: paddle.dtype, tensor_parallel_degree=1
) -> Tensor:
attention_mask = bool_attention_mask.astype("float32")
batch_size, seq_length = attention_mask.shape[0], attention_mask.shape[-1]
slopes = paddle.to_tensor(_get_interleave(num_heads), dtype="float32")
alibi = slopes.unsqueeze(axis=[1, 2]) * paddle.arange(seq_length, dtype="float32").unsqueeze(axis=[0, 1]).expand(
[num_heads, -1, -1]
)
alibi = alibi.reshape(shape=(1, num_heads, 1, seq_length)).expand([batch_size, -1, -1, -1])
return paddle.cast(alibi, dtype)
def get_triangle_upper_mask(x, mask=None):
if mask is not None:
return mask
# [bsz, n_head, q_len, kv_seq_len]
shape = x.shape
# [bsz, 1, q_len, kv_seq_len]
shape[1] = 1
mask = paddle.full(shape, paddle.finfo(x.dtype).min, dtype=x.dtype)
mask = paddle.triu(mask, diagonal=1)
mask.stop_gradient = True
return mask
def assign_kv_heads(num_kv_heads: int, num_gpus: int):
# Initialize the assignment list
"""
Assign kv heads to different GPUs in the Tensor Parallel Setup
Examples:
assign_kv_heads(num_kv_heads=1, num_gpus=2): [[0], [0]]
assign_kv_heads(num_kv_heads=2, num_gpus=2): [[0], [1]]
assign_kv_heads(num_kv_heads=4, num_gpus=2): [[0,1], [2,3]]
assign_kv_heads(num_kv_heads=1, num_gpus=4): [[0],[0],[0],[0]]
assign_kv_heads(num_kv_heads=2, num_gpus=4): [[0],[0],[1],[1]]
assign_kv_heads(num_kv_heads=4, num_gpus=4): [[0],[1],[2],[3]]
"""
assignment_list = [[] for _ in range(num_gpus)]
# Case 1: more heads than cards
if num_kv_heads > num_gpus:
num_heads_per_card = num_kv_heads // num_gpus
for i in range(num_gpus):
for j in range(num_heads_per_card):
assignment_list[i].append(i * num_heads_per_card + j)
# Case 2: more cards than heads. each card get only 1 head.
else:
num_card_per_heads = num_gpus // num_kv_heads
for i in range(num_kv_heads):
for j in range(num_card_per_heads):
assignment_list[i * num_card_per_heads + j].append(i)
return assignment_list
def parallel_matmul(x: Tensor, y: Tensor, tensor_parallel_output=True):
is_fleet_init = True
tensor_parallel_degree = 1
try:
hcg = fleet.get_hybrid_communicate_group()
model_parallel_group = hcg.get_model_parallel_group()
tensor_parallel_degree = hcg.get_model_parallel_world_size()
except:
is_fleet_init = False
if paddle.in_dynamic_mode():
y_is_distributed = y.is_distributed
else:
y_is_distributed = tensor_parallel_degree > 1
if is_fleet_init and tensor_parallel_degree > 1 and y_is_distributed:
# if not running under distributed.launch, it will raise AttributeError: 'Fleet' object has no attribute '_hcg'
input_parallel = paddle.distributed.collective._c_identity(x, group=model_parallel_group)
logits = paddle.matmul(input_parallel, y, transpose_y=False)
if tensor_parallel_output:
return logits
return paddle.distributed.collective._c_concat(logits, group=model_parallel_group)
else:
logits = paddle.matmul(x, y, transpose_y=False)
return logits
def scaled_dot_product_attention(
query_states,
config,
key_states,
value_states,
attention_mask,
output_attentions,
alibi=None,
sequence_parallel=False,
):
bsz, q_len, num_heads, head_dim = query_states.shape
_, kv_seq_len, _, _ = value_states.shape
if config.use_flash_attention and flash_attention:
# Paddle Flash Attention input [ bz, seqlen, nhead, head_dim]
# Torch Flash Attention input [ bz, nhead, seqlen, head_dim]
version = paddle.version.full_version
if version != "0.0.0" and version <= "2.5.2":
if alibi is not None:
raise ValueError("Flash Attention doesn't support alibi")
attn_output, attn_weights = flash_attention(
query_states,
key_states,
value_states,
causal=True,
return_softmax=output_attentions,
)
else:
if alibi is not None:
alibi = alibi.reshape([bsz, num_heads, 1, -1])
attention_mask = attention_mask.cast(alibi.dtype) + alibi
attn_output = F.scaled_dot_product_attention(
query_states,
key_states,
value_states,
attn_mask=attention_mask,
is_causal=attention_mask is None,
)
attn_weights = None
if sequence_parallel:
attn_output = attn_output.reshape([bsz * q_len, head_dim * num_heads])
else:
attn_output = attn_output.reshape([bsz, q_len, head_dim * num_heads])
return (attn_output, attn_weights) if output_attentions else attn_output
else:
# [ bz, seqlen, nhead, head_dim] -> [bs, nhead, seq_len, head_dim]
query_states = paddle.transpose(query_states, [0, 2, 1, 3])
# merge with the next tranpose
key_states = paddle.transpose(key_states, [0, 2, 1, 3])
value_states = paddle.transpose(value_states, [0, 2, 1, 3])
# matmul and devide by sqrt(head_dim)
attn_weights = paddle.matmul(query_states / math.sqrt(head_dim), key_states.transpose([0, 1, 3, 2]))
# then add alibi bias
if alibi is not None:
alibi = alibi.reshape([bsz, num_heads, 1, -1])
attn_weights = attn_weights + alibi
if attn_weights.shape != [bsz, num_heads, q_len, kv_seq_len]:
raise ValueError(
f"Attention weights should be of shape {(bsz, num_heads, q_len, kv_seq_len)}, but is"
f" {attn_weights.shape}"
)
# NOTE: we only call get_triangle_upper_mask under PP setup
# FIXME ZHUI when we use pipeline parallel, the attention_mask can be None
# we just make it triangle_upper_mask
if attention_mask is None:
attention_mask = get_triangle_upper_mask(attn_weights)
attention_mask = attention_mask.reshape([bsz, 1, q_len, kv_seq_len])
if attention_mask.shape != [bsz, 1, q_len, kv_seq_len]:
raise ValueError(
f"Attention mask should be of shape {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.shape}"
)
attn_weights = attn_weights + attention_mask
if not paddle.in_dynamic_mode():
attn_weights = F.softmax(attn_weights, axis=-1, dtype="float32").astype(query_states.dtype)
else:
with paddle.amp.auto_cast(False):
attn_weights = F.softmax(attn_weights, axis=-1, dtype="float32").astype(query_states.dtype)
attn_output = paddle.matmul(attn_weights, value_states)
attn_output = attn_output.transpose([0, 2, 1, 3])
if sequence_parallel:
attn_output = attn_output.reshape([bsz * q_len, head_dim * num_heads])
else:
attn_output = attn_output.reshape([bsz, q_len, head_dim * num_heads])
return (attn_output, attn_weights) if output_attentions else attn_output
def masked_fill(x, mask, value):
y = paddle.full(x.shape, value, x.dtype)
return paddle.where(mask, y, x)
def is_casual_mask(attention_mask):
"""
Upper triangular of attention_mask equals to attention_mask is casual
"""
return (paddle.triu(attention_mask) == attention_mask).all().item()
def _make_causal_mask(input_ids_shape, past_key_values_length):
"""
Make causal mask used for self-attention
"""
batch_size, target_length = input_ids_shape # target_length: seq_len
mask = paddle.tril(paddle.ones((target_length, target_length), dtype="bool"))
if past_key_values_length > 0:
# [tgt_len, tgt_len + past_len]
mask = paddle.concat([paddle.ones([target_length, past_key_values_length], dtype="bool"), mask], axis=-1)
# [bs, 1, tgt_len, tgt_len + past_len]
return mask[None, None, :, :].expand([batch_size, 1, target_length, target_length + past_key_values_length])
def _expand_2d_mask(mask, dtype, tgt_length):
"""
Expands attention_mask from `[batch_size, src_length]` to `[batch_size, 1, tgt_length, src_length]`.
"""
batch_size, src_length = mask.shape[0], mask.shape[-1]
tgt_length = tgt_length if tgt_length is not None else src_length
mask = mask[:, None, None, :].astype("bool")
mask.stop_gradient = True
expanded_mask = mask.expand([batch_size, 1, tgt_length, src_length])
return expanded_mask
def rms_norm_fused(x_in, w, eps):
fused_ln = try_import("fused_ln")
return fused_ln.fused_rms_norm(x_in, w, eps)[0]
class LlamaRMSNorm(nn.Layer):
def __init__(self, config):
super().__init__()
self.hidden_size = config.hidden_size
self.weight = paddle.create_parameter(
shape=[self.hidden_size],
dtype=paddle.get_default_dtype(),
default_initializer=nn.initializer.Constant(1.0),
)
self.variance_epsilon = config.rms_norm_eps
self.config = config
if config.sequence_parallel:
mark_as_sequence_parallel_parameter(self.weight)
def forward(self, hidden_states):
if self.config.use_fused_rms_norm:
return rms_norm_fused(hidden_states, self.weight, self.variance_epsilon)
if paddle.in_dynamic_mode():
with paddle.amp.auto_cast(False):
variance = hidden_states.astype("float32").pow(2).mean(-1, keepdim=True)
hidden_states = paddle.rsqrt(variance + self.variance_epsilon) * hidden_states
else:
variance = hidden_states.astype("float32").pow(2).mean(-1, keepdim=True)
hidden_states = paddle.rsqrt(variance + self.variance_epsilon) * hidden_states
if self.weight.dtype in [paddle.float16, paddle.bfloat16]:
hidden_states = paddle.cast(hidden_states, self.weight.dtype)
return hidden_states * self.weight
def repeat_kv(hidden_states: paddle.Tensor, n_rep: int) -> paddle.Tensor:
"""
This is the equivalent of paddle.repeat_interleave(hidden_states, n_rep, axis=1). The hidden states go from (batch,
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
"""
batch, slen, num_key_value_heads, head_dim = hidden_states.shape
if n_rep == 1:
return hidden_states
hidden_states = hidden_states.unsqueeze(-2).tile([1, 1, 1, n_rep, 1])
return hidden_states.reshape([batch, slen, num_key_value_heads * n_rep, head_dim])
class LlamaRotaryEmbedding(nn.Layer):
def __init__(self, dim, max_position_embeddings=2048, base=10000):
super().__init__()
self.dim = dim
self.max_position_embeddings = max_position_embeddings
self.base = base
# [dim / 2]
self.inv_freq = 1.0 / (self.base ** (paddle.cast(paddle.arange(0, self.dim, 2), dtype="float32") / self.dim))
self._set_cos_sin_cache(seq_len=max_position_embeddings)
def _set_cos_sin_cache(self, seq_len):
self.max_seq_len_cached = seq_len
# [seq_len]
t = paddle.arange(seq_len, dtype="float32")
# [seq_len, dim/2]
freqs = paddle.einsum("i,j->ij", t, self.inv_freq)
# Different from paper, but it uses a different permutation in order to obtain the same calculation
# [seq_len, dim]
emb = paddle.concat([freqs, freqs], axis=-1)
# [1, seqlen, 1, dim]
self.cos_cached = emb.cos()[None, :, None, :]
self.sin_cached = emb.sin()[None, :, None, :]
def forward(self, x, seq_len=None):
# x: [bs, num_attention_heads, seq_len, head_size]
cos = self.cos_cached[:, :, :seq_len, ...]
sin = self.sin_cached[:, :, :seq_len, ...]
return (
cos.cast(x.dtype) if cos.dtype != x.dtype else cos,
sin.cast(x.dtype) if sin.dtype != x.dtype else sin,
)
class LlamaLinearScalingRotaryEmbedding(LlamaRotaryEmbedding):
def __init__(self, dim, max_position_embeddings=2048, base=10000, scaling_factor=1.0):
self.scaling_factor = scaling_factor
super().__init__(dim, max_position_embeddings * scaling_factor, base)
def _set_cos_sin_cache(self, seq_len):
self.max_seq_len_cached = seq_len
# [seq_len]
t = paddle.arange(seq_len, dtype="float32")
t = t / self.scaling_factor
# [seq_len, dim/2]
freqs = paddle.einsum("i,j->ij", t, self.inv_freq)
# Different from paper, but it uses a different permutation in order to obtain the same calculation
# [seq_len, dim]
emb = paddle.concat([freqs, freqs], axis=-1)
# [1, seqlen, 1, dim]
self.cos_cached = emb.cos()[None, :, None, :]
self.sin_cached = emb.sin()[None, :, None, :]
class LlamaNTKScalingRotaryEmbedding(LlamaRotaryEmbedding):
"""LlamaRotaryEmbedding extended with NTK scaling. https://www.reddit.com/r/LocalLLaMA/comments/14lz7j5/ntkaware_scaled_rope_allows_llama_models_to_have/"""
def __init__(self, dim, max_position_embeddings=2048, base=10000, scaling_factor=1.0):
base = base * scaling_factor ** (dim / (dim - 2))
self.scaling_factor = scaling_factor
super().__init__(dim, max_position_embeddings * scaling_factor, base)
class LlamaDynamicNTKScalingRotaryEmbedding(LlamaRotaryEmbedding):
"""LlamaRotaryEmbedding extended with Dynamic NTK scaling. https://www.reddit.com/r/LocalLLaMA/comments/14mrgpr/dynamically_scaled_rope_further_increases/"""
def __init__(self, dim, max_position_embeddings=2048, base=10000, scaling_factor=1.0):
self.scaling_factor = scaling_factor
super().__init__(dim, max_position_embeddings, base)
def _scale_cos_sin(self, seq_len):
# [seq_len]
t = paddle.arange(seq_len, dtype="float32")
# [seq_len, dim/2]
alpha = (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
base = self.base * alpha ** (self.dim / (self.dim - 2))
inv_freq = 1.0 / (base ** (paddle.cast(paddle.arange(0, self.dim, 2), dtype="float32") / self.dim))
freqs = paddle.einsum("i,j->ij", t, inv_freq)
# Different from paper, but it uses a different permutation in order to obtain the same calculation
# [seq_len, dim]
emb = paddle.concat([freqs, freqs], axis=-1)
# [1, seqlen, 1, dim]
scale_cos = emb.cos()[None, :, None, :]
scale_sin = emb.sin()[None, :, None, :]
return scale_cos, scale_sin
def forward(self, x, seq_len=None):
# x: [bs, num_attention_heads, seq_len, head_size]
if seq_len > self.max_position_embeddings:
scale_cos, scale_sin = self._scale_cos_sin(seq_len=seq_len)
else:
scale_cos, scale_sin = self.cos_cached, self.sin_cached
cos = scale_cos[:, :seq_len, :, ...]
sin = scale_sin[:, :seq_len, :, ...]
return (
cos.cast(x.dtype) if cos.dtype != x.dtype else cos,
sin.cast(x.dtype) if sin.dtype != x.dtype else sin,
)
def rotate_half(x):
"""Rotates half the hidden dims of the input."""
x1 = x[..., : x.shape[-1] // 2]
x2 = x[..., x.shape[-1] // 2 :]
return paddle.concat([-x2, x1], axis=-1) # shape is the same as x
def apply_rotary_pos_emb(q, k, cos, sin, position_ids):
if position_ids is None:
# Note: Only for LlamaForCausalLMPipe model pretraining
cos = cos[:, : q.shape[1], :, :] # [bs, seq_len, 1, dim]
sin = sin[:, : q.shape[1], :, :] # [bs, seq_len, 1, dim]
else:
cos = cos.squeeze(axis=[0, 2]) # [seq_len, dim]
sin = sin.squeeze(axis=[0, 2]) # [seq_len, dim]
cos = cos[position_ids].unsqueeze(2) # [bs, seq_len, 1, dim]
sin = sin[position_ids].unsqueeze(2) # [bs, seq_len, 1, dim]
q_embed = (q * cos) + (rotate_half(q) * sin)
k_embed = (k * cos) + (rotate_half(k) * sin)
return q_embed, k_embed
class LlamaMLP(nn.Layer):
def __init__(self, config):
super().__init__()
self.hidden_size = config.hidden_size
self.intermediate_size = config.intermediate_size
self.tensor_parallel_degree = config.tensor_parallel_degree
self.fuse_attention_ffn = config.fuse_attention_ffn
if config.sequence_parallel:
ColumnParallelLinear = ColumnSequenceParallelLinear
RowParallelLinear = RowSequenceParallelLinear
else:
ColumnParallelLinear = fleet.meta_parallel.ColumnParallelLinear
RowParallelLinear = fleet.meta_parallel.RowParallelLinear
if config.tensor_parallel_degree > 1:
if config.fuse_attention_ffn:
self.gate_up_fused_proj = ColumnParallelLinear(
self.hidden_size,
self.intermediate_size * 2,
gather_output=False,
has_bias=False,
)
else:
self.gate_proj = ColumnParallelLinear(
self.hidden_size,
self.intermediate_size,
gather_output=False,
has_bias=False,
)
self.up_proj = ColumnParallelLinear(
self.hidden_size,
self.intermediate_size,
gather_output=False,
has_bias=False,
)
self.down_proj = RowParallelLinear(
self.intermediate_size,
self.hidden_size,
input_is_parallel=True,
has_bias=False,
)
else:
if config.fuse_attention_ffn:
self.gate_up_fused_proj = nn.Linear(self.hidden_size, self.intermediate_size * 2, bias_attr=False)
else:
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias_attr=False)
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias_attr=False)
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias_attr=False)
def forward(self, x):
if self.fuse_attention_ffn:
gate_out, up_out = paddle.chunk(self.gate_up_fused_proj(x), chunks=2, axis=-1)
out = self.down_proj(F.silu(gate_out) * up_out)
else:
out = self.down_proj(F.silu(self.gate_proj(x)) * self.up_proj(x))
return out
class LlamaAttention(nn.Layer):
"""Multi-headed attention from 'Attention Is All You Need' paper"""
def __init__(self, config: LlamaConfig, layerwise_recompute: bool = False):
super().__init__()
self.config = config
self.hidden_size = config.hidden_size
self.num_heads = config.num_attention_heads
self.head_dim = self.hidden_size // config.num_attention_heads
self.num_key_value_heads = config.num_key_value_heads
self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
self.max_position_embeddings = config.max_position_embeddings
self.seq_length = config.seq_length
self.sequence_parallel = config.sequence_parallel
self.fuse_attention_qkv = config.fuse_attention_qkv
if self.fuse_attention_qkv and config.num_attention_heads != config.num_key_value_heads:
raise ValueError(
f"fuse_attention_qkv can't be True when num_attention_heads {config.num_attention_heads}!= num_key_value_heads {config.num_key_value_heads}"
)
self.kv_indices = None
# Note that we will actually perform a recompute only if both enable_recompute and layerwise_recompute are set to True
# Enable_recompute defaults to False and is controlled by Trainer
self.enable_recompute = False
self.layerwise_recompute = layerwise_recompute
self.recompute_granularity = config.recompute_granularity
if config.tensor_parallel_degree > 1:
assert (
self.num_heads % config.tensor_parallel_degree == 0
), f"num_heads: {self.num_heads}, tensor_parallel_degree: {config.tensor_parallel_degree}"
self.num_heads = self.num_heads // config.tensor_parallel_degree
if self.num_key_value_heads % config.tensor_parallel_degree == 0:
self.num_key_value_heads = self.num_key_value_heads // config.tensor_parallel_degree
else:
logger.warning(
f"Get num_key_value_heads: {self.num_key_value_heads}, can't split to tensor_parallel_degree: {config.tensor_parallel_degree}, so we don't spilt key value weight."
)
self.kv_indices = paddle.to_tensor(
assign_kv_heads(self.num_key_value_heads, config.tensor_parallel_degree)[
config.tensor_parallel_rank
]
)
self.use_fused_rope = config.use_fused_rope
if self.use_fused_rope:
if "gpu" not in paddle.device.get_device() or fused_rotary_position_embedding is None:
warnings.warn(
"Enable fuse rope in the config, but fuse rope is not available. "
"Will disable fuse rope. Try using latest gpu version of Paddle."
)
self.use_fused_rope = False
if config.sequence_parallel:
ColumnParallelLinear = ColumnSequenceParallelLinear
RowParallelLinear = RowSequenceParallelLinear
else:
ColumnParallelLinear = fleet.meta_parallel.ColumnParallelLinear
RowParallelLinear = fleet.meta_parallel.RowParallelLinear
if config.tensor_parallel_degree > 1:
if self.fuse_attention_qkv:
self.qkv_proj = ColumnParallelLinear(
self.hidden_size,
3 * self.hidden_size,
has_bias=False,
gather_output=False,
)
else:
self.q_proj = ColumnParallelLinear(
self.hidden_size,
self.hidden_size,
has_bias=False,
gather_output=False,
)
if self.kv_indices is None:
self.k_proj = ColumnParallelLinear(
self.hidden_size,
self.config.num_key_value_heads * self.head_dim,
has_bias=False,
gather_output=False,
)
self.v_proj = ColumnParallelLinear(
self.hidden_size,
self.config.num_key_value_heads * self.head_dim,
has_bias=False,
gather_output=False,
)
else:
self.k_proj = nn.Linear(
self.hidden_size,
self.config.num_key_value_heads * self.head_dim,
bias_attr=False,
)
self.v_proj = nn.Linear(
self.hidden_size,
self.config.num_key_value_heads * self.head_dim,
bias_attr=False,
)
else:
if self.fuse_attention_qkv:
self.qkv_proj = nn.Linear(
self.hidden_size,
3 * self.hidden_size,
bias_attr=False,
)
else:
self.q_proj = nn.Linear(
self.hidden_size,
self.hidden_size,
bias_attr=False,
)
self.k_proj = nn.Linear(
self.hidden_size,
self.config.num_key_value_heads * self.head_dim,
bias_attr=False,
)
self.v_proj = nn.Linear(
self.hidden_size,
self.config.num_key_value_heads * self.head_dim,
bias_attr=False,
)
if config.tensor_parallel_degree > 1:
self.o_proj = RowParallelLinear(
self.hidden_size,
self.hidden_size,
has_bias=False,
input_is_parallel=True,
)
else:
self.o_proj = nn.Linear(
self.hidden_size,
self.hidden_size,
bias_attr=False,
)
if config.rope:
self._init_rope()
self.config = config
def _init_rope(self):
if self.config.rope_scaling_type is None:
self.rotary_emb = LlamaRotaryEmbedding(
self.head_dim,
max_position_embeddings=self.max_position_embeddings,
)
elif self.config.rope_scaling_type == "linear":
self.rotary_emb = LlamaLinearScalingRotaryEmbedding(
self.head_dim,
max_position_embeddings=self.max_position_embeddings,
scaling_factor=self.config.rope_scaling_factor,
)
elif self.config.rope_scaling_type == "ntk":
self.rotary_emb = LlamaNTKScalingRotaryEmbedding(
self.head_dim,
max_position_embeddings=self.max_position_embeddings,
scaling_factor=self.config.rope_scaling_factor,
)
elif self.config.rope_scaling_type == "dynamic_ntk":
self.rotary_emb = LlamaDynamicNTKScalingRotaryEmbedding(
self.head_dim,
max_position_embeddings=self.max_position_embeddings,
scaling_factor=self.config.rope_scaling_factor,
)
else:
raise ValueError(f"Unknown RoPE scaling type {self.config.rope_scaling_type}")
def forward(
self,
hidden_states,
position_ids: Optional[Tuple[paddle.Tensor]] = None,
past_key_value: Optional[Tuple[paddle.Tensor]] = None,
attention_mask: Optional[paddle.Tensor] = None,
output_attentions: bool = False,
use_cache: bool = False,
alibi: Optional[paddle.Tensor] = None,
) -> Tuple[paddle.Tensor, Optional[paddle.Tensor], Optional[Tuple[paddle.Tensor]]]:
"""Input shape: Batch x Time x Channel"""
# [bs, seq_len, num_head * head_dim] -> [seq_len / n, bs, num_head * head_dim] (n is model parallelism)
if self.fuse_attention_qkv:
if self.sequence_parallel:
target_shape = [-1, self.seq_length, self.num_heads, 3 * self.head_dim]
else:
target_shape = [0, 0, self.num_heads, 3 * self.head_dim]
mix_layer = self.qkv_proj(hidden_states)
mix_layer = paddle.reshape_(mix_layer, target_shape)
query_states, key_states, value_states = paddle.split(mix_layer, num_or_sections=3, axis=-1)
else:
if self.sequence_parallel:
target_query_shape = [-1, self.seq_length, self.num_heads, self.head_dim]
target_key_value_shape = [-1, self.seq_length, self.num_key_value_heads, self.head_dim]
else:
target_query_shape = [0, 0, self.num_heads, self.head_dim]
target_key_value_shape = [0, 0, self.num_key_value_heads, self.head_dim]
query_states = self.q_proj(hidden_states).reshape(shape=target_query_shape)
key_states = self.k_proj(hidden_states).reshape(shape=target_key_value_shape)
value_states = self.v_proj(hidden_states).reshape(shape=target_key_value_shape)
kv_seq_len = key_states.shape[-3]
if past_key_value is not None:
kv_seq_len += past_key_value[0].shape[-3]
if self.config.rope:
if self.use_fused_rope:
assert past_key_value is None, "fuse rotary not support cache kv for now"
cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
query_states, key_states, _ = fused_rotary_position_embedding(
query_states,
key_states,
v=None,
sin=sin,
cos=cos,
position_ids=position_ids,
use_neox_rotary_style=False,
)
else:
cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
# [bs, seq_len, num_head, head_dim]
if past_key_value is not None:
# reuse k, v, self_attention
key_states = paddle.concat([past_key_value[0], key_states], axis=1)
value_states = paddle.concat([past_key_value[1], value_states], axis=1)
past_key_value = (key_states, value_states) if use_cache else None
if self.kv_indices is not None:
key_states = paddle.index_select(key_states, self.kv_indices, axis=2)
value_states = paddle.index_select(value_states, self.kv_indices, axis=2)
# TODO(wj-Mcat): use broadcast strategy when n_kv_heads = 1
# repeat k/v heads if n_kv_heads < n_heads
key_states = repeat_kv(key_states, self.num_key_value_groups)
value_states = repeat_kv(value_states, self.num_key_value_groups)
has_gradient = not (query_states.stop_gradient and key_states.stop_gradient and value_states.stop_gradient)
if (
self.enable_recompute
and self.layerwise_recompute
and has_gradient
and self.recompute_granularity == "core_attn"
):
outputs = recompute(
scaled_dot_product_attention,
query_states,
self.config,
key_states,
value_states,
attention_mask,
output_attentions,
alibi,
self.sequence_parallel,
use_reentrant=self.config.recompute_use_reentrant,
)
else:
outputs = scaled_dot_product_attention(
query_states,
self.config,
key_states,
value_states,
attention_mask,
output_attentions,
alibi,
self.sequence_parallel,
)
if output_attentions:
attn_output, attn_weights = outputs
else:
attn_output = outputs
# if sequence_parallel is true, out shape are [q_len / n, bs, num_head * head_dim]
# else their shape are [bs, q_len, num_head * head_dim], n is mp parallelism.
attn_output = self.o_proj(attn_output)
if not output_attentions:
attn_weights = None
outputs = (attn_output,)
if output_attentions:
outputs += (attn_weights,)
if use_cache:
outputs += (past_key_value,)
if type(outputs) is tuple and len(outputs) == 1:
outputs = outputs[0]
return outputs
class LlamaDecoderLayer(nn.Layer):
def __init__(self, config, layerwise_recompute: bool = False):
super().__init__()
self.config = config
self.hidden_size = config.hidden_size
self.self_attn = LlamaAttention(config, layerwise_recompute)
self.mlp = LlamaMLP(config)
self.input_layernorm = LlamaRMSNorm(config)
self.post_attention_layernorm = LlamaRMSNorm(config)
self.sequence_parallel = config.sequence_parallel
# Note that we will actually perform a recompute only if both enable_recompute and layerwise_recompute are set to True
# Enable_recompute defaults to False and is controlled by Trainer
self.enable_recompute = False
self.layerwise_recompute = layerwise_recompute
self.recompute_granularity = config.recompute_granularity
def forward(
self,
hidden_states: paddle.Tensor,
position_ids: Optional[Tuple[paddle.Tensor]] = None,
attention_mask: Optional[paddle.Tensor] = None,
output_attentions: Optional[bool] = False,
past_key_value: Optional[Tuple[paddle.Tensor]] = None,
use_cache: Optional[bool] = False,
alibi: Optional[paddle.Tensor] = None,
) -> Tuple[paddle.Tensor, Optional[Tuple[paddle.Tensor, paddle.Tensor]]]:
"""
Args:
hidden_states (`paddle.Tensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
attention_mask (`paddle.Tensor`, *optional*): attention mask of size
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
output_attentions (`bool`, *optional*):
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
returned tensors for more detail.
use_cache (`bool`, *optional*):
If set to `True`, `cache` key value states are returned and can be used to speed up decoding
(see `cache`).
cache (`Tuple(paddle.Tensor)`, *optional*): cached past key and value projection states
"""
# [bs * seq_len, embed_dim] -> [seq_len * bs / n, embed_dim] (sequence_parallel)
residual = hidden_states
hidden_states = self.input_layernorm(hidden_states)
# Self Attention
has_gradient = not hidden_states.stop_gradient
if (
self.enable_recompute
and self.layerwise_recompute
and has_gradient
and self.recompute_granularity == "full_attn"
):
outputs = recompute(
self.self_attn,
hidden_states,
position_ids,
past_key_value,
attention_mask,
output_attentions,
use_cache,
alibi,
use_reentrant=self.config.recompute_use_reentrant,
)
else:
outputs = self.self_attn(
hidden_states,
position_ids,
past_key_value,
attention_mask,
output_attentions,
use_cache,
alibi,
)
if type(outputs) is tuple:
hidden_states = outputs[0]
else:
hidden_states = outputs
if output_attentions:
self_attn_weights = outputs[1]
if use_cache:
present_key_value = outputs[2 if output_attentions else 1]
hidden_states = residual + hidden_states
# Fully Connected
residual = hidden_states
hidden_states = self.post_attention_layernorm(hidden_states)
hidden_states = self.mlp(hidden_states)
hidden_states = residual + hidden_states
outputs = (hidden_states,)
if output_attentions:
outputs += (self_attn_weights,)
if use_cache:
outputs += (present_key_value,)
# remove empty tuple for pipeline parallel
if type(outputs) is tuple and len(outputs) == 1:
outputs = outputs[0]
return outputs
class LlamaPretrainedModel(PretrainedModel):
config_class = LlamaConfig
base_model_prefix = "llama"
pretrained_init_configuration = LLAMA_PRETRAINED_INIT_CONFIGURATION
pretrained_resource_files_map = LLAMA_PRETRAINED_RESOURCE_FILES_MAP
_keys_to_ignore_on_load_unexpected = [r"self_attn.rotary_emb.inv_freq"]
@classmethod
def _get_name_mappings(cls, config: LlamaConfig) -> list[StateDictNameMapping]:
mappings: list[StateDictNameMapping] = []
model_mappings = [
["embed_tokens.weight"],
["norm.weight"],
]
for layer_index in range(config.num_hidden_layers):
layer_mappings = [
[f"layers.{layer_index}.self_attn.q_proj.weight", None, "transpose"],
[f"layers.{layer_index}.self_attn.k_proj.weight", None, "transpose"],
[f"layers.{layer_index}.self_attn.v_proj.weight", None, "transpose"],
[f"layers.{layer_index}.self_attn.o_proj.weight", None, "transpose"],
[f"layers.{layer_index}.self_attn.rotary_emb.inv_freq"],
[f"layers.{layer_index}.mlp.gate_proj.weight", None, "transpose"],
[f"layers.{layer_index}.mlp.down_proj.weight", None, "transpose"],
[f"layers.{layer_index}.mlp.up_proj.weight", None, "transpose"],
[f"layers.{layer_index}.input_layernorm.weight"],
[f"layers.{layer_index}.post_attention_layernorm.weight"],
]
model_mappings.extend(layer_mappings)
init_name_mappings(mappings=model_mappings)
# base-model prefix "LlamaModel"
if "LlamaModel" not in config.architectures:
for mapping in model_mappings:
mapping[0] = "model." + mapping[0]
mapping[1] = "llama." + mapping[1]
model_mappings.append(["lm_head.weight", "lm_head.weight", "transpose"])
mappings = [StateDictNameMapping(*mapping, index=index) for index, mapping in enumerate(model_mappings)]
return mappings
@classmethod
def _get_tensor_parallel_mappings(cls, config: LlamaConfig, is_split=True):
from paddlenlp.transformers.conversion_utils import split_or_merge_func