forked from skeskinen/bert.cpp
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathbert.cpp
More file actions
1599 lines (1326 loc) · 51.7 KB
/
Copy pathbert.cpp
File metadata and controls
1599 lines (1326 loc) · 51.7 KB
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
#include "bert.h"
#include "ggml.h"
#include "gguf.h"
#include "tokenizer.h"
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <fstream>
#include <map>
#include <string>
#include <vector>
#include <iostream>
#include <regex>
#include <thread>
#include <algorithm>
// default hparams (all-MiniLM-L6-v2)
struct bert_hparams
{
int32_t n_vocab = 30522;
int32_t n_max_tokens = 512;
int32_t n_embd = 256;
int32_t n_intermediate = 1536;
int32_t n_head = 12;
int32_t n_layer = 6;
int32_t n_vocab_size = 2;
int32_t f16 = 0;
float eps = 1e-12;
};
struct bert_layer
{
// normalization
struct ggml_tensor *ln_att_w;
struct ggml_tensor *ln_att_b;
struct ggml_tensor *ln_out_w;
struct ggml_tensor *ln_out_b;
// attention
struct ggml_tensor *q_w;
struct ggml_tensor *q_b;
struct ggml_tensor *k_w;
struct ggml_tensor *k_b;
struct ggml_tensor *v_w;
struct ggml_tensor *v_b;
struct ggml_tensor *o_w;
struct ggml_tensor *o_b;
// ff
struct ggml_tensor *ff_i_w;
struct ggml_tensor *ff_i_b;
struct ggml_tensor *ff_o_w;
struct ggml_tensor *ff_o_b;
};
struct bert_model
{
bert_hparams hparams;
// embeddings weights
struct ggml_tensor *word_embeddings;
struct ggml_tensor *token_type_embeddings;
struct ggml_tensor *position_embeddings;
struct ggml_tensor *ln_e_w;
struct ggml_tensor *ln_e_b;
std::vector<bert_layer> layers;
struct ggml_context *ctx;
struct gguf_context *gguf;
std::map<std::string, struct ggml_tensor *> tensors;
};
// Replacement for std::vector<uint8_t> that doesn't require zero-initialization.
struct bert_buffer
{
uint8_t *data = NULL;
size_t size = 0;
void resize(size_t size)
{
delete[] data;
data = new uint8_t[size];
this->size = size;
}
~bert_buffer()
{
delete[] data;
}
};
struct bert_vocab
{
using id = int32_t;
using token = std::string;
using ttype = gguf_token_type;
struct token_data
{
token text;
float score;
ttype type;
};
std::string tokenizer_json;
std::unordered_map<token, id> token_to_id;
std::vector<token_data> id_to_token;
std::map<std::pair<std::string, std::string>, int> bpe_ranks;
// default bert special tokens
id special_bos_id = 1;
id special_eos_id = 2;
id special_unk_id = 0;
id special_sep_id = -1; // init with -1 to make it easy to check, default in bert is 102
id special_pad_id = -1; // default in bert is 0
id special_cls_id = -1; // default in bert is 101
};
struct bert_ctx
{
bert_model model;
bert_vocab vocab;
bert_tokenizer tokenizer;
size_t mem_per_token;
int64_t mem_per_input;
int32_t max_batch_n;
bert_buffer buf_compute;
};
//
// Loading and setup
//
struct bert_loader
{
int n_kv = 0;
int n_tensors = 0;
int n_created = 0;
int64_t n_elements = 0;
size_t n_bytes = 0;
bool use_mmap = false;
ggml_type ftype = ggml_type::GGML_TYPE_COUNT;
gguf_file file;
gguf_fver fver;
struct gguf_context *ctx_gguf = NULL;
struct ggml_context *ctx_meta = NULL;
~bert_loader()
{
if (ctx_gguf)
{
gguf_free(ctx_gguf);
}
if (ctx_meta)
{
ggml_free(ctx_meta);
}
}
bert_loader(const char *fname) : file(fname, "rb")
{
struct gguf_init_params params = {
/*.no_alloc = */ true,
/*.ctx = */ &ctx_meta,
};
ctx_gguf = gguf_init_from_file(fname, params);
if (!ctx_gguf)
{
throw std::runtime_error(format("%s: failed to load model from %s\n", __func__, fname));
}
n_kv = gguf_get_n_kv(ctx_gguf);
n_tensors = gguf_get_n_tensors(ctx_gguf);
fver = (gguf_fver)gguf_get_version(ctx_gguf);
for (int i = 0; i < n_tensors; i++)
{
const char *name = gguf_get_tensor_name(ctx_gguf, i);
struct ggml_tensor *t = ggml_get_tensor(ctx_meta, name);
if (t == NULL)
{
throw std::runtime_error(format("%s: can not get tensor %s\n", __func__, name));
}
n_elements += ggml_nelements(t);
n_bytes += ggml_nbytes(t);
}
printf("%s: loaded meta data with %d key-value pairs and %d tensors from %s (version %s)\n",
__func__, n_kv, n_tensors, fname, gguf_file_version_name(fver));
// determine file type based on the number of tensors for each quantization and print meta data
// TODO: make optional
{
std::map<enum ggml_type, uint32_t> n_type;
uint32_t n_type_max = 0;
enum ggml_type type_max = GGML_TYPE_F32;
for (int i = 0; i < n_tensors; i++)
{
const char *name = gguf_get_tensor_name(ctx_gguf, i);
struct ggml_tensor *meta = ggml_get_tensor(ctx_meta, name);
n_type[meta->type]++;
if (n_type_max < n_type[meta->type])
{
n_type_max = n_type[meta->type];
type_max = meta->type;
}
printf("%s: - tensor %4d: %32s %-8s [ %s ]\n", __func__, i, name, ggml_type_name(meta->type), format_tensor_shape(meta).c_str());
}
switch (type_max)
{
case GGML_TYPE_F32:
case GGML_TYPE_F16:
case GGML_TYPE_Q4_0:
case GGML_TYPE_Q4_1:
// case GGML_TYPE_Q5_0:
// case GGML_TYPE_Q5_1:
// case GGML_TYPE_Q8_0:
// case GGML_TYPE_Q2_K:
// case GGML_TYPE_Q3_K:
// case GGML_TYPE_Q4_K:
// case GGML_TYPE_Q5_K:
// case GGML_TYPE_Q6_K:
ftype = type_max;
break;
default:
{
// LLAMA_LOG_WARN("%s: unknown type %s\n", __func__, ggml_type_name(type_max));
ftype = ggml_type::GGML_TYPE_COUNT;
}
break;
}
// this is a way to mark that we have "guessed" the file type
// ftype = (llama_ftype)(ftype | LLAMA_FTYPE_GUESSED);
// {
// const int kid = gguf_find_key(ctx_gguf, "general.file_type");
// if (kid >= 0)
// {
// ftype = (llama_ftype)gguf_get_val_u32(ctx_gguf, kid);
// }
// }
for (int i = 0; i < n_kv; i++)
{
const char *name = gguf_get_key(ctx_gguf, i);
const enum gguf_type type = gguf_get_kv_type(ctx_gguf, i);
printf("%s: - kv %3d: %42s %-8s\n", __func__, i, name, gguf_type_name(type));
}
// print type counts
for (auto &kv : n_type)
{
if (kv.second == 0)
{
continue;
}
printf("%s: - type %4s: %4d tensors\n", __func__, ggml_type_name(kv.first), kv.second);
}
}
// if (!llama_mmap::SUPPORTED) {
// LLAMA_LOG_WARN("%s: mmap is not supported on this platform\n", __func__);
// use_mmap = false;
// }
// this->use_mmap = use_mmap;
}
const char *get_tensor_name(int i) const
{
return gguf_get_tensor_name(ctx_gguf, i);
}
struct ggml_tensor *get_tensor_meta(int i) const
{
return ggml_get_tensor(ctx_meta, get_tensor_name(i));
}
void calc_sizes(bert_model &model, size_t &ctx_size_p, size_t &mmapped_size_p) const
{
// ctx_size_p = 0;
// mmapped_size_p = 0;
// for (int i = 0; i < n_tensors; i++)
// {
// struct ggml_tensor *meta = get_tensor_meta(i);
// ctx_size_p += sizeof(struct ggml_tensor) + GGML_OBJECT_SIZE;
// (use_mmap ? mmapped_size_p : ctx_size_p) += ggml_nbytes_pad(meta);
// }
const auto &hparams = model.hparams;
const int n_embd = hparams.n_embd;
const int n_layer = hparams.n_layer;
const int n_max_tokens = hparams.n_max_tokens;
const int n_intermediate = hparams.n_intermediate;
const int n_vocab = hparams.n_vocab;
// Calculate size requirements
mmapped_size_p += n_embd * n_vocab * ggml_type_sizef(ftype); // word_embeddings
mmapped_size_p += n_embd * 2 * ggml_type_sizef(ftype); // token_type_embeddings
mmapped_size_p += n_embd * n_max_tokens * ggml_type_sizef(ftype); // position_embeddings
mmapped_size_p += 2 * n_embd * ggml_type_sizef(GGML_TYPE_F32); // ln_e_*
mmapped_size_p += 4 * n_layer * (n_embd * ggml_type_sizef(GGML_TYPE_F32)); // ln_*
mmapped_size_p += 4 * n_layer * (n_embd * n_embd * ggml_type_sizef(ftype)); // kqvo weights
mmapped_size_p += 4 * n_layer * (n_embd * ggml_type_sizef(GGML_TYPE_F32)); // kqvo bias
mmapped_size_p += 2 * n_layer * (n_embd * n_intermediate * ggml_type_sizef(ftype)); // ff_*_w
mmapped_size_p += n_layer * (n_intermediate * ggml_type_sizef(GGML_TYPE_F32)); // ff_i_b
mmapped_size_p += n_layer * (n_embd * ggml_type_sizef(GGML_TYPE_F32)); // ff_o_b
mmapped_size_p += (5 + 16 * n_layer) * 512; // object overhead
printf("%s: ggml ctx size = %6.2f MB\n", __func__, mmapped_size_p / (1024.0 * 1024.0));
}
struct ggml_tensor *create_tensor_for(struct ggml_context *ctx, struct ggml_tensor *meta, ggml_backend_type backend)
{
if (backend != GGML_BACKEND_CPU)
{
ggml_set_no_alloc(ctx, true);
}
struct ggml_tensor *tensor = ggml_dup_tensor(ctx, meta);
tensor->backend = backend; // TODO: ggml_set_backend
ggml_set_name(tensor, ggml_get_name(meta));
if (backend != GGML_BACKEND_CPU)
{
ggml_set_no_alloc(ctx, use_mmap);
}
n_created++;
return tensor;
}
struct ggml_tensor *create_tensor(struct ggml_context *ctx, const std::string &name, const std::vector<int64_t> &ne, ggml_backend_type backend)
{
struct ggml_tensor *cur = ggml_get_tensor(ctx_meta, name.c_str());
if (cur == NULL)
{
throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name.c_str()));
}
{
bool is_ok = true;
for (size_t i = 0; i < ne.size(); ++i)
{
if (ne[i] != cur->ne[i])
{
is_ok = false;
break;
}
}
if (!is_ok)
{
throw std::runtime_error(
format("%s: tensor '%s' has wrong shape; expected %s, got %s",
__func__, name.c_str(),
format_tensor_shape(ne).c_str(),
format_tensor_shape(cur).c_str()));
}
}
return create_tensor_for(ctx, cur, backend);
}
size_t file_offset(const char *name) const
{
const int idx = gguf_find_tensor(ctx_gguf, name);
if (idx < 0)
{
throw std::runtime_error(format("%s: tensor '%s' not found in the file", __func__, name));
}
return gguf_get_data_offset(ctx_gguf) + gguf_get_tensor_offset(ctx_gguf, idx);
}
void load_data_for(struct ggml_tensor *cur) const
{
const size_t offs = file_offset(ggml_get_name(cur));
file.seek(offs, SEEK_SET);
file.read_raw(cur->data, ggml_nbytes(cur));
// if (use_mmap)
// {
// cur->data = (uint8_t *)mapping->addr + offs;
// }
// else
// {
// file.seek(offs, SEEK_SET);
// file.read_raw(cur->data, ggml_nbytes(cur));
// }
}
void load_all_data(struct ggml_context *ctx)
{
size_t size_data = 0;
size_t size_lock = 0;
size_t size_pref = 0; // prefetch
for (int i = 0; i < gguf_get_n_tensors(ctx_gguf); i++)
{
struct ggml_tensor *cur = ggml_get_tensor(ctx, gguf_get_tensor_name(ctx_gguf, i));
size_data += ggml_nbytes(cur);
if (cur->backend == GGML_BACKEND_CPU)
{
size_pref += ggml_nbytes(cur);
}
}
// if (use_mmap)
// {
// mapping.reset(new llama_mmap(&file, size_pref, ggml_is_numa()));
// if (lmlock)
// {
// lmlock->init(mapping->addr);
// }
// }
size_t done_size = 0;
for (int i = 0; i < gguf_get_n_tensors(ctx_gguf); i++)
{
struct ggml_tensor *cur = ggml_get_tensor(ctx, gguf_get_tensor_name(ctx_gguf, i));
GGML_ASSERT(cur); // unused tensors should have been caught by load_data already
// allocate temp buffer if not using mmap
if (!use_mmap && cur->data == NULL)
{
GGML_ASSERT(cur->backend != GGML_BACKEND_CPU);
#ifdef GGML_USE_CPU_HBM
cur->data = (uint8_t *)hbw_malloc(ggml_nbytes(cur));
#else
cur->data = (uint8_t *)malloc(ggml_nbytes(cur));
#endif
}
load_data_for(cur);
done_size += ggml_nbytes(cur);
}
}
void llm_print_meta(bert_ctx *bert)
{
auto &hparams = bert->model.hparams;
printf("%s: n_vocab = %d\n", __func__, hparams.n_vocab);
printf("%s: n_max_tokens = %d\n", __func__, hparams.n_max_tokens);
printf("%s: n_embd = %d\n", __func__, hparams.n_embd);
printf("%s: n_intermediate = %d\n", __func__, hparams.n_intermediate);
printf("%s: n_head = %d\n", __func__, hparams.n_head);
printf("%s: n_layer = %d\n", __func__, hparams.n_layer);
printf("%s: n_vocab_size = %d\n", __func__, hparams.n_vocab_size);
printf("%s: f16 = %d\n", __func__, hparams.f16);
auto &vocab = bert->vocab;
printf("%s: vocab.special_bos_id = %d\n", __func__, vocab.special_bos_id);
printf("%s: vocab.special_eos_id = %d\n", __func__, vocab.special_eos_id);
printf("%s: vocab.special_unk_id = %d\n", __func__, vocab.special_unk_id);
printf("%s: vocab.special_sep_id = %d\n", __func__, vocab.special_sep_id);
printf("%s: vocab.special_pad_id = %d\n", __func__, vocab.special_pad_id);
printf("%s: vocab.special_cls_id = %d\n", __func__, vocab.special_cls_id);
}
void llm_load_hparams(bert_ctx *bert, const LLM_KV &kv)
{
// auto *ctx = bert->model.gguf;
auto *ctx = ctx_gguf;
bert_hparams &hparams = bert->model.hparams;
// get general kv
// GGUF_GET_KEY(ctx, model.name, gguf_get_val_str, GGUF_TYPE_STRING, false, kv(LLM_KV_GENERAL_NAME));
// get hparams kv
GGUF_GET_KEY(ctx, hparams.n_vocab, gguf_get_arr_n, GGUF_TYPE_ARRAY, true, kv(LLM_KV_TOKENIZER_LIST));
GGUF_GET_KEY(ctx, hparams.n_max_tokens, gguf_get_val_u32, GGUF_TYPE_UINT32, true, kv(LLM_KV_CONTEXT_LENGTH));
GGUF_GET_KEY(ctx, hparams.n_embd, gguf_get_val_u32, GGUF_TYPE_UINT32, true, kv(LLM_KV_EMBEDDING_LENGTH));
GGUF_GET_KEY(ctx, hparams.n_intermediate, gguf_get_val_u32, GGUF_TYPE_UINT32, true, kv(LLM_KV_FEED_FORWARD_LENGTH));
GGUF_GET_KEY(ctx, hparams.n_head, gguf_get_val_u32, GGUF_TYPE_UINT32, true, kv(LLM_KV_ATTENTION_HEAD_COUNT));
GGUF_GET_KEY(ctx, hparams.n_layer, gguf_get_val_u32, GGUF_TYPE_UINT32, true, kv(LLM_KV_BLOCK_COUNT));
GGUF_GET_KEY(ctx, hparams.eps, gguf_get_val_f32, GGUF_TYPE_FLOAT32, true, kv(LLM_KV_ATTENTION_LAYERNORM_EPS));
}
void llm_load_tokenizer(bert_ctx *bert, const LLM_KV &kv)
{
bert_model &model = bert->model;
bert_vocab &vocab = bert->vocab;
auto *ctx = ctx_gguf;
// general
const int token_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_LIST).c_str());
if (token_idx == -1)
{
throw std::runtime_error("cannot find tokenizer vocab in model file\n");
}
const int score_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_SCORES).c_str());
if (score_idx == -1)
{
throw std::runtime_error("cannot find tokenizer scores in model file\n");
}
const float *scores = (const float *)gguf_get_arr_data(ctx, score_idx);
const int toktype_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_TOKEN_TYPE).c_str());
if (toktype_idx == -1)
{
throw std::runtime_error("cannot find token type list in GGUF file\n");
}
const int *toktypes = (const int *)gguf_get_arr_data(ctx, toktype_idx);
// determine vocab type
{
std::string tokenizer_name;
GGUF_GET_KEY(ctx, tokenizer_name, gguf_get_val_str, GGUF_TYPE_STRING, true, kv(LLM_KV_TOKENIZER_MODEL));
}
const uint32_t n_vocab = gguf_get_arr_n(ctx, token_idx);
vocab.id_to_token.resize(n_vocab);
for (uint32_t i = 0; i < n_vocab; i++)
{
std::string word = gguf_get_arr_str(ctx, token_idx, i);
vocab.token_to_id[word] = i;
auto &token_data = vocab.id_to_token[i];
token_data.text = std::move(word);
token_data.score = scores[i];
token_data.type = (gguf_token_type)toktypes[i];
}
// special tokens
GGUF_GET_KEY(ctx, vocab.special_bos_id, gguf_get_val_u32, GGUF_TYPE_UINT32, false, kv(LLM_KV_TOKENIZER_BOS_ID));
GGUF_GET_KEY(ctx, vocab.special_eos_id, gguf_get_val_u32, GGUF_TYPE_UINT32, false, kv(LLM_KV_TOKENIZER_EOS_ID));
GGUF_GET_KEY(ctx, vocab.special_unk_id, gguf_get_val_u32, GGUF_TYPE_UINT32, false, kv(LLM_KV_TOKENIZER_UNK_ID));
GGUF_GET_KEY(ctx, vocab.special_sep_id, gguf_get_val_u32, GGUF_TYPE_UINT32, false, kv(LLM_KV_TOKENIZER_SEP_ID));
GGUF_GET_KEY(ctx, vocab.special_pad_id, gguf_get_val_u32, GGUF_TYPE_UINT32, false, kv(LLM_KV_TOKENIZER_PAD_ID));
GGUF_GET_KEY(ctx, vocab.special_cls_id, gguf_get_val_u32, GGUF_TYPE_UINT32, false, kv(LLM_KV_TOKENIZER_CLS_ID));
// extra kv process for tokenizers-cpp
GGUF_GET_KEY(ctx, vocab.tokenizer_json, gguf_get_val_str, GGUF_TYPE_STRING, true, "blob.tokenizer.json");
bert->tokenizer.load(vocab.tokenizer_json);
}
void llm_load_tensors(bert_ctx *bert)
{
bert_model &model = bert->model;
size_t mmapped_size_p = 0;
size_t tx_size_p = 0;
calc_sizes(model, tx_size_p, mmapped_size_p);
// create the ggml context
{
struct ggml_init_params params = {
.mem_size = mmapped_size_p,
.mem_buffer = NULL,
.no_alloc = false,
};
model.ctx = ggml_init(params);
if (!model.ctx)
{
throw std::runtime_error(format("%s: ggml_init() failed\n", __func__));
}
}
// prepare memory for the weights
{
const auto &hparams = model.hparams;
auto *ctx = model.ctx;
const int n_embd = hparams.n_embd;
const int n_layer = hparams.n_layer;
const int n_intermediate = hparams.n_intermediate;
const int n_max_tokens = hparams.n_max_tokens;
const int n_vocab = hparams.n_vocab;
const int n_vocab_size = hparams.n_vocab_size;
const ggml_backend_type backend = GGML_BACKEND_CPU;
size_t ctx_size;
size_t mmapped_size;
model.layers.resize(n_layer);
model.word_embeddings = create_tensor(ctx, "embeddings.word_embeddings.weight", {n_embd, n_vocab}, backend);
model.token_type_embeddings = create_tensor(ctx, "embeddings.token_type_embeddings.weight", {n_embd, n_vocab_size}, backend);
model.position_embeddings = create_tensor(ctx, "embeddings.position_embeddings.weight", {n_embd, n_max_tokens}, backend);
model.ln_e_w = create_tensor(ctx, "embeddings.LayerNorm.weight", {n_embd}, backend);
model.ln_e_b = create_tensor(ctx, "embeddings.LayerNorm.bias", {n_embd}, backend);
for (int i = 0; i < n_layer; ++i)
{
auto &layer = model.layers[i];
layer.ln_att_w = create_tensor(ctx, "encoder.layer." + std::to_string(i) + ".attention.output.LayerNorm.weight", {n_embd}, backend);
layer.ln_att_b = create_tensor(ctx, "encoder.layer." + std::to_string(i) + ".attention.output.LayerNorm.bias", {n_embd}, backend);
layer.ln_out_w = create_tensor(ctx, "encoder.layer." + std::to_string(i) + ".output.LayerNorm.weight", {n_embd}, backend);
layer.ln_out_b = create_tensor(ctx, "encoder.layer." + std::to_string(i) + ".output.LayerNorm.bias", {n_embd}, backend);
layer.q_w = create_tensor(ctx, "encoder.layer." + std::to_string(i) + ".attention.self.query.weight", {n_embd, n_embd}, backend);
layer.q_b = create_tensor(ctx, "encoder.layer." + std::to_string(i) + ".attention.self.query.bias", {n_embd}, backend);
layer.k_w = create_tensor(ctx, "encoder.layer." + std::to_string(i) + ".attention.self.key.weight", {n_embd, n_embd}, backend);
layer.k_b = create_tensor(ctx, "encoder.layer." + std::to_string(i) + ".attention.self.key.bias", {n_embd}, backend);
layer.v_w = create_tensor(ctx, "encoder.layer." + std::to_string(i) + ".attention.self.value.weight", {n_embd, n_embd}, backend);
layer.v_b = create_tensor(ctx, "encoder.layer." + std::to_string(i) + ".attention.self.value.bias", {n_embd}, backend);
layer.o_w = create_tensor(ctx, "encoder.layer." + std::to_string(i) + ".attention.output.dense.weight", {n_embd, n_embd}, backend);
layer.o_b = create_tensor(ctx, "encoder.layer." + std::to_string(i) + ".attention.output.dense.bias", {n_embd}, backend);
layer.ff_i_w = create_tensor(ctx, "encoder.layer." + std::to_string(i) + ".intermediate.dense.weight", {n_embd, n_intermediate}, backend);
layer.ff_i_b = create_tensor(ctx, "encoder.layer." + std::to_string(i) + ".intermediate.dense.bias", {n_intermediate}, backend);
layer.ff_o_w = create_tensor(ctx, "encoder.layer." + std::to_string(i) + ".output.dense.weight", {n_intermediate, n_embd}, backend);
layer.ff_o_b = create_tensor(ctx, "encoder.layer." + std::to_string(i) + ".output.dense.bias", {n_embd}, backend);
}
}
// load read weights
load_all_data(model.ctx);
}
};
int32_t bert_n_embd(bert_ctx *ctx)
{
return ctx->model.hparams.n_embd;
}
int32_t bert_n_max_tokens(bert_ctx *ctx)
{
return ctx->model.hparams.n_max_tokens;
}
const char *bert_vocab_id_to_token(bert_ctx *ctx, bert_vocab_id id)
{
bert_vocab &vocab = ctx->vocab;
return vocab.id_to_token.at(id).text.c_str();
}
//
// Cli interface
//
void bert_print_usage(char **argv, const bert_params ¶ms)
{
fprintf(stderr, "usage: %s [options]\n", argv[0]);
fprintf(stderr, "\n");
fprintf(stderr, "options:\n");
fprintf(stderr, " -h, --help show this help message and exit\n");
fprintf(stderr, " -s SEED, --seed SEED RNG seed (default: -1)\n");
fprintf(stderr, " -t N, --threads N number of threads to use during computation (default: %d)\n", params.n_threads);
fprintf(stderr, " -p PROMPT, --prompt PROMPT\n");
fprintf(stderr, " prompt to start generation with (default: random)\n");
fprintf(stderr, " --port p port to bind in server mode (default: %d)\n", params.port);
fprintf(stderr, " -m FNAME, --model FNAME\n");
fprintf(stderr, " model path (default: %s)\n", params.model);
fprintf(stderr, "\n");
}
bool bert_params_parse(int argc, char **argv, bert_params ¶ms)
{
for (int i = 1; i < argc; i++)
{
std::string arg = argv[i];
if (arg == "-t" || arg == "--threads")
{
params.n_threads = std::stoi(argv[++i]);
}
else if (arg == "-p" || arg == "--prompt")
{
params.prompt = argv[++i];
}
else if (arg == "--port")
{
params.port = std::stoi(argv[++i]);
}
else if (arg == "-m" || arg == "--model")
{
params.model = argv[++i];
}
else if (arg == "-h" || arg == "--help")
{
bert_print_usage(argv, params);
exit(0);
}
else
{
fprintf(stderr, "error: unknown argument: %s\n", arg.c_str());
bert_print_usage(argv, params);
exit(0);
}
}
return true;
}
//
// Tokenizing
//
void bert_tokenize(
struct bert_ctx *ctx,
const char *text,
bert_vocab_id *tokens,
int32_t *n_tokens,
int32_t n_max_tokens)
{
auto &tokenizer = ctx->tokenizer;
// TODO: add normalization
// call Encode to turn prompt into token ids
std::vector<int> ids = tokenizer.encode(text);
int cls_tok_id = ctx->vocab.special_cls_id;
int sep_tok_id = ctx->vocab.special_sep_id;
int pad_tok_id = ctx->vocab.special_pad_id;
int32_t t = 0;
tokens[t++] = cls_tok_id;
for (auto it = ids.begin(); it != ids.end(); it++)
{
// since tokenizers-cpp may do some padding (according to tokenizer.json)
if (*it == pad_tok_id)
{
break;
}
tokens[t++] = *it;
if (t >= n_max_tokens)
{
break;
}
}
if (t >= n_max_tokens)
{
tokens[n_max_tokens - 1] = sep_tok_id;
}
else
{
tokens[t++] = sep_tok_id;
}
*n_tokens = t;
}
struct bert_ctx *
bert_load_from_file(const char *fname)
{
printf("%s: loading model from '%s' - please wait ...\n", __func__, fname);
auto *loader = new bert_loader(fname);
bert_ctx *new_bert = new bert_ctx;
bert_model &model = new_bert->model;
bert_vocab &vocab = new_bert->vocab;
const auto kv = LLM_KV(LLM_ARCH_BERT);
loader->llm_load_hparams(new_bert, kv);
loader->llm_load_tokenizer(new_bert, kv);
loader->llm_print_meta(new_bert);
loader->llm_load_tensors(new_bert);
printf(" done\n");
// Calculate space requirements for setting up context buffers later
{
bert_vocab_id tokens[] = {0, 1, 2, 3};
// TODO: We set the initial buffer size to 32MB and hope it's enough. Maybe there is a better way to do this?
new_bert->buf_compute.resize(32 * 1024 * 1024);
bert_eval(new_bert, 1, tokens, 4, nullptr);
new_bert->max_batch_n = 0;
// TODO: Max tokens should be a param?
int32_t N = new_bert->model.hparams.n_max_tokens;
new_bert->mem_per_input = 1.1 * (new_bert->mem_per_token * N); // add 10% to account for ggml object overhead
}
printf("%s: mem_per_token %zu KB, mem_per_input %lld MB\n", __func__, new_bert->mem_per_token / (1 << 10), new_bert->mem_per_input / (1 << 20));
return new_bert;
}
void bert_resize_ctx(bert_ctx *ctx, int32_t new_size)
{
int64_t buf_size_new = ctx->mem_per_input * new_size;
// TODO: Max memory should be a param? Now just 1 GB
int64_t GB = 1 << 30;
// printf("%s: requested_buf_size %lldMB\n", __func__, buf_size_new / (1 << 20));
if (buf_size_new > GB)
{
int32_t adjusted_new_size = GB / ctx->mem_per_input;
if (adjusted_new_size < 1)
adjusted_new_size = 1;
// printf("%s: requested batch size %d, actual new batch size %d\n", __func__, new_size, adjusted_new_size);
new_size = adjusted_new_size;
buf_size_new = ctx->mem_per_input * new_size;
}
if (new_size > ctx->max_batch_n)
{
ctx->buf_compute.resize(buf_size_new);
ctx->max_batch_n = new_size;
}
}
// build the bert model graph with given tokens
static ggml_cgraph *bert_build(bert_ctx *ctx, struct ggml_context *ctx0, bert_vocab_id *const tokens, int N)
{
const bert_model &model = ctx->model;
const float eps = model.hparams.eps;
const auto &hparams = model.hparams;
const int n_embd = hparams.n_embd;
const int n_layer = hparams.n_layer;
const int n_max_tokens = hparams.n_max_tokens;
const int n_head = hparams.n_head;
const int d_head = n_embd / n_head;
auto &mem_per_token = ctx->mem_per_token;
auto &buf_compute = ctx->buf_compute;
ggml_cgraph *gf = ggml_new_graph(ctx0);
// Embeddings. word_embeddings + token_type_embeddings + position_embeddings
// in bert, it is
// token_embedding + segment_embedding + position_embedding
struct ggml_tensor *token_layer = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, N);
memcpy(token_layer->data, tokens, N * ggml_element_size(token_layer));
struct ggml_tensor *token_types = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, N);
ggml_set_zero(token_types);
struct ggml_tensor *positions = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, N);
for (int i = 0; i < N; i++)
{
ggml_set_i32_1d(positions, i, i);
}
struct ggml_tensor *inpL = ggml_get_rows(ctx0, model.word_embeddings, token_layer);
inpL = ggml_add(ctx0,
ggml_get_rows(ctx0, model.token_type_embeddings, token_types),
inpL);
inpL = ggml_add(ctx0,
ggml_get_rows(ctx0, model.position_embeddings, positions),
inpL);
// embd norm
{
inpL = ggml_norm(ctx0, inpL, eps);
inpL = ggml_add(ctx0,
ggml_mul(ctx0,
ggml_repeat(ctx0, model.ln_e_w, inpL),
inpL),
ggml_repeat(ctx0, model.ln_e_b, inpL));
}
// layers
for (int il = 0; il < n_layer; il++)
{
struct ggml_tensor *cur = inpL;
// self-attention (multiple head)
{
// linear
struct ggml_tensor *Qcur = cur;
Qcur = ggml_reshape_3d(ctx0,
ggml_add(ctx0, ggml_repeat(ctx0, model.layers[il].q_b, Qcur),
ggml_mul_mat(ctx0, model.layers[il].q_w, Qcur)),
d_head, n_head, N);
struct ggml_tensor *Q = ggml_permute(ctx0, Qcur, 0, 2, 1, 3);
struct ggml_tensor *Kcur = cur;
Kcur = ggml_reshape_3d(ctx0,
ggml_add(ctx0, ggml_repeat(ctx0, model.layers[il].k_b, Kcur),
ggml_mul_mat(ctx0, model.layers[il].k_w, Kcur)),
d_head, n_head, N);
struct ggml_tensor *K = ggml_permute(ctx0, Kcur, 0, 2, 1, 3);
struct ggml_tensor *Vcur = cur;
Vcur = ggml_reshape_3d(ctx0,
ggml_add(ctx0, ggml_repeat(ctx0, model.layers[il].v_b, Vcur),
ggml_mul_mat(ctx0, model.layers[il].v_w, Vcur)),
d_head, n_head, N);
struct ggml_tensor *V = ggml_permute(ctx0, Vcur, 0, 2, 1, 3);
// Scaled Dot-Product Attention
// KQ = soft_max(KQ / sqrt(head width))
struct ggml_tensor *KQ = ggml_mul_mat(ctx0, K, Q);
KQ = ggml_soft_max(ctx0,
ggml_scale(ctx0,
KQ,
ggml_new_f32(ctx0, 1.0f / sqrt((float)d_head))));
V = ggml_cont(ctx0, ggml_transpose(ctx0, V));
struct ggml_tensor *KQV = ggml_mul_mat(ctx0, V, KQ);
KQV = ggml_permute(ctx0, KQV, 0, 2, 1, 3);
cur = ggml_cpy(ctx0,
KQV,
ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, N));
}
// attention output
cur = ggml_add(ctx0,
ggml_repeat(ctx0, model.layers[il].o_b, cur),
ggml_mul_mat(ctx0, model.layers[il].o_w, cur));
// Add & Norm
// re-add the layer input
cur = ggml_add(ctx0, cur, inpL);
// attention norm
{
cur = ggml_norm(ctx0, cur, eps);
cur = ggml_add(ctx0,
ggml_mul(ctx0,
ggml_repeat(ctx0, model.layers[il].ln_att_w, cur),
cur),
ggml_repeat(ctx0, model.layers[il].ln_att_b, cur));
}
struct ggml_tensor *att_output = cur;
// Forward Feed
// intermediate_output = self.intermediate(attention_output)
cur = ggml_mul_mat(ctx0, model.layers[il].ff_i_w, cur);
cur = ggml_add(ctx0,
ggml_repeat(ctx0, model.layers[il].ff_i_b, cur),
cur);
cur = ggml_gelu(ctx0, cur);
// layer_output = self.output(intermediate_output, attention_output)
cur = ggml_mul_mat(ctx0, model.layers[il].ff_o_w, cur);
cur = ggml_add(ctx0,
ggml_repeat(ctx0, model.layers[il].ff_o_b, cur),
cur);
// Add & Norm
// attentions bypass the intermediate layer
cur = ggml_add(ctx0, att_output, cur);
// output norm
{
cur = ggml_norm(ctx0, cur, eps);
cur = ggml_add(ctx0,
ggml_mul(ctx0,
ggml_repeat(ctx0, model.layers[il].ln_out_w, cur),
cur),
ggml_repeat(ctx0, model.layers[il].ln_out_b, cur));
}
inpL = cur;
}
inpL = ggml_cont(ctx0, ggml_transpose(ctx0, inpL));
// pooling
// FIXME: pooling method is hard code here
struct ggml_tensor *sum = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, N, 1);
ggml_set_f32(sum, 1.0f / N);