/
llm_chat.cc
1885 lines (1745 loc) · 76.8 KB
/
llm_chat.cc
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
/*!
* Copyright (c) 2023 by Contributors
* \file llm_chat.cc
* \brief Implementation of llm chat.
*/
#include "llm_chat.h"
#include <picojson.h>
#include <tvm/runtime/c_runtime_api.h>
#include <tvm/runtime/disco/session.h>
#include <tvm/runtime/memory/memory_manager.h>
#include <tvm/runtime/module.h>
#include <tvm/runtime/ndarray.h>
#include <tvm/runtime/packed_func.h>
#include <tvm/runtime/registry.h>
#include <tvm/runtime/relax_vm/ndarray_cache_support.h>
#include <chrono>
#include <filesystem>
#include <fstream>
#include <iomanip>
#include <memory>
#include <string>
#include <vector>
#include "./metadata/model.h"
#include "./serve/config.h"
#include "./support/load_bytes_from_file.h"
#include "conversation.h"
#include "random.h"
#include "tokenizers.h"
namespace mlc {
namespace llm {
using tvm::Device;
using namespace tvm::runtime;
namespace {
//------------------------------
// support functions
//------------------------------
inline size_t FindEffectiveUTF8Pos(const std::string& s) {
int pos = s.size() - 1;
for (; pos >= 0; pos--) {
if ((s[pos] & 0x80) == 0x00) {
return pos + 1;
} else if (pos - 1 >= 0 && (s[pos - 1] & 0xE0) == 0xC0 && (s[pos] & 0xC0) == 0x80) {
return pos + 1;
} else if (pos - 2 >= 0 && (s[pos - 2] & 0xF0) == 0xE0 && (s[pos - 1] & 0xC0) == 0x80 &&
(s[pos] & 0xC0) == 0x80) {
return pos + 1;
} else if (pos - 3 >= 0 && (s[pos - 3] & 0xF8) == 0xF0 && (s[pos - 2] & 0xC0) == 0x80 &&
(s[pos - 1] & 0xC0) == 0x80 && (s[pos] & 0xC0) == 0x80) {
return pos + 1;
}
}
return pos + 1;
}
inline std::string Concat(const std::vector<std::string>& inputs) {
std::ostringstream os;
for (const auto& x : inputs) {
os << x;
}
return os.str();
}
struct FunctionTable {
static PackedFunc SessionFuncAsPackedFunc(Session sess, DRef sess_func, String name) {
return PackedFunc([sess, func = std::move(sess_func), name = std::move(name)](
TVMArgs args, TVMRetValue* rv) -> void {
std::vector<TVMValue> tvm_values(args.num_args + 3);
std::vector<int> tvm_type_codes(args.num_args + 3);
TVMArgsSetter setter(tvm_values.data(), tvm_type_codes.data());
setter(0, static_cast<int>(DiscoAction::kCallPacked));
setter(1, 0);
setter(2, func);
for (int i = 0; i < args.num_args; ++i) {
tvm_values[i + 3] = args.values[i];
tvm_type_codes[i + 3] = args.type_codes[i];
}
*rv = sess->CallWithPacked(
TVMArgs(tvm_values.data(), tvm_type_codes.data(), args.num_args + 3));
});
}
void Init(TVMArgValue reload_lib, Device device, picojson::object model_config) {
Device null_device{DLDeviceType(0), 0};
int num_shards;
{
if (model_config.count("tensor_parallel_shards")) {
CHECK(model_config["tensor_parallel_shards"].is<int64_t>());
num_shards = model_config["tensor_parallel_shards"].get<int64_t>();
} else {
num_shards = 1;
}
}
this->model_config = model_config;
if (num_shards > 1) {
String lib_path{nullptr};
try {
lib_path = reload_lib.operator String();
} catch (...) {
LOG(FATAL)
<< "ValueError: In multi-GPU inference, we expect the first argument to Reload to be a "
"string path to the model library (.so on Linux or .dll on Windows), but got: "
<< ArgTypeCode2Str(reload_lib.type_code());
}
constexpr const char* f_create_process_pool = "runtime.disco.create_process_pool";
if (Registry::Get(f_create_process_pool) == nullptr) {
LOG(FATAL) << "Cannot find process launcher `" << f_create_process_pool << "`. "
<< "Multi-GPU inference depends on MLC LLM Python API to launch process.";
}
std::string ccl;
if (device.device_type == kDLCUDA) {
ccl = "nccl";
} else if (device.device_type == kDLROCM) {
ccl = "rccl";
} else {
LOG(FATAL) << "ValueError: Multi-GPU on device " << DLDeviceType2Str(device.device_type)
<< " is not supported. Currently, only NCCL and RCCL are integrated.";
}
std::vector<int64_t> device_ids(num_shards);
for (int i = 0; i < num_shards; ++i) {
device_ids[i] = i;
}
this->use_disco = true;
this->sess = Session::ProcessSession(num_shards, f_create_process_pool, "mlc_llm.cli.worker");
this->sess->InitCCL(ccl, ShapeTuple(device_ids));
this->disco_mod = sess->CallPacked(sess->GetGlobalFunc("runtime.disco.load_vm_module"),
lib_path, null_device);
this->mod_get_func = [this, fmodule_get_function =
sess->GetGlobalFunc("runtime.ModuleGetFunction")](
const std::string& name) -> PackedFunc {
DRef func = sess->CallPacked(fmodule_get_function, this->disco_mod, name, false);
bool exists = (func->DebugGetFromRemote(0).operator PackedFunc()) != nullptr;
if (!exists) {
return PackedFunc(nullptr);
}
return SessionFuncAsPackedFunc(sess, func, name);
};
this->get_global_func = [this](const std::string& name) -> PackedFunc {
return SessionFuncAsPackedFunc(sess, sess->GetGlobalFunc(name), name);
};
this->_InitFunctions();
{
Module mod = this->disco_mod->DebugGetFromRemote(0);
this->softmax_func_ = mod->GetFunction("softmax_with_temperature");
this->model_metadata_ = ModelMetadata::FromModule(mod, std::move(model_config));
}
} else {
Module executable{nullptr};
if (reload_lib.type_code() == kTVMModuleHandle) {
executable = reload_lib.operator Module();
} else {
String lib_path = reload_lib.operator String();
executable = tvm::runtime::Module::LoadFromFile(lib_path);
}
this->use_disco = false;
auto fload_exec = executable->GetFunction("vm_load_executable");
ICHECK(fload_exec.defined()) << "TVM runtime cannot find vm_load_executable";
this->local_vm = fload_exec();
this->local_vm->GetFunction("vm_initialization")(
static_cast<int>(device.device_type), device.device_id,
static_cast<int>(memory::AllocatorType::kPooled), static_cast<int>(kDLCPU), 0,
static_cast<int>(memory::AllocatorType::kPooled));
this->mod_get_func = [this](const std::string& name) -> PackedFunc {
PackedFunc func = this->local_vm->GetFunction(name, false);
return func;
};
this->get_global_func = [](const std::string& name) -> PackedFunc {
const auto* f = tvm::runtime::Registry::Get(name);
CHECK(f != nullptr) << "ValueError: Cannot find function " << name;
return *f;
};
this->model_metadata_ = ModelMetadata::FromModule(this->local_vm, std::move(model_config));
this->_InitFunctions();
}
}
ObjectRef LoadParams(const std::string& model_path, Device device, bool use_presharded_weights) {
if (this->use_disco) {
DRef params{nullptr};
if (this->model_metadata_.params.empty()) {
std::filesystem::path fs_model_path = model_path;
std::string metadata_path = (fs_model_path / "ndarray-cache.json").string();
std::string ndarray_cache_metadata = LoadBytesFromFile(metadata_path);
PackedFunc loader_create = this->get_global_func("runtime.disco.ShardLoader");
auto load_all_func_name = use_presharded_weights
? "runtime.disco.ShardLoaderLoadAllPresharded"
: "runtime.disco.ShardLoaderLoadAll";
PackedFunc loader_load_all = this->get_global_func(load_all_func_name);
CHECK(loader_create != nullptr);
CHECK(loader_load_all != nullptr);
DRef loader = loader_create(metadata_path, ndarray_cache_metadata, "", this->disco_mod);
params = loader_load_all(loader);
} else {
auto load_func_name = use_presharded_weights ? "mlc.loader.LoadMultiGPUPresharded"
: "mlc.loader.LoadMultiGPU";
PackedFunc loader = this->get_global_func(load_func_name);
params =
loader(model_path, this->disco_mod, picojson::value(this->model_config).serialize());
}
return params;
} else {
CHECK(!use_presharded_weights) << "Use of pre-sharded weights requires more than one GPU";
const PackedFunc* fload_cache = tvm::runtime::Registry::Get("vm.builtin.ndarray_cache.load");
ICHECK(fload_cache) << "TVM runtime cannot find vm.builtin.ndarray_cache.load";
(*fload_cache)(model_path, static_cast<int32_t>(device.device_type), device.device_id);
Array<NDArray> params;
if (this->model_metadata_.params.empty()) {
constexpr const char* name_loader = "vm.builtin.param_array_from_cache";
const PackedFunc* fload_params = tvm::runtime::Registry::Get(name_loader);
ICHECK(fload_params) << "Cannot find env function: " << name_loader;
params = (*fload_params)("param", -1);
} else {
constexpr const char* name_loader = "vm.builtin.param_array_from_cache_by_name";
const PackedFunc* fload_params = tvm::runtime::Registry::Get(name_loader);
ICHECK(fload_params) << "Cannot find env function: " << name_loader;
Array<String> param_names;
param_names.reserve(this->model_metadata_.params.size());
for (const auto& param : this->model_metadata_.params) {
param_names.push_back(param.name);
}
params = (*fload_params)(param_names);
}
// after we get params, it is safe to simply clear the cached version
// as these params are referenced by params_
const PackedFunc* fclear_ndarray_cache =
tvm::runtime::Registry::Get("vm.builtin.ndarray_cache.clear");
ICHECK(fclear_ndarray_cache) << "Cannot find env function vm.builtin.ndarray_cache.clear";
(*fclear_ndarray_cache)();
return params;
}
}
void _TryInitKVState() {
PackedFunc f_flashinfer_paged_kv_cache = mod_get_func("create_flashinfer_paged_kv_cache");
PackedFunc f_tir_paged_kv_cache = mod_get_func("create_tir_paged_kv_cache");
PackedFunc f_create_rnn_state = mod_get_func("create_rnn_state");
if (f_flashinfer_paged_kv_cache.defined() || f_tir_paged_kv_cache.defined() ||
f_create_rnn_state.defined()) {
// Prefer to use flashinfer paged kv cache, but fall back to tir paged kv cache
if (f_flashinfer_paged_kv_cache.defined()) {
this->use_kv_state = KVStateKind::kAttention;
this->create_kv_cache_func_ = f_flashinfer_paged_kv_cache;
} else if (f_tir_paged_kv_cache.defined()) {
this->use_kv_state = KVStateKind::kAttention;
this->create_kv_cache_func_ = f_tir_paged_kv_cache;
} else if (f_create_rnn_state.defined()) {
this->use_kv_state = KVStateKind::kRNNState;
this->create_kv_cache_func_ = f_create_rnn_state;
}
this->reset_kv_cache_func_ = get_global_func("vm.builtin.kv_state_clear");
this->kv_cache_add_sequence_func_ = get_global_func("vm.builtin.kv_state_add_sequence");
this->kv_cache_remove_sequence_func_ = get_global_func("vm.builtin.kv_state_remove_sequence");
this->kv_cache_enable_sliding_window_for_seq_ =
get_global_func("vm.builtin.attention_kv_cache_enable_sliding_window_for_seq");
this->kv_cache_begin_forward_func_ = get_global_func("vm.builtin.kv_state_begin_forward");
this->kv_cache_end_forward_func_ = get_global_func("vm.builtin.kv_state_end_forward");
this->fkvcache_array_popn_ = get_global_func("vm.builtin.kv_state_popn");
// note: We use max sequence length = 1 for RNN state for now, so disable back tracking
this->support_backtracking_kv_ = this->use_kv_state == KVStateKind::kAttention;
}
}
void _InitFunctions() {
this->prefill_func_ = mod_get_func("prefill");
this->embed_func_ = mod_get_func("embed");
this->prefill_with_embed_func_ = mod_get_func("prefill_with_embed");
this->decode_func_ = mod_get_func("decode");
this->softmax_func_ = mod_get_func("softmax_with_temperature");
this->encoding_without_cache_func_ = mod_get_func("encoding_without_cache");
_TryInitKVState();
// Fall back to the old way of creating kv cache if neither paged kv cache nor rnn state is used
if (!this->use_kv_state) {
this->create_kv_cache_func_ = mod_get_func("create_kv_cache");
if (this->create_kv_cache_func_ == nullptr) {
this->create_kv_cache_func_ = mod_get_func("_initialize_effect");
}
this->reset_kv_cache_func_ = mod_get_func("reset_kv_cache");
if (this->reset_kv_cache_func_ == nullptr) {
this->reset_kv_cache_func_ = get_global_func("vm.builtin.attention_kv_cache_array_clear");
support_backtracking_kv_ = true;
} else {
support_backtracking_kv_ = false;
}
this->fkvcache_array_popn_ = get_global_func("vm.builtin.attention_kv_cache_array_popn");
}
this->nd_view_func_ = get_global_func("vm.builtin.reshape");
this->nd_get_shape_func_ = get_global_func("vm.builtin.shape_of");
}
ObjectRef Empty(ShapeTuple shape, DataType dtype, Device device) const {
Device null_device{DLDeviceType(0), 0};
if (this->use_disco) {
DRef empty_func = sess->GetGlobalFunc("runtime.disco.empty");
return sess->CallPacked(empty_func, shape, dtype, null_device);
} else {
return NDArray::Empty(shape, dtype, device);
}
}
ObjectRef CopyToWorker0(const NDArray& host_array) {
Device null_device{DLDeviceType(0), 0};
if (this->use_disco) {
DRef array =
Downcast<DRef>(this->Empty(host_array.Shape(), host_array.DataType(), null_device));
sess->CopyToWorker0(host_array, array);
return array;
} else {
return host_array;
}
}
bool use_disco = false;
enum KVStateKind {
kNone = 0,
kAttention = 1,
kRNNState = 2,
};
KVStateKind use_kv_state = kNone;
Session sess{nullptr};
DRef disco_mod{nullptr};
tvm::runtime::Module local_vm{nullptr};
picojson::object model_config;
TypedPackedFunc<PackedFunc(const std::string&)> mod_get_func;
TypedPackedFunc<PackedFunc(const std::string&)> get_global_func;
PackedFunc prefill_func_;
PackedFunc embed_func_;
PackedFunc prefill_with_embed_func_;
PackedFunc decode_func_;
PackedFunc encoding_without_cache_func_;
PackedFunc softmax_func_;
PackedFunc create_kv_cache_func_;
PackedFunc reset_kv_cache_func_;
PackedFunc kv_cache_add_sequence_func_;
PackedFunc kv_cache_remove_sequence_func_;
PackedFunc kv_cache_enable_sliding_window_for_seq_;
PackedFunc kv_cache_begin_forward_func_;
PackedFunc kv_cache_end_forward_func_;
bool support_backtracking_kv_;
PackedFunc fkvcache_array_popn_;
ModelMetadata model_metadata_;
PackedFunc nd_view_func_;
PackedFunc nd_get_shape_func_;
};
} // namespace
//------------------------------
// Chat module
//------------------------------
class LLMChatModule;
/*!
* \brief Implements the chat conversation wrapper
*/
class LLMChat {
friend class LLMChatModule;
public:
explicit LLMChat(DLDevice device) : device_(device) {}
/*!
* \return Text describing runtime stats.
*/
std::string RuntimeStatsText() {
std::ostringstream os;
os << "prefill: " << std::setprecision(1) << std::fixed
<< this->prefill_total_tokens / (this->prefill_total_time + this->embed_total_time)
<< " tok/s"
<< ", decode: " << std::setprecision(1) << std::fixed
<< this->decode_total_tokens / this->decode_total_time << " tok/s";
return os.str();
}
void UpdateConfigFromMetadata() {
if (ft_.use_disco) {
return;
}
PackedFunc fget_metadata = ft_.mod_get_func("_metadata"); // name in SLIM
if (fget_metadata == nullptr) {
fget_metadata = ft_.mod_get_func("get_metadata"); // backward-compatible name
if (fget_metadata == nullptr) {
return; // Skip if neither exists
}
}
ObjectRef ret = fget_metadata();
std::string metadata_str = std::string(Downcast<String>(ret));
picojson::value metadata_info;
picojson::parse(metadata_info, std::string(metadata_str));
auto metadata = metadata_info.get<picojson::object>();
std::string key = "max_window_size";
if (!metadata.count(key)) {
key = "context_window_size";
ICHECK(metadata.count(key))
<< "Key \"max_window_size\" or \"context_window_size\" not found.";
}
ICHECK(metadata[key].is<int64_t>());
max_window_size_ = std::min(max_window_size_, metadata[key].get<int64_t>());
if (metadata.count("prefill_chunk_size")) {
ICHECK(metadata["prefill_chunk_size"].is<int64_t>());
prefill_chunk_size_ =
std::min(prefill_chunk_size_, metadata["prefill_chunk_size"].get<int64_t>());
}
if (metadata.count("sliding_window_size")) {
ICHECK(metadata["sliding_window_size"].is<int64_t>());
sliding_window_size_ =
std::min(sliding_window_size_, metadata["sliding_window_size"].get<int64_t>());
}
// to be removed after SLM migration
if (metadata.count("sliding_window")) {
ICHECK(metadata["sliding_window"].is<int64_t>());
sliding_window_size_ =
std::min(sliding_window_size_, metadata["sliding_window"].get<int64_t>());
}
}
/*!
* \return Text describing verbose runtime stats.
*/
std::string VerboseRuntimeStatsText() {
std::ostringstream os;
os << "----------- prefill -----------\n"
<< "throughput: " << std::setprecision(3) << std::fixed
<< this->prefill_total_tokens / (this->prefill_total_time + this->embed_total_time)
<< " tok/s\n"
<< "total tokens: " << this->prefill_total_tokens << " tok\n"
<< "total time: " << this->prefill_total_time << " s\n"
<< "------------ decode ------------\n"
<< "throughput: " << std::setprecision(3) << std::fixed
<< this->decode_total_tokens / this->decode_total_time << " tok/s\n"
<< "total tokens: " << this->decode_total_tokens << " tok\n"
<< "total time: " << this->decode_total_time << " s\n";
return os.str();
}
/*!
* \brief Load JSON config and override options.
* \param config_json A json config in picojson type that is partially specifies
* some of the options.
* \param partial_update Whether it's a partial update or full update, if set to true,
* we perform a partial update on some of the provided options; if set to false, all
* options must be provided.
* \note This function overrides existing configurations.
*/
void LoadJSONOverride(const picojson::value& config_json, bool partial_update = false) {
picojson::object config = config_json.get<picojson::object>();
if (config.count("temperature")) {
CHECK(config["temperature"].is<double>());
this->temperature_ = config["temperature"].get<double>();
} else {
CHECK(partial_update) << "Key \"temperature\" not found.";
}
if (config.count("repetition_penalty")) {
CHECK(config["repetition_penalty"].is<double>());
CHECK(this->repetition_penalty_ > 0) << "Repetition penalty must be a positive number!";
this->repetition_penalty_ = config["repetition_penalty"].get<double>();
} else {
CHECK(partial_update) << "Key \"repetition_penalty\" not found.";
}
if (config.count("presence_penalty")) {
CHECK(config["presence_penalty"].is<double>());
this->presence_penalty_ = config["presence_penalty"].get<double>();
CHECK(fabs(this->presence_penalty_) <= 2.0) << "Presence penalty must be in [-2, 2]";
}
if (config.count("frequency_penalty")) {
CHECK(config["frequency_penalty"].is<double>());
this->frequency_penalty_ = config["frequency_penalty"].get<double>();
CHECK(fabs(this->frequency_penalty_) <= 2.0) << "Frequency penalty must be in [-2, 2]";
}
if (config.count("vocab_size")) {
CHECK(config["vocab_size"].is<int64_t>());
this->vocab_size_ = config["vocab_size"].get<int64_t>();
} else {
CHECK(partial_update) << "Key \"vocab_size\" not found.";
}
if (config.count("use_presharded_weights")) {
CHECK(config["use_presharded_weights"].is<bool>());
this->use_presharded_weights_ = config["use_presharded_weights"].get<bool>();
} else {
this->use_presharded_weights_ = false;
}
if (config.count("max_window_size")) {
CHECK(config["max_window_size"].is<int64_t>());
this->max_window_size_ =
std::min(this->max_window_size_, config["max_window_size"].get<int64_t>());
}
if (config.count("context_window_size")) {
CHECK(config["context_window_size"].is<int64_t>());
this->max_window_size_ =
std::min(this->max_window_size_, config["context_window_size"].get<int64_t>());
}
if (config.count("sliding_window_size")) {
CHECK(config["sliding_window_size"].is<int64_t>());
CHECK(!config.count("max_window_size"))
<< "Cannot specify both sliding_window and max_window_size.";
this->sliding_window_size_ = config["sliding_window_size"].get<int64_t>();
CHECK(this->sliding_window_size_ > 0 || this->sliding_window_size_ == -1)
<< "Sliding window size needs to be -1 or positive";
CHECK(config.count("prefill_chunk_size"))
<< "Need to specify chunk size if using sliding window attention.";
}
// to be removed after SLM migration
if (config.count("sliding_window")) {
CHECK(config["sliding_window"].is<int64_t>());
CHECK(!config.count("max_window_size"))
<< "Cannot specify both sliding_window and max_window_size.";
this->sliding_window_size_ = config["sliding_window"].get<int64_t>();
CHECK(this->sliding_window_size_ > 0 || this->sliding_window_size_ == -1)
<< "Sliding window size needs to be -1 or positive";
CHECK(config.count("prefill_chunk_size"))
<< "Need to specify chunk size if using sliding window attention.";
}
if (config.count("prefill_chunk_size")) {
CHECK(config["prefill_chunk_size"].is<int64_t>());
this->prefill_chunk_size_ = config["prefill_chunk_size"].get<int64_t>();
}
if (config.count("attention_sink_size")) {
CHECK(config["attention_sink_size"].is<int64_t>());
this->attention_sink_size_ = config["attention_sink_size"].get<int64_t>();
}
if (config.count("top_p")) {
CHECK(config["top_p"].is<double>());
this->top_p_ = config["top_p"].get<double>();
} else {
CHECK(partial_update) << "Key \"top_p\" not found.";
}
if (config.count("mean_gen_len")) {
CHECK(config["mean_gen_len"].is<int64_t>());
this->mean_gen_len_ = config["mean_gen_len"].get<int64_t>();
} else {
CHECK(partial_update) << "Key \"mean_gen_len\" not found.";
}
// NOTE: for backward compact
// max gen len is optional
if (config.count("max_gen_len")) {
CHECK(config["max_gen_len"].is<int64_t>());
this->max_gen_len_ = config["max_gen_len"].get<int64_t>();
}
if (config.count("shift_fill_factor")) {
CHECK(config["shift_fill_factor"].is<double>());
this->shift_fill_factor_ = config["shift_fill_factor"].get<double>();
} else {
CHECK(partial_update) << "Key \"shift_fill_factor\" not found.";
}
if (config.count("conv_template")) {
if (config["conv_template"].is<picojson::object>()) {
this->conversation_.LoadJSONOverride(config["conv_template"], false);
} else {
ICHECK(config["conv_template"].is<std::string>());
LOG(WARNING)
<< "Legacy conversation template detected. It will be deprecated in the future. "
"Please regenerate mlc-chat-config.json with the latest version";
std::string conv_template = config["conv_template"].get<std::string>();
this->conversation_ = Conversation::FromTemplate(conv_template);
}
if (config.count("conv_config")) {
// conv_config can override conv_template
try {
this->conversation_.LoadJSONOverride(config["conv_config"], true);
} catch (...) {
this->conversation_.LoadJSONOverrideLegacy(config["conv_config"], true);
}
}
} else if (config.count("conv_config")) {
// without conv template, conv_config needs to be a complete config
try {
this->conversation_.LoadJSONOverride(config["conv_config"], false);
} catch (...) {
this->conversation_.LoadJSONOverrideLegacy(config["conv_config"], false);
}
} else {
CHECK(partial_update) << "Key \"conv_template\" and \"conv_config\" not found.";
}
if (config.count("bos_token_id")) {
CHECK(config["bos_token_id"].is<int64_t>());
this->bos_token_id_ = config["bos_token_id"].get<int64_t>();
}
}
/*!
* \brief Load JSON config and override options.
* \param config_str A json config string that partially specifies some of the options.
* \param partial_update Whether it's a partial update or full update, if set to true,
* we perform a partial update on some of the provided options; if set to false, all
* options must be provided.
* \note This function overrides existing configurations.
*/
picojson::object LoadJSONOverride(const std::string& config_str, bool partial_update = false) {
picojson::value config_json;
std::string err = picojson::parse(config_json, config_str);
if (!err.empty()) {
LOG(FATAL) << err;
}
LoadJSONOverride(config_json, partial_update);
return config_json.get<picojson::object>();
}
std::string GetConfigJSON() const { return SerializeConfigToJSONValue().serialize(true); }
/*!
* \brief Reload model, tokenizers and configurations from the specified model path.
* \param reload_lib The module to reload, it can either be a path to the library or a tvm Module.
* \param model_path The path to search for models.
* \param app_config_json The JSON string used to partially override the configuration loaded from
* disk, default to empty string.
*/
void Reload(TVMArgValue reload_lib, String model_path, String app_config_json = "") {
// Step 1. Process config json string.
picojson::object model_config;
{
std::ifstream config_istream((model_path + "/mlc-chat-config.json").c_str());
std::ostringstream config_ostream;
ICHECK(config_istream);
config_ostream << config_istream.rdbuf();
std::string config_str = config_ostream.str();
model_config = LoadJSONOverride(config_str, false);
if (!app_config_json.empty()) {
// Override configuration from app_config_json.
picojson::object app_config = LoadJSONOverride(app_config_json, true);
if (app_config.count("tensor_parallel_shards")) {
model_config["tensor_parallel_shards"] = app_config["tensor_parallel_shards"];
}
}
}
// Step 2. Set tokenizer.
this->tokenizer_ = Tokenizer::FromPath(model_path);
// Step 3. Initialize vm, we use the packed function mechanism
// so there is no explicit abi dependency on these extra
// classes other than basic tvm runtime.
this->ft_.Init(reload_lib, device_, model_config);
UpdateConfigFromMetadata();
if (this->sliding_window_size_ == -1) {
CHECK(max_window_size_ != std::numeric_limits<int64_t>::max())
<< "Key \"max_window_size\" not found.";
}
// Step 4. Initialize sample functions.
auto fsample_topp_from_prob_ptr =
tvm::runtime::Registry::Get("vm.builtin.sample_top_p_from_prob");
ICHECK(fsample_topp_from_prob_ptr)
<< "Cannot find env function vm.builtin.sample_top_p_from_prob";
fsample_topp_from_prob_ = *fsample_topp_from_prob_ptr;
auto fsample_topp_from_logits_ptr =
tvm::runtime::Registry::Get("vm.builtin.sample_top_p_from_logits");
ICHECK(fsample_topp_from_logits_ptr)
<< "Cannot find env function vm.builtin.sample_top_p_from_logits";
fsample_topp_from_logits_ = *fsample_topp_from_logits_ptr;
// Step 5. Load params in nd-array cache.
this->params_ = ft_.LoadParams(model_path, device_, use_presharded_weights_);
// Step 6. KV cache creation.
if (ft_.use_kv_state == FunctionTable::KVStateKind::kAttention) {
int max_total_seq_length =
this->max_window_size_ == -1 ? this->sliding_window_size_ : this->max_window_size_;
ICHECK_GT(max_total_seq_length, 0);
IntTuple max_num_sequence{1};
IntTuple max_total_sequence_length{max_total_seq_length};
IntTuple prefill_chunk_size{this->prefill_chunk_size_};
IntTuple page_size{16};
IntTuple support_sliding_window{sliding_window_size_ != -1};
this->kv_cache_ =
ft_.create_kv_cache_func_(max_num_sequence, max_total_sequence_length, prefill_chunk_size,
page_size, support_sliding_window);
} else if (ft_.use_kv_state == FunctionTable::KVStateKind::kRNNState) {
IntTuple max_num_sequence{1};
IntTuple max_history_length{1};
this->kv_cache_ = ft_.create_kv_cache_func_(max_num_sequence, max_history_length);
} else {
this->kv_cache_ = ft_.create_kv_cache_func_();
}
// Step 7. Pre-allocate fixed size ndarray
this->temperature_arr_ = NDArray::Empty({1}, DataType::Float(32), device_);
float temperature = static_cast<float>(this->temperature_);
this->temperature_arr_.CopyFromBytes(&temperature, sizeof(float));
if (ft_.use_disco) {
Device null_device{DLDeviceType(0), 0};
this->input_tokens_decode_ =
Downcast<DRef>(ft_.Empty(ShapeTuple({1, 1}), DataType::Int(32), null_device));
}
// Step 8. Reset chat
this->ResetChat();
}
void ResetChat() {
// TODO(mlc-team): add conversation_.Reset to preserve system prompt
// and initial message.
// this->conversation_ = Conversation::Create(this->conversation_.conv_template);
this->conversation_.Reset();
this->ResetRuntimeStats();
this->ResetKVCache();
this->total_seq_len_ = 0;
}
/*! \brief reset the runtime stats. */
void ResetRuntimeStats() {
this->prefill_total_tokens = 0;
this->decode_total_tokens = -1;
this->embed_total_time = 0;
this->prefill_total_time = 0;
this->decode_total_time = 0;
this->sample_total_time = 0;
}
static std::string GetConcatPrompt(const std::vector<std::string>& prompt_array,
size_t prefix_end, size_t suffix_start) {
std::ostringstream os;
for (size_t i = 0; i < prefix_end; ++i) {
os << prompt_array[i];
}
for (size_t i = suffix_start; i < prompt_array.size(); ++i) {
os << prompt_array[i];
}
return os.str();
}
/**
* \brief Get input tokens based on history
* \param place_in_prompt The place of the input message in the prompt.
*/
std::vector<int32_t> GetInputTokens(PlaceInPrompt place_in_prompt = PlaceInPrompt::kAll,
picojson::object generation_config = picojson::object()) {
// prepare generation settings
// the generation_config will not override the original config
// since is only used for this generation
int64_t gen_mean_gen_len;
if (generation_config.count("mean_gen_len")) {
CHECK(generation_config["mean_gen_len"].is<int64_t>());
gen_mean_gen_len = generation_config["mean_gen_len"].get<int64_t>();
} else {
gen_mean_gen_len = this->mean_gen_len_;
}
// work on input tokens
std::vector<int32_t> tokens;
std::vector<std::string> prompts;
if (this->total_seq_len_ == 0) {
prompts = this->conversation_.GetPromptArray(place_in_prompt);
if (this->conversation_.add_bos) {
tokens.insert(tokens.begin(), bos_token_id_);
}
if (this->conversation_.prefix_tokens.size() != 0) {
tokens.insert(tokens.begin(), this->conversation_.prefix_tokens.begin(),
this->conversation_.prefix_tokens.end());
}
} else {
prompts = this->conversation_.GetPromptArrayLastRound(place_in_prompt);
}
// first try to encode all
std::string all_prompt = GetConcatPrompt(prompts, 0, 0);
std::vector<int32_t> encoded = this->tokenizer_->Encode(all_prompt);
tokens.insert(tokens.end(), encoded.begin(), encoded.end());
if (this->sliding_window_size_ != -1 || // There is no max window size if we use sliding window
this->total_seq_len_ + tokens.size() + gen_mean_gen_len < this->max_window_size_) {
return tokens;
}
// need shift window and re-encode
this->total_seq_len_ = 0;
this->ResetKVCache();
tokens.clear();
if (this->conversation_.add_bos) {
tokens.insert(tokens.begin(), bos_token_id_);
}
if (this->conversation_.prefix_tokens.size() != 0) {
tokens.insert(tokens.begin(), this->conversation_.prefix_tokens.begin(),
this->conversation_.prefix_tokens.end());
}
std::vector<std::string> all_prompts = this->conversation_.GetPromptArray();
// get estimate of the fragment
size_t ctx_length = this->tokenizer_->Encode(all_prompts[0]).size();
size_t start_re_encode_pos = 0;
for (int i = all_prompts.size() - 1; i > 0; --i) {
ctx_length += this->tokenizer_->Encode(all_prompts[i]).size();
if (ctx_length >= this->shift_fill_factor_ * this->max_window_size_ &&
i + 2 < all_prompts.size()) {
start_re_encode_pos = i;
break;
}
}
// keep system
if (this->conversation_.system.empty()) {
all_prompt = GetConcatPrompt(all_prompts, 0, start_re_encode_pos);
} else {
all_prompt = GetConcatPrompt(all_prompts, 1, start_re_encode_pos);
}
encoded = this->tokenizer_->Encode(all_prompt);
tokens.insert(tokens.end(), encoded.begin(), encoded.end());
if (tokens.size() >= this->max_window_size_) {
LOG(WARNING)
<< "The prompt tokens are more than `max_window_size`, the input will be truncated.";
ICHECK_GT(this->max_window_size_, gen_mean_gen_len);
std::vector<int32_t> truncated_tokens(
tokens.end() - (this->max_window_size_ - gen_mean_gen_len), tokens.end());
return truncated_tokens;
} else if (tokens.size() + gen_mean_gen_len >= this->max_window_size_) {
LOG(WARNING)
<< "The prompt tokens are too long and the generated text may be incomplete, due to "
"limited `max_window_size`. ";
}
return tokens;
}
// get statically allocated input token
NDArray GetInputTokenNDArray(const std::vector<int32_t>& token_ids) {
// try realloc
if (!input_token_ids_.defined()) {
int64_t init_size = 2048;
while (init_size < static_cast<int64_t>(token_ids.size())) {
init_size *= 2;
}
input_token_ids_ = NDArray::Empty({1, init_size}, DataType::Int(32), device_);
} else {
int64_t init_size = input_token_ids_->shape[1];
while (init_size < static_cast<int64_t>(token_ids.size())) {
init_size *= 2;
}
if (init_size != input_token_ids_->shape[1]) {
input_token_ids_ = NDArray::Empty({1, init_size}, DataType::Int(32), device_);
}
}
ICHECK_LE(token_ids.size(), input_token_ids_->shape[1]) << "Input tokens exceed window size";
NDArray view = input_token_ids_.CreateView(
ShapeTuple({1, static_cast<int64_t>(token_ids.size())}), input_token_ids_->dtype);
if (token_ids.size() > 0) {
view.CopyFromBytes(token_ids.data(), token_ids.size() * sizeof(int32_t));
}
return view;
}
std::vector<int32_t> PrepareBeforeEmbedding(
std::string inp, bool append_conversation = true,
PlaceInPrompt place_in_prompt = PlaceInPrompt::kAll,
picojson::object generation_config = picojson::object()) {
if (conversation_.separator_style == SeparatorStyle::kLM ||
conversation_.separator_style == SeparatorStyle::kCodeCompletion) {
this->ResetChat();
}
if (reset_stats_per_prefill_) {
this->ResetRuntimeStats();
}
output_ids_.clear();
appeared_token_freq_.clear();
output_message_.clear();
stop_triggered_ = false;
if (append_conversation) {
conversation_.AppendMessage(conversation_.roles[0], inp);
conversation_.AppendReplyHeader(conversation_.roles[1]);
}
return this->GetInputTokens(place_in_prompt, generation_config);
}
/*!
* \brief Given the text input, generate the embedding of the tokenized prompt.
* \param inp The input text string.
* \param append_conversation Whether to append the input message to conversation.
* \param place_in_prompt The place of the input message in the prompt.
* \return the embedding of the tokenized prompt.
*/
ObjectRef EmbedStep(std::string inp, bool append_conversation = true,
PlaceInPrompt place_in_prompt = PlaceInPrompt::kAll,
String generation_config_str = "") {
// process generation settings
picojson::object generation_config =
this->LoadGenerationConfigFromString(generation_config_str);
std::vector<int32_t> prompt_tokens =
PrepareBeforeEmbedding(inp, append_conversation, place_in_prompt, generation_config);
int64_t token_len = static_cast<int64_t>(prompt_tokens.size());
if (token_len == 0) {
return NDArray::Empty({}, DataType::Float(32), device_);
}
CHECK(ft_.embed_func_.defined())
<< "In order to use the embedding functionality, make sure you "
"build the model in MLC-LLM with `sep_embed` option on.";
auto tstart = std::chrono::high_resolution_clock::now();
NDArray input_data = this->GetInputTokenNDArray(prompt_tokens);
ObjectRef embedding = ft_.embed_func_(ft_.CopyToWorker0(input_data), params_);
int32_t new_seq_len = total_seq_len_ + token_len;
total_seq_len_ = new_seq_len;
auto tend = std::chrono::high_resolution_clock::now();
this->embed_total_time += static_cast<double>((tend - tstart).count()) / 1e9;
return embedding;
}
/*!
* \brief Prefill given embeddings. Can optionally decode the output next token.
* \param embedding The embedding to prefill with.
* \param decode_next_token Whether to decode next token.
*/
void PrefillWithEmbedStep(NDArray embedding, bool decode_next_token = true,
String generation_config_str = "") {
if (ft_.use_disco) {
LOG(FATAL) << "NotImplementedError: Distributed inference is not supported for this model";
throw;
}
if (embedding.Shape().size() == 0) {
return;
}
auto tstart = std::chrono::high_resolution_clock::now();
int64_t token_len = embedding.Shape()[1];
NDArray logits_on_device = this->ForwardEmbeddings(embedding, total_seq_len_);
if (!decode_next_token) {
auto tend = std::chrono::high_resolution_clock::now();
this->prefill_total_time += static_cast<double>((tend - tstart).count()) / 1e9;
this->prefill_total_tokens += token_len;
return;
}
picojson::object generation_config =
this->LoadGenerationConfigFromString(generation_config_str);
int32_t next_token = this->SampleTokenFromLogits(logits_on_device, generation_config);
auto tend = std::chrono::high_resolution_clock::now();
this->prefill_total_time += static_cast<double>((tend - tstart).count()) / 1e9;
this->prefill_total_tokens += token_len;
this->ProcessNextToken(next_token, generation_config);
}
/*!
* \brief Generate the next token given a prompt. Can optionally decode the output next token.
* \param inp The input text string.
* \param append_conversation Whether to append the input message to conversation.
* \param decode_next_token Whether to decode next token.
* \param place_in_prompt The place of the input message in the prompt.
*/
void PrefillStep(std::string inp, bool append_conversation = true, bool decode_next_token = true,
PlaceInPrompt place_in_prompt = PlaceInPrompt::kAll,
String generation_config_str = "") {
if (ft_.embed_func_.defined() && ft_.prefill_with_embed_func_.defined()) {
// Temporarily placed inside `PrefillStep` for compatibility in transition.
// Will be separated out in the future.
if (ft_.use_disco) {
LOG(FATAL) << "NotImplementedError: Distributed inference is not supported for this model";
}
if (this->prefill_chunk_size_ != -1) {
LOG(FATAL) << "NotImplementedError: Separate embedding does not support chunking";
}
NDArray embedding = Downcast<NDArray>(
EmbedStep(inp, append_conversation, place_in_prompt, generation_config_str));
PrefillWithEmbedStep(embedding, decode_next_token, generation_config_str);
return;
}
picojson::object generation_config =
this->LoadGenerationConfigFromString(generation_config_str);
std::vector<int32_t> prompt_tokens =
this->PrepareBeforeEmbedding(inp, append_conversation, place_in_prompt, generation_config);
int64_t token_len = static_cast<int64_t>(prompt_tokens.size());
if (token_len == 0) return;
if (ft_.use_disco) {
// exclude load shard time from prefill
this->ft_.sess->SyncWorker(0);
}
auto tstart = std::chrono::high_resolution_clock::now();
int32_t new_seq_len = total_seq_len_;
NDArray logits_on_device;
if (this->prefill_chunk_size_ > 0) {
// Perform chunking.
for (int64_t begin = 0; begin < token_len; begin += this->prefill_chunk_size_) {
int64_t end = std::min(token_len, begin + this->prefill_chunk_size_);
std::vector<int32_t> chunk =
std::vector<int32_t>(prompt_tokens.begin() + begin, prompt_tokens.begin() + end);
new_seq_len += static_cast<int64_t>(chunk.size());
logits_on_device = this->ForwardTokens(chunk, new_seq_len);
}
ICHECK_EQ(new_seq_len, total_seq_len_ + token_len) << "Expect chunking process all tokens";
} else {
// Otherwise, prefill entire prompt at once.
CHECK(sliding_window_size_ == -1) << "Expect chunking with sliding window attention";
new_seq_len += token_len;
logits_on_device = this->ForwardTokens(prompt_tokens, new_seq_len);
}