forked from mlc-ai/web-llm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathengine.ts
1390 lines (1302 loc) · 46 KB
/
engine.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
import * as tvmjs from "@mlc-ai/web-runtime";
import log from "loglevel";
import {
ChatConfig,
ChatOptions,
AppConfig,
prebuiltAppConfig,
GenerationConfig,
postInitAndCheckGenerationConfigValues,
Role,
MLCEngineConfig,
DefaultLogLevel,
ModelType,
} from "./config";
import { LLMChatPipeline } from "./llm_chat";
import {
// ChatCompletion
ChatCompletionRequest,
ChatCompletion,
ChatCompletionChunk,
ChatCompletionMessageParam,
ChatCompletionRequestNonStreaming,
ChatCompletionRequestStreaming,
ChatCompletionRequestBase,
CompletionUsage,
ChatCompletionMessageToolCall,
// Completion
CompletionCreateParamsNonStreaming,
CompletionCreateParamsStreaming,
CompletionCreateParamsBase,
CompletionCreateParams,
Completion,
CompletionChoice,
EmbeddingCreateParams,
CreateEmbeddingResponse,
Embedding,
} from "./openai_api_protocols/index";
import * as API from "./openai_api_protocols/index";
import {
InitProgressCallback,
MLCEngineInterface,
LogitProcessor,
LogLevel,
} from "./types";
import {
compareConversationObject,
getConversation,
getConversationFromChatCompletionRequest,
} from "./conversation";
import {
cleanModelUrl,
CustomLock,
findModelRecord,
getModelIdToUse,
getToolCallFromOutputMessage,
} from "./support";
import {
ConfigurationNotInitializedError,
DeviceLostError,
EmbeddingUnsupportedModelError,
FeatureSupportError,
MissingModelWasmError,
ShaderF16SupportError,
WebGPUNotAvailableError,
ReloadArgumentSizeUnmatchedError,
IncorrectPipelineLoadedError,
ReloadModelIdNotUniqueError,
SpecifiedModelNotFoundError,
ModelNotLoadedError,
} from "./error";
import { asyncLoadTokenizer } from "./cache_util";
import { EmbeddingPipeline } from "./embedding";
/**
* Creates `MLCEngine`, and loads `modelId` onto WebGPU.
*
* Equivalent to `new webllm.MLCEngine().reload(...)`.
*
* @param modelId model_id of the model to load, either string or string[]. When multiple models
* are provided, we load all models sequentially. Each modelId needs to either be in
* `webllm.prebuiltAppConfig`, or in `engineCOnfig.appConfig`.
* @param engineConfig Optionally configures the engine, see `webllm.MLCEngineConfig`.
* @param chatOpts Extra options to optionally override the `mlc-chat-config.json` of `modelId`.
* The size of which needs to match that of `modelId`; chatOpts[i] will be used for modelId[i].
* @returns An initialized `WebLLM.MLCEngine` with `modelId` loaded.
* @throws Throws error when device lost (mostly due to OOM); users should re-call `CreateMLCEngine()`,
* potentially with a smaller model or smaller context window size.
*/
export async function CreateMLCEngine(
modelId: string | string[],
engineConfig?: MLCEngineConfig,
chatOpts?: ChatOptions | ChatOptions[],
): Promise<MLCEngine> {
const engine = new MLCEngine(engineConfig);
await engine.reload(modelId, chatOpts);
return engine;
}
/**
* The main interface of MLCEngine, which loads a model and performs tasks.
*
* You can either initialize one with `webllm.CreateMLCEngine(modelId)`, or
* `webllm.MLCEngine().reload(modelId)`.
*/
export class MLCEngine implements MLCEngineInterface {
// APIs
/** For chat.completions.create() */
public chat: API.Chat;
/** For completions.create() */
public completions: API.Completions;
/** For embeddings.create() */
public embeddings: API.Embeddings;
// Maps to maintain states of loaded model(s)
/** Maps each loaded model's modelId to its pipeline */
private loadedModelIdToPipeline: Map<
string,
LLMChatPipeline | EmbeddingPipeline
>;
/** Maps each loaded model's modelId to its chatConfig */
private loadedModelIdToChatConfig: Map<string, ChatConfig>;
/** Maps each loaded model's modelId to its modelType */
private loadedModelIdToModelType: Map<string, ModelType>;
/** Maps each loaded model's modelId to a lock. Ensures
* each model only processes one request at at time.
*/
private loadedModelIdToLock: Map<string, CustomLock>;
// Others
private logger: (msg: string) => void = log.info;
private logitProcessorRegistry?: Map<string, LogitProcessor>;
private initProgressCallback?: InitProgressCallback;
private appConfig: AppConfig;
// Signals and flags
private interruptSignal = false;
private deviceLostIsError = true; // whether device.lost is due to actual error or model reload
private reloadController: AbortController | undefined;
constructor(engineConfig?: MLCEngineConfig) {
this.loadedModelIdToPipeline = new Map<
string,
LLMChatPipeline | EmbeddingPipeline
>();
this.loadedModelIdToChatConfig = new Map<string, ChatConfig>();
this.loadedModelIdToModelType = new Map<string, ModelType>();
this.loadedModelIdToLock = new Map<string, CustomLock>();
this.appConfig = engineConfig?.appConfig || prebuiltAppConfig;
this.setLogLevel(engineConfig?.logLevel || DefaultLogLevel);
this.setInitProgressCallback(engineConfig?.initProgressCallback);
this.setLogitProcessorRegistry(engineConfig?.logitProcessorRegistry);
this.chat = new API.Chat(this);
this.completions = new API.Completions(this);
this.embeddings = new API.Embeddings(this);
}
//-----------------------
// 0. Setters and getters
//-----------------------
setAppConfig(appConfig: AppConfig) {
this.appConfig = appConfig;
}
setInitProgressCallback(initProgressCallback?: InitProgressCallback) {
this.initProgressCallback = initProgressCallback;
}
getInitProgressCallback() {
return this.initProgressCallback;
}
setLogitProcessorRegistry(
logitProcessorRegistry?: Map<string, LogitProcessor>,
) {
this.logitProcessorRegistry = logitProcessorRegistry;
}
/**
* Set MLCEngine logging output level
*
* @param logLevel The new log level
*/
setLogLevel(logLevel: LogLevel) {
log.setLevel(logLevel);
}
//----------------------------------------
// 1. Model/pipeline loading and unloading
//----------------------------------------
async reload(
modelId: string | string[],
chatOpts?: ChatOptions | ChatOptions[],
): Promise<void> {
// 0. Unload all loaded models
await this.unload();
// 1. Convert inputs to arrays
if (!Array.isArray(modelId)) {
modelId = [modelId];
}
if (chatOpts !== undefined && !Array.isArray(chatOpts)) {
chatOpts = [chatOpts];
}
// 2. Check whether size matches
if (chatOpts !== undefined && modelId.length !== chatOpts.length) {
throw new ReloadArgumentSizeUnmatchedError(
modelId.length,
chatOpts.length,
);
}
// 3. Make sure each model in modelId is unique
if (new Set(modelId).size < modelId.length) {
throw new ReloadModelIdNotUniqueError(modelId);
}
// 4. Sequentially load each model
// Single abort should stop all to-be-loaded models
this.reloadController = new AbortController();
try {
for (let i = 0; i < modelId.length; i++) {
await this.reloadInternal(
modelId[i],
chatOpts ? chatOpts[i] : undefined,
);
}
} catch (error) {
if (error instanceof DOMException && error.name === "AbortError") {
log.warn("Reload() is aborted.", error.message);
return;
}
throw error;
} finally {
this.reloadController = undefined;
}
}
private async reloadInternal(
modelId: string,
chatOpts?: ChatOptions,
): Promise<void> {
const logitProcessor = this.logitProcessorRegistry?.get(modelId);
const tstart = performance.now();
// look up and parse model record, record model type
const modelRecord = findModelRecord(modelId, this.appConfig);
const baseUrl =
typeof document !== "undefined"
? document.URL
: globalThis.location.origin;
let modelUrl = cleanModelUrl(modelRecord.model);
if (!modelUrl.startsWith("http")) {
modelUrl = new URL(modelUrl, baseUrl).href;
}
const modelType =
modelRecord.model_type === undefined || modelRecord.model_type === null
? ModelType.LLM
: modelRecord.model_type;
this.loadedModelIdToModelType.set(modelId, modelType);
// instantiate cache
let configCache: tvmjs.ArtifactCacheTemplate;
if (this.appConfig.useIndexedDBCache) {
configCache = new tvmjs.ArtifactIndexedDBCache("webllm/config");
} else {
configCache = new tvmjs.ArtifactCache("webllm/config");
}
// load config
const configUrl = new URL("mlc-chat-config.json", modelUrl).href;
const curModelConfig = {
...(await configCache.fetchWithCache(
configUrl,
"json",
this.reloadController?.signal,
)),
...modelRecord.overrides,
...chatOpts,
} as ChatConfig;
this.loadedModelIdToChatConfig.set(modelId, curModelConfig);
// load tvm wasm
let wasmCache: tvmjs.ArtifactCacheTemplate;
if (this.appConfig.useIndexedDBCache) {
wasmCache = new tvmjs.ArtifactIndexedDBCache("webllm/wasm");
} else {
wasmCache = new tvmjs.ArtifactCache("webllm/wasm");
}
const wasmUrl = modelRecord.model_lib;
if (wasmUrl === undefined) {
throw new MissingModelWasmError(modelRecord.model_id);
}
const fetchWasmSource = async () => {
if (wasmUrl.includes("localhost")) {
// do not cache wasm on local host as we might update code frequently
return (await fetch(wasmUrl)).arrayBuffer();
} else if (!wasmUrl.startsWith("http")) {
// do not cache wasm on the same server as it can also refresh
// rely on the normal caching strategy
return (await fetch(new URL(wasmUrl, baseUrl).href)).arrayBuffer();
} else {
return await wasmCache.fetchWithCache(
wasmUrl,
"arraybuffer",
this.reloadController?.signal,
);
}
};
const wasmSource = await fetchWasmSource();
const tvm = await tvmjs.instantiate(
new Uint8Array(wasmSource),
tvmjs.createPolyfillWASI(),
this.logger,
);
if (this.initProgressCallback !== undefined) {
tvm.registerInitProgressCallback(this.initProgressCallback);
}
// detect GPU
const gpuDetectOutput = await tvmjs.detectGPUDevice();
if (gpuDetectOutput == undefined) {
throw new WebGPUNotAvailableError();
}
let gpuLabel = "WebGPU";
if (gpuDetectOutput.adapterInfo.description.length != 0) {
gpuLabel += " - " + gpuDetectOutput.adapterInfo.description;
} else {
gpuLabel += " - " + gpuDetectOutput.adapterInfo.vendor;
}
if (modelRecord.required_features !== undefined) {
for (const feature of modelRecord.required_features) {
if (!gpuDetectOutput.device.features.has(feature)) {
if (feature == "shader-f16") {
throw new ShaderF16SupportError();
}
throw new FeatureSupportError(feature);
}
}
}
// Most device lost happens in `reload()` since we allocate memory ahead of time. So we can
// use this flag at the end of `reload()` to make the error handling synchronous.
// This `.then()` exists throughout the lifetime of the device. Though we have not
// experienced device error outside of `reload()`, it is still possible this `.then()` is
// triggered outside of `reload()`. TODO: does this cause unexpected behavior?
let deviceLostInReload = false;
gpuDetectOutput.device.lost.then((info: any) => {
if (this.deviceLostIsError) {
log.error(
`Device was lost. This can happen due to insufficient memory or other GPU constraints. ` +
`Detailed error: ${info}. Please try to reload WebLLM with a less resource-intensive model.`,
);
this.unload();
deviceLostInReload = true;
}
});
tvm.initWebGPU(gpuDetectOutput.device);
const tokenizer = await asyncLoadTokenizer(
modelUrl,
curModelConfig,
this.appConfig,
this.logger,
);
const cacheType = this.appConfig.useIndexedDBCache ? "indexeddb" : "cache";
await tvm.fetchNDArrayCache(
modelUrl,
tvm.webgpu(),
"webllm/model",
cacheType,
this.reloadController?.signal,
);
// Instantiate pipeline
// TODO: would be good to somehow check for error when LLMChatPipeline is loaded for an
// embedding model, and prompt user to use ModelRecord.model_type
let newPipeline: LLMChatPipeline | EmbeddingPipeline;
if (modelRecord.model_type === ModelType.embedding) {
newPipeline = new EmbeddingPipeline(tvm, tokenizer, curModelConfig);
} else {
newPipeline = new LLMChatPipeline(
tvm,
tokenizer,
curModelConfig,
logitProcessor,
);
}
await newPipeline.asyncLoadWebGPUPipelines();
this.loadedModelIdToPipeline.set(modelId, newPipeline);
this.loadedModelIdToLock.set(modelId, new CustomLock());
// Clean up
const tend = performance.now();
if (this.initProgressCallback !== undefined) {
const text = "Finish loading on " + gpuLabel;
this.initProgressCallback({
progress: 1,
timeElapsed: (tend - tstart) / 1e3,
text: text,
});
}
if (deviceLostInReload) {
throw new DeviceLostError();
}
}
async unload() {
this.deviceLostIsError = false; // so that unload() does not trigger device.lost error
// TODO: can optimize by calling dispose() to all pipelines in parallel. However, need to wait
// for all sync() to finish before proceeding (e.g. naive forEach does not work)
for (const entry of Array.from(this.loadedModelIdToPipeline.entries())) {
const pipeline = entry[1];
pipeline.dispose();
// Wait until device is actually destroyed so we can safely set deviceLostIsError back to true
await pipeline.sync();
}
this.loadedModelIdToPipeline.clear();
this.loadedModelIdToChatConfig.clear();
this.loadedModelIdToModelType.clear();
this.loadedModelIdToLock.clear();
this.deviceLostIsError = true;
if (this.reloadController) {
this.reloadController.abort("Engine.unload() is called.");
this.reloadController = undefined;
}
}
//---------------------------------------------------
// 2. Underlying auto-regressive generation functions
//---------------------------------------------------
private async _generate(
input:
| ChatCompletionRequestNonStreaming
| CompletionCreateParamsNonStreaming,
pipeline: LLMChatPipeline,
chatConfig: ChatConfig,
genConfig: GenerationConfig,
): Promise<string> {
this.interruptSignal = false;
if (genConfig !== undefined) {
postInitAndCheckGenerationConfigValues(genConfig);
}
await this.prefill(input, pipeline, chatConfig, genConfig);
while (!pipeline.stopped()) {
if (this.interruptSignal) {
pipeline.triggerStop();
break;
}
await this.decode(pipeline, genConfig);
}
return pipeline.getMessage();
}
/**
* Similar to `_generate()`; but instead of using callback, we use an async iterable.
*/
asyncGenerate(
request: ChatCompletionRequestStreaming,
model: string,
pipeline: LLMChatPipeline,
chatConfig: ChatConfig,
genConfig: GenerationConfig,
timeReceived: number,
): AsyncGenerator<ChatCompletionChunk, void, void>;
asyncGenerate(
request: CompletionCreateParamsStreaming,
model: string,
pipeline: LLMChatPipeline,
chatConfig: ChatConfig,
genConfig: GenerationConfig,
timeReceived: number,
): AsyncGenerator<Completion, void, void>;
async *asyncGenerate(
request: ChatCompletionRequestStreaming | CompletionCreateParamsStreaming,
model: string,
pipeline: LLMChatPipeline,
chatConfig: ChatConfig,
genConfig: GenerationConfig,
timeReceived: number,
): AsyncGenerator<ChatCompletionChunk | Completion, void, void> {
// Since it is an async generator, we need to do fine-grained try-catch to ensure lock is
// released only when errors occur. Then release at the very end when no error occurs.
// TODO: This makes code less readable, is there a better way to do this?
const lock = this.loadedModelIdToLock.get(model)!;
// 0. Pre-processing
const isChatCompletion = "messages" in request;
const isFunctionCalling =
"tools" in request &&
request.tools !== undefined &&
request.tools !== null;
try {
if (isFunctionCalling && !isChatCompletion) {
throw new Error(
"Expect `chat.completions` with tools, not `completions`.",
);
}
postInitAndCheckGenerationConfigValues(genConfig);
if (request.seed !== null && request.seed !== undefined) {
pipeline.setSeed(request.seed);
}
} catch (err) {
await lock.release();
throw err;
}
// 1. Helper function that generates the chunk
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const created = Date.now();
const id = crypto.randomUUID();
this.interruptSignal = false;
let prevMessageLength = 0; // to know where to start slicing the delta; does not count �
function _countTrailingReplacementChar(curMessage: string): number {
let cntr = 0;
for (let i = curMessage.length - 1; i >= 0; i--) {
if (curMessage.charAt(i) === "�") {
cntr += 1;
} else {
return cntr;
}
}
return cntr;
}
async function _getChunk(
selectedPipeline: LLMChatPipeline,
): Promise<ChatCompletionChunk | Completion | undefined> {
// Remove the replacement character (U+FFFD) from the response to handle emojis.
// Each emoji is made up of multiples of 4 tokens; when truncated, it is displayed as �, so
// we skip this delta until a full emoji is rendered
// TODO(Charlie): This does not consider cases of � not being emoji, need to fix with Streamer
const curMessage = selectedPipeline.getMessage();
const numTrailingReplacementChar =
_countTrailingReplacementChar(curMessage);
if (numTrailingReplacementChar % 4 !== 0) {
return undefined;
}
const deltaMessage = curMessage.slice(prevMessageLength);
prevMessageLength = curMessage.length;
const logprobs = request.logprobs
? ({
content: selectedPipeline.getTokenLogprobArray().slice(-1), // always the last entry
} as ChatCompletionChunk.Choice.Logprobs)
: null;
if (isChatCompletion) {
const chunk: ChatCompletionChunk = {
id: id,
choices: [
{
delta: { content: deltaMessage, role: "assistant" },
finish_reason: null, // not finished yet
index: 0,
logprobs: logprobs,
},
],
model: model,
object: "chat.completion.chunk",
created: created,
};
return chunk;
} else {
const chunk: Completion = {
id: id,
choices: [
{
text: deltaMessage,
finish_reason: null, // not finished yet
index: 0,
logprobs: logprobs,
},
],
model: model,
object: "text_completion",
created: created,
};
return chunk;
}
}
// 2. Auto-regressive loop
let curChunk;
try {
await this.prefill(request, pipeline, chatConfig, genConfig);
curChunk = await _getChunk(pipeline); // prefill produces a chunk
} catch (err) {
await lock.release();
throw err;
}
if (curChunk) {
yield curChunk;
}
while (!pipeline.stopped()) {
if (this.interruptSignal) {
// TODO: should we directly release lock here and return the async
// generator? Though no issue observed as of now with interruptGenerate()
pipeline.triggerStop();
break;
}
try {
await this.decode(pipeline, genConfig);
curChunk = await _getChunk(pipeline);
} catch (err) {
await lock.release();
throw err;
}
if (curChunk) {
yield curChunk;
}
}
// Reset seed -- we do not want this seed to affect future requests
if (request.seed !== null && request.seed !== undefined) {
pipeline.setSeed(Date.now());
}
// 3. Last chunk empty marking the end
// If function calling, use the last chunk to return tool_calls
let finish_reason = pipeline.getFinishReason()!;
let tool_calls:
| Array<ChatCompletionChunk.Choice.Delta.ToolCall>
| undefined;
try {
if (pipeline.getFinishReason() === "stop" && isFunctionCalling) {
// If stopped due to length or abort, cannot output return tool_calls field
finish_reason = "tool_calls";
const outputMessage = pipeline.getMessage();
tool_calls = getToolCallFromOutputMessage(
outputMessage,
/*isStreaming=*/ true,
) as Array<ChatCompletionChunk.Choice.Delta.ToolCall>;
}
} catch (err) {
await lock.release();
throw err;
}
if (isChatCompletion) {
const lastChunk: ChatCompletionChunk = {
id: id,
choices: [
{
delta: isFunctionCalling
? {
role: "assistant",
tool_calls: tool_calls,
}
: {},
finish_reason: finish_reason,
index: 0,
},
],
model: model,
object: "chat.completion.chunk",
created: created,
};
yield lastChunk;
} else {
const lastChunk: Completion = {
id: id,
choices: [
{
text: "",
finish_reason: finish_reason,
index: 0,
},
],
model: model,
object: "text_completion",
created: created,
};
yield lastChunk;
}
// 4. Usage chunk
if (request.stream_options?.include_usage) {
const usedGrammar =
"response_format" in request &&
(request.response_format?.type === "grammar" ||
request.response_format?.type === "json_object");
const completion_tokens = pipeline.getCurRoundDecodingTotalTokens();
const prompt_tokens = pipeline.getCurRoundPrefillTotalTokens();
const prefill_tokens_per_s = pipeline.getCurRoundPrefillTokensPerSec();
const decode_tokens_per_s = pipeline.getCurRoundDecodingTokensPerSec();
const grammar_init_s = pipeline.getCurRoundGrammarInitTotalTime();
const prefill_time = pipeline.getCurRoundPrefillTotalTime();
const decode_time = pipeline.getCurRoundDecodingTotalTime();
const grammar_per_token_s =
pipeline.getCurRoundGrammarPerTokenTotalTime();
const defaultExtra = {
e2e_latency_s: (Date.now() - timeReceived) / 1000,
prefill_tokens_per_s: prefill_tokens_per_s,
decode_tokens_per_s: decode_tokens_per_s,
time_to_first_token_s: prefill_time,
time_per_output_token_s: decode_time / completion_tokens,
};
const usage: CompletionUsage = {
completion_tokens: completion_tokens,
prompt_tokens: prompt_tokens,
total_tokens: completion_tokens + prompt_tokens,
extra: usedGrammar
? {
...defaultExtra,
...{
grammar_init_s: grammar_init_s,
grammar_per_token_s: grammar_per_token_s / completion_tokens,
},
}
: defaultExtra,
};
if (isChatCompletion) {
const usageChunk: ChatCompletionChunk = {
id: id,
choices: [],
usage: usage,
model: model,
object: "chat.completion.chunk",
created: created,
};
yield usageChunk;
} else {
const usageChunk: Completion = {
id: id,
choices: [],
usage: usage,
model: model,
object: "text_completion",
created: created,
};
yield usageChunk;
}
}
await lock.release();
}
async interruptGenerate() {
this.interruptSignal = true;
}
//------------------------------
// 3. High-level generation APIs
//------------------------------
/**
* Completes a single ChatCompletionRequest.
*
* @param request A OpenAI-style ChatCompletion request.
*
* @note For each choice (i.e. `n`), a request is defined by a single `prefill()` and multiple
* `decode()`. This is important as it determines the behavior of various fields including `seed`.
*/
async chatCompletion(
request: ChatCompletionRequestNonStreaming,
): Promise<ChatCompletion>;
async chatCompletion(
request: ChatCompletionRequestStreaming,
): Promise<AsyncIterable<ChatCompletionChunk>>;
async chatCompletion(
request: ChatCompletionRequestBase,
): Promise<AsyncIterable<ChatCompletionChunk> | ChatCompletion>;
async chatCompletion(
request: ChatCompletionRequest,
): Promise<AsyncIterable<ChatCompletionChunk> | ChatCompletion> {
const timeReceived = Date.now();
// 0. Check model loaded and preprocess inputs
const [selectedModelId, selectedPipeline, selectedChatConfig] =
this.getLLMStates("ChatCompletionRequest", request.model);
const selectedModelType =
this.loadedModelIdToModelType.get(selectedModelId);
API.postInitAndCheckFieldsChatCompletion(
request,
selectedModelId,
selectedModelType!,
);
const genConfig: GenerationConfig = {
frequency_penalty: request.frequency_penalty,
presence_penalty: request.presence_penalty,
max_tokens: request.max_tokens,
stop: request.stop,
top_p: request.top_p,
temperature: request.temperature,
logit_bias: request.logit_bias,
logprobs: request.logprobs,
top_logprobs: request.top_logprobs,
response_format: request.response_format,
ignore_eos: request.ignore_eos,
};
// 0.5 Block wait until this pipeline finishes all previous requests
const lock = this.loadedModelIdToLock.get(selectedModelId)!;
await lock.acquire();
// 1. If request is streaming, return an AsyncIterable (an iterable version of `_generate()`)
if (request.stream) {
return this.asyncGenerate(
request,
selectedModelId,
selectedPipeline,
selectedChatConfig,
genConfig,
timeReceived,
);
}
// Big try-finally to release lock in case of errors
try {
if (request.seed !== null && request.seed !== undefined) {
selectedPipeline.setSeed(request.seed);
}
// 2. If request is non-streaming, directly reuse `_generate()`
const n = request.n ? request.n : 1;
const choices: Array<ChatCompletion.Choice> = [];
let completion_tokens = 0;
let prompt_tokens = 0;
let prefill_time = 0;
let decode_time = 0;
let grammar_init_s = 0;
let grammar_per_token_s = 0;
for (let i = 0; i < n; i++) {
let outputMessage: string;
if (this.interruptSignal) {
// A single interrupt signal should stop all choices' generations
selectedPipeline.triggerStop();
outputMessage = "";
} else {
outputMessage = await this._generate(
request,
selectedPipeline,
selectedChatConfig,
genConfig,
);
}
let finish_reason = selectedPipeline.getFinishReason()!;
// 3. Post processing for function calling
const isFunctionCalling =
request.tools !== undefined && request.tools !== null;
let tool_calls: Array<ChatCompletionMessageToolCall> | undefined;
if (
selectedPipeline.getFinishReason() === "stop" &&
isFunctionCalling
) {
// If stopped due to length or abort, cannot output return tool_calls field
finish_reason = "tool_calls";
tool_calls = getToolCallFromOutputMessage(
outputMessage,
/*isStreaming=*/ false,
);
}
choices.push({
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
finish_reason: finish_reason,
index: i,
logprobs: request.logprobs
? ({
content: selectedPipeline.getTokenLogprobArray(),
} as ChatCompletion.Choice.Logprobs)
: null,
message: isFunctionCalling
? {
content: null,
tool_calls: tool_calls,
role: "assistant",
}
: {
content: outputMessage,
role: "assistant",
},
});
completion_tokens += selectedPipeline.getCurRoundDecodingTotalTokens();
prompt_tokens += selectedPipeline.getCurRoundPrefillTotalTokens();
prefill_time += selectedPipeline.getCurRoundPrefillTotalTime();
decode_time += selectedPipeline.getCurRoundDecodingTotalTime();
grammar_init_s += selectedPipeline.getCurRoundGrammarInitTotalTime();
grammar_per_token_s +=
selectedPipeline.getCurRoundGrammarPerTokenTotalTime();
}
const usedGrammar =
"response_format" in request &&
(request.response_format?.type === "grammar" ||
request.response_format?.type === "json_object");
const defaultExtra = {
e2e_latency_s: (Date.now() - timeReceived) / 1000,
prefill_tokens_per_s: prompt_tokens / prefill_time,
decode_tokens_per_s: completion_tokens / decode_time,
time_to_first_token_s: prefill_time,
time_per_output_token_s: decode_time / completion_tokens,
};
const response: ChatCompletion = {
id: crypto.randomUUID(),
choices: choices,
model: selectedModelId,
object: "chat.completion",
created: Date.now(),
usage: {
completion_tokens: completion_tokens,
prompt_tokens: prompt_tokens,
total_tokens: completion_tokens + prompt_tokens,
extra: usedGrammar
? {
...defaultExtra,
...{
grammar_init_s: grammar_init_s,
grammar_per_token_s: grammar_per_token_s / completion_tokens,
},
}
: defaultExtra,
} as CompletionUsage,
};
// Reset seed -- we do not want this seed to affect future requests
if (request.seed !== null && request.seed !== undefined) {
selectedPipeline.setSeed(Date.now());
}
return response;
} finally {
await lock.release();
}
}
/**
* Completes a single CompletionCreateParams, a text completion with no chat template.
*
* @param request A OpenAI-style Completion request.
*
* @note For each choice (i.e. `n`), a request is defined by a single `prefill()` and multiple
* `decode()`. This is important as it determines the behavior of various fields including `seed`.
*/
async completion(
request: CompletionCreateParamsNonStreaming,
): Promise<Completion>;
async completion(
request: CompletionCreateParamsStreaming,
): Promise<AsyncIterable<Completion>>;
async completion(
request: CompletionCreateParamsBase,
): Promise<AsyncIterable<Completion> | Completion>;
async completion(
request: CompletionCreateParams,
): Promise<AsyncIterable<Completion> | Completion> {
const timeReceived = Date.now();
// 0. Check model loaded and preprocess inputs
const [selectedModelId, selectedPipeline, selectedChatConfig] =
this.getLLMStates("CompletionCreateParams", request.model);
API.postInitAndCheckFieldsCompletion(request, selectedModelId);
const genConfig: GenerationConfig = {
frequency_penalty: request.frequency_penalty,
presence_penalty: request.presence_penalty,
max_tokens: request.max_tokens,
stop: request.stop,
top_p: request.top_p,
temperature: request.temperature,
logit_bias: request.logit_bias,
logprobs: request.logprobs,
top_logprobs: request.top_logprobs,
ignore_eos: request.ignore_eos,
};
// 0.5 Block wait until this pipeline finishes all previous requests
const lock = this.loadedModelIdToLock.get(selectedModelId)!;
await lock.acquire();
// 1. If request is streaming, return an AsyncIterable (an iterable version of `_generate()`)
if (request.stream) {
return this.asyncGenerate(
request,
selectedModelId,
selectedPipeline,
selectedChatConfig,
genConfig,
timeReceived,
);
}
// Big try-finally to release lock in case of errors
try {
if (request.seed !== null && request.seed !== undefined) {
selectedPipeline.setSeed(request.seed);
}
// 2. If request is non-streaming, directly reuse `_generate()`
const n = request.n ? request.n : 1;
const choices: Array<CompletionChoice> = [];
let completion_tokens = 0;
let prompt_tokens = 0;
let prefill_time = 0;
let decode_time = 0;
for (let i = 0; i < n; i++) {
let outputMessage: string;