forked from mlc-ai/web-llm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathllm_chat.ts
1435 lines (1323 loc) · 48.7 KB
/
llm_chat.ts
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
/* eslint-disable @typescript-eslint/no-non-null-assertion */
/* eslint-disable no-prototype-builtins */
import * as tvmjs from "@mlc-ai/web-runtime";
import * as xgr from "@mlc-ai/web-xgrammar";
import log from "loglevel";
import { Tokenizer } from "@mlc-ai/web-tokenizers";
import { ChatConfig, GenerationConfig, Role } from "./config";
import { getConversation, Conversation } from "./conversation";
import { LogitProcessor } from "./types";
import {
getChunkedPrefillInputData,
getImageDataFromURL,
getRGBArrayFromImageData,
getTokenTableFromTokenizer,
getTopProbs,
IMAGE_EMBED_SIZE,
} from "./support";
import {
ChatCompletionFinishReason,
ChatCompletionTokenLogprob,
TopLogprob,
ResponseFormat,
ChatCompletionContentPartImage,
} from "./openai_api_protocols/index";
import {
AttentionSinkSizeError,
ContextWindowSizeExceededError,
MinValueError,
RangeError,
WindowSizeConfigurationError,
WindowSizeSpecificationError,
MessageOrderError,
TextCompletionExpectsKVEmptyError,
PrefillChunkSizeSmallerThanImageError,
CannotFindImageEmbedError,
} from "./error";
type ImageURL = ChatCompletionContentPartImage.ImageURL;
export class LLMChatPipeline {
private config: ChatConfig;
private tokenizer: Tokenizer;
// TVM functions
private tvm: tvmjs.Instance;
private device: tvmjs.DLDevice;
private vm: tvmjs.VirtualMachine;
private prefill: tvmjs.PackedFunc;
private decoding: tvmjs.PackedFunc;
private image_embed: tvmjs.PackedFunc | undefined;
private embed: tvmjs.PackedFunc;
private fapplyBitmask: tvmjs.PackedFunc;
// Functions related to PagedKVCache
private fclearKVCaches: tvmjs.PackedFunc;
private fKVCacheAddSequence: tvmjs.PackedFunc;
private fKVCacheRemoveSequence: tvmjs.PackedFunc;
private fKVCacheBeginForward: tvmjs.PackedFunc;
private fKVCacheEndForward: tvmjs.PackedFunc;
private fKVCacheEnableSlidingWindowForSeq: tvmjs.PackedFunc;
// parameter states
private params: tvmjs.TVMObject;
private kvCache: tvmjs.TVMObject;
private logitsOnCPU?: tvmjs.NDArray = undefined;
private filledKVCacheLength = 0;
// meta data
private bosTokenId = 1;
private contextWindowSize = -1;
private slidingWindowSize = -1;
private attentionSinkSize = -1;
private prefillChunkSize = -1;
private resetStatsPerPrefill = true;
private stopStr: string[];
private stopTokens: Array<number>;
// states
private outputMessage = "";
private outputIds: Array<number> = [];
private stopTriggered = false;
private finishReason: ChatCompletionFinishReason | undefined = undefined;
// frequency of appeared token ids till now (refresh after PrefillStep); token_id mapped to freq
private appearedTokensFreq = new Map<number, number>();
private conversation: Conversation;
// The logprob information of all tokens for this current round (cleared upon each prefillStep)
// Cleared & updated at the exact same spots as `outputMessage`. Only updated when
// `genConfig.logprobs` is true. Each entry corresponds to a single autoregressive step.
private tokenLogprobArray: Array<ChatCompletionTokenLogprob> = [];
// stats, reset at every `resetChat(keepstats=false)`
private decodingTotalTime = 0;
private decodingTotalTokens = 0;
private prefillTotalTime = 0;
private prefillTotalTokens = 0;
// same stats as above, but reset at every `prefillStep()`
private curRoundDecodingTotalTokens = 0;
private curRoundPrefillTotalTokens = 0;
private curRoundDecodingTotalTime = 0;
private curRoundPrefillTotalTime = 0;
// LogitProcessor
private logitProcessor?: LogitProcessor = undefined;
// Grammar-related
// A grammar matcher for this current round if response_format is set. Reinitialized upon
// each step regardless of whether the chat is multi-round or not.
private grammarMatcher?: xgr.GrammarMatcher = undefined;
// The current schema or grammar string used for grammarMatcher; if undefined, grammarMatcher is
// simply using JSON mode. We use this field to determine whether we re-initiate a GrammarMatcher
// or simply reset the state during each round (i.e. during prefillStep).
private schemaOrGrammarStr?: string = undefined;
// A string list of tokens ordered by their token id, post-processed. Once initialized, will not
// be reinitialized since `this.tokenizer` does not change throughout the lifetime of LLMChatPipeline.
private xgTokenizerInfo?: xgr.TokenizerInfo = undefined;
// Compiler for grammar. It is persistent since it specializes on xgTokenizerInfo.
private grammarCompiler?: xgr.GrammarCompiler = undefined;
// Size of the bitmask for grammar, determined by fullVocabSize
private bitmaskSize: number;
// `vocab_size` read from `config.json`. Can be different from the size of the tokenTable for some
// models due to dummy padded tokens.
private fullVocabSize: number;
// Method to post process the token for grammar; either "byte_level" or default "byte_fallback".
private token_postproc_method: string;
// Whether to prepend space for grammar
private prepend_space_in_encode: boolean;
// stats for grammar-related overhead
// Time to initialize grammar matcher in seconds
private curRoundGrammarInitTotalTime = 0;
// Total time of getting next bitmask and accepting token in seconds
private curRoundGrammarPerTokenTotalTime = 0;
constructor(
tvm: tvmjs.Instance,
tokenizer: Tokenizer,
config: ChatConfig,
logitProcessor?: LogitProcessor,
) {
// 0. Setting attributes
this.tvm = tvm;
this.tokenizer = tokenizer;
this.config = config;
this.logitProcessor = logitProcessor;
this.fullVocabSize = this.config.vocab_size;
this.bitmaskSize = Math.ceil(this.fullVocabSize / 32);
this.conversation = getConversation(
config.conv_template,
config.conv_config,
);
this.stopStr = this.conversation.getStopStr();
this.stopTokens = this.conversation.getStopTokens();
if (config.bos_token_id !== undefined) {
this.bosTokenId = config.bos_token_id;
}
// Set token_post_proc_method, currently mlc-chat-config.json are unstable, hence various
// fallback mechanisms
if (config.tokenizer_info !== undefined) {
this.token_postproc_method = config.tokenizer_info.token_postproc_method;
this.prepend_space_in_encode =
config.tokenizer_info.prepend_space_in_encode;
} else if (config.token_table_postproc_method !== undefined) {
this.token_postproc_method = config.token_table_postproc_method;
this.prepend_space_in_encode = false;
} else {
log.warn(
"Cannot find `tokenizer_info` or `token_table_postproc_method` in `mlc-chat-config.json`, " +
"using default token_postproc_method `raw`.\n" +
"This field is only used for json mode.",
);
this.token_postproc_method = "raw";
this.prepend_space_in_encode = false;
}
log.info("token_postproc_method: ", this.token_postproc_method);
log.info("prepend_space_in_encode: ", this.prepend_space_in_encode);
this.device = this.tvm.webgpu();
// 1. Create VM and get the core functions
tvm.beginScope();
this.vm = this.tvm.detachFromCurrentScope(
this.tvm.createVirtualMachine(this.device),
);
this.prefill = this.tvm.detachFromCurrentScope(
this.vm.getFunction("prefill"),
);
this.embed = this.tvm.detachFromCurrentScope(this.vm.getFunction("embed"));
this.decoding = this.tvm.detachFromCurrentScope(
this.vm.getFunction("decode"),
);
this.fapplyBitmask = this.tvm.detachFromCurrentScope(
this.vm.getFunction("apply_bitmask_inplace"),
);
try {
this.image_embed = this.tvm.detachFromCurrentScope(
this.vm.getFunction("image_embed"),
);
} catch {
log.info("Cannot find function image_embed.");
}
// 2. Get json stored in the vm's metadata function
const fgetMetadata = this.vm.getFunction("_metadata");
const ret_value = fgetMetadata();
const metadataStr = this.tvm.detachFromCurrentScope(ret_value).toString();
const metadata = JSON.parse(metadataStr);
// 3. Load parameters by name
const paramNames: string[] = [];
metadata.params.forEach((param: any) => {
paramNames.push(param.name);
});
this.params = this.tvm.detachFromCurrentScope(
this.tvm.getParamsFromCacheByName(paramNames),
);
// 4. Read in compilation configurations from metadata
this.prefillChunkSize = metadata.prefill_chunk_size;
log.info("Using prefillChunkSize: ", this.prefillChunkSize);
if (this.prefillChunkSize <= 0) {
throw new MinValueError("prefill_chunk_size", 0);
}
// 5. Consolidate KVCache settings: context window, sliding window, attention sink
this.slidingWindowSize = config.sliding_window_size;
this.contextWindowSize = config.context_window_size;
this.attentionSinkSize = config.attention_sink_size;
if (this.contextWindowSize !== -1 && this.slidingWindowSize !== -1) {
throw new WindowSizeConfigurationError(
this.contextWindowSize,
this.slidingWindowSize,
);
} else if (this.slidingWindowSize != -1) {
// Use sliding window and attention sink
log.info("Using slidingWindowSize: ", this.slidingWindowSize);
if (this.attentionSinkSize >= 0) {
log.info("Using attentionSinkSize: ", this.attentionSinkSize);
} else {
throw new AttentionSinkSizeError();
}
} else if (this.contextWindowSize != -1) {
// Use default kv cache without sliding window
log.info("Using contextWindowSize: ", this.contextWindowSize);
} else {
throw new WindowSizeSpecificationError();
}
// 5. Create cache
// Load cache functions and instantiate KVCache
this.fclearKVCaches = this.tvm.detachFromCurrentScope(
this.tvm.getGlobalFunc("vm.builtin.kv_state_clear"),
);
this.fKVCacheAddSequence = this.tvm.detachFromCurrentScope(
this.tvm.getGlobalFunc("vm.builtin.kv_state_add_sequence"),
);
this.fKVCacheRemoveSequence = this.tvm.detachFromCurrentScope(
this.tvm.getGlobalFunc("vm.builtin.kv_state_remove_sequence"),
);
this.fKVCacheBeginForward = this.tvm.detachFromCurrentScope(
this.tvm.getGlobalFunc("vm.builtin.kv_state_begin_forward"),
);
this.fKVCacheEndForward = this.tvm.detachFromCurrentScope(
this.tvm.getGlobalFunc("vm.builtin.kv_state_end_forward"),
);
this.fKVCacheEnableSlidingWindowForSeq = this.tvm.detachFromCurrentScope(
this.tvm.getGlobalFunc(
"vm.builtin.attention_kv_cache_enable_sliding_window_for_seq",
),
);
// Create PagedKVCache; we do not expose KVCache config for now
const fcreateCache = this.vm.getFunction("create_tir_paged_kv_cache");
const defaultPageSize = 16;
const defaultMaxNumSequence = 1;
const maxTotalSeqLen =
this.slidingWindowSize != -1
? this.slidingWindowSize
: this.contextWindowSize;
this.kvCache = this.tvm.detachFromCurrentScope(
fcreateCache(
this.tvm.makeShapeTuple([defaultMaxNumSequence]), // max_num_sequence
this.tvm.makeShapeTuple([maxTotalSeqLen]), // max_total_sequence_length
this.tvm.makeShapeTuple([this.prefillChunkSize]), // prefill_chunk_size
this.tvm.makeShapeTuple([defaultPageSize]), // page_size, hard coded for now
this.tvm.makeShapeTuple([this.slidingWindowSize != -1 ? 1 : 0]),
),
);
this.filledKVCacheLength = 0;
this.resetChat(); // especially needed for PagedKVCache as we need to call fKVCacheAddSequence
tvm.endScope();
}
dispose() {
// TODO: Do we need to dispose all PackedFuncs here?
this.grammarMatcher?.dispose();
this.params.dispose();
this.decoding.dispose();
this.prefill.dispose();
this.embed.dispose();
this.image_embed?.dispose();
this.vm.dispose();
this.kvCache.dispose();
this.fclearKVCaches.dispose();
this.logitsOnCPU?.dispose();
this.tvm.dispose();
this.tokenizer.dispose();
this.xgTokenizerInfo?.dispose();
this.grammarCompiler?.dispose();
}
/**
* Get the current message.
*/
getMessage() {
return this.outputMessage;
}
/**
* Reset the runtime statistics
*/
resetRuntimeStats() {
this.prefillTotalTime = 0;
this.prefillTotalTokens = 0;
this.decodingTotalTime = 0;
this.decodingTotalTokens = 0;
}
/**
* Reset the chat history
*/
resetChat(keepStats = false) {
this.tvm.beginScope();
this.conversation.reset();
if (!keepStats) {
this.resetRuntimeStats();
}
this.resetKVCache();
this.filledKVCacheLength = 0;
this.logitProcessor?.resetState();
this.tvm.endScope();
}
/**
* Reset KV Cache
*/
resetKVCache() {
this.fclearKVCaches(this.kvCache);
this.fKVCacheAddSequence!(this.kvCache, new tvmjs.Scalar(0, "int64"));
if (this.slidingWindowSize != -1) {
this.fKVCacheEnableSlidingWindowForSeq(
this.kvCache,
new tvmjs.Scalar(0, "int64"),
new tvmjs.Scalar(this.slidingWindowSize, "int32"),
new tvmjs.Scalar(this.attentionSinkSize, "int32"),
);
}
}
/**
* @returns Whether stop is triggered.
*/
stopped(): boolean {
return this.stopTriggered;
}
/**
* @returns Finish reason; undefined if generation not started/stopped yet.
*/
getFinishReason(): ChatCompletionFinishReason | undefined {
return this.finishReason;
}
/**
* @returns tokenLogprobArray for this current round of autoregressive generation.
* Updated upon each sampled token, cleared upon each prefillStep().
*/
getTokenLogprobArray(): Array<ChatCompletionTokenLogprob> {
return this.tokenLogprobArray;
}
/**
* @returns the number of tokens decoded for a single request or a single choice in the request.
*/
getCurRoundDecodingTotalTokens(): number {
return this.curRoundDecodingTotalTokens;
}
/**
* @returns the number of tokens decoded for a single request or a single choice in the request.
*/
getCurRoundPrefillTotalTokens(): number {
return this.curRoundPrefillTotalTokens;
}
/**
* @returns the time spent on decode for a single request or a single choice in the request.
*/
getCurRoundDecodingTotalTime(): number {
return this.curRoundDecodingTotalTime;
}
/**
* @returns the time spent on for a single request or a single choice in the request.
*/
getCurRoundPrefillTotalTime(): number {
return this.curRoundPrefillTotalTime;
}
/**
* @returns the time (seconds) spent on for initializing grammar matcher for a single request.
*/
getCurRoundGrammarInitTotalTime(): number {
return this.curRoundGrammarInitTotalTime;
}
/**
* @returns the total time (seconds) spent on creating bitmask and accepting token grammar matcher
* for all the generated tokens in a single request.
*/
getCurRoundGrammarPerTokenTotalTime(): number {
return this.curRoundGrammarPerTokenTotalTime;
}
/**
* @returns Runtime stats information.
*/
runtimeStatsText(): string {
return (
`prefill: ${(this.prefillTotalTokens / this.prefillTotalTime).toFixed(4)} tokens/sec, ` +
`decoding: ${(this.decodingTotalTokens / this.decodingTotalTime).toFixed(4)} tokens/sec`
);
}
/**
* @returns Runtime stats information, starting from the last prefill performed.
*/
curRoundRuntimeStatsText(): string {
return (
`prefill: ${this.getCurRoundPrefillTokensPerSec().toFixed(4)} tokens/sec, ` +
`decoding: ${this.getCurRoundDecodingTokensPerSec().toFixed(4)} tokens/sec`
);
}
/**
* @returns Prefill tokens per second, starting from the last prefill performed.
*/
getCurRoundPrefillTokensPerSec(): number {
return this.curRoundPrefillTotalTokens / this.curRoundPrefillTotalTime;
}
/**
* @returns Prefill tokens per second, starting from the last prefill performed.
*/
getCurRoundDecodingTokensPerSec(): number {
return this.curRoundDecodingTotalTokens / this.curRoundDecodingTotalTime;
}
/**
* Set the seed for the RNG `this.tvm.rng`.
*/
setSeed(seed: number): void {
this.tvm.setSeed(seed);
}
// Getters and setters for this.conversation.
/**
* @returns The conversation object (not a deep copy).
*/
getConversationObject(): Conversation {
return this.conversation;
}
/**
* Set this.conversation to a new conversation object.
*/
setConversation(newConv: Conversation) {
this.conversation = newConv;
this.stopStr = this.conversation.getStopStr();
this.stopTokens = this.conversation.getStopTokens();
}
async asyncLoadWebGPUPipelines() {
await this.tvm.asyncLoadWebGPUPipelines(this.vm.getInternalModule());
}
/**
* Generate the first token given input prompt
*/
async prefillStep(
inp: string,
msgRole: Role, // either user or tool
inp_role_str?: string,
genConfig?: GenerationConfig,
): Promise<void> {
if (msgRole !== Role.user && msgRole !== Role.tool) {
throw new MessageOrderError(
"The last message should be from `user` or `tool`.",
);
}
if (this.resetStatsPerPrefill) {
this.resetRuntimeStats();
}
const tstart = performance.now();
// cleanup the per convo states
this.outputIds = [];
this.appearedTokensFreq.clear();
this.outputMessage = "";
this.tokenLogprobArray = [];
this.curRoundDecodingTotalTokens = 0;
this.curRoundPrefillTotalTokens = 0;
this.curRoundPrefillTotalTime = 0;
this.curRoundDecodingTotalTime = 0;
this.curRoundGrammarInitTotalTime = 0;
this.curRoundGrammarPerTokenTotalTime = 0;
this.stopTriggered = false;
const conversation = this.conversation;
// -1. Instantiate grammar matcher according to generation config. This step is overlapped
// with prefilling the prompt to hide overhead by using this promise.
let grammarMatcherInitPromise: Promise<void> | undefined = undefined;
if (
genConfig?.response_format?.type === "json_object" ||
genConfig?.response_format?.type === "grammar"
) {
const curSchemaOrGrammarStr =
genConfig.response_format.schema || genConfig.response_format.grammar;
if (
curSchemaOrGrammarStr === this.schemaOrGrammarStr &&
this.grammarMatcher
) {
// If we did not change the schema and have instantiated a GrammarMatcher, we reuse it.
const tGrammarInitStart = performance.now();
log.info("Reuse grammar matcher.");
this.grammarMatcher.reset();
this.curRoundGrammarInitTotalTime =
(performance.now() - tGrammarInitStart) / 1e3;
} else {
// Else dispose current grammarMatcher, reinitialize, and update this.schema.
/* eslint-disable no-async-promise-executor */
grammarMatcherInitPromise = new Promise(async (resolve) => {
const tGrammarInitStart = performance.now();
log.info("Initialize new grammar matcher.");
if (this.grammarMatcher) {
this.grammarMatcher.dispose();
}
if (this.xgTokenizerInfo === undefined) {
log.info("Initialize token table.");
// Post process entire table
const rawTokenTable = getTokenTableFromTokenizer(this.tokenizer);
this.xgTokenizerInfo = await xgr.TokenizerInfo.createTokenizerInfo(
rawTokenTable,
this.token_postproc_method,
this.prepend_space_in_encode,
this.fullVocabSize,
this.stopTokens,
);
this.grammarCompiler =
await xgr.GrammarCompiler.createGrammarCompiler(
this.xgTokenizerInfo,
);
}
const grammar: xgr.CompiledGrammar =
curSchemaOrGrammarStr === undefined
? await this.grammarCompiler!.compileBuiltinJSONGrammar()
: genConfig?.response_format?.type === "json_object"
? await this.grammarCompiler!.compileJSONSchema(
curSchemaOrGrammarStr,
)
: await this.grammarCompiler!.compileGrammar(
curSchemaOrGrammarStr,
);
this.grammarMatcher =
await xgr.GrammarMatcher.createGrammarMatcher(grammar);
grammar.dispose();
this.schemaOrGrammarStr = curSchemaOrGrammarStr;
this.curRoundGrammarInitTotalTime =
(performance.now() - tGrammarInitStart) / 1e3;
resolve();
});
}
}
// 0. Get inputData from conversation
if (conversation.isTextCompletion) {
conversation.prompt = inp;
} else {
conversation.appendMessage(msgRole, inp, inp_role_str);
conversation.appendReplyHeader(Role.assistant);
}
const retGetInputData = this.getInputData();
const inputData: Array<Array<number> | ImageURL> = retGetInputData[0];
const promptLen: number = retGetInputData[1];
// Check if LLMChatPipeline fits for forwarding image input
let hasImageInput = false;
inputData.forEach((data) => {
if (!Array.isArray(data)) {
hasImageInput = true;
}
});
if (hasImageInput && this.prefillChunkSize < IMAGE_EMBED_SIZE) {
throw new PrefillChunkSizeSmallerThanImageError(
this.prefillChunkSize,
IMAGE_EMBED_SIZE,
);
}
if (hasImageInput && this.image_embed === undefined) {
throw new CannotFindImageEmbedError();
}
// 1. Chunk inputData to embed and forward in one shot for each, minimize intermediate data
const retGetChunks = getChunkedPrefillInputData(
inputData,
this.prefillChunkSize,
);
const chunks: Array<Array<number> | ImageURL>[] = retGetChunks[0];
const chunkLens: Array<number> = retGetChunks[1];
// 2. Prefill each chunk
this.tvm.beginScope();
let logits: tvmjs.NDArray;
for (let i = 0; i < chunks.length; i++) {
const chunk = chunks[i];
const chunkLen = chunkLens[i];
const prevFilledLen = this.filledKVCacheLength;
logits = this.tvm.detachFromCurrentScope(
await this.embedAndForward(chunk, chunkLen),
);
if (this.filledKVCacheLength !== prevFilledLen + chunkLen) {
throw new Error(
"Internal Error: filledKVCacheLength does not match expected value.",
);
}
}
this.tvm.endScope();
// 4. Sample, stats, post process token sampled.
// We wait for prefill and grammar matcher init to finish
await Promise.all([this.device.sync(), grammarMatcherInitPromise]);
const nextToken = await this.sampleTokenFromLogits(logits!, genConfig);
logits!.dispose();
const tend = performance.now();
this.prefillTotalTime += (tend - tstart) / 1e3;
this.prefillTotalTokens += promptLen;
this.curRoundPrefillTotalTokens += promptLen;
this.curRoundPrefillTotalTime += (tend - tstart) / 1e3;
this.processNextToken(nextToken, genConfig);
}
async decodeStep(genConfig?: GenerationConfig): Promise<void> {
if (this.stopTriggered) {
throw Error("Cannot run decode when stopped");
}
const tstart = performance.now();
this.tvm.beginScope();
const chunk: Array<Array<number>> = [
this.outputIds.slice(this.outputIds.length - 1),
];
const chunkLen = chunk.length;
const prevFilledLen = this.filledKVCacheLength;
const logits = this.tvm.detachFromCurrentScope(
await this.embedAndForward(chunk, chunkLen),
);
if (this.filledKVCacheLength !== prevFilledLen + chunkLen) {
throw new Error(
"Internal Error: filledKVCacheLength does not match expected value.",
);
}
this.tvm.endScope();
// sample from logits
const nextToken = await this.sampleTokenFromLogits(logits, genConfig);
logits.dispose();
const tend = performance.now();
this.decodingTotalTime += (tend - tstart) / 1e3;
this.decodingTotalTokens += 1;
this.curRoundDecodingTotalTokens += 1;
this.curRoundDecodingTotalTime += (tend - tstart) / 1e3;
this.processNextToken(nextToken, genConfig);
}
/**
* Manually trigger stop if it is not stopped.
*/
triggerStop() {
if (this.stopTriggered) {
return;
}
this.stopTriggered = true;
this.finishReason = "abort";
if (!this.conversation.isTextCompletion) {
this.conversation.finishReply(this.outputMessage);
}
}
/**
* Add a generated token and check for stop.
*
* @param nextToken The next token.
* @param genConfig Configs that override `this.config` for this round of generation.
*/
private processNextToken(
nextToken: number,
genConfig?: GenerationConfig,
): void {
if (this.stopTriggered) {
throw Error("Cannot call process when it is stoppped");
}
// Get max_tokens from generationConfig (specified by user in completion request)
// If not specified, do not set a limit
let max_tokens = Infinity;
if (genConfig !== undefined && genConfig.max_tokens) {
max_tokens = genConfig.max_tokens;
}
if (max_tokens <= 0) {
throw new MinValueError("max_tokens", 0);
}
// Get ignore_eos from generationConfig (specified by user in completion request)
let ignore_eos = false;
if (
genConfig !== undefined &&
genConfig.ignore_eos !== undefined &&
genConfig.ignore_eos !== null
) {
ignore_eos = genConfig.ignore_eos;
}
// Get stopStrs, possibly overridden by genConfig for this round
let stopStrs = this.stopStr;
if (genConfig !== undefined && genConfig.stop) {
stopStrs = stopStrs.concat(genConfig.stop);
}
let stopTokens = this.stopTokens;
if (ignore_eos) {
stopTokens = [];
stopStrs = [];
}
// Stop condition 1: stop token; otherwise, append to `this.outputIds`
if (stopTokens.includes(nextToken)) {
this.stopTriggered = true;
this.finishReason = "stop";
}
if (!this.stopTriggered) {
this.outputIds.push(nextToken);
// Update token appearance frequency
const curFreq = this.appearedTokensFreq.get(nextToken);
if (curFreq !== undefined) {
this.appearedTokensFreq.set(nextToken, curFreq + 1);
} else {
this.appearedTokensFreq.set(nextToken, 1);
}
}
// Stop condition 2: stop string; update `this.outputMessage` subsequently
let outputMessage = this.tokenizer.decode(new Int32Array(this.outputIds));
let stopPos = -1;
for (const stopStr of stopStrs) {
// Stop at the first stopStr we find
stopPos = outputMessage.lastIndexOf(stopStr);
if (stopPos != -1) {
outputMessage = outputMessage.substring(0, stopPos);
this.stopTriggered = true;
this.finishReason = "stop";
break;
}
}
this.outputMessage = outputMessage;
// Stop condition 3: exceed max_tokens
if (this.outputIds.length >= max_tokens) {
this.stopTriggered = true;
this.finishReason = "length";
log.info("Generation stopped due to exceeding max_tokens.");
}
// Stop condition 4: exceed KVCache's context window size
if (
this.slidingWindowSize == -1 &&
this.filledKVCacheLength == this.contextWindowSize
) {
this.stopTriggered = true;
this.finishReason = "length";
log.info("Generation stopped due to exceeding context_window_size.");
}
// Finally, modify conversation history if stopped
if (this.stopTriggered) {
if (!this.conversation.isTextCompletion) {
this.conversation.finishReply(this.outputMessage);
}
}
}
/**
* Given input tokens, return embeddings of them by calling embed kernel.
*
* @note precondition: inputTokens.length <= prefillChunkSize, since we take care of
* chunking in `getChunkedPrefillInputData()`.
*/
private getTokensEmbeddings(inputTokens: number[]): tvmjs.NDArray {
this.tvm.beginScope();
if (inputTokens.length > this.prefillChunkSize) {
throw new Error(
"Internal Error: getTokensEmbeddings input should be <= prefillChunkSize.",
);
}
const inputData = this.tvm.empty(
[inputTokens.length],
"int32",
this.device,
);
inputData.copyFrom(inputTokens);
const embed: tvmjs.NDArray = this.tvm.detachFromCurrentScope(
this.embed!(inputData, this.params),
);
this.tvm.endScope();
this.tvm.attachToCurrentScope(embed); // tracked by scope of embedAndForward
return embed;
}
/**
* Embed an image input.
*/
private async getImageEmbeddings(
inputImage: ImageURL,
): Promise<tvmjs.NDArray> {
this.tvm.beginScope();
// 1. Transform ImageURL into image input in NDArray
const url = inputImage.url;
// url starting with `data:image` and `http` share the same loading method
const imgData: ImageData = await getImageDataFromURL(url);
const pixelValues: Uint8ClampedArray = getRGBArrayFromImageData(imgData);
const pixelArray = this.tvm
// .empty([imgData.height, imgData.width, 3], "uint8", this.device)
.empty([imgData.height, imgData.width, 3], "uint32", this.device)
.copyFrom(pixelValues)
.view([1, imgData.height, imgData.width, 3]); // NHWC
// 2. Call image embed kernel
const embed: tvmjs.NDArray = this.tvm.detachFromCurrentScope(
this.image_embed!(pixelArray, this.params),
);
if (embed.shape[0] !== IMAGE_EMBED_SIZE) {
throw new Error(
`InternalError: expect embed.shape[0] to be ${IMAGE_EMBED_SIZE}, ` +
`but got ${embed.shape[0]}`,
);
}
this.tvm.endScope();
this.tvm.attachToCurrentScope(embed); // tracked by scope of embedAndForward
return embed;
}
/**
* Embed and forward input data, that can be either array of tokens, or an image.
* This will increment `this.filledKVCacheLength`.
*
* @param inputData data to embed and forward
* @param inputDataLen length of this inputData, should smaller than prefill chunk size.
* @returns The logits returned by this forward as tvmjs.NDArray on GPU.
*
* @note Precondition: inputData's data length is smaller than prefill chunk size
*/
private async embedAndForward(
inputData: Array<Array<number> | ImageURL>,
inputDataLen: number,
): Promise<tvmjs.NDArray> {
if (inputDataLen > this.prefillChunkSize) {
throw new Error(
"InternalError: expect inputDataLen <= this.prefillChunkSize.",
);
}
// TODO: we should combine string data to embed once, then rearrange the embeddings; currently
// ["hi", imageUrl, "hi"] would call embed kernels 3 times, while 2 would suffice.
// 1. Embed all inputData
this.tvm.beginScope();
const embeddings: tvmjs.NDArray[] = [];
for (let i = 0; i < inputData.length; i++) {
const data = inputData[i];
if (Array.isArray(data)) {
embeddings.push(this.getTokensEmbeddings(data));
} else {
embeddings.push(await this.getImageEmbeddings(data));
}
}
// 2. Concatenate embeddings
let allEmbeddings: tvmjs.NDArray;
if (embeddings.length === 1) {
allEmbeddings = embeddings[0];
} else {
allEmbeddings = this.tvm.concatEmbeddings(embeddings);
}
if (inputDataLen !== allEmbeddings.shape[0]) {
throw new Error("InternalError: expect seqLen == allEmbeddings.shape[0]");
}
allEmbeddings = allEmbeddings.view([1].concat(allEmbeddings.shape));
// TODO: Should we end this scope here and begin another scope? Will this dispose embeddings to
// save RAM? We will detach allEmbeddings from this scope and attach to the next scope.
// 3. Forward the concatenated embeddings
const inputLenShape = this.tvm.makeShapeTuple([inputDataLen]);
const seqIdsTuple = this.tvm.makeShapeTuple([0]);
this.fKVCacheBeginForward!(this.kvCache, seqIdsTuple, inputLenShape);
let retValue;
if (inputDataLen > 1) {
retValue = this.prefill(allEmbeddings, this.kvCache, this.params);
} else {
retValue = this.decoding(allEmbeddings, this.kvCache, this.params);
}
// Epilogue
this.fKVCacheEndForward!(this.kvCache);
this.filledKVCacheLength += inputDataLen;
const logits = this.tvm.detachFromCurrentScope(retValue.get(0));
this.tvm.endScope();
this.tvm.attachToCurrentScope(logits);
return logits;
}
// NOTE: caller must call device.sync()
private updateLogitsOnCPU(logits: tvmjs.NDArray): tvmjs.NDArray {
if (this.logitsOnCPU == undefined) {
this.logitsOnCPU = this.tvm.detachFromCurrentScope(
this.tvm.empty(logits.shape, logits.dtype, this.tvm.cpu()),
);
} else {
if (logits.shape[0] != this.logitsOnCPU.shape[0]) {
throw Error("We expect the size of logits to remain unchanged");
}
}
this.logitsOnCPU.copyFrom(logits);
return this.logitsOnCPU;
}
private async sampleTokenFromLogits(
logitsOnGPU: tvmjs.NDArray,
genConfig?: GenerationConfig,
) {
// 0. Get value of temperature, top_p, and various penalties, possibly overridden by genConfig
// Also load other genConfig items like logit_bias. Consume all fields of `genConfig` here.
function _hasValue(value: any): boolean {
// if we use `if value` directly, `value` being 0 evaluates to false, violating semantics
return value !== undefined && value !== null;
}
let temperature: number = this.config.temperature;
let top_p: number = this.config.top_p;
let repetition_penalty: number = this.config.repetition_penalty;
let frequency_penalty: number = this.config.frequency_penalty;
let presence_penalty: number = this.config.presence_penalty;
let logit_bias: Record<string, number> | undefined = undefined;
let logprobs: boolean | undefined = undefined;
let top_logprobs: number | undefined = undefined;
let response_format: ResponseFormat | undefined = undefined;
if (genConfig !== undefined) {
if (_hasValue(genConfig.temperature)) {
temperature = genConfig.temperature!;
}
if (_hasValue(genConfig.top_p)) {
top_p = genConfig.top_p!;
}
if (_hasValue(genConfig.repetition_penalty)) {
repetition_penalty = genConfig.repetition_penalty!;
}
if (_hasValue(genConfig.frequency_penalty)) {
frequency_penalty = genConfig.frequency_penalty!;
}
if (_hasValue(genConfig.presence_penalty)) {
presence_penalty = genConfig.presence_penalty!;
}
// If only one of frequency or presence penatly is set, make the other one 0.0
if (_hasValue(frequency_penalty) && !_hasValue(presence_penalty)) {
presence_penalty = 0.0;
}
if (_hasValue(presence_penalty) && !_hasValue(frequency_penalty)) {
frequency_penalty = 0.0;
}
if (_hasValue(genConfig.logit_bias)) {
logit_bias = genConfig.logit_bias!;
}
if (_hasValue(genConfig.logprobs)) {
logprobs = genConfig.logprobs!;
}
if (_hasValue(genConfig.top_logprobs)) {
top_logprobs = genConfig.top_logprobs!;
}