-
Notifications
You must be signed in to change notification settings - Fork 234
/
request_manager.cc
3210 lines (2878 loc) · 123 KB
/
request_manager.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 2023 CMU, Stanford, Facebook, LANL
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "flexflow/request_manager.h"
#include "flexflow/ops/fused.h"
#include "flexflow/ops/lora_linear.h"
#include "flexflow/parallel_ops/parallel_op.h"
// #include "flexflow/tokenizers.h"
#include <bitset>
#include <filesystem>
#include <future>
#include <iomanip>
#include <new>
#include <nlohmann/json.hpp>
#include <stack>
#include <stdexcept>
namespace FlexFlow {
using namespace Legion;
using tokenizers::Tokenizer;
using json = nlohmann::json;
Legion::Logger log_req_mgr("RequestManager");
std::string LoadBytesFromFile(std::string const &path) {
std::ifstream fs(path, std::ios::in | std::ios::binary);
if (fs.fail()) {
std::cerr << "Failed to open file: " << path << std::endl;
assert(false);
}
std::string data;
fs.seekg(0, std::ios::end);
size_t size = static_cast<size_t>(fs.tellg());
fs.seekg(0, std::ios::beg);
data.resize(size);
fs.read(data.data(), size);
return data;
}
std::ostream &operator<<(std::ostream &os, Request const &req) {
os << "Request {\n";
os << " guid: " << req.guid << "\n";
os << " peft_model_id: " << req.peft_model_id << "\n";
os << " max_length: " << req.max_length << "\n";
os << " max_new_tokens: " << req.max_new_tokens << "\n";
os << " add_special_tokens: " << req.add_special_tokens << "\n";
os << " initial_len: " << req.initial_len << "\n";
os << " ssm_cache_size: " << req.ssm_cache_size << "\n";
os << " llm_cache_size: " << req.llm_cache_size << "\n";
os << " status: " << static_cast<int>(req.status) << "\n";
os << " tokens: [";
for (auto const &token : req.tokens) {
os << token << " ";
}
os << "]\n";
os << " prompt: " << req.prompt << "\n";
// os << " beam_trees: [";
// for (const auto& tree : req.beam_trees) {
// // Assuming BeamTree has its own << operator defined
// os << tree << " ";
// }
// os << "]\n";
os << " req_type: " << static_cast<int>(req.req_type) << "\n";
os << " completed_training_steps: " << req.completed_training_steps << "\n";
os << " gradient_accumulation_steps: " << req.gradient_accumulation_steps
<< "\n";
os << " max_training_steps: " << req.max_training_steps << "\n";
os << " dataset_filepath: " << req.dataset_filepath << "\n";
os << " dataset: [";
for (auto const &pair : req.dataset) {
os << "[";
for (auto const &token : pair.first) {
os << token << " ";
}
os << "], [";
for (auto const &token : pair.second) {
os << token << " ";
}
os << "] ";
}
os << "]\n";
os << "}\n";
return os;
}
bool RequestManager::inference_finished = false;
RequestManager::RequestManager()
: request_manager_status(INITIALIZED), verbose(false),
next_available_guid(1000000), num_processed_requests(0),
total_request_run_time(0.0f) {
// The following config parameters are set
// during ffmodel.compile()
// Initialize them to -1 to make sure no one
// gets an incorrect value of them before
// ffmodel.compile()
max_requests_per_batch = -1;
max_tokens_per_batch = -1;
max_spec_tree_token_num = -1;
max_sequence_length = -1;
}
void RequestManager::set_max_requests_per_batch(int max_num_requests) {
assert(max_requests_per_batch == -1 ||
max_requests_per_batch == max_num_requests);
max_requests_per_batch = max_num_requests;
assert(max_requests_per_batch <= BatchConfig::MAX_NUM_REQUESTS);
}
int RequestManager::get_max_requests_per_batch() {
assert(max_requests_per_batch > 0);
return max_requests_per_batch;
}
void RequestManager::set_max_tokens_per_batch(int max_num_tokens) {
assert(max_tokens_per_batch == -1 || max_tokens_per_batch == max_num_tokens);
max_tokens_per_batch = max_num_tokens;
assert(max_tokens_per_batch <= BatchConfig::MAX_NUM_TOKENS);
}
void RequestManager::set_max_spec_tree_token_num(int max_num_tokens) {
assert(max_spec_tree_token_num == -1 ||
max_spec_tree_token_num == max_num_tokens);
max_spec_tree_token_num = max_num_tokens;
assert(max_spec_tree_token_num <= BatchConfig::MAX_SPEC_TREE_TOKEN_NUM);
}
int RequestManager::get_max_tokens_per_batch() {
assert(max_tokens_per_batch > 0);
return max_tokens_per_batch;
}
int RequestManager::get_max_spec_tree_token_num() {
assert(max_spec_tree_token_num > 0);
return max_spec_tree_token_num;
}
int RequestManager::get_max_verify_tokens_per_batch() {
assert(max_tokens_per_batch > 0);
return max_tokens_per_batch +
max_spec_tree_token_num * max_requests_per_batch;
}
void RequestManager::set_max_sequence_length(int max_seq_length) {
assert(max_sequence_length == -1 || max_sequence_length == max_seq_length);
max_sequence_length = max_seq_length;
}
int RequestManager::get_max_sequence_length() {
assert(max_sequence_length > 0);
return max_sequence_length;
}
void RequestManager::push_spec_infer_tree_width(int tree_width) {
assert(tree_width <= BeamSearchBatchConfig::MAX_BEAM_WIDTH);
spec_infer_tree_width.emplace_back(tree_width);
}
void RequestManager::set_enable_peft_finetuning(bool enable_peft_finetuning_) {
enable_peft_finetuning = enable_peft_finetuning_;
}
void RequestManager::set_inference_finished(bool finished) {
inference_finished = finished;
}
void RequestManager::register_tokenizer(ModelType type,
int bos_token_id,
std::vector<int> eos_token_ids,
std::string const &path) {
this->model_type = type;
this->bos_token_id = bos_token_id;
this->eos_token_ids = eos_token_ids;
std::filesystem::path tokenizer_folder(path);
if (model_type == ModelType::LLAMA) {
// try with tokenizer.json first
std::filesystem::path tokenizer_json_path;
if (std::filesystem::is_directory(tokenizer_folder)) {
tokenizer_json_path =
std::filesystem::path(tokenizer_folder) / "tokenizer.json";
} else {
tokenizer_json_path = tokenizer_folder;
}
if (std::filesystem::exists(tokenizer_json_path)) {
// load from tokenizer.json
this->tokenizer_ = Tokenizer::FromBlobJSON(
LoadBytesFromFile(tokenizer_json_path.string()));
} else {
// load from tokenizer.model
std::filesystem::path tokenizer_model_path;
if (std::filesystem::is_directory(tokenizer_folder)) {
tokenizer_model_path =
std::filesystem::path(tokenizer_folder) / "tokenizer.model";
} else {
tokenizer_model_path = tokenizer_folder;
}
if (!std::filesystem::exists(tokenizer_model_path)) {
std::cerr << "Failed to open file: " << tokenizer_model_path
<< std::endl;
assert(false);
}
old_llama_tokenizer = true;
this->tokenizer_ = Tokenizer::FromBlobSentencePiece(
LoadBytesFromFile(tokenizer_model_path.string()));
}
} else if (model_type == ModelType::OPT) {
std::filesystem::path vocab_file = tokenizer_folder / "vocab.json";
std::filesystem::path merges_file = tokenizer_folder / "merges.txt";
std::filesystem::path added_tokens_file =
tokenizer_folder / "special_tokens_map.json";
assert(std::filesystem::exists(vocab_file) &&
"Vocab file vocab.json does not exist at the specified path");
assert(std::filesystem::exists(merges_file) &&
"Merge file merges.txt does not exist at the specified path");
// opt_tokenizer = new OptTokenizer(vocab_file, merges_file);
std::string vocab = LoadBytesFromFile(vocab_file.string());
std::string merges = LoadBytesFromFile(merges_file.string());
std::string added_tokens = LoadBytesFromFile(added_tokens_file.string());
this->tokenizer_ =
Tokenizer::FromBlobByteLevelBPE(vocab, merges, added_tokens);
} else if (model_type == ModelType::FALCON ||
model_type == ModelType::STARCODER ||
model_type == ModelType::MPT) {
std::string falcon_tokenizer_path = join_path({path, "tokenizer.json"});
this->tokenizer_ =
Tokenizer::FromBlobJSON(LoadBytesFromFile(falcon_tokenizer_path));
}
}
void RequestManager::register_output_filepath(
std::string const &_output_filepath) {
this->output_filepath = _output_filepath;
}
int RequestManager::register_ssm_model(FFModel *model) {
int model_id = ssm_models.size();
ssm_models.push_back(model);
std::cout << "Register new ssm model with id: " << model_id << std::endl;
return model_id;
}
FFModel *RequestManager::get_ssm_model(int model_id) {
assert(model_id < ssm_models.size());
return ssm_models[model_id];
}
size_t RequestManager::get_num_ssms() {
return ssm_models.size();
}
void RequestManager::set_peft_config(PEFTModelID const &peft_model_id,
LoraLinearConfig const &peft_config) {
// check that peft_model_id is not already in use
assert(peft_configs.find(peft_model_id) == peft_configs.end() &&
"PEFT model ID already in use");
// LoraLinearConfig new_config =
// LoraLinearConfig::deserialize_from_json_string(
// peft_config.serialize_to_json_string());
peft_configs[peft_model_id] = peft_config;
}
LoraLinearConfig const &
RequestManager::get_peft_config(PEFTModelID const &peft_model_id) {
assert(peft_configs.find(peft_model_id) != peft_configs.end() &&
"PEFT model ID not found");
return peft_configs[peft_model_id];
}
void RequestManager::set_max_lora_rank(int max_lora_rank_) {
max_lora_rank = max_lora_rank_;
}
void RequestManager::set_max_concurrent_adapters(int max_concurrent_adapters_) {
max_concurrent_adapters = max_concurrent_adapters_;
}
int RequestManager::get_max_lora_rank() {
return max_lora_rank;
}
int RequestManager::get_max_concurrent_adapters() {
return max_concurrent_adapters;
}
PEFTModelID *
FFModel::register_peft_adapter(LoraLinearConfig const &peft_config) {
assert(config.enable_peft &&
"Cannot add a LoRA layer if PEFT mode is not enabled");
if (peft_config.target_modules.size() == 0) {
printf("PEFT config does not contain any target module\n");
std::cout << peft_config << std::endl;
assert(false);
}
std::cout << "Registering PEFT adapter"
<< peft_config.serialize_to_json_string() << std::endl;
// go over base_layer_to_peft_layer and check that you can find at least one
// match
for (int i = 0; i < peft_config.target_modules.size(); i++) {
bool found = false;
for (auto const &pair : base_layer_to_peft_layer) {
Layer *base_layer = pair.first;
if (base_layer->name != nullptr && strlen(base_layer->name) > 0 &&
std::string(base_layer->name).find(peft_config.target_modules[0]) !=
std::string::npos) {
found = true;
break;
}
}
assert(found && "Attempting to add LoRA to a LLM target module that does "
"not exist or does not support LoRA");
}
PEFTModelID *peft_model_id = new PEFTModelID(peft_model_global_guid++);
RequestManager *rm = RequestManager::get_request_manager();
rm->set_peft_config(*peft_model_id, peft_config);
return peft_model_id;
}
RequestManager::RequestGuid
RequestManager::register_new_request(Request const &request_) {
const std::lock_guard<std::mutex> lock(request_queue_mutex);
// Add a new request
Request request;
request.status = Request::PENDING;
request.guid = next_available_guid++;
request.max_length = request_.max_length;
request.max_new_tokens = request_.max_new_tokens;
request.add_special_tokens = request_.add_special_tokens;
// both unset
if (request.max_length == -1 && request.max_new_tokens == -1) {
request.max_length = get_max_sequence_length() - 1;
}
// both set
if (request.max_length != -1 && request.max_new_tokens != -1) {
request.max_length = -1;
std::cout
<< "Both `max_new_tokens` (=" << request.max_new_tokens
<< ") and `max_length`(=" << request.max_length
<< ") seem to have been set. `max_new_tokens` will take precedence.";
}
request.peft_model_id = request_.peft_model_id;
request.warmup = request_.warmup;
if (bos_token_id >= 0 && model_type != ModelType::FALCON &&
request.add_special_tokens) {
request.tokens.push_back(bos_token_id);
}
if (request_.benchmarking_tokens >= 0) {
assert(request_.benchmarking_tokens < get_max_sequence_length() &&
"Benchmarking tokens exceed max sequence length");
request.benchmarking_tokens = request_.benchmarking_tokens;
request.tokens.insert(request.tokens.end(),
request_.benchmarking_tokens,
15); // insert random number
} else {
std::vector<int32_t> tokens = this->tokenizer_->Encode(request_.prompt);
// from here on, we will only use the max_length parameter
if (request.max_new_tokens != -1) {
request.max_length = tokens.size() + request.max_new_tokens;
}
// check that max sequence length is not exceeded
// 1. prompt itself should be less than max sequence length
if (tokens.size() >= get_max_sequence_length()) {
std::cout << "Error: prompt (" << tokens.size()
<< " tokens) exceeds max sequence length of "
<< get_max_sequence_length() << ".\n";
return INVALID_GUID;
}
// 2. max_length should not exceed the max_sequence_length
if (request.max_length >= get_max_sequence_length()) {
std::cout << "Error: max_length (" << request.max_length
<< ") exceeds max sequence length of "
<< get_max_sequence_length() << ".\n";
return INVALID_GUID;
}
for (int i = 0; i < tokens.size(); i++) {
std::cout << "[" << i << "]" << tokens.at(i) << "\n";
}
request.tokens.insert(request.tokens.end(), tokens.begin(), tokens.end());
}
request.initial_len = request.tokens.size();
if (get_num_ssms() == 0) {
std::cout << "No small speculative model registered, using incremental "
"decoding."
<< std::endl;
} else {
std::cout << "Num of SSMs: " << get_num_ssms() << std::endl;
for (int i = 0; i < get_num_ssms(); i++) {
BeamTree beam_tree = BeamTree{};
request.beam_trees.push_back(beam_tree);
}
}
pending_infr_request_queue.push(request);
all_requests[request.guid] = request;
{
const std::lock_guard<std::mutex> lock(request_to_promise_mutex);
request_to_promise[request.guid] = new std::promise<void>();
}
{
std::string output = "New request tokens:";
output = "[" + std::to_string(request.guid) + "]" + output;
for (int i = 0; i < request.tokens.size(); i++) {
output = output + " " + std::to_string(request.tokens[i]);
}
log_req_mgr.print("%s", output.c_str());
}
GenerationResult gr;
gr.guid = request.guid;
gr.input_text = request_.prompt;
gr.input_tokens = request.tokens;
gr.output_text = request_.prompt;
gr.output_tokens = request.tokens;
request_generation_results[request.guid] = gr;
ProfileInfo profile_info;
profile_info.registration_time = Realm::Clock::current_time_in_microseconds();
profiling_requests[request.guid] = profile_info;
return request.guid;
}
RequestManager::RequestGuid
RequestManager::register_new_peft_request(Request const &request_) {
assert(enable_peft_finetuning && "PEFT finetuning is not enabled");
const std::lock_guard<std::mutex> lock(request_queue_mutex);
// Add a new request
Request request;
request.status = Request::PENDING;
request.guid = next_available_guid++;
request.initial_len = 0;
request.max_length = request_.max_length;
request.max_new_tokens = request_.max_new_tokens;
request.add_special_tokens = request_.add_special_tokens;
if (request.max_new_tokens != -1) {
std::cerr
<< "Error: max_new_tokens is not allowed for PEFT finetuning requests"
<< std::endl;
assert(false);
}
if (request.max_length == -1) {
request.max_length = get_max_sequence_length() - 1;
}
request.peft_model_id = request_.peft_model_id;
request.req_type = RequestType::REQ_FINETUNING;
request.completed_training_steps = 0;
request.gradient_accumulation_steps = request_.gradient_accumulation_steps;
request.max_training_steps = request_.max_training_steps;
request.dataset_filepath = request_.dataset_filepath;
request.warmup = request_.warmup;
// Load dataset
if (request_.benchmarking_tokens >= 0) {
assert(request_.benchmarking_tokens <= get_max_sequence_length() &&
"Benchmarking tokens exceed max sequence length");
request.benchmarking_tokens = request_.benchmarking_tokens;
std::vector<int32_t> input_tokens;
std::vector<int32_t> output_tokens;
bool bos_added = (bos_token_id >= 0 && request.add_special_tokens &&
model_type != ModelType::FALCON);
if (bos_added) {
input_tokens.push_back(bos_token_id);
}
input_tokens.insert(input_tokens.end(),
request_.benchmarking_tokens - (int)bos_added,
15); // insert random number
request.dataset.push_back(std::make_pair(input_tokens, output_tokens));
} else {
using json = nlohmann::json;
std::ifstream file_handle(request.dataset_filepath);
assert(file_handle.good() && "Dataset file does not exist.");
json dataset_json = json::parse(file_handle,
/*parser_callback_t */ nullptr,
/*allow_exceptions */ true,
/*ignore_comments */ true);
for (auto &prompt : dataset_json) {
std::string text = prompt.get<std::string>();
std::string output_text("");
std::vector<int32_t> input_tokens;
input_tokens = this->tokenizer_->Encode(text);
if (bos_token_id >= 0 && model_type != ModelType::FALCON &&
request.add_special_tokens) {
input_tokens.insert(input_tokens.begin(), bos_token_id);
}
std::vector<int32_t> output_tokens =
this->tokenizer_->Encode(output_text);
if (input_tokens.size() + output_tokens.size() >
get_max_sequence_length()) {
std::cout << "Error: sample in training dataset is "
<< input_tokens.size() + output_tokens.size()
<< " tokens long, exceeding the maximum sequence length of "
<< get_max_sequence_length() << " tokens.\n";
return INVALID_GUID;
} else {
request.dataset.push_back(std::make_pair(input_tokens, output_tokens));
}
}
}
if (request.gradient_accumulation_steps == -1) {
request.gradient_accumulation_steps = request.dataset.size();
}
assert(request.gradient_accumulation_steps > 0 &&
"Invalid gradient accumulation steps");
assert(request.gradient_accumulation_steps <= request.max_training_steps &&
"Gradient accumulation steps should be less than or equal to max "
"training steps");
// Currently don't support speculative inference for PEFT
assert(get_num_ssms() == 0);
if (get_num_ssms() == 0) {
std::cout << "No small speculative model registered, using incremental "
"decoding."
<< std::endl;
} else {
std::cout << "Num of SSMs: " << get_num_ssms() << std::endl;
for (int i = 0; i < get_num_ssms(); i++) {
BeamTree beam_tree = BeamTree{};
request.beam_trees.push_back(beam_tree);
}
}
pending_peft_request_queue.push(request);
all_requests[request.guid] = request;
{
const std::lock_guard<std::mutex> lock(request_to_promise_mutex);
request_to_promise[request.guid] = new std::promise<void>();
}
for (size_t r = 0; r < request.dataset.size(); r++) {
std::string input = "[" + std::to_string(r) + "] input:";
std::string output = "[" + std::to_string(r) + "] output:";
for (size_t i = 0; i < request.dataset[r].first.size(); i++) {
input = input + " " + std::to_string(request.dataset[r].first[i]);
}
for (size_t i = 0; i < request.dataset[r].second.size(); i++) {
output = output + " " + std::to_string(request.dataset[r].second[i]);
}
log_req_mgr.print("%s", input.c_str());
log_req_mgr.print("%s", output.c_str());
}
GenerationResult gr;
gr.guid = request.guid;
// gr.input_text = prompt;
// gr.input_tokens = request.tokens;
// gr.output_text = prompt;
// gr.output_tokens = request.tokens;
request_generation_results[request.guid] = gr;
ProfileInfo profile_info;
profile_info.registration_time = Realm::Clock::current_time_in_microseconds();
profiling_requests[request.guid] = profile_info;
return request.guid;
}
bool RequestManager::is_request_completed(RequestGuid const &guid) {
const std::lock_guard<std::mutex> lock(request_queue_mutex);
assert(all_requests.find(guid) != all_requests.end());
Request const &request = all_requests[guid];
// return request.tokens.size() >= request.max_sequence_length;
return request.status == Request::COMPLETED;
}
GenerationResult
RequestManager::get_generation_result(RequestGuid const &guid) {
// First get the future of the request
std::future<void> future;
{
const std::lock_guard<std::mutex> lock(request_to_promise_mutex);
assert(request_to_promise.find(guid) != request_to_promise.end());
future = request_to_promise[guid]->get_future();
}
// Wait until the result is completed
future.get();
// Get the generation result
{
const std::lock_guard<std::mutex> lock(request_queue_mutex);
assert(request_generation_results.find(guid) !=
request_generation_results.end());
return request_generation_results[guid];
}
}
size_t RequestManager::get_num_processed_requests() {
return num_processed_requests;
}
BatchConfigFuture
RequestManager::prepare_next_batch(BatchConfigFuture const &old_bc,
InferenceResultFuture const &result,
Context ctx,
Runtime *runtime) {
RequestManager *rm = this;
TaskLauncher launcher(RM_PREPARE_NEXT_BATCH_TASK_ID,
TaskArgument(&rm, sizeof(RequestManager *)));
launcher.add_future(old_bc);
launcher.add_future(result);
return runtime->execute_task(ctx, launcher);
}
BatchConfig RequestManager::prepare_next_batch_task(
Task const *task,
std::vector<PhysicalRegion> const ®ions,
Context ctx,
Runtime *runtime) {
RequestManager *rm = *((RequestManager **)task->args);
BatchConfig const *bc = BatchConfig::from_future(task->futures[0]);
InferenceResult const &result =
Future(task->futures[1]).get_result<InferenceResult>();
return rm->prepare_next_batch(*bc, result);
}
bool RequestManager::is_eos_token(int token_id) {
for (int eos_token : eos_token_ids) {
if (token_id == eos_token) {
return true;
}
}
return false;
}
bool RequestManager::check_inf_req_completion(BatchConfig const &old_bc,
int i) {
Request &request = all_requests[old_bc.requestsInfo[i].request_guid];
bool request_completed = false;
// printf("model_type = %d\n", this->model_type);
if (request.tokens.size() >= old_bc.requestsInfo[i].max_length) {
request_completed = true;
} else if (is_eos_token(request.tokens.back())) {
// Encounter EOS token id
request_completed = true;
}
return request_completed;
}
void RequestManager::check_batch(BatchConfig const &old_bc,
BatchConfig const &new_bc) {
int num_incomplete_prompts = 0;
for (int i = 0; i < BatchConfig::max_requests_per_batch(); i++) {
if (new_bc.request_completed[i]) {
continue;
}
// ensure there is no request with zero tokens
assert(new_bc.requestsInfo[i].num_tokens_in_batch > 0);
// ensure there is no more than one incomplete prompt
if (new_bc.requestsInfo[i].prompt_phase &&
new_bc.requestsInfo[i].num_tokens_in_batch +
new_bc.requestsInfo[i].first_token_depth_in_request <
all_requests[new_bc.requestsInfo[i].request_guid].tokens.size()) {
num_incomplete_prompts++;
}
}
if (num_incomplete_prompts > 1) {
std::cout << "Error: more than one incomplete prompt in the batch\n";
pid_t pid = getpid();
std::string filenamen = "new_bc_" + std::to_string(pid) + ".txt";
std::ofstream filen(filenamen);
if (filen.is_open()) {
filen << new_bc << std::endl;
filen.close();
std::cout << "String written to file: " << filenamen << std::endl;
} else {
std::cout << "Unable to open file: " << filenamen << std::endl;
}
std::string filenameo = "old_bc_" + std::to_string(pid) + ".txt";
std::ofstream fileo(filenameo);
if (fileo.is_open()) {
fileo << old_bc << std::endl;
fileo.close();
std::cout << "String written to file: " << filenameo << std::endl;
} else {
std::cout << "Unable to open file: " << filenameo << std::endl;
}
assert(false);
}
}
void RequestManager::add_peft_config_to_request_info(
BatchConfig &bc, int req_idx, LoraLinearConfig const &peft_config) {
std::memset(bc.requestsInfo[req_idx].peft_model_config_str,
0,
BatchConfig::MAX_PEFT_CONFIG_SIZE);
std::string peft_config_str = peft_config.serialize_to_json_string();
std::strcpy(bc.requestsInfo[req_idx].peft_model_config_str,
peft_config_str.c_str());
// std::cout << "Added PEFT config to request info: "
// << bc.requestsInfo[req_idx].peft_model_config_str << std::endl;
}
BatchConfig RequestManager::prepare_next_batch(BatchConfig const &old_bc,
InferenceResult const &result) {
const std::lock_guard<std::mutex> lock(request_queue_mutex);
// Step 1: append result from previous iteration to request's tokens
for (int i = 0; i < old_bc.num_active_tokens(); i++) {
size_t guid =
old_bc.requestsInfo[old_bc.tokensInfo[i].request_index].request_guid;
Request &request = all_requests[guid];
if (request.req_type == RequestType::REQ_FINETUNING) {
continue;
}
if (old_bc.tokensInfo[i].abs_depth_in_request + 1 < request.tokens.size()) {
// This is a prompt token
continue;
} else {
// This is a decoding token
assert(old_bc.tokensInfo[i].abs_depth_in_request + 1 ==
request.tokens.size());
if (!profiling_requests[guid].first_token_time_set) {
profiling_requests[guid].first_token_time =
Realm::Clock::current_time_in_microseconds();
profiling_requests[guid].first_token_time_set = true;
}
log_req_mgr.print("Output token is: %d", result.token_ids[i]);
request.tokens.push_back(result.token_ids[i]);
// std::string output = this->tokenizer_->Decode(request.tokens);
// log_req_mgr.print("Output: %s", output.c_str());
}
}
int num_generation_tokens = 0;
int num_active_req = -1;
// when finetuning is enabled, the last entry in the batch cannot be used for
// inference
int inference_batch_size =
BatchConfig::max_requests_per_batch() - (int)enable_peft_finetuning;
int num_concurrent_adapters = 0;
// Step 2: prepare the next batch for existing inference requests
BatchConfig new_bc;
for (int i = 0; i < inference_batch_size; i++) {
if (old_bc.request_completed[i]) {
// no need to carry over tokens to new batch for this request
continue;
} else {
assert(old_bc.requestsInfo[i].num_tokens_in_batch > 0);
Request &request = all_requests[old_bc.requestsInfo[i].request_guid];
assert(request.req_type == RequestType::REQ_INFERENCE &&
"Found misplaced finetuning request");
int processed_tokens =
old_bc.requestsInfo[i].first_token_depth_in_request +
old_bc.requestsInfo[i].num_tokens_in_batch;
assert(processed_tokens < request.tokens.size());
bool request_completed = check_inf_req_completion(old_bc, i);
if (request_completed) {
if (is_eos_token(request.tokens.back())) {
// remove the EOS token
request.tokens.pop_back();
}
std::string output = this->tokenizer_->Decode(request.tokens);
// Unlike Huggingface, the sentencepiece C++ library automatically
// removes the BOS token
if (model_type == ModelType::LLAMA && old_llama_tokenizer &&
request.add_special_tokens &&
request.tokens.at(0) == bos_token_id) {
output = "<s> " + output;
}
{
// update generation result
GenerationResult &gr = request_generation_results[request.guid];
assert(gr.guid == request.guid);
gr.output_tokens = request.tokens;
gr.output_text = output;
}
request.status = Request::COMPLETED;
trigger_request_completion_future(request.guid);
log_req_mgr.print("[Done] guid(%zu) final_length(%zu)",
old_bc.requestsInfo[i].request_guid,
request.tokens.size());
log_req_mgr.print("Final output: %s", output.c_str());
num_processed_requests++;
ProfileInfo profile_info = profiling_requests[request.guid];
profile_info.finish_time = Realm::Clock::current_time_in_microseconds();
total_request_run_time +=
profile_info.finish_time - profile_info.start_time;
profiling_requests[request.guid] = profile_info;
log_req_mgr.print("[%s] guid(%zu) llm_decoding_steps(%d) start(%.1lf) "
"finish(%.1lf) latency(%.1lf) ttft(%.1lf)",
request.warmup ? "Warmup" : "Profile",
request.guid,
profile_info.llm_decoding_steps,
profile_info.start_time,
profile_info.finish_time,
profile_info.finish_time - profile_info.start_time,
profile_info.first_token_time -
profile_info.registration_time);
// Write output to file if needed:
if (!output_filepath.empty()) {
std::ofstream outputFile(output_filepath, std::ios::app);
if (outputFile.is_open()) {
outputFile << "[" << (request.warmup ? "Warmup" : "Profile")
<< "] guid(" << request.guid << ") llm_decoding_steps("
<< profile_info.llm_decoding_steps << ") latency("
<< std::fixed << std::setprecision(3)
<< (profile_info.finish_time - profile_info.start_time)
<< ") ttft(" << std::fixed << std::setprecision(3)
<< (profile_info.first_token_time -
profile_info.registration_time)
<< ")\n";
if (request.benchmarking_tokens <= 0) {
outputFile << "token IDs: ";
for (int i = 0; i < request.tokens.size(); i++) {
outputFile << request.tokens[i];
if (i < request.tokens.size() - 1) {
outputFile << ",";
}
}
outputFile << std::endl;
outputFile << output;
}
outputFile.close();
} else {
std::cout << "Unable to open the output file: " << output_filepath
<< std::endl;
assert(false);
}
}
} else {
new_bc.request_completed[i] = false;
new_bc.requestsInfo[i].first_token_depth_in_request = processed_tokens;
new_bc.requestsInfo[i].first_token_offset_in_batch = new_bc.num_tokens;
new_bc.requestsInfo[i].request_guid =
old_bc.requestsInfo[i].request_guid;
new_bc.requestsInfo[i].peft_model_id =
old_bc.requestsInfo[i].peft_model_id;
std::strcpy(new_bc.requestsInfo[i].peft_model_config_str,
old_bc.requestsInfo[i].peft_model_config_str);
if (old_bc.requestsInfo[i].peft_model_id != PEFTModelID::NO_ID) {
num_concurrent_adapters += 1;
}
new_bc.requestsInfo[i].peft_bwd = old_bc.requestsInfo[i].peft_bwd;
new_bc.requestsInfo[i].max_length = old_bc.requestsInfo[i].max_length;
num_active_req++;
new_bc.requestsInfo[num_active_req].batch_config_request_id = i;
if (new_bc.requestsInfo[i].first_token_depth_in_request + 1 ==
request.tokens.size()) {
// Incremental phase
new_bc.requestsInfo[i].num_tokens_in_batch = 1;
num_generation_tokens++;
new_bc.requestsInfo[i].prompt_phase = false;
} else {
// Prompt phase
assert(old_bc.requestsInfo[i].prompt_phase == true);
int space_for_incr_dec_requests = 0;
// If the prompt can't fit in the batch, compute how much space we
// need to leave out for incomplete requests in decoding phase at
// higher indices.
for (int ii = i + 1; ii < inference_batch_size; ii++) {
if (old_bc.request_completed[ii]) {
continue;
}
Request &old_request =
all_requests[old_bc.requestsInfo[ii].request_guid];
bool req_completed = check_inf_req_completion(old_bc, ii);
if (!req_completed) {
space_for_incr_dec_requests++;
}
}
new_bc.requestsInfo[i].num_tokens_in_batch =
std::min(get_max_tokens_per_batch() - new_bc.num_tokens -
space_for_incr_dec_requests,
(int)request.tokens.size() -
new_bc.requestsInfo[i].first_token_depth_in_request);
new_bc.requestsInfo[i].prompt_phase = true;
}
for (int j = 0; j < new_bc.requestsInfo[i].num_tokens_in_batch; j++) {
int depth = new_bc.requestsInfo[i].first_token_depth_in_request + j;
new_bc.tokensInfo[new_bc.num_tokens].request_index = i;
new_bc.tokensInfo[new_bc.num_tokens].abs_depth_in_request = depth;
assert(depth < request.tokens.size());
new_bc.tokensInfo[new_bc.num_tokens].token_id = request.tokens[depth];
new_bc.num_tokens++;
}
// Update profiling
profiling_requests[new_bc.requestsInfo[i].request_guid]
.llm_decoding_steps++;
}
}
}
new_bc.num_generation_tokens = num_generation_tokens;
assert(num_concurrent_adapters <= get_max_concurrent_adapters() &&
"Number of concurrent adapters exceeded the limit");
// Step 3: add new inference requests to the next batch if there is space
for (int i = 0; i < inference_batch_size; i++) {
if (new_bc.request_completed[i]) {
if (!pending_infr_request_queue.empty() &&
new_bc.num_tokens < get_max_tokens_per_batch()) {
Request new_request = pending_infr_request_queue.front();
assert(new_request.req_type == RequestType::REQ_INFERENCE);
// if the request has peft adapters and we are at capacity, don't add it
// yet
if (new_request.peft_model_id != PEFTModelID::NO_ID &&
num_concurrent_adapters == get_max_concurrent_adapters()) {
break;
}
pending_infr_request_queue.pop();
// all_requests[new_request.guid] = new_request;
new_bc.requestsInfo[i].first_token_depth_in_request = 0;
new_bc.requestsInfo[i].first_token_offset_in_batch = new_bc.num_tokens;
new_bc.requestsInfo[i].request_guid = new_request.guid;
new_bc.requestsInfo[i].num_tokens_in_batch =
std::min(get_max_tokens_per_batch() - new_bc.num_tokens,
(int)new_request.tokens.size());
new_bc.requestsInfo[i].max_length = new_request.max_length;
new_bc.requestsInfo[i].peft_model_id = new_request.peft_model_id;
if (new_request.peft_model_id != PEFTModelID::NO_ID) {
add_peft_config_to_request_info(
new_bc, i, get_peft_config(new_request.peft_model_id));
}
new_bc.requestsInfo[i].peft_bwd = false;
new_bc.request_completed[i] = false;
new_bc.requestsInfo[i].prompt_phase = true;
num_active_req++;
new_bc.requestsInfo[num_active_req].batch_config_request_id = i;
// add start time to profile_info for the new request
profiling_requests[new_request.guid].llm_decoding_steps = 1;
profiling_requests[new_request.guid].start_time =
Realm::Clock::current_time_in_microseconds();
for (int j = 0; j < new_bc.requestsInfo[i].num_tokens_in_batch; j++) {
int depth = new_bc.requestsInfo[i].first_token_depth_in_request + j;
new_bc.tokensInfo[new_bc.num_tokens].request_index = i;
new_bc.tokensInfo[new_bc.num_tokens].abs_depth_in_request = depth;
assert(depth < new_request.tokens.size());
new_bc.tokensInfo[new_bc.num_tokens].token_id =
new_request.tokens[depth];
new_bc.num_tokens++;
}
if (new_bc.num_tokens == get_max_tokens_per_batch()) {
break;
}
}
}
}
if (enable_peft_finetuning &&
!old_bc.request_completed[inference_batch_size]) {
assert(old_bc.requestsInfo[inference_batch_size].num_tokens_in_batch > 0);
Request &request =
all_requests[old_bc.requestsInfo[inference_batch_size].request_guid];
assert(request.req_type == RequestType::REQ_FINETUNING &&
"Found misplaced inference request");
request.finetuning_losses.push_back(result.finetuning_loss);
request.dataset_entry_processed_tokens +=
old_bc.requestsInfo[inference_batch_size].num_tokens_in_batch;
request.processed_finetuning_tokens +=
old_bc.requestsInfo[inference_batch_size].num_tokens_in_batch;
request.finetuning_tokens_per_batch.push_back(
old_bc.requestsInfo[inference_batch_size].num_tokens_in_batch);
int dataset_entry =
request.completed_training_steps % request.dataset.size();
if (old_bc.requestsInfo[inference_batch_size].first_token_depth_in_request +
old_bc.requestsInfo[inference_batch_size].num_tokens_in_batch ==
request.dataset[dataset_entry].first.size()) {
// completed the current dataset entry
assert(request.dataset_entry_processed_tokens ==
request.dataset[dataset_entry].first.size());
request.completed_training_steps += 1;
request.dataset_entry_processed_tokens = 0;
}
assert(request.completed_training_steps <= request.max_training_steps);
if (request.completed_training_steps == request.max_training_steps ||
inference_finished) {
// check if the fine tuning request has completed
request.status = Request::COMPLETED;
GenerationResult &gr = request_generation_results[request.guid];
assert(gr.guid == request.guid);
gr.finetuning_losses = request.finetuning_losses;
trigger_request_completion_future(request.guid);
num_processed_requests++;