FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
chatglm.cpp/chatglm.cpp at main · li-plus/chatglm.cpp · GitHub
li-plus
/
chatglm.cpp
Public
Notifications
You must be signed in to change notification settings
Fork
326
Star
3k
Code
Issues
159
Pull requests
1
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
chatglm.cpp
/
chatglm.cpp
Copy path
More file actions
More file actions
Latest commit
History
History
History
2244 lines (1934 loc) · 95.2 KB
Breadcrumbs
chatglm.cpp
/
chatglm.cpp
Copy path
File metadata and controls
2244 lines (1934 loc) · 95.2 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
"
chatglm.h
"
#
include
<
algorithm
>
#
include
<
codecvt
>
#
include
<
cstring
>
#
include
<
fcntl.h
>
#
include
<
fstream
>
#
include
<
functional
>
#
include
<
ggml-quants.h
>
#
include
<
google/protobuf/stubs/strutil.h
>
#
include
<
iomanip
>
#
include
<
iostream
>
#
include
<
locale
>
#
include
<
numeric
>
#
include
<
random
>
#
include
<
regex
>
#
include
<
string
>
#
include
<
sys/stat.h
>
#
include
<
thread
>
#
define
STB_IMAGE_IMPLEMENTATION
#
define
STB_IMAGE_RESIZE2_IMPLEMENTATION
#
include
<
stb_image.h
>
#
include
<
stb_image_resize2.h
>
#
ifdef
__has_include
#
if
__has_include(<unistd.h>)
#
include
<
unistd.h
>
#
if
defined(_POSIX_MAPPED_FILES)
#
include
<
sys/mman.h
>
#
endif
#
if
defined(_POSIX_MEMLOCK_RANGE)
#
include
<
sys/resource.h
>
#
endif
#
endif
#
endif
#
if
defined(_WIN32)
#
define
WIN32_LEAN_AND_MEAN
#
ifndef
NOMINMAX
#
define
NOMINMAX
#
endif
#
include
<
io.h
>
#
include
<
stdio.h
>
#
include
<
windows.h
>
#
endif
#
ifdef
GGML_USE_CUDA
#
include
<
ggml-cuda.h
>
#
endif
#
ifdef
GGML_USE_METAL
#
include
<
ggml-metal.h
>
#
endif
namespace
chatglm
{
static
std::string
shape_to_string
(ggml_tensor *tensor) {
std::ostringstream oss;
oss <<
'
[
'
;
for
(
int
i =
ggml_n_dims
(tensor) -
1
; i >=
0
; i--) {
oss << tensor->
ne
[i] << (i >
0
?
"
,
"
:
"
"
);
}
oss <<
'
]
'
;
return
oss.
str
();
}
static
std::string
strides_to_string
(ggml_tensor *tensor) {
std::ostringstream oss;
oss <<
'
[
'
;
for
(
int
i =
ggml_n_dims
(tensor) -
1
; i >=
0
; i--) {
oss << tensor->
nb
[i] << (i >
0
?
"
,
"
:
"
"
);
}
oss <<
'
]
'
;
return
oss.
str
();
}
std::string
to_string
(ggml_tensor *tensor,
bool
with_data) {
std::vector<
char
>
buf
(
ggml_nbytes
(tensor));
if
(tensor->
buffer
) {
ggml_backend_tensor_get
(tensor, buf.
data
(),
0
, buf.
size
());
}
else
{
memcpy
(buf.
data
(), tensor->
data
, buf.
size
());
}
std::vector<
float
>
float_buf
(
ggml_nelements
(tensor));
switch
(tensor->
type
) {
case
GGML_TYPE_F32
:
memcpy
(float_buf.
data
(), buf.
data
(), buf.
size
());
break
;
case
GGML_TYPE_F16
:
ggml_fp16_to_fp32_row
((
ggml_fp16_t
*)buf.
data
(), float_buf.
data
(),
ggml_nelements
(tensor));
break
;
case
GGML_TYPE_Q4_0
:
dequantize_row_q4_0
((block_q4_0 *)buf.
data
(), float_buf.
data
(),
ggml_nelements
(tensor));
break
;
case
GGML_TYPE_Q4_1
:
dequantize_row_q4_1
((block_q4_1 *)buf.
data
(), float_buf.
data
(),
ggml_nelements
(tensor));
break
;
case
GGML_TYPE_Q5_0
:
dequantize_row_q5_0
((block_q5_0 *)buf.
data
(), float_buf.
data
(),
ggml_nelements
(tensor));
break
;
case
GGML_TYPE_Q5_1
:
dequantize_row_q5_1
((block_q5_1 *)buf.
data
(), float_buf.
data
(),
ggml_nelements
(tensor));
break
;
case
GGML_TYPE_Q8_0
:
dequantize_row_q8_0
((block_q8_0 *)buf.
data
(), float_buf.
data
(),
ggml_nelements
(tensor));
break
;
default
:
CHATGLM_THROW
<<
"
Unsupported dtype
"
<< tensor->
type
;
}
std::ostringstream oss;
oss <<
"
ggml_tensor(
"
;
if
(with_data) {
const
int
n_dims =
ggml_n_dims
(tensor);
if
(n_dims >
3
)
oss <<
"
[
"
;
for
(
int
i3 =
0
; i3 < tensor->
ne
[
3
]; i3++) {
if
(n_dims >
2
)
oss << (i3 >
0
?
"
,
\n\n
[
"
:
"
[
"
);
for
(
int
i2 =
0
; i2 < tensor->
ne
[
2
]; i2++) {
if
(n_dims >
1
)
oss << (i2 >
0
?
"
,
\n\n
[
"
:
"
[
"
);
for
(
int
i1 =
0
; i1 < tensor->
ne
[
1
]; i1++) {
oss << (i1 >
0
?
"
,
\n
[
"
:
"
[
"
);
for
(
int
i0 =
0
; i0 < tensor->
ne
[
0
]; i0++) {
oss << (i0 >
0
?
"
,
"
:
"
"
);
const
int
i = ((i3 * tensor->
ne
[
2
] + i2) * tensor->
ne
[
1
] + i1) * tensor->
ne
[
0
] + i0;
oss <<
std::setw
(
7
) << std::fixed <<
std::setprecision
(
4
) << float_buf[i];
}
oss <<
"
]
"
;
}
if
(n_dims >
1
)
oss <<
"
]
"
;
}
if
(n_dims >
2
)
oss <<
"
]
"
;
}
if
(n_dims >
3
)
oss <<
"
]
"
;
oss <<
"
,
"
;
}
oss <<
"
shape=
"
<<
shape_to_string
(tensor) <<
"
, stride=
"
<<
strides_to_string
(tensor) <<
"
)
"
;
return
oss.
str
();
}
const
std::string ToolCallMessage::
TYPE_FUNCTION
=
"
function
"
;
const
std::string ToolCallMessage::
TYPE_CODE
=
"
code
"
;
const
std::string ChatMessage::
ROLE_USER
=
"
user
"
;
const
std::string ChatMessage::
ROLE_ASSISTANT
=
"
assistant
"
;
const
std::string ChatMessage::
ROLE_SYSTEM
=
"
system
"
;
const
std::string ChatMessage::
ROLE_OBSERVATION
=
"
observation
"
;
void
BaseTokenizer::check_chat_messages
(
const
std::vector<ChatMessage> &messages) {
std::string target_role = ChatMessage::
ROLE_USER
;
for
(
size_t
i =
0
; i < messages.
size
(); i++) {
if
(messages[i].
role
!= ChatMessage::
ROLE_USER
&& messages[i].
role
!= ChatMessage::
ROLE_ASSISTANT
) {
continue
;
}
CHATGLM_CHECK
(messages[i].
role
== target_role)
<<
"
expect messages[
"
<< i <<
"
].role to be
"
<< target_role <<
"
, but got
"
<< messages[i].
role
;
target_role = (target_role == ChatMessage::
ROLE_USER
) ? ChatMessage::
ROLE_ASSISTANT
: ChatMessage::
ROLE_USER
;
}
CHATGLM_CHECK
(target_role == ChatMessage::
ROLE_ASSISTANT
)
<<
"
expect last message role to be
"
<< ChatMessage::
ROLE_USER
<<
"
, but got
"
<< ChatMessage::
ROLE_ASSISTANT
;
}
std::vector<ChatMessage>
BaseTokenizer::filter_user_assistant_messages
(
const
std::vector<ChatMessage> &messages) {
std::vector<ChatMessage> user_assistant_messages;
user_assistant_messages.
reserve
(messages.
size
());
for
(
const
auto
&msg : messages) {
if
(msg.
role
== ChatMessage::
ROLE_USER
|| msg.
role
== ChatMessage::
ROLE_ASSISTANT
) {
user_assistant_messages.
emplace_back
(msg);
}
}
return
user_assistant_messages;
}
//
for debugging purpose
[[maybe_unused]]
static
inline
ggml_tensor *
add_zero
(ggml_context *ctx, ggml_tensor *tensor) {
ggml_tensor *zeros =
ggml_new_tensor
(ctx,
GGML_TYPE_F32
,
ggml_n_dims
(tensor), tensor->
ne
);
ggml_set_f32
(zeros,
0
);
ggml_tensor *out =
ggml_add
(ctx, tensor, zeros);
return
out;
}
// ===== streamer =====
void
StreamerGroup::put
(
const
std::vector<
int
> &output_ids) {
for
(
auto
&streamer : streamers_) {
streamer->
put
(output_ids);
}
}
void
StreamerGroup::end
() {
for
(
auto
&streamer : streamers_) {
streamer->
end
();
}
}
//
reference: https://stackoverflow.com/questions/216823/how-to-trim-a-stdstring
//
trim from start (in place)
static
inline
void
ltrim
(std::string &s) {
s.
erase
(s.
begin
(),
std::find_if
(s.
begin
(), s.
end
(), [](
unsigned
char
ch) {
return
!
std::isspace
(ch); }));
}
//
trim from end (in place)
static
inline
void
rtrim
(std::string &s) {
s.
erase
(
std::find_if
(s.
rbegin
(), s.
rend
(), [](
unsigned
char
ch) {
return
!
std::isspace
(ch); }).
base
(), s.
end
());
}
//
trim from both ends (in place)
static
inline
void
trim
(std::string &s) {
rtrim
(s);
ltrim
(s);
}
void
TextStreamer::put
(
const
std::vector<
int
> &output_ids) {
if
(is_prompt_) {
//
skip prompt
is_prompt_ =
false
;
return
;
}
static
const
std::vector<
char
> puncts{
'
,
'
,
'
!
'
,
'
:
'
,
'
;
'
,
'
?
'
};
token_cache_.
insert
(token_cache_.
end
(), output_ids.
begin
(), output_ids.
end
());
std::string text = tokenizer_->
decode
(token_cache_);
if
(is_first_line_) {
ltrim
(text);
}
if
(text.
empty
()) {
return
;
}
std::string printable_text;
if
(text.
back
() ==
'
\n
'
) {
//
flush the cache after newline
printable_text = text.
substr
(print_len_);
is_first_line_ =
false
;
token_cache_.
clear
();
print_len_ =
0
;
}
else
if
(
std::find
(puncts.
begin
(), puncts.
end
(), text.
back
()) != puncts.
end
()) {
//
last symbol is a punctuation, hold on
}
else
if
(text.
size
() >=
3
&& text.
compare
(text.
size
() -
3
,
3
,
"
�
"
) ==
0
) {
//
ends with an incomplete token, hold on
}
else
{
printable_text = text.
substr
(print_len_);
print_len_ = text.
size
();
}
os_ << printable_text << std::flush;
}
void
TextStreamer::end
() {
std::string text = tokenizer_->
decode
(token_cache_);
if
(is_first_line_) {
ltrim
(text);
}
os_ << text.
substr
(print_len_) << std::endl;
is_prompt_ =
true
;
is_first_line_ =
true
;
token_cache_.
clear
();
print_len_ =
0
;
}
void
PerfStreamer::put
(
const
std::vector<
int
> &output_ids) {
CHATGLM_CHECK
(!output_ids.
empty
());
if
(num_prompt_tokens_ ==
0
) {
//
before prompt eval
start_us_ =
ggml_time_us
();
num_prompt_tokens_ = output_ids.
size
();
}
else
{
if
(num_output_tokens_ ==
0
) {
//
first new token
prompt_us_ =
ggml_time_us
();
}
num_output_tokens_ += output_ids.
size
();
}
}
void
PerfStreamer::reset
() {
start_us_ = prompt_us_ = end_us_ =
0
;
num_prompt_tokens_ = num_output_tokens_ =
0
;
}
std::string
PerfStreamer::to_string
()
const
{
std::ostringstream oss;
oss <<
"
prompt time:
"
<<
prompt_total_time_us
() /
1000
.
f
<<
"
ms /
"
<<
num_prompt_tokens
() <<
"
tokens (
"
<<
prompt_token_time_us
() /
1000
.
f
<<
"
ms/token)
\n
"
<<
"
output time:
"
<<
output_total_time_us
() /
1000
.
f
<<
"
ms /
"
<<
num_output_tokens
() <<
"
tokens (
"
<<
output_token_time_us
() /
1000
.
f
<<
"
ms/token)
\n
"
<<
"
total time:
"
<< (
prompt_total_time_us
() +
output_total_time_us
()) /
1000
.
f
<<
"
ms
"
;
return
oss.
str
();
}
#
ifdef
_POSIX_MAPPED_FILES
MappedFile::MappedFile
(
const
std::string &path) {
int
fd =
open
(path.
c_str
(),
O_RDONLY
);
CHATGLM_CHECK
(fd >
0
) <<
"
cannot open file
"
<< path <<
"
:
"
<<
strerror
(errno);
struct
stat
sb;
CHATGLM_CHECK
(
fstat
(fd, &sb) ==
0
) <<
strerror
(errno);
size = sb.
st_size
;
data = (
char
*)
mmap
(
nullptr
, size,
PROT_READ
,
MAP_SHARED
, fd,
0
);
CHATGLM_CHECK
(data !=
MAP_FAILED
) <<
strerror
(errno);
CHATGLM_CHECK
(
close
(fd) ==
0
) <<
strerror
(errno);
}
MappedFile::~MappedFile
() {
CHATGLM_CHECK
(
munmap
(data, size) ==
0
) <<
strerror
(errno); }
#
elif
defined(_WIN32)
MappedFile::MappedFile
(
const
std::string &path) {
int
fd =
open
(path.
c_str
(),
O_RDONLY
);
CHATGLM_CHECK
(fd >
0
) <<
"
cannot open file
"
<< path <<
"
:
"
<<
strerror
(errno);
struct
_stat64
sb;
CHATGLM_CHECK
(
_fstat64
(fd, &sb) ==
0
) <<
strerror
(errno);
size = sb.
st_size
;
HANDLE
hFile = (
HANDLE
)
_get_osfhandle
(fd);
HANDLE
hMapping =
CreateFileMappingA
(hFile,
NULL
,
PAGE_READONLY
,
0
,
0
,
NULL
);
CHATGLM_CHECK
(hMapping !=
NULL
) <<
strerror
(errno);
data = (
char
*)
MapViewOfFile
(hMapping,
FILE_MAP_READ
,
0
,
0
,
0
);
CloseHandle
(hMapping);
CHATGLM_CHECK
(data !=
NULL
) <<
strerror
(errno);
CHATGLM_CHECK
(
close
(fd) ==
0
) <<
strerror
(errno);
}
MappedFile::~MappedFile
() {
CHATGLM_CHECK
(
UnmapViewOfFile
(data)) <<
strerror
(errno); }
#
endif
void
ModelLoader::seek
(
int64_t
offset,
int
whence) {
if
(whence ==
SEEK_SET
) {
ptr = data + offset;
}
else
if
(whence ==
SEEK_CUR
) {
ptr += offset;
}
else
if
(whence ==
SEEK_END
) {
ptr = data + size + offset;
}
else
{
CHATGLM_THROW
<<
"
invalid seek mode
"
<< whence;
}
}
std::string
ModelLoader::read_string
(
size_t
length) {
std::string
s
(ptr, ptr + length);
ptr += length;
return
s;
}
StateDict
ModelLoader::read_state_dict
() {
StateDict sd;
sd.
ctx
=
make_unique_ggml_context
(
GGML_DEFAULT_GRAPH_SIZE
*
ggml_tensor_overhead
(),
nullptr
,
true
);
sd.
buf
=
unique_ggml_backend_buffer_t
(
ggml_backend_cpu_buffer_from_ptr
(data, size));
//
assume state dict is stored at the back of file
while
(
tell
() < (
int64_t
)size) {
//
tensor name
int
name_size = read_basic<
int
>();
std::string weight_name =
read_string
(name_size);
//
tensor shape
int64_t
ne[
4
]{
1
,
1
,
1
,
1
};
int
ndim = read_basic<
int
>();
CHATGLM_CHECK
(
0
< ndim && ndim <=
4
);
for
(
int
i = ndim -
1
; i >=
0
; i--) {
ne[i] = read_basic<
int
>();
}
//
tensor dtype
ggml_type dtype = (ggml_type)read_basic<
int
>();
//
tensor data
ggml_tensor *tensor =
ggml_new_tensor
(sd.
ctx
.
get
(), dtype, ndim, ne);
constexpr
int64_t
MEM_ALIGNED
=
16
;
const
int64_t
data_offset = (
tell
() + (
MEM_ALIGNED
-
1
)) & ~(
MEM_ALIGNED
-
1
);
ggml_backend_tensor_alloc
(sd.
buf
.
get
(), tensor, data + data_offset);
//
tensor->data = data + data_offset;
seek
(data_offset +
ggml_nbytes
(tensor),
SEEK_SET
);
//
add to state dict
sd.
kv
.
emplace
(weight_name, tensor);
}
return
sd;
}
Image
Image::open
(
const
std::string &path) {
int
width, height, channels;
uint8_t
*buffer =
stbi_load
(path.
c_str
(), &width, &height, &channels,
3
);
CHATGLM_CHECK
(channels ==
3
);
Image
image
(width, height, channels, buffer);
stbi_image_free
(buffer);
return
image;
}
Image
Image::resize
(
size_t
new_width,
size_t
new_height)
const
{
Image
output
(new_width, new_height, channels);
stbir_resize_uint8_srgb
(pixels.
data
(), width, height,
0
, output.
pixels
.
data
(), new_width, new_height,
0
,
STBIR_RGB
);
return
output;
}
ModelContext::ModelContext
()
: compute_meta(ggml_tensor_overhead() * (
GGML_DEFAULT_GRAPH_SIZE
*
4
) + ggml_graph_overhead()),
ctx_w
(make_unique_ggml_context(ggml_tensor_overhead() * GGML_DEFAULT_GRAPH_SIZE, nullptr, true)),
ctx_kv(make_unique_ggml_context(ggml_tensor_overhead() * GGML_DEFAULT_GRAPH_SIZE, nullptr, true)),
ctx_b(make_unique_ggml_context(compute_meta.size(), compute_meta.data(), true)),
gf(ggml_new_graph_custom(ctx_b.get(), GGML_DEFAULT_GRAPH_SIZE * 4, false)) {
#
if
defined(GGML_USE_CUDA)
backend =
unique_ggml_backend_t
(
ggml_backend_cuda_init
(
0
));
#
elif
defined(GGML_USE_METAL)
backend =
unique_ggml_backend_t
(
ggml_backend_metal_init
());
#
else
backend =
unique_ggml_backend_t
(
ggml_backend_cpu_init
());
#
endif
CHATGLM_CHECK
(backend) <<
"
failed to initialize ggml backend
"
;
allocr =
unique_ggml_gallocr_t
(
ggml_gallocr_new
(
ggml_backend_get_default_buffer_type
(backend.
get
())));
}
// ===== modules =====
ggml_tensor *
Embedding::forward
(ModelContext *mctx, ggml_tensor *input)
const
{
ggml_tensor *output =
ggml_get_rows
(mctx->
ctx_b
.
get
(), weight, input);
return
output;
}
ggml_tensor *
Linear::forward
(ModelContext *mctx, ggml_tensor *input)
const
{
//
input: [seqlen, in_features]
ggml_context *ctx = mctx->
ctx_b
.
get
();
ggml_tensor *output =
ggml_mul_mat
(ctx, weight, input);
//
[seqlen, out_features]
if
(bias) {
output =
ggml_add_inplace
(ctx, output, bias);
}
return
output;
}
ggml_tensor *
LayerNorm::forward
(ModelContext *mctx, ggml_tensor *input)
const
{
//
input: [seqlen, normalized_shape]
ggml_context *ctx = mctx->
ctx_b
.
get
();
ggml_tensor *output =
ggml_norm
(ctx, input, eps);
output =
ggml_mul_inplace
(ctx, output, weight);
output =
ggml_add_inplace
(ctx, output, bias);
return
output;
}
ggml_tensor *
RMSNorm::forward
(ModelContext *mctx, ggml_tensor *input)
const
{
ggml_context *ctx = mctx->
ctx_b
.
get
();
ggml_tensor *output =
ggml_rms_norm
(ctx, input, eps);
output =
ggml_mul_inplace
(ctx, output, weight);
return
output;
}
static
ggml_tensor *
apply_activation_inplace
(ggml_context *ctx, ggml_tensor *hidden_states, ActivationType hidden_act) {
switch
(hidden_act) {
case
ActivationType::
GELU
:
return
ggml_gelu_inplace
(ctx, hidden_states);
case
ActivationType::
SILU
:
return
ggml_silu_inplace
(ctx, hidden_states);
default
:
CHATGLM_THROW
<<
"
Unknown activation type
"
<< (
int
)hidden_act;
}
}
ggml_tensor *
BasicMLP::forward
(ModelContext *mctx, ggml_tensor *hidden_states)
const
{
ggml_context *ctx = mctx->
ctx_b
.
get
();
hidden_states = dense_h_to_4h.
forward
(mctx, hidden_states);
hidden_states =
apply_activation_inplace
(ctx, hidden_states, hidden_act);
hidden_states = dense_4h_to_h.
forward
(mctx, hidden_states);
return
hidden_states;
}
ggml_tensor *
BasicGLU::forward
(ModelContext *mctx, ggml_tensor *hidden_states)
const
{
ggml_context *ctx = mctx->
ctx_b
.
get
();
ggml_tensor *gate = gate_proj.
forward
(mctx, hidden_states);
gate =
apply_activation_inplace
(ctx, gate, hidden_act);
hidden_states = up_proj.
forward
(mctx, hidden_states);
hidden_states =
ggml_mul_inplace
(ctx, hidden_states, gate);
hidden_states = down_proj.
forward
(mctx, hidden_states);
return
hidden_states;
}
//
Adapted from https://github.com/ggerganov/llama.cpp/blob/master/common/common.cpp
static
int
get_num_physical_cores
() {
unsigned
int
n_threads =
std::thread::hardware_concurrency
();
return
n_threads >
0
? (n_threads <=
4
? n_threads : n_threads /
2
) :
4
;
}
static
void
set_default_num_threads
(
ggml_backend_t
backend,
int
num_tokens) {
int
n_threads =
1
;
if
(
ggml_backend_is_cpu
(backend)) {
if
(num_tokens >
1
) {
//
context
n_threads =
get_num_physical_cores
();
}
else
{
//
decode
n_threads =
std::min
(
get_num_physical_cores
(),
16
);
}
}
if
(num_tokens >=
32
&&
ggml_cpu_has_blas
() && !
ggml_cpu_has_gpublas
()) {
//
BLAS is enabled
n_threads =
std::min
(
4
, n_threads);
}
if
(
ggml_backend_is_cpu
(backend)) {
ggml_backend_cpu_set_n_threads
(backend, n_threads);
}
#
ifdef
GGML_USE_METAL
if
(
ggml_backend_is_metal
(backend)) {
ggml_backend_metal_set_n_cb
(backend, n_threads);
}
#
endif
}
std::string
to_string
(ModelType model_type) {
static
const
std::unordered_map<ModelType, std::string> m{{ModelType::
CHATGLM
,
"
ChatGLM
"
},
{ModelType::
CHATGLM2
,
"
ChatGLM2
"
},
{ModelType::
CHATGLM3
,
"
ChatGLM3
"
},
{ModelType::
CHATGLM4
,
"
ChatGLM4
"
},
{ModelType::
CHATGLM4V
,
"
ChatGLM4V
"
}};
return
m.
at
(model_type);
}
static
ggml_tensor *
apply_rotary_emb_basic
(ModelContext *mctx, ggml_tensor *layer, ggml_tensor *position_ids,
RopeType rope_type,
float
rope_theta) {
//
tensor a (activation) is of shape [s, #h, d]
//
tensor b (position_ids) is of shape [s]
ggml_context *ctx = mctx->
ctx_b
.
get
();
if
(
ggml_cpu_has_cuda
() && !
ggml_is_contiguous
(layer)) {
layer =
ggml_cont
(ctx, layer);
}
const
int
head_size = layer->
ne
[
0
];
layer =
ggml_rope_ext_inplace
(ctx, layer, position_ids,
nullptr
, head_size, (
int
)rope_type,
0
, rope_theta,
1
.
0f
,
0
.
0f
,
1
.
0f
,
0
.
0f
,
0
.
0f
);
//
[s, #h, d]
return
layer;
}
static
ggml_tensor *
apply_rotary_emb_glm
(ModelContext *mctx, ggml_tensor *layer, ggml_tensor *position_ids) {
//
tensor a (activation) is of shape [s, #h, d]
//
tensor b (position_ids) is of shape [2 * s]
ggml_context *ctx = mctx->
ctx_b
.
get
();
const
int
head_size = layer->
ne
[
0
];
const
int
num_heads = layer->
ne
[
1
];
const
int
qlen = layer->
ne
[
2
];
const
int
rope_dim = head_size /
2
;
ggml_tensor *b1 =
ggml_view_1d
(ctx, position_ids, qlen,
0
);
ggml_tensor *b2 =
ggml_view_1d
(ctx, position_ids, qlen, qlen *
ggml_element_size
(position_ids));
ggml_tensor *a1 =
ggml_view_3d
(ctx, layer, head_size /
2
, num_heads, qlen, layer->
nb
[
1
], layer->
nb
[
2
],
0
);
ggml_tensor *a2 =
ggml_view_3d
(ctx, layer, head_size /
2
, num_heads, qlen, layer->
nb
[
1
], layer->
nb
[
2
],
head_size /
2
*
ggml_element_size
(layer));
ggml_tensor *a1_rope = a1;
ggml_tensor *a2_rope = a2;
if
(
ggml_cpu_has_cuda
()) {
a1_rope =
ggml_cont
(ctx, a1_rope);
a2_rope =
ggml_cont
(ctx, a2_rope);
}
a1_rope =
ggml_rope_inplace
(ctx, a1_rope, b1, rope_dim, (
int
)RopeType::
NEOX
);
//
[s, #h, d/2]
a2_rope =
ggml_rope_inplace
(ctx, a2_rope, b2, rope_dim, (
int
)RopeType::
NEOX
);
//
[s, #h, d/2]
if
(
ggml_cpu_has_cuda
()) {
a1_rope =
ggml_cpy
(ctx, a1_rope, a1);
a2_rope =
ggml_cpy
(ctx, a2_rope, a2);
}
ggml_build_forward_expand
(mctx->
gf
, a1_rope);
ggml_build_forward_expand
(mctx->
gf
, a2_rope);
return
layer;
}
static
ggml_tensor *
apply_rotary_emb_glm2
(ModelContext *mctx, ggml_tensor *layer, ggml_tensor *position_ids,
float
rope_theta) {
//
NOTE: ChatGLM2 applies RoPE only on half of the features. The remaining half is skipped.
//
layer: [s, #h, d], position_ids: [s]
ggml_context *ctx = mctx->
ctx_b
.
get
();
const
int
head_size = layer->
ne
[
0
];
const
int
rope_dim = head_size /
2
;
ggml_tensor *half_layer_view =
ggml_view_3d
(ctx, layer, rope_dim, layer->
ne
[
1
], layer->
ne
[
2
], layer->
nb
[
1
], layer->
nb
[
2
],
0
);
ggml_tensor *half_layer = half_layer_view;
if
(
ggml_cpu_has_cuda
()) {
half_layer =
ggml_cont
(ctx, half_layer);
}
ggml_tensor *roped_half_layer =
ggml_rope_ext_inplace
(ctx, half_layer, position_ids,
nullptr
, rope_dim, (
int
)RopeType::
GPTJ
,
0
, rope_theta,
1
.
0f
,
0
.
0f
,
1
.
0f
,
0
.
0f
,
0
.
0f
);
//
[s, #h, d]
if
(
ggml_cpu_has_cuda
()) {
roped_half_layer =
ggml_cpy
(ctx, roped_half_layer, half_layer_view);
}
ggml_build_forward_expand
(mctx->
gf
, roped_half_layer);
return
layer;
}
static
ggml_tensor *
apply_rotary_emb
(ModelContext *mctx, ggml_tensor *layer, ggml_tensor *position_ids,
RopeType rope_type,
float
rope_theta) {
switch
(rope_type) {
case
RopeType::
GPTJ
:
case
RopeType::
NEOX
:
return
apply_rotary_emb_basic
(mctx, layer, position_ids, rope_type, rope_theta);
case
RopeType::
CHATGLM
:
return
apply_rotary_emb_glm
(mctx, layer, position_ids);
case
RopeType::
CHATGLM2
:
return
apply_rotary_emb_glm2
(mctx, layer, position_ids, rope_theta);
case
RopeType::
DISABLED
:
return
layer;
default
:
CHATGLM_THROW
<<
"
Unknown rope type
"
<< (
int
)rope_type;
}
}
ggml_tensor *
BasicAttention::forward
(ModelContext *mctx, ggml_tensor *hidden_states, ggml_tensor *attention_mask,
ggml_tensor *position_ids,
int
n_past)
const
{
ggml_context *ctx = mctx->
ctx_b
.
get
();
const
int
hidden_size = hidden_states->
ne
[
0
];
const
int
qlen = hidden_states->
ne
[
1
];
const
int
head_size = hidden_size / num_attention_heads;
const
int
num_shared_q_heads = num_attention_heads / num_key_value_heads;
ggml_tensor *qkv = query_key_value.
forward
(mctx, hidden_states);
//
[sq, (#h + 2 * #kvh) * d]
//
split mixed qkv into separate query, key and value
ggml_tensor *query_layer;
//
[s, #h, d]
ggml_tensor *key_layer;
//
[s, #kvh, d]
ggml_tensor *value_layer;
//
[s, #kvh, d]
if
(interleaved_qkv) {
CHATGLM_CHECK
(num_shared_q_heads ==
1
) <<
"
interleaved qkv is not supported for GQA
"
;
query_layer =
ggml_view_3d
(ctx, qkv, head_size, num_attention_heads, qlen,
3
* head_size *
ggml_element_size
(qkv), qkv->
nb
[
1
],
0
);
key_layer =
ggml_view_3d
(ctx, qkv, head_size, num_attention_heads, qlen,
3
* head_size *
ggml_element_size
(qkv),
qkv->
nb
[
1
], head_size *
ggml_element_size
(qkv));
value_layer =
ggml_view_3d
(ctx, qkv, head_size, num_attention_heads, qlen,
3
* head_size *
ggml_element_size
(qkv),
qkv->
nb
[
1
],
2
* head_size *
ggml_element_size
(qkv));
}
else
{
query_layer =
ggml_view_3d
(ctx, qkv, head_size, num_attention_heads, qlen, head_size *
ggml_element_size
(qkv),
qkv->
nb
[
1
],
0
);
key_layer =
ggml_view_3d
(ctx, qkv, head_size, num_key_value_heads, qlen, head_size *
ggml_element_size
(qkv),
qkv->
nb
[
1
], hidden_size *
ggml_element_size
(qkv));
value_layer =
ggml_view_3d
(ctx, qkv, head_size, num_key_value_heads, qlen, head_size *
ggml_element_size
(qkv), qkv->
nb
[
1
],
(hidden_size + head_size * num_key_value_heads) *
ggml_element_size
(qkv));
}
query_layer =
apply_rotary_emb
(mctx, query_layer, position_ids, rope_type, rope_theta);
key_layer =
apply_rotary_emb
(mctx, key_layer, position_ids, rope_type, rope_theta);
query_layer =
ggml_cont
(ctx,
ggml_permute
(ctx, query_layer,
0
,
2
,
1
,
3
));
//
[#h, s, d]
if
(num_shared_q_heads >
1
) {
query_layer =
ggml_reshape_3d
(ctx, query_layer, head_size, num_shared_q_heads * qlen,
num_key_value_heads);
//
[#kvh, (#h/#kvh) * s, d]
}
key_layer =
ggml_permute
(ctx, key_layer,
0
,
2
,
1
,
3
);
//
[#kvh, s, d]
value_layer =
ggml_permute
(ctx, value_layer,
1
,
2
,
0
,
3
);
//
[#kvh, d, s]
ggml_tensor *context_layer;
if
(k_cache && v_cache) {
//
store key & value to cache
ggml_tensor *k_cache_view =
ggml_view_3d
(ctx, k_cache, head_size, qlen, num_key_value_heads, k_cache->
nb
[
1
], k_cache->
nb
[
2
],
(num_virtual_tokens + n_past) * k_cache->
nb
[
1
]);
//
[#kvh, s, d]
ggml_tensor *v_cache_view =
ggml_view_3d
(ctx, v_cache, qlen, head_size, num_key_value_heads, v_cache->
nb
[
1
], v_cache->
nb
[
2
],
(num_virtual_tokens + n_past) * v_cache->
nb
[
0
]);
//
[#kvh, d, s]
ggml_build_forward_expand
(mctx->
gf
,
ggml_cpy
(ctx, key_layer, k_cache_view));
ggml_build_forward_expand
(mctx->
gf
,
ggml_cpy
(ctx, value_layer, v_cache_view));
//
concat key & value with past kv
key_layer =
ggml_view_3d
(ctx, k_cache, head_size, num_virtual_tokens + n_past + qlen, num_key_value_heads,
k_cache->
nb
[
1
], k_cache->
nb
[
2
],
0
);
//
[#kvh, kvs, d]
value_layer =
ggml_view_3d
(ctx, v_cache, num_virtual_tokens + n_past + qlen, head_size, num_key_value_heads,
v_cache->
nb
[
1
], v_cache->
nb
[
2
],
0
);
//
[#kvh, d, kvs]
//
attention
query_layer =
ggml_scale_inplace
(ctx, query_layer,
1
.
f
/
std::sqrt
(head_size));
ggml_tensor *attn_scores =
ggml_mul_mat
(ctx, key_layer, query_layer);
//
[#kvh, (#h/#kvh) * s, kvs]
if
(n_past ==
0
) {
//
build attention mask for context input
if
(num_shared_q_heads >
1
) {
attn_scores =
ggml_reshape_3d
(ctx, attn_scores, num_virtual_tokens + n_past + qlen, qlen,
num_attention_heads);
//
[#h, s, kvs]
}
if
(attention_mask) {
attn_scores =
ggml_add_inplace
(ctx, attn_scores, attention_mask);
}
if
(num_shared_q_heads >
1
) {
attn_scores =
ggml_reshape_3d
(ctx, attn_scores, num_virtual_tokens + n_past + qlen, num_shared_q_heads * qlen,
num_key_value_heads);
//
[#kvh, (#h/#kvh) * s, kvs]
}
}
ggml_tensor *attn_probs =
ggml_soft_max_inplace
(ctx, attn_scores);
//
[#kvh, (#h/#kvh) * s, kvs]
context_layer =
ggml_mul_mat
(ctx, value_layer, attn_probs);
//
[#kvh, (#h/#kvh) * s, d]
if
(num_shared_q_heads >
1
) {
context_layer =
ggml_reshape_3d
(ctx, context_layer, head_size, qlen,
num_attention_heads);
//
[#h, s, d]
}
context_layer =
ggml_cont
(ctx,
ggml_permute
(ctx, context_layer,
0
,
2
,
1
,
3
));
//
[s, #h, d]
}
else
{
//
qkv must be correctly padded
key_layer =
ggml_cast
(ctx, key_layer,
GGML_TYPE_F16
);
//
[#kvh, s, d]
value_layer =
ggml_cast
(ctx,
ggml_permute
(ctx, value_layer,
1
,
0
,
2
,
3
),
GGML_TYPE_F16
);
//
[#kvh, s, d]
context_layer =
ggml_flash_attn_ext
(ctx, query_layer, key_layer, value_layer, attention_mask,
1
.
f
/
std::sqrt
(head_size),
0
);
ggml_flash_attn_ext_set_prec
(context_layer,
GGML_PREC_F32
);
}
context_layer =
ggml_reshape_2d
(ctx, context_layer, hidden_size, qlen);
//
[s, #h * d]
ggml_tensor *attn_output = dense.
forward
(mctx, context_layer);
return
attn_output;
}
BaseModelForCausalLM::BaseModelForCausalLM
(ModelConfig config)
: config(config), mctx_(std::make_unique<ModelContext>()) {}
ggml_tensor *
BaseModelForCausalLM::forward_graph_compute
(
const
std::vector<
int
> &input_ids,
const
std::optional<Image> &image,
int
n_past,
int
n_ctx,
bool
is_decoding) {
mctx_->
ctx_b
=
make_unique_ggml_context
(mctx_->
compute_meta
.
size
(), mctx_->
compute_meta
.
data
(),
true
);
mctx_->
gf
=
ggml_new_graph_custom
(mctx_->
ctx_b
.
get
(),
GGML_DEFAULT_GRAPH_SIZE
*
4
,
false
);
const
int
qlen = (n_past ==
0
) ? input_ids.
size
() :
1
;
ggml_tensor *curr_input_ids =
ggml_new_tensor_1d
(mctx_->
ctx_b
.
get
(),
GGML_TYPE_I32
, qlen);
ggml_set_name
(curr_input_ids,
"
input_ids
"
);
ggml_set_input
(curr_input_ids);
ggml_tensor *curr_image =
nullptr
;
if
(n_past ==
0
&& image) {
curr_image =
ggml_new_tensor_3d
(mctx_->
ctx_b
.
get
(),
GGML_TYPE_F32
, config.
vision
.
image_size
,
config.
vision
.
image_size
, config.
vision
.
in_channels
);
ggml_set_name
(curr_image,
"
image
"
);
ggml_set_input
(curr_image);
}
ggml_tensor *lm_logits =
forward
(mctx_.
get
(), curr_input_ids, curr_image, input_ids, n_past, is_decoding);
ggml_set_output
(lm_logits);
ggml_build_forward_expand
(mctx_->
gf
, lm_logits);
CHATGLM_CHECK
(
ggml_gallocr_alloc_graph
(mctx_->
allocr
.
get
(), mctx_->
gf
));
//
TODO: move into set_graph_inputs
curr_input_ids =
ggml_graph_get_tensor
(mctx_->
gf
,
"
input_ids
"
);
if
(curr_input_ids) {
ggml_backend_tensor_set
(curr_input_ids, input_ids.
data
() + input_ids.
size
() - qlen,
0
, qlen *
sizeof
(
int
));
}
set_graph_inputs
(input_ids, image, n_past, n_ctx);
set_default_num_threads
(mctx_->
backend
.
get
(), qlen);
CHATGLM_CHECK
(
ggml_backend_graph_compute
(mctx_->
backend
.
get
(), mctx_->
gf
) ==
GGML_STATUS_SUCCESS
);
#
ifdef
GGML_PERF
ggml_graph_print
(mctx_->
gf
);
#
endif
return
lm_logits;
}
int
BaseModelForCausalLM::generate_next_token
(
const
std::vector<
int
> &input_ids,
const
std::optional<Image> &image,
const
GenerationConfig &gen_config,
int
n_past,
int
n_ctx) {
ggml_tensor *lm_logits =
forward_graph_compute
(input_ids, image, n_past, n_ctx,
true
);
CHATGLM_CHECK
(
ggml_n_dims
(lm_logits) ==
1
);
int
vocab_size = lm_logits->
ne
[
0
];
std::vector<
float
>
next_token_logits
(vocab_size);
ggml_backend_tensor_get
(lm_logits, next_token_logits.
data
(),
0
, vocab_size *
sizeof
(
float
));
//
check nan
for
(
int
i =
0
; i < vocab_size; i++) {
CHATGLM_CHECK
(
std::isfinite
(next_token_logits[i])) <<
"
nan/inf encountered at lm_logits[
"
<< i <<
"
]
"
;
}
//
logits pre-process
if
(gen_config.
repetition_penalty
!=
1
.
f
) {
sampling_repetition_penalty
(next_token_logits.
data
(), next_token_logits.
data
() + vocab_size, input_ids,
gen_config.
repetition_penalty
);
}
int
next_token_id;
if
(gen_config.
do_sample
) {
//
temperature sampling
if
(gen_config.
temperature
>
0
) {
sampling_temperature
(next_token_logits.
data
(), next_token_logits.
data
() + vocab_size,
gen_config.
temperature
);
}
std::vector<TokenIdScore>
token_scores
(vocab_size);
for
(
int
i =
0
; i < vocab_size; i++) {
token_scores[i] =
TokenIdScore
(i, next_token_logits[i]);
}
//
top_k sampling
if
(
0
< gen_config.
top_k
&& gen_config.
top_k
< (
int
)token_scores.
size
()) {
sampling_top_k
(token_scores.
data
(), token_scores.
data
() + gen_config.
top_k
,
token_scores.
data
() + token_scores.
size
());
token_scores.
resize
(gen_config.
top_k
);
}
//
top_p sampling
if
(
0
.
f
< gen_config.
top_p
&& gen_config.
top_p
<
1
.
f
) {
auto
pos =
sampling_top_p
(token_scores.
data
(), token_scores.
data
() + token_scores.
size
(), gen_config.
top_p
);
token_scores.
resize
(pos - token_scores.
data
());
}
//
sample next token
sampling_softmax_inplace
(token_scores.
data
(), token_scores.
data
() + token_scores.
size
());
for
(
size_t
i =
0
; i < token_scores.
size
(); i++) {
next_token_logits[i] = token_scores[i].
score
;
}
thread_local
std::random_device rd;
thread_local
std::mt19937
gen
(
rd
());
std::discrete_distribution<>
dist
(next_token_logits.
data
(), next_token_logits.
data
() + token_scores.
size
());
next_token_id = token_scores[
dist
(gen)].
id
;
}
else
{
//
greedy search
next_token_id =
std::max_element
(next_token_logits.
begin
(), next_token_logits.
end
()) - next_token_logits.
begin
();
}
return
next_token_id;
}
void
BaseModelForCausalLM::sampling_repetition_penalty
(
float
*first,
float
*last,
const
std::vector<
int
> &input_ids,
float
penalty) {
CHATGLM_CHECK
(penalty >
0
) <<
"
penalty must be a positive float, but got
"
<< penalty;
const
float
inv_penalty =
1
.
f
/ penalty;
const
int
vocab_size = last - first;
std::vector<
bool
>
occurrence
(vocab_size,
false
);
for
(
const
int
id : input_ids) {
if
(!occurrence[id]) {
first[id] *= (first[id] >
0
) ? inv_penalty : penalty;
}
occurrence[id] =
true
;
}
}
void
BaseModelForCausalLM::sampling_temperature
(
float
*first,
float
*last,
float
temp) {
const
float
inv_temp =
1
.
f
/ temp;
for
(
float
*it = first; it != last; it++) {
*it *= inv_temp;
}
}
void
BaseModelForCausalLM::sampling_top_k
(TokenIdScore *first, TokenIdScore *kth, TokenIdScore *last) {
std::nth_element
(first, kth, last, std::greater<TokenIdScore>());
}
TokenIdScore *
BaseModelForCausalLM::sampling_top_p
(TokenIdScore *first, TokenIdScore *last,
float
top_p) {
//
fast top_p in expected O(n) time complexity
sampling_softmax_inplace
(first, last);
while
(first +
1
< last) {
const
float
pivot_score = (last -
1
)->
score
;
//
use mid score?
TokenIdScore *mid =
std::partition
(first, last -
1
, [pivot_score](
const
TokenIdScore &x) {
return
x.
score
> pivot_score; });
std::swap
(*mid, *(last -
1
));
const
float
prefix_sum =
std::accumulate
(first, mid,
0
.
f
, [](
float
sum,
const
TokenIdScore &x) {
return
sum + x.
score
; });
if
(prefix_sum >= top_p) {
last = mid;
}
else
if
(prefix_sum + mid->
score
< top_p) {
first = mid +
1
;
top_p -= prefix_sum + mid->
score
;
}
else
{
return
mid +
1
;
}
}
return
last;
}
void
BaseModelForCausalLM::sampling_softmax_inplace
(TokenIdScore *first, TokenIdScore *last) {
float
max_score =
std::max_element
(first, last)->
score
;
float
sum =
0
.
f
;
for
(TokenIdScore *p = first; p != last; p++) {
float
s =
std::exp
(p->
score
- max_score);
p->
score
= s;
sum += s;
}
float
inv_sum =
1
.
f
/ sum;
for
(TokenIdScore *p = first; p != last; p++) {
p->
score
*= inv_sum;
}
}
std::vector<
int
>
BaseModelForCausalLM::generate
(
const
std::vector<
int
> &input_ids,
const
std::optional<Image> &image,
const
GenerationConfig &gen_config, BaseStreamer *streamer) {
CHATGLM_CHECK
(gen_config.
max_length
<= config.
max_length
)
<<
"
Requested max_length (
"
<< gen_config.
max_length
<<
"
) exceeds pre-configured model max_length (
"
<< config.
max_length
<<
"
)
"
;
std::vector<
int
> output_ids;
output_ids.
reserve
(gen_config.
max_length
);
output_ids = input_ids;
if
(streamer) {
streamer->
put
(input_ids);
}
int
n_past =
0
;
const
int
n_ctx = input_ids.
size
();
const
int
max_new_tokens = (gen_config.
max_new_tokens
>
0
) ? gen_config.
max_new_tokens
: gen_config.
max_length
;
while
((
int
)output_ids.
size
() <
std::min
(gen_config.
max_length
, n_ctx + max_new_tokens)) {
int
next_token_id =
generate_next_token
(output_ids, image, gen_config, n_past, n_ctx);
n_past =
count_tokens
(output_ids, image);
output_ids.
emplace_back
(next_token_id);
if
(streamer) {
streamer->
put
({next_token_id});
}
if
(next_token_id == config.
eos_token_id
||
std::find
(config.
extra_eos_token_ids
.
begin
(), config.
extra_eos_token_ids
.
end
(), next_token_id) !=
config.
extra_eos_token_ids
.
end
()) {
break
;
}
}
if
(streamer) {
streamer->
end
();
}
return
output_ids;
}
// ===== ChatGLM-6B =====
ChatGLMTokenizer::ChatGLMTokenizer
(std::string_view serialized_model_proto) {
const
auto
status = sp.
LoadFromSerializedProto
(serialized_model_proto);
CHATGLM_CHECK
(status.
ok
()) << status.
ToString
();
bos_token_id = sp.
PieceToId
(
"
<sop>
"
);
eos_token_id = sp.
PieceToId
(
"
<eop>
"
);
mask_token_id = sp.
PieceToId
(
"
[MASK]
"
);
gmask_token_id = sp.
PieceToId
(
"
[gMASK]
"
);
pad_token_id = sp.
PieceToId
(
"
<pad>
"
);
}
std::vector<
int
>
ChatGLMTokenizer::encode
(
const
std::string &text,
int
max_length)
const
{
std::string input =
preprocess
(text);
std::vector<
int
> ids;
sp.
Encode
(input, &ids);
ids.
insert
(ids.
end
(), {gmask_token_id, bos_token_id});
if
((
int
)ids.
size
() > max_length) {
//
sliding window: always take the last max_length tokens
ids.
erase
(ids.
begin
(), ids.
end
() - max_length);
}
return
ids;
}
std::vector<
int
>
ChatGLMTokenizer::apply_chat_template
(
const
std::vector<ChatMessage> &messages,
int
max_length)
const
{
std::string prompt =
apply_chat_template_text
(messages);
std::vector<
int
> input_ids =
encode
(prompt, max_length);
return
input_ids;
}
std::string
ChatGLMTokenizer::apply_chat_template_text
(
const
std::vector<ChatMessage> &messages) {
check_chat_messages
(messages);
std::vector<ChatMessage> user_assistant_messages =
filter_user_assistant_messages
(messages);
std::ostringstream oss_prompt;
if
(user_assistant_messages.
size
() ==
1
) {
oss_prompt << user_assistant_messages.
front
().
content
;
}
else
{
for
(
size_t
i =
0
; i < user_assistant_messages.
size
(); i +=
2
) {
View remainder of file in raw view
Back
|
FazBrowse Home
|
New Git URL