-
Notifications
You must be signed in to change notification settings - Fork 18
/
layers.h
2300 lines (1913 loc) · 93.6 KB
/
layers.h
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
#pragma once
#include <ggml.h>
#include <memory>
#include <sstream>
#include <unordered_map>
#include <vector>
#include <iostream>
#include "chat.h"
namespace chatllm
{
[[ noreturn ]]
void inspect_tensor(ggml_tensor *tensor, const char *msg,
ggml_tensor *temp1 = nullptr, ggml_tensor *temp2 = nullptr, ggml_tensor *temp3 = nullptr, ggml_tensor *temp4 = nullptr, ggml_tensor *temp5 = nullptr);
enum ActFunc
{
GELU, // equivelent to `gelu_new`
SILU,
Tanh,
RELU,
RELU2, // square . relu
};
ggml_tensor *inplace_act(ggml_context *ctx, ActFunc act, ggml_tensor *input);
class Block
{
public:
Block(): prec(ggml_prec::GGML_PREC_DEFAULT), id(0) {}
virtual ggml_tensor *forward(ForwardContext *ctx, ggml_tensor *input)
{
CHATLLM_THROW << "forward(ForwardContext *ctx, ggml_tensor *input): not implemented";
return NULL;
}
virtual ggml_tensor *forward(ForwardContext *ctx, ggml_tensor *input, int n_past)
{
CHATLLM_THROW << "forward(ForwardContext *ctx, ggml_tensor *input, int n_past): not implemented";
return NULL;
}
virtual void set_ctx(int n_ctx) { }
virtual void shift_cache(int shift, int total) { }
virtual void set_prec(ggml_prec prec)
{
this->prec = prec;
}
virtual void set_id(int id)
{
this->id = id;
}
virtual int64_t get_param_num(bool effective_only) const
{
return 0;
}
virtual size_t get_cache_size(void) const { return 0; }
virtual void *set_cache_buffer(void *buffer) { return buffer; }
protected:
ggml_prec prec;
int id;
};
class Identity : public Block
{
public:
Identity() {}
Identity(InitContext *ctx, int a) {}
Identity(InitContext *ctx, int a, int b) {}
ggml_tensor *forward(ForwardContext *ctx, ggml_tensor *input) override
{
return input;
}
ggml_tensor *forward(ForwardContext *ctx, ggml_tensor *input, int n_past) override
{
return input;
}
};
class ShiftPending
{
public:
ShiftPending() : ShiftPending(0, 0) {}
ShiftPending(int shift, int total) : shift(shift), total(total) {}
void clear(void) { shift = 0; }
public:
int shift;
int total;
};
class Embedding : public Block
{
public:
Embedding() : weight(nullptr) {}
Embedding(InitContext *ctx, int num_embeddings, int embedding_dim)
: weight(ggml_new_tensor_2d(ctx->gctx.get(), ctx->dtype, embedding_dim, num_embeddings)) {}
Embedding(InitContext *ctx, int num_embeddings, int embedding_dim, int pos_max)
: Embedding(ctx, num_embeddings, embedding_dim) {}
using Block::forward;
ggml_tensor *forward(ForwardContext *ctx, ggml_tensor *input) override;
int64_t get_param_num(bool effective_only) const override
{
return ggml_nelements(weight);
}
public:
ggml_tensor *weight;
};
class VisualEmbedding : public Embedding
{
public:
VisualEmbedding(InitContext *ctx, int num_embeddings, int embedding_dim)
: Embedding(ctx, num_embeddings, embedding_dim) {}
virtual ggml_tensor *forward(ForwardContext *ctx, ggml_tensor *patches, int patches_per_row, ggml_tensor *text_input) = 0;
};
class Linear : public Block
{
public:
Linear() : weight(nullptr), bias(nullptr) {}
Linear(InitContext *ctx, int in_features, int out_features, bool use_bias = true)
: weight(ggml_new_tensor_2d(ctx->gctx.get(), ctx->dtype, in_features, out_features)),
bias(use_bias ? ggml_new_tensor_1d(ctx->gctx.get(), GGML_TYPE_F32, out_features) : nullptr) {}
Linear(InitContext *ctx, int in_features, int out_features, ggml_tensor *weight, bool use_bias = true)
: weight(weight != NULL ? weight : ggml_new_tensor_2d(ctx->gctx.get(), ctx->dtype, in_features, out_features)),
bias(use_bias ? ggml_new_tensor_1d(ctx->gctx.get(), GGML_TYPE_F32, out_features) : nullptr) {}
int in_features() const { return (int)weight->ne[0]; }
int out_features() const { return (int)weight->ne[1]; }
using Block::forward;
ggml_tensor *forward(ForwardContext *ctx, ggml_tensor *input) override;
int64_t get_param_num(bool effective_only) const override
{
int64_t r = ggml_nelements(weight);
if (bias) r += ggml_nelements(bias);
return r;
}
public:
ggml_tensor *weight; // [out_features, in_features]
ggml_tensor *bias; // [out_features]
};
class LayerNorm : public Block
{
public:
LayerNorm() : weight(nullptr), bias(nullptr) {}
LayerNorm(InitContext *ctx, int normalized_shape)
: LayerNorm(ctx, normalized_shape, true)
{
}
LayerNorm(InitContext *ctx, int normalized_shape, bool use_bias)
: weight(ggml_new_tensor_1d(ctx->gctx.get(), GGML_TYPE_F32, normalized_shape)),
bias(use_bias ? ggml_new_tensor_1d(ctx->gctx.get(), GGML_TYPE_F32, normalized_shape) : nullptr),
eps(1e-5f) {}
using Block::forward;
ggml_tensor *forward(ForwardContext *ctx, ggml_tensor *input) override;
int64_t get_param_num(bool effective_only) const override
{
int64_t r = ggml_nelements(weight);
if (bias) r += ggml_nelements(bias);
return r;
}
public:
ggml_tensor *weight; // [normalized_shape]
ggml_tensor *bias; // [normalized_shape]
float eps;
};
class LayerNormNoBias : public LayerNorm
{
public:
LayerNormNoBias() : LayerNorm() {}
LayerNormNoBias(InitContext *ctx, int normalized_shape)
: LayerNorm(ctx, normalized_shape, false)
{
}
};
class RobertaEmbedding : public Block
{
public:
RobertaEmbedding() : word_weight(nullptr), position_weight(nullptr) {}
RobertaEmbedding(InitContext *ctx, int num_embeddings, int embedding_dim, int pos_max)
: word_weight(ggml_new_tensor_2d(ctx->gctx.get(), ctx->dtype, embedding_dim, num_embeddings)),
position_weight(ggml_new_tensor_2d(ctx->gctx.get(), ctx->dtype, embedding_dim, pos_max)),
indices(ggml_new_tensor_1d(ctx->gctx.get(), GGML_TYPE_I32, pos_max)),
ln(ctx, embedding_dim),
pad_index(2)
{
indices->data = new char[ggml_nbytes(indices)];
int32_t *p = (int32_t *)indices->data;
for (int i = 0; i < pos_max; i++)
p[i] = i;
}
using Block::forward;
ggml_tensor *forward(ForwardContext *ctx, ggml_tensor *input, int n_past) override;
int64_t get_param_num(bool effective_only) const override
{
int64_t r = ln.get_param_num(effective_only);
if (word_weight) r += ggml_nelements(word_weight);
if (position_weight) r += ggml_nelements(position_weight);
return r;
}
public:
ggml_tensor *word_weight;
ggml_tensor *position_weight;
ggml_tensor *indices;
LayerNorm ln;
int pad_index;
};
class RMSNorm : public Block
{
public:
RMSNorm() : weight(nullptr) {}
RMSNorm(InitContext *ctx, int normalized_shape)
: weight(ggml_new_tensor_1d(ctx->gctx.get(), GGML_TYPE_F32, normalized_shape)),
eps(1e-5f) {}
using Block::forward;
ggml_tensor *forward(ForwardContext *ctx, ggml_tensor *input) override;
int64_t get_param_num(bool effective_only) const override
{
return ggml_nelements(weight);
}
public:
ggml_tensor *weight;
float eps;
};
// This is **the** feed forward network (Multi-Layer Perceptron) in _Attention Is All You Need_.
class TheMLP : public Block
{
public:
TheMLP() = default;
TheMLP(InitContext *ctx, int hidden_size, int intermediate_size, ActFunc act, bool bias)
: fc0(ctx, hidden_size, intermediate_size, bias),
fc1(ctx, intermediate_size, hidden_size, bias),
act(act)
{}
using Block::forward;
ggml_tensor *forward(ForwardContext *ctx, ggml_tensor *hidden_states) override;
void set_prec(ggml_prec prec) override;
int64_t get_param_num(bool effective_only) const override
{
int64_t r = 0;
r += fc0.get_param_num(effective_only);
r += fc1.get_param_num(effective_only);
return r;
}
public:
Linear fc0;
Linear fc1;
ActFunc act;
};
class GLMMLP : public TheMLP
{
public:
GLMMLP() = default;
GLMMLP(InitContext *ctx, int hidden_size)
: GLMMLP(ctx, hidden_size, 4 * hidden_size) {}
GLMMLP(InitContext *ctx, int hidden_size, int intermediate_size)
: TheMLP(ctx, hidden_size, intermediate_size, ActFunc::GELU, true) {}
};
class GLMSelfAttention : public Block
{
public:
// TODO: kv cache type
GLMSelfAttention() : num_attention_heads(0), n_ctx(0) {}
GLMSelfAttention(InitContext *ctx, int hidden_size, int num_attention_heads, int max_length)
: query_key_value(ctx, hidden_size, 3 * hidden_size), dense(ctx, hidden_size, hidden_size),
num_attention_heads(num_attention_heads),
k_cache(ggml_new_tensor_3d(ctx->gctx.get(), GGML_TYPE_F16, hidden_size / num_attention_heads, max_length,
num_attention_heads)),
v_cache(ggml_new_tensor_3d(ctx->gctx.get(), GGML_TYPE_F16, max_length, hidden_size / num_attention_heads,
num_attention_heads)),
pos(ggml_new_tensor_1d(ctx->gctx.get(), GGML_TYPE_I32, max_length)),
n_ctx(0),
shift_pending()
{
pos->data = new char[ggml_nbytes(pos)]();
}
using Block::forward;
ggml_tensor *forward(ForwardContext *ctx, ggml_tensor *hidden_states, int n_past) override;
void set_ctx(int n_ctx) override { this->n_ctx = n_ctx; }
void shift_cache(int shift, int total) override
{
shift_pending = ShiftPending(shift, total);
}
int64_t get_param_num(bool effective_only) const override
{
int64_t r = 0;
r += query_key_value.get_param_num(effective_only);
r += dense.get_param_num(effective_only);
return r;
}
size_t get_cache_size(void) const override
{
return ggml_nbytes(k_cache) + ggml_nbytes(v_cache);
}
void *set_cache_buffer(void *buffer) override
{
uint8_t *b = (uint8_t *)buffer;
k_cache->data = b; b += ggml_nbytes(k_cache);
v_cache->data = b; b += ggml_nbytes(v_cache);
return b;
}
public:
Linear query_key_value;
Linear dense;
int num_attention_heads;
ggml_tensor *k_cache; // [n_head, maxlen, head_size]
ggml_tensor *v_cache; // [n_head, head_size, maxlen]
ggml_tensor *pos;
int n_ctx;
private:
ShiftPending shift_pending;
};
class GLMBlock : public Block
{
public:
GLMBlock() : num_hidden_layers(0) {}
GLMBlock(InitContext *ctx, int hidden_size, int num_attention_heads, int num_hidden_layers, int max_length)
: input_layernorm(ctx, hidden_size),
attention(ctx, hidden_size, num_attention_heads, max_length),
post_attention_layernorm(ctx, hidden_size),
mlp(ctx, hidden_size),
num_hidden_layers(num_hidden_layers) {}
using Block::forward;
virtual ggml_tensor *forward(ForwardContext *ctx, ggml_tensor *hidden_states, int n_past) override;
void set_ctx(int n_ctx) override { attention.set_ctx(n_ctx); }
int64_t get_param_num(bool effective_only) const override
{
int64_t r = 0;
r += input_layernorm.get_param_num(effective_only);
r += attention.get_param_num(effective_only);
r += post_attention_layernorm.get_param_num(effective_only);
r += mlp.get_param_num(effective_only);
return r;
}
size_t get_cache_size(void) const override
{
return attention.get_cache_size();
}
void *set_cache_buffer(void *buffer) override
{
return attention.set_cache_buffer(buffer);
}
public:
LayerNorm input_layernorm;
GLMSelfAttention attention;
LayerNorm post_attention_layernorm;
GLMMLP mlp;
int num_hidden_layers;
};
class GLM2MLP : public Block
{
public:
GLM2MLP(InitContext *ctx, int hidden_size, int intermediate_size)
: dense_h_to_4h(ctx, hidden_size, intermediate_size * 2, false),
dense_4h_to_h(ctx, intermediate_size, hidden_size, false) {}
using Block::forward;
ggml_tensor *forward(ForwardContext *ctx, ggml_tensor *hidden_states) override;
int64_t get_param_num(bool effective_only) const override
{
int64_t r = 0;
r += dense_h_to_4h.get_param_num(effective_only);
r += dense_4h_to_h.get_param_num(effective_only);
return r;
}
public:
Linear dense_h_to_4h;
Linear dense_4h_to_h;
};
template <class InputNormBlock,
class AttentionBlock,
class PostNormBlock,
class MLPBlock> class LMBlock1 : public Block
{
public:
LMBlock1() = default;
LMBlock1(InitContext *ctx, int hidden_size, int num_attention_heads, int intermediate_size,
int max_length)
: input_layernorm(ctx, hidden_size),
attention(ctx, hidden_size, num_attention_heads, max_length),
post_attention_layernorm(ctx, hidden_size),
mlp(ctx, hidden_size, intermediate_size) {}
LMBlock1(InitContext *ctx, int hidden_size, int num_attention_heads, int intermediate_size, int num_kv_heads,
int max_length)
: input_layernorm(ctx, hidden_size),
attention(ctx, hidden_size, num_attention_heads, num_kv_heads, max_length),
post_attention_layernorm(ctx, hidden_size),
mlp(ctx, hidden_size, intermediate_size) {}
LMBlock1(InitContext *ctx, int hidden_size, int num_attention_heads, int intermediate_size, int num_kv_heads,
int head_dim, int max_length)
: input_layernorm(ctx, hidden_size),
attention(ctx, hidden_size, num_attention_heads, num_kv_heads, head_dim, max_length),
post_attention_layernorm(ctx, hidden_size),
mlp(ctx, hidden_size, intermediate_size) {}
LMBlock1(InitContext *ctx, int hidden_size, int num_attention_heads, int intermediate_size,
int mlp_intermediate_size1, int mlp_intermediate_size2,
int num_kv_heads,
int head_dim, int max_length)
: input_layernorm(ctx, hidden_size),
attention(ctx, hidden_size, num_attention_heads, num_kv_heads, head_dim, max_length),
post_attention_layernorm(ctx, hidden_size),
mlp(ctx, hidden_size, mlp_intermediate_size1, mlp_intermediate_size2) {}
LMBlock1(InitContext *ctx, int hidden_size, int num_attention_heads, int intermediate_size,
int mlp_intermediate_size1, int mlp_intermediate_size2,
int num_kv_heads, int max_length,
int q_lora_rank, int kv_lora_rank, int rope_dim, int qk_nope_head_dim, int v_head_dim,
bool use_bias)
: input_layernorm(ctx, hidden_size),
attention(ctx, hidden_size, num_attention_heads, num_kv_heads, max_length,
q_lora_rank, kv_lora_rank, rope_dim, qk_nope_head_dim, v_head_dim,
use_bias),
post_attention_layernorm(ctx, hidden_size),
mlp(ctx, hidden_size, mlp_intermediate_size1, mlp_intermediate_size2) {}
LMBlock1(InitContext *ctx, int hidden_size, int num_attention_heads, int intermediate_size,
int num_kv_heads, int max_length,
int q_lora_rank, int kv_lora_rank, int rope_dim, int qk_nope_head_dim, int v_head_dim,
bool use_bias)
: input_layernorm(ctx, hidden_size),
attention(ctx, hidden_size, num_attention_heads, num_kv_heads, max_length,
q_lora_rank, kv_lora_rank, rope_dim, qk_nope_head_dim, v_head_dim,
use_bias),
post_attention_layernorm(ctx, hidden_size),
mlp(ctx, hidden_size, intermediate_size) {}
using Block::forward;
ggml_tensor *forward(ForwardContext *ctx, ggml_tensor *hidden_states, int n_past) override
{
ggml_tensor *residual = ggml_dup(ctx->gctx.get(), hidden_states);
ggml_build_forward_expand(ctx->gf, residual);
hidden_states = input_layernorm.forward(ctx, hidden_states);
hidden_states = attention.forward(ctx, hidden_states, n_past);
hidden_states = ggml_add_inplace(ctx->gctx.get(), hidden_states, residual);
residual = ggml_dup(ctx->gctx.get(), hidden_states);
ggml_build_forward_expand(ctx->gf, residual);
hidden_states = post_attention_layernorm.forward(ctx, hidden_states);
hidden_states = mlp.forward(ctx, hidden_states);
hidden_states = ggml_add_inplace(ctx->gctx.get(), hidden_states, residual);
return hidden_states;
}
void shift_cache(int shift, int total) override
{
attention.shift_cache(shift, total);
}
int64_t get_param_num(bool effective_only) const override
{
int64_t r = 0;
r += input_layernorm.get_param_num(effective_only);
r += attention.get_param_num(effective_only);
r += post_attention_layernorm.get_param_num(effective_only);
r += mlp.get_param_num(effective_only);
return r;
}
void set_id(int id) override
{
Block::set_id(id);
input_layernorm.set_id(id);
attention.set_id(id);
post_attention_layernorm.set_id(id);
mlp.set_id(id);
}
size_t get_cache_size(void) const override
{
return attention.get_cache_size();
}
void *set_cache_buffer(void *buffer) override
{
return attention.set_cache_buffer(buffer);
}
public:
InputNormBlock input_layernorm;
AttentionBlock attention;
PostNormBlock post_attention_layernorm;
MLPBlock mlp;
};
template <class PreAttnNormBlock,
class AttentionBlock,
class PostAttnNormBlock,
class PreMLPNormBlock,
class MLPBlock,
class PostMLPNormBlock> class LMBlock4 : public Block
{
public:
LMBlock4() = default;
LMBlock4(InitContext *ctx, int hidden_size, int num_attention_heads, int intermediate_size,
int max_length)
: pre_attention_layernorm(ctx, hidden_size),
attention(ctx, hidden_size, num_attention_heads, max_length),
post_attention_layernorm(ctx, hidden_size),
pre_mlp_layernorm(ctx, hidden_size),
mlp(ctx, hidden_size, intermediate_size),
post_mlp_layernorm(ctx, hidden_size) {}
LMBlock4(InitContext *ctx, int hidden_size, int num_attention_heads, int intermediate_size, int num_kv_heads,
int max_length)
: pre_attention_layernorm(ctx, hidden_size),
attention(ctx, hidden_size, num_attention_heads, num_kv_heads, max_length),
post_attention_layernorm(ctx, hidden_size),
pre_mlp_layernorm(ctx, hidden_size),
mlp(ctx, hidden_size, intermediate_size),
post_mlp_layernorm(ctx, hidden_size) {}
LMBlock4(InitContext *ctx, int hidden_size, int num_attention_heads, int intermediate_size, int num_kv_heads,
int head_dim, int max_length)
: pre_attention_layernorm(ctx, hidden_size),
attention(ctx, hidden_size, num_attention_heads, num_kv_heads, head_dim, max_length),
post_attention_layernorm(ctx, hidden_size),
pre_mlp_layernorm(ctx, hidden_size),
mlp(ctx, hidden_size, intermediate_size),
post_mlp_layernorm(ctx, hidden_size) {}
using Block::forward;
ggml_tensor *forward(ForwardContext *ctx, ggml_tensor *hidden_states, int n_past) override
{
ggml_tensor *residual = ggml_dup(ctx->gctx.get(), hidden_states);
ggml_build_forward_expand(ctx->gf, residual);
hidden_states = pre_attention_layernorm.forward(ctx, hidden_states);
hidden_states = attention.forward(ctx, hidden_states, n_past);
hidden_states = post_attention_layernorm.forward(ctx, hidden_states);
hidden_states = ggml_add_inplace(ctx->gctx.get(), hidden_states, residual);
residual = ggml_cpy(ctx->gctx.get(), hidden_states, residual);
ggml_build_forward_expand(ctx->gf, residual);
hidden_states = pre_mlp_layernorm.forward(ctx, hidden_states);
hidden_states = mlp.forward(ctx, hidden_states);
hidden_states = post_mlp_layernorm.forward(ctx, hidden_states);
hidden_states = ggml_add_inplace(ctx->gctx.get(), hidden_states, residual);
return hidden_states;
}
void shift_cache(int shift, int total) override
{
attention.shift_cache(shift, total);
}
int64_t get_param_num(bool effective_only) const override
{
int64_t r = 0;
r += pre_attention_layernorm.get_param_num(effective_only);
r += attention.get_param_num(effective_only);
r += post_attention_layernorm.get_param_num(effective_only);
r += pre_mlp_layernorm.get_param_num(effective_only);
r += mlp.get_param_num(effective_only);
r += post_mlp_layernorm.get_param_num(effective_only);
return r;
}
void set_id(int id) override
{
Block::set_id(id);
pre_attention_layernorm.set_id(id);
attention.set_id(id);
post_attention_layernorm.set_id(id);
pre_mlp_layernorm.set_id(id);
mlp.set_id(id);
post_mlp_layernorm.set_id(id);
}
size_t get_cache_size(void) const override
{
return attention.get_cache_size();
}
void *set_cache_buffer(void *buffer) override
{
return attention.set_cache_buffer(buffer);
}
public:
PreAttnNormBlock pre_attention_layernorm;
AttentionBlock attention;
PostAttnNormBlock post_attention_layernorm;
PreMLPNormBlock pre_mlp_layernorm;
MLPBlock mlp;
PostMLPNormBlock post_mlp_layernorm;
};
template <class InputNormBlock,
class AttentionBlock,
class PostNormBlock,
class MLPBlock> class LMBlock3 : public LMBlock1<InputNormBlock, AttentionBlock, PostNormBlock, MLPBlock>
{
public:
typedef LMBlock1<InputNormBlock, AttentionBlock, PostNormBlock, MLPBlock> Base;
LMBlock3() = default;
LMBlock3(InitContext *ctx, int hidden_size, int num_attention_heads, int intermediate_size,
int max_length)
: Base::LMBlock1(ctx, hidden_size, num_attention_heads, intermediate_size, max_length),
hidden_scaling(1.0f) {}
LMBlock3(InitContext *ctx, int hidden_size, int num_attention_heads, int intermediate_size, int num_kv_heads,
int max_length)
: Base::LMBlock1(ctx, hidden_size, num_attention_heads, intermediate_size, num_kv_heads, max_length),
hidden_scaling(1.0f) {}
using Block::forward;
ggml_tensor *forward(ForwardContext *ctx, ggml_tensor *hidden_states, int n_past) override
{
ggml_context * ggctx = ctx->gctx.get();
ggml_tensor *residual = ggml_dup(ggctx, hidden_states);
ggml_build_forward_expand(ctx->gf, residual);
hidden_states = Base::input_layernorm.forward(ctx, hidden_states);
hidden_states = Base::attention.forward(ctx, hidden_states, n_past);
hidden_states = ggml_scale_inplace(ggctx, hidden_states, hidden_scaling);
hidden_states = ggml_add_inplace(ggctx, hidden_states, residual);
residual = ggml_dup(ggctx, hidden_states);
ggml_build_forward_expand(ctx->gf, residual);
hidden_states = Base::post_attention_layernorm.forward(ctx, hidden_states);
hidden_states = Base::mlp.forward(ctx, hidden_states);
hidden_states = ggml_scale_inplace(ggctx, hidden_states, hidden_scaling);
hidden_states = ggml_add_inplace(ggctx, hidden_states, residual);
return hidden_states;
}
public:
float hidden_scaling;
};
class CoreAttention : public Block
{
public:
CoreAttention() : num_attention_heads(0), num_kv_heads(0), max_length(0) {}
CoreAttention(InitContext *ctx, int num_attention_heads, int num_kv_heads, int max_length, ggml_type cache_type,
int k_cache_ele_num, int v_cache_ele_num)
: num_attention_heads(num_attention_heads),
num_kv_heads(num_kv_heads),
k_cache(k_cache_ele_num > 0 ? ggml_new_tensor_1d(ctx->gctx.get(), cache_type, k_cache_ele_num)
: nullptr),
v_cache(v_cache_ele_num > 0 ? ggml_new_tensor_1d(ctx->gctx.get(), cache_type, v_cache_ele_num)
: nullptr),
pos(ggml_new_tensor_1d(ctx->gctx.get(), GGML_TYPE_I32, max_length)),
max_length(max_length),
attn_scaling_factor(-1.0f),
shift_pending(),
attn_scaling(true),
causal(true),
last_attn_scores(nullptr)
{
if (k_cache_ele_num > 0)
{
ggml_set_name(k_cache, "k_cache");
}
if (v_cache_ele_num > 0)
{
ggml_set_name(v_cache, "v_cache");
}
pos->data = new char[ggml_nbytes(pos)]();
}
void shift_cache(int shift, int total) override
{
shift_pending = ShiftPending(shift, total);
}
size_t get_cache_size(void) const override
{
size_t r = 0;
if (k_cache)
r += ggml_nbytes(k_cache);
if (v_cache)
r += ggml_nbytes(v_cache);
return r;
}
void *set_cache_buffer(void *buffer) override
{
uint8_t *b = (uint8_t *)buffer;
if (k_cache)
{
k_cache->data = b;
b += ggml_nbytes(k_cache);
}
if (v_cache)
{
v_cache->data = b;
b += ggml_nbytes(v_cache);
}
return b;
}
protected:
// k: [heads, qlen, head_size]
// q: [heads, qlen, head_size]
// v: [heads, head_size, klen]
virtual ggml_tensor *calc_attn_scores(ForwardContext *ctx, int hidden_size, const int n_past, const int qlen,
ggml_tensor *key_layer, ggml_tensor *query_layer, ggml_tensor *value_layer);
// input & output: [qlen, heads, head_size]
virtual ggml_tensor *apply_pos_embedding_k(ForwardContext *ctx, ggml_tensor *k, int hidden_size, int qlen, ggml_tensor * past) const { return k; }
virtual ggml_tensor *apply_pos_embedding_q(ForwardContext *ctx, ggml_tensor *q, int hidden_size, int qlen, ggml_tensor * past) const { return q; }
virtual ggml_tensor *apply_pos_embedding_kq(ForwardContext *ctx, ggml_tensor *kq, int hidden_size, int qlen, ggml_tensor *past) const { return kq; }
virtual void before_forward(ForwardContext *ctx, const int n_past, const int qlen);
// k: [qlen, heads, head_size]
// v: [qlen, hidden_size]
virtual void save_to_cache(ForwardContext *ctx, const int n_past, const int qlen, ggml_tensor *k, ggml_tensor *v) = 0;
// output: [heads, qlen, head_size]
virtual ggml_tensor *get_k_from_cache(ForwardContext *ctx, const int hidden_size, const int n_past, const int qlen) = 0;
// output: [heads, head_size, klen]
virtual ggml_tensor *get_v_from_cache(ForwardContext *ctx, const int hidden_size, const int n_past, const int qlen) = 0;
virtual ggml_tensor *cross_attention_after_pe(ForwardContext *ctx, const int hidden_size, const int n_past, const int qlen,
ggml_tensor *query_layer, ggml_tensor *key_layer, ggml_tensor *v);
virtual ggml_tensor *cross_attention(ForwardContext *ctx, const int hidden_size, const int n_past, const int qlen,
ggml_tensor *q, ggml_tensor *k, ggml_tensor *v);
// q & k: [qlen, heads, head_size]
virtual ggml_tensor *cross_attention_3d(ForwardContext *ctx, const int hidden_size, const int n_past, const int qlen,
ggml_tensor *query_layer, ggml_tensor *key_layer, ggml_tensor *v);
ggml_tensor *get_last_attn_scores(void)
{
return last_attn_scores;
}
public:
const int num_attention_heads;
const int num_kv_heads;
ggml_tensor *k_cache;
ggml_tensor *v_cache;
ggml_tensor *pos;
const int max_length;
float attn_scaling_factor;
protected:
ShiftPending shift_pending;
bool attn_scaling;
bool causal;
ggml_tensor *last_attn_scores;
};
class KVCacheAttention : public CoreAttention
{
public:
KVCacheAttention() : CoreAttention(), k_hidden_size(0), v_hidden_size(0), cache_length(0) {}
KVCacheAttention(InitContext *ctx, int num_attention_heads, int num_kv_heads, int k_hidden_size, int v_hidden_size, int max_length,
ggml_type cache_type, int cache_length)
: CoreAttention(ctx, num_attention_heads, num_kv_heads, max_length, cache_type,
k_hidden_size * cache_length,
v_hidden_size * cache_length),
k_hidden_size(k_hidden_size),
v_hidden_size(v_hidden_size),
cache_length(cache_length)
{
}
protected:
virtual void before_forward(ForwardContext *ctx, const int n_past, const int qlen);
// k: [qlen, heads, head_size]
// v: [qlen, hidden_size]
virtual void save_to_cache(ForwardContext *ctx, const int n_past, const int qlen, ggml_tensor *k, ggml_tensor *v);
// output: [heads, qlen, head_size]
virtual ggml_tensor *get_k_from_cache(ForwardContext *ctx, const int hidden_size, const int n_past, const int qlen);
// output: [heads, head_size, klen]
virtual ggml_tensor *get_v_from_cache(ForwardContext *ctx, const int hidden_size, const int n_past, const int qlen);
public:
const int k_hidden_size;
const int v_hidden_size;
const int cache_length;
};
class BaseConsolidatedQKVAttention : public KVCacheAttention
{
public:
BaseConsolidatedQKVAttention() : KVCacheAttention() {}
BaseConsolidatedQKVAttention(InitContext *ctx, int hidden_size, int num_attention_heads, int num_kv_heads, int head_dim, int max_length, bool qkv_bias, bool o_bias)
: BaseConsolidatedQKVAttention(ctx, hidden_size, num_attention_heads, num_kv_heads, head_dim, max_length, qkv_bias, o_bias, GGML_TYPE_F16, max_length)
{}
BaseConsolidatedQKVAttention(InitContext *ctx, int hidden_size, int num_attention_heads, int num_kv_heads, int head_dim, int max_length, bool qkv_bias, bool o_bias,
ggml_type cache_type, int cache_length)
: KVCacheAttention(ctx, num_attention_heads, num_kv_heads,
head_dim * num_kv_heads,
head_dim * num_kv_heads,
max_length, cache_type, cache_length),
query_key_value(ctx, hidden_size, hidden_size + 2 * (hidden_size / num_attention_heads) * num_kv_heads, qkv_bias),
dense(ctx, hidden_size, hidden_size, o_bias)
{
}
using Block::forward;
ggml_tensor *forward(ForwardContext *ctx, ggml_tensor *hidden_states, int n_past) override;
int64_t get_param_num(bool effective_only) const override
{
int64_t r = 0;
r += query_key_value.get_param_num(effective_only);
r += dense.get_param_num(effective_only);
return r;
}
public:
Linear query_key_value;
Linear dense;
};
class BaseAttention : public KVCacheAttention
{
public:
BaseAttention() : KVCacheAttention() {}
BaseAttention(InitContext *ctx, int hidden_size, int num_attention_heads, int num_kv_heads, int head_dim, int max_length,
bool qkv_bias, bool o_bias,
ggml_type cache_type, int cache_length)
: KVCacheAttention(ctx, num_attention_heads, num_kv_heads, head_dim * num_kv_heads, head_dim * num_kv_heads, max_length, cache_type, cache_length),
q_proj(ctx, hidden_size, head_dim * num_attention_heads, nullptr, qkv_bias),
k_proj(ctx, hidden_size, head_dim * num_kv_heads, nullptr, qkv_bias),
v_proj(ctx, hidden_size, head_dim * num_kv_heads, nullptr, qkv_bias),
o_proj(ctx, head_dim * num_attention_heads, hidden_size, o_bias)
{
}
BaseAttention(InitContext *ctx, int hidden_size, int num_attention_heads, int num_kv_heads, int max_length,
bool qkv_bias, bool o_bias,
ggml_type cache_type, int cache_length)
: BaseAttention(ctx, hidden_size, num_attention_heads, num_kv_heads, hidden_size / num_attention_heads, max_length, qkv_bias, o_bias,
cache_type, cache_length)
{}
BaseAttention(InitContext *ctx, int hidden_size, int num_attention_heads, int num_kv_heads, int max_length, bool qkv_bias, bool o_bias)
: BaseAttention(ctx, hidden_size, num_attention_heads, num_kv_heads, hidden_size / num_attention_heads, max_length, qkv_bias, o_bias,
GGML_TYPE_F16, max_length)
{}
BaseAttention(InitContext *ctx, int hidden_size, int num_attention_heads, int num_kv_heads, int head_dim, int max_length,
bool qkv_bias, bool o_bias)
: BaseAttention(ctx, hidden_size, num_attention_heads, num_kv_heads, head_dim, max_length, qkv_bias, o_bias,
GGML_TYPE_F16, max_length)
{}
int64_t get_param_num(bool effective_only) const override
{
int64_t r = 0;
r += q_proj.get_param_num(effective_only);
r += k_proj.get_param_num(effective_only);
r += v_proj.get_param_num(effective_only);
r += o_proj.get_param_num(effective_only);
return r;
}
using Block::forward;
ggml_tensor *forward(ForwardContext *ctx, ggml_tensor *hidden_states, int n_past) override;
public:
Linear q_proj, k_proj, v_proj;
Linear o_proj;
};
class BaseCachelessAttention : public BaseAttention
{
public:
BaseCachelessAttention() = default;
BaseCachelessAttention(InitContext *ctx, int hidden_size, int num_attention_heads, int num_kv_heads, int max_length, bool qkv_bias, bool o_bias)
: BaseCachelessAttention(ctx, hidden_size, num_attention_heads, num_kv_heads, hidden_size / num_attention_heads, max_length, qkv_bias, o_bias)
{}
BaseCachelessAttention(InitContext *ctx, int hidden_size, int num_attention_heads, int num_kv_heads, int head_dim, int max_length, bool qkv_bias, bool o_bias)
: BaseAttention(ctx, hidden_size, num_attention_heads, num_kv_heads, head_dim, max_length, qkv_bias, o_bias, GGML_TYPE_F16, 0),
raw_k(nullptr),
raw_v(nullptr)
{}
protected:
void save_to_cache(ForwardContext *ctx, const int n_past, const int qlen, ggml_tensor *k, ggml_tensor *v) override;
// output: [heads, qlen, head_size]
ggml_tensor *get_k_from_cache(ForwardContext *ctx, const int hidden_size, const int n_past, const int qlen) override;
// output: [heads, head_size, klen]
ggml_tensor *get_v_from_cache(ForwardContext *ctx, const int hidden_size, const int n_past, const int qlen) override;
private:
ggml_tensor *raw_k;
ggml_tensor *raw_v;
};
void fill_pos_vector(ggml_tensor *pos, int n_past, int qlen);
// TODO: Optimize this !!! (after ggml support matrix with ring buffer?)
// qlen must be 1.
// This is just a proof of concept.
template <int sliding_window_len> class BaseSlidingWindowAttentionRingCache : public BaseAttention
{
public:
BaseSlidingWindowAttentionRingCache(InitContext *ctx, int hidden_size, int num_attention_heads, int num_kv_heads, int max_length, bool qkv_bias, bool o_bias)
: BaseAttention(ctx, hidden_size, num_attention_heads, num_kv_heads, max_length, qkv_bias, o_bias, GGML_TYPE_F16, sliding_window_len),
cache_offset(0),
indices(ggml_new_tensor_1d(ctx->gctx.get(), GGML_TYPE_I32, sliding_window_len))
{
indices->data = new char[ggml_nbytes(indices)];
}
protected:
void before_forward(ForwardContext *ctx, const int n_past, const int qlen) override
{
if (n_past == 0) cache_offset = 0;
fill_pos_vector(pos, n_past, qlen);
// shift cache
if (shift_pending.shift > 0)
{
cache_offset += shift_pending.shift;
shift_pending.clear();
}
}
void save_to_cache(ForwardContext *ctx, const int n_past, const int qlen, ggml_tensor *k, ggml_tensor *v) override
{