-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathllama_server_context.cc
1710 lines (1479 loc) · 55.8 KB
/
llama_server_context.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
#include "llama_server_context.h"
#include "sampling.h"
namespace {
struct llava_embd_batch {
std::vector<llama_pos> pos;
std::vector<int32_t> n_seq_id;
std::vector<llama_seq_id> seq_id_0;
std::vector<llama_seq_id*> seq_ids;
std::vector<int8_t> logits;
llama_batch batch;
llava_embd_batch(float* embd, int32_t n_tokens, llama_pos pos_0,
llama_seq_id seq_id) {
pos.resize(n_tokens);
n_seq_id.resize(n_tokens);
seq_ids.resize(n_tokens + 1);
logits.resize(n_tokens);
seq_id_0.resize(1);
seq_id_0[0] = seq_id;
seq_ids[n_tokens] = nullptr;
batch = {
/*n_tokens =*/n_tokens,
/*tokens =*/nullptr,
/*embd =*/embd,
/*pos =*/pos.data(),
/*n_seq_id =*/n_seq_id.data(),
/*seq_id =*/seq_ids.data(),
/*logits =*/logits.data(),
};
for (int i = 0; i < n_tokens; i++) {
batch.pos[i] = pos_0 + i;
batch.n_seq_id[i] = 1;
batch.seq_id[i] = seq_id_0.data();
batch.logits[i] = false;
}
}
};
const std::string base64_chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/";
bool is_base64(uint8_t c) {
return (isalnum(c) || (c == '+') || (c == '/'));
}
std::vector<uint8_t> base64_decode(const std::string& encoded_string) {
int i = 0;
int j = 0;
int in_ = 0;
int in_len = encoded_string.size();
uint8_t char_array_4[4];
uint8_t char_array_3[3];
std::vector<uint8_t> ret;
while (in_len-- && (encoded_string[in_] != '=') &&
is_base64(encoded_string[in_])) {
char_array_4[i++] = encoded_string[in_];
in_++;
if (i == 4) {
for (i = 0; i < 4; i++) {
char_array_4[i] = base64_chars.find(char_array_4[i]);
}
char_array_3[0] =
((char_array_4[0]) << 2) + ((char_array_4[1] & 0x30) >> 4);
char_array_3[1] =
((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
for (i = 0; (i < 3); i++) {
ret.push_back(char_array_3[i]);
}
i = 0;
}
}
if (i) {
for (j = i; j < 4; j++) {
char_array_4[j] = 0;
}
for (j = 0; j < 4; j++) {
char_array_4[j] = base64_chars.find(char_array_4[j]);
}
char_array_3[0] =
((char_array_4[0]) << 2) + ((char_array_4[1] & 0x30) >> 4);
char_array_3[1] =
((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
for (j = 0; (j < i - 1); j++) {
ret.push_back(char_array_3[j]);
}
}
return ret;
}
size_t common_part(const std::vector<llama_token>& a,
const std::vector<llama_token>& b) {
size_t i;
for (i = 0; i < a.size() && i < b.size() && a[i] == b[i]; i++) {}
return i;
}
bool ends_with(const std::string& str, const std::string& suffix) {
return str.size() >= suffix.size() &&
0 == str.compare(str.size() - suffix.size(), suffix.size(), suffix);
}
size_t find_partial_stop_string(const std::string& stop,
const std::string& text) {
if (!text.empty() && !stop.empty()) {
const char text_last_char = text.back();
for (int64_t char_index = stop.size() - 1; char_index >= 0; char_index--) {
if (stop[char_index] == text_last_char) {
const std::string current_partial = stop.substr(0, char_index + 1);
if (ends_with(text, current_partial)) {
return text.size() - char_index - 1;
}
}
}
}
return std::string::npos;
}
// format incomplete utf-8 multibyte character for output
inline std::string tokens_to_output_formatted_string(const llama_context* ctx,
const llama_token token) {
std::string out = token == -1 ? "" : common_token_to_piece(ctx, token);
// if the size is 1 and first bit is 1, meaning it's a partial character
// (size > 1 meaning it's already a known token)
if (out.size() == 1 && (out[0] & 0x80) == 0x80) {
std::stringstream ss;
ss << std::hex << (out[0] & 0xff);
std::string res(ss.str());
out = "byte: \\x" + res;
}
return out;
}
// convert a vector of CompletionTokenOutput to json
inline json probs_vector_to_json(
const llama_context* ctx, const std::vector<CompletionTokenOutput>& probs) {
json out = json::array();
for (const auto& prob : probs) {
json probs_for_token = json::array();
for (const auto& p : prob.probs) {
std::string tok_str = tokens_to_output_formatted_string(ctx, p.tok);
probs_for_token.push_back(json{
{"tok_str", tok_str},
{"prob", p.prob},
});
}
std::string tok_str = tokens_to_output_formatted_string(ctx, prob.tok);
out.push_back(json{
{"content", tok_str},
{"probs", probs_for_token},
});
}
return out;
}
bool IsLlava_1_6(const std::string& model) {
if (model.find("llava-v1.6") != std::string::npos) {
return true;
}
return false;
}
} // namespace
LlamaServerContext::~LlamaServerContext() {
}
bool LlamaServerContext::LoadModel(const common_params& params_) {
params = params_;
if (!params.mmproj.empty()) {
multimodal = true;
LOG_DEBUG << "Multi Modal Mode Enabled";
clp_ctx = clip_model_load(params.mmproj.c_str(), /*verbosity=*/1);
if (clp_ctx == nullptr) {
LOG_ERROR_LLAMA("unable to load clip model", {{"model", params.mmproj}});
return false;
}
// https://github.com/ggerganov/llama.cpp/blob/master/examples/llava/README.md
// note llava-1.6 needs more context than llava-1.5, at least 3000 is needed (just run it at -c 4096)
if (params.n_ctx < 4096 && IsLlava_1_6(params.model)) {
params.n_ctx = 4096;
LOG_DEBUG << "Request " << params.n_ctx
<< " for context length for llava-1.6";
} else if (params.n_ctx <
2048) { // request larger context for the image embedding
params.n_ctx = 2048;
LOG_DEBUG << "Request " << params.n_ctx
<< " for context length for the image embedding";
}
}
llama_init = common_init_from_params(params);
model = llama_init.model.get();
ctx = llama_init.context.get();
if (model == nullptr) {
LOG_ERROR_LLAMA("llama.cpp unable to load model",
{{"model", params.model}});
return false;
}
if (multimodal) {
const int n_embd_clip = clip_n_mmproj_embd(clp_ctx);
const int n_embd_llm = llama_n_embd(model);
if (n_embd_clip != n_embd_llm) {
LOG_DEBUG << __func__ << ": embedding dim of the multimodal projector ("
<< n_embd_clip
<< ") is not "
"equal to that of LLaMA ("
<< n_embd_llm
<< "). Make sure that you use the "
"correct mmproj file.";
return false;
}
}
if (ctx == nullptr) {
LOG_ERROR_LLAMA("Unable to get llama.cpp context", {});
return false;
}
vocab = llama_model_get_vocab(model);
n_ctx = llama_n_ctx(ctx);
add_bos_token = llama_add_bos_token(vocab);
has_eos_token = !llama_add_eos_token(vocab);
return true;
}
void LlamaServerContext::Initialize() {
id_gen = 0;
// create slots
all_slots_are_idle = true;
const int32_t n_ctx_slot = n_ctx / params.n_parallel;
LOG_DEBUG << "Available slots: ";
for (int i = 0; i < params.n_parallel; i++) {
LlamaClientSlot slot;
slot.id = i;
slot.n_ctx = n_ctx_slot;
slot.Reset();
LOG_DEBUG << " -> Slot " << slot.id << " - max context: " << n_ctx_slot;
slots.push_back(slot);
}
try {
batch = llama_batch_init(n_ctx, 0, params.n_parallel);
} catch (const std::exception& e) {
LOG_ERROR_LLAMA("Failed to allocate llama.cpp batch metadata",
{{"exception", e.what()},
{"n_tokens_alloc", n_ctx},
{"embd", 0},
{"n_seq_max", params.n_parallel}});
}
// empty system prompt
system_prompt = "";
system_tokens.clear();
model_loaded_external = true;
LOG_INFO << "Started background task here!";
bgr_thread =
std::thread(std::bind(&LlamaServerContext::DoBackgroundTasks, this));
}
void LlamaServerContext::KvCacheClear() {
LOG_DEBUG << "Clear the entire KV cache";
// clear the entire KV cache
llama_kv_cache_clear(ctx);
clean_kv_cache = false;
}
json LlamaServerContext::GetModelProps() {
return GetFormatedGeneration(slots[0]);
}
int LlamaServerContext::RequestCompletion(json data, bool infill,
bool embedding, int multitask_id) {
// From this commit: 'llama : allow pooled embeddings on any model (#7477)'
// we need to explicitly set embedding flad for each request
llama_set_embeddings(ctx, embedding);
TaskServer task;
task.id = id_gen++;
task.target_id = 0;
task.data = std::move(data);
task.infill_mode = infill;
task.embedding_mode = embedding;
task.type = TaskType::kCompletionTask;
task.multitask_id = multitask_id;
// when a completion task's prompt array is not a singleton, we split it
// into multiple requests
if (task.data.at("prompt").size() > 1) {
return SplitMultipromptTask(task);
}
// otherwise, it's a single-prompt task, we actually queue it
{
std::lock_guard<std::mutex> lock(mutex_tasks);
queue_tasks.push_back(task);
}
condition_tasks.notify_one();
return task.id;
}
TaskResult LlamaServerContext::NextResult(int task_id) {
while (true) {
std::unique_lock<std::mutex> lock(mutex_results);
condition_results.wait(lock, [&] { return !queue_results.empty(); });
for (int i = 0; i < (int)queue_results.size(); i++) {
// for now, tasks that have associated parent multitasks just get erased
// once multitask picks up the result
if (queue_results[i].multitask_id == task_id) {
UpdateMultiTask(task_id, queue_results[i].id, queue_results[i]);
queue_results.erase(queue_results.begin() + i);
continue;
}
if (queue_results[i].id == task_id) {
if (queue_results[i].multitask_id != -1) {
LOG_ERROR_LLAMA("Incorrect multitask ID", {{"task_id", task_id}});
}
TaskResult res = queue_results[i];
queue_results.erase(queue_results.begin() + i);
return res;
}
}
}
// never reached
// return TaskResult{-1, false, false, {}};
}
void LlamaServerContext::RequestCancel(int task_id) {
TaskServer task;
task.id = id_gen++;
task.type = TaskType::kCancelTask;
task.target_id = task_id;
{
std::lock_guard<std::mutex> lock(mutex_tasks);
queue_tasks.push_back(task);
}
condition_tasks.notify_one();
}
void LlamaServerContext::ReleaseResources() {
if (model_loaded_external) {
LOG_INFO << "Releasing llama_server_context resources";
model_loaded_external = false;
condition_tasks.notify_one();
if (bgr_thread.joinable()) {
bgr_thread.join();
}
ctx = nullptr;
model = nullptr;
LOG_INFO << "Released llama_server_context resources";
}
}
std::vector<llama_token> LlamaServerContext::Tokenize(
const json& json_prompt, bool add_special, bool parse_special) const {
// If `add_bos` is true, we only add BOS, when json_prompt is a string,
// or the first element of the json_prompt array is a string.
std::vector<llama_token> prompt_tokens;
if (json_prompt.is_array()) {
bool first = true;
for (const auto& p : json_prompt) {
if (p.is_string()) {
auto s = p.template get<std::string>();
std::vector<llama_token> p;
if (first) {
p = common_tokenize(ctx, s, add_special, parse_special);
first = false;
} else {
p = common_tokenize(ctx, s, false, parse_special);
}
prompt_tokens.insert(prompt_tokens.end(), p.begin(), p.end());
} else {
if (first) {
first = false;
}
prompt_tokens.push_back(p.template get<llama_token>());
}
}
} else {
auto s = json_prompt.template get<std::string>();
prompt_tokens = common_tokenize(ctx, s, add_special, parse_special);
}
return prompt_tokens;
}
LlamaClientSlot* LlamaServerContext::GetSlot(int id) {
int64_t t_last = ggml_time_us();
LlamaClientSlot* last_used = nullptr;
for (LlamaClientSlot& slot : slots) {
if (slot.id == id && slot.Available()) {
return &slot;
}
if (slot.Available() && slot.t_last_used < t_last) {
last_used = &slot;
t_last = slot.t_last_used;
}
}
return last_used;
}
bool LlamaServerContext::LaunchSlotWithData(LlamaClientSlot*& slot, json data) {
SlotParams default_params;
// Sampling parameter defaults are loaded from the global server context (but individual requests can still override them)
auto default_sparams = params.sampling;
if (data.count("__oaicompat") != 0) {
slot->oaicompat = true;
slot->oaicompat_model =
json_value(data, "model", std::string(DEFAULT_OAICOMPAT_MODEL));
} else {
slot->oaicompat = false;
slot->oaicompat_model = "";
}
slot->params.stream = json_value(data, "stream", false);
slot->params.cache_prompt = json_value(data, "cache_prompt", false);
slot->params.n_predict =
json_value(data, "n_predict", default_params.n_predict);
slot->sparams.top_k = json_value(data, "top_k", default_sparams.top_k);
slot->sparams.top_p = json_value(data, "top_p", default_sparams.top_p);
slot->sparams.min_p = json_value(data, "min_p", default_sparams.min_p);
slot->sparams.typ_p = json_value(data, "typical_p", default_sparams.typ_p);
slot->sparams.temp = json_value(data, "temperature", default_sparams.temp);
slot->sparams.penalty_last_n =
json_value(data, "repeat_last_n", default_sparams.penalty_last_n);
slot->sparams.penalty_repeat =
json_value(data, "repeat_penalty", default_sparams.penalty_repeat);
slot->sparams.penalty_freq =
json_value(data, "frequency_penalty", default_sparams.penalty_freq);
slot->sparams.penalty_present =
json_value(data, "presence_penalty", default_sparams.penalty_present);
slot->sparams.mirostat =
json_value(data, "mirostat", default_sparams.mirostat);
slot->sparams.mirostat_tau =
json_value(data, "mirostat_tau", default_sparams.mirostat_tau);
slot->sparams.mirostat_eta =
json_value(data, "mirostat_eta", default_sparams.mirostat_eta);
slot->params.n_keep = json_value(data, "n_keep", slot->params.n_keep);
slot->params.seed = json_value(data, "seed", default_params.seed);
slot->sparams.grammar = json_value(data, "grammar", default_sparams.grammar);
slot->sparams.n_probs = json_value(data, "n_probs", default_sparams.n_probs);
slot->sparams.min_keep =
json_value(data, "min_keep", default_sparams.min_keep);
slot->sparams.seed = json_value(data, "seed", default_sparams.seed);
slot->sparams.dynatemp_range =
json_value(data, "dynatemp_range", default_sparams.dynatemp_range);
slot->sparams.dynatemp_exponent =
json_value(data, "dynatemp_exponent", default_sparams.dynatemp_exponent);
slot->sparams.ignore_eos =
json_value(data, "ignore_eos", default_sparams.ignore_eos);
slot->prompt_tokens =
json_value(data, "prompt_tokens", json::array()).get<std::vector<int>>();
slot->num_prompt_tokens = slot->prompt_tokens.size();
// infill
if (data.count("input_prefix") != 0) {
slot->params.input_prefix = data["input_prefix"];
} else {
slot->params.input_prefix = "";
}
if (data.count("input_suffix") != 0) {
slot->params.input_suffix = data["input_suffix"];
} else {
slot->params.input_suffix = "";
}
if (data.count("prompt") != 0) {
slot->prompt = data["prompt"];
} else {
slot->prompt = "";
}
{
slot->sparams.logit_bias.clear();
if (json_value(data, "ignore_eos", false) && has_eos_token) {
slot->sparams.logit_bias.push_back({llama_vocab_eos(vocab), -INFINITY});
}
const auto& logit_bias = data.find("logit_bias");
if (logit_bias != data.end() && logit_bias->is_array()) {
const int n_vocab = llama_vocab_n_tokens(vocab);
for (const auto& el : *logit_bias) {
// TODO: we may want to throw errors here, in case "el" is incorrect
if (el.is_array() && el.size() == 2) {
float bias;
if (el[1].is_number()) {
bias = el[1].get<float>();
} else if (el[1].is_boolean() && !el[1].get<bool>()) {
bias = -INFINITY;
} else {
continue;
}
if (el[0].is_number_integer()) {
llama_token tok = el[0].get<llama_token>();
if (tok >= 0 && tok < n_vocab) {
slot->sparams.logit_bias.push_back({tok, bias});
}
} else if (el[0].is_string()) {
auto toks = common_tokenize(vocab, el[0].get<std::string>(), false);
for (auto tok : toks) {
slot->sparams.logit_bias.push_back({tok, bias});
}
}
}
}
}
}
slot->params.antiprompt.clear();
const auto& stop = data.find("stop");
if (stop != data.end() && stop->is_array()) {
for (const auto& word : *stop) {
if (!word.empty()) {
slot->params.antiprompt.push_back(word);
}
}
}
if (multimodal) {
const auto& images_data = data.find("image_data");
if (images_data != data.end() && images_data->is_array()) {
for (const auto& img : *images_data) {
const std::vector<uint8_t> image_buffer =
base64_decode(img["data"].get<std::string>());
SlotImage img_sl;
img_sl.id =
img.count("id") != 0 ? img["id"].get<int>() : slot->images.size();
img_sl.img_data = clip_image_u8_init();
if (!clip_image_load_from_bytes(image_buffer.data(),
image_buffer.size(), img_sl.img_data)) {
LOG_DEBUG << "slot " << slot->id
<< " - failed to load image [id: " << img_sl.id << "]";
return false;
}
LOG_DEBUG << "slot " << slot->id << " - loaded image";
img_sl.request_encode_image = true;
slot->images.push_back(img_sl);
}
// process prompt
// example: system prompt [img-102] user [img-103] describe [img-134] ->
// [{id: 102, prefix: 'system prompt '}, {id: 103, prefix: ' user '},
// {id: 134, prefix: ' describe '}]}
if (slot->images.size() > 0 && !slot->prompt.is_array()) {
std::string prompt = slot->prompt.get<std::string>();
size_t pos = 0, begin_prefix = 0;
std::string pattern = "[img-";
while ((pos = prompt.find(pattern, pos)) != std::string::npos) {
size_t end_prefix = pos;
pos += pattern.length();
size_t end_pos = prompt.find("]", pos);
if (end_pos != std::string::npos) {
std::string image_id = prompt.substr(pos, end_pos - pos);
try {
int img_id = std::stoi(image_id);
bool found = false;
for (SlotImage& img : slot->images) {
if (img.id == img_id) {
found = true;
img.prefix_prompt =
prompt.substr(begin_prefix, end_prefix - begin_prefix);
begin_prefix = end_pos + 1;
break;
}
}
if (!found) {
LOG_WARN << "ERROR: Image with id: " << img_id
<< ", not found.\n";
slot->images.clear();
return false;
}
} catch (const std::invalid_argument& e) {
LOG_WARN << "Invalid image number id in prompt: " << e.what();
slot->images.clear();
return false;
}
}
}
slot->prompt = "";
slot->params.input_suffix = prompt.substr(begin_prefix);
slot->params.cache_prompt =
false; // multimodal doesn't support cache prompt
}
}
}
if (slot->smpl != nullptr) {
common_sampler_free(slot->smpl);
}
slot->smpl = common_sampler_init(model, slot->sparams);
// llama_set_rng_seed(ctx, slot->params.seed);
slot->command = SlotCommand::kLoadPrompt;
if (slot->num_prompt_tokens == 0 && !slot->embedding) {
slot->prompt_tokens.clear();
}
all_slots_are_idle = false;
LOG_DEBUG << "slot " << slot->id
<< " is processing [task id: " << slot->task_id << "]";
return true;
}
void LlamaServerContext::UpdateSystemPrompt() {
system_tokens = ::common_tokenize(ctx, system_prompt, add_bos_token);
common_batch_clear(batch);
KvCacheClear();
for (int i = 0; i < (int)system_tokens.size(); ++i) {
common_batch_add(batch, system_tokens[i], i, {0}, false);
}
if (llama_decode(ctx, batch) != 0) {
LOG_WARN << __func__ << ": llama_decode() failed";
return;
}
// assign the system KV cache to all parallel sequences
for (int32_t i = 1; i < params.n_parallel; ++i) {
llama_kv_cache_seq_cp(ctx, 0, i, 0, system_tokens.size());
}
LOG_DEBUG << "system prompt updated";
system_need_update = false;
}
void LlamaServerContext::NotifySystemPromptChanged() {
// release all slots
for (LlamaClientSlot& slot : slots) {
slot.Release();
}
system_need_update = true;
}
void LlamaServerContext::ProcessSystemPromptData(const json& sys_props) {
system_prompt = sys_props.value("prompt", "");
name_user = sys_props.value("anti_prompt", "");
name_assistant = sys_props.value("assistant_name", "");
if (slots.size() > 0) {
NotifySystemPromptChanged();
}
}
size_t LlamaServerContext::FindStoppingStrings(const std::string& text,
const size_t last_token_size,
const StopType type,
LlamaClientSlot& slot) {
size_t stop_pos = std::string::npos;
for (const std::string& word : slot.params.antiprompt) {
size_t pos;
if (type == StopType::kStopFull) {
const size_t tmp = word.size() + last_token_size;
const size_t from_pos = text.size() > tmp ? text.size() - tmp : 0;
pos = text.find(word, from_pos);
} else {
pos = find_partial_stop_string(word, text);
}
if (pos != std::string::npos &&
(stop_pos == std::string::npos || pos < stop_pos)) {
if (type == StopType::kStopFull) {
slot.stopped_word = true;
slot.stopping_word = word;
slot.has_next_token = false;
}
stop_pos = pos;
}
}
return stop_pos;
}
bool LlamaServerContext::ProcessToken(CompletionTokenOutput& result,
LlamaClientSlot& slot) {
// remember which tokens were sampled - used for repetition penalties during
// sampling
const std::string token_str = common_token_to_piece(ctx, result.tok);
slot.sampled = result.tok;
// search stop word and delete it
slot.generated_text += token_str;
slot.has_next_token = true;
// check if there is incomplete UTF-8 character at the end
bool incomplete = false;
for (unsigned i = 1; i < 5 && i <= slot.generated_text.size(); ++i) {
unsigned char c = slot.generated_text[slot.generated_text.size() - i];
if ((c & 0xC0) == 0x80) {
// continuation byte: 10xxxxxx
continue;
}
if ((c & 0xE0) == 0xC0) {
// 2-byte character: 110xxxxx ...
incomplete = i < 2;
} else if ((c & 0xF0) == 0xE0) {
// 3-byte character: 1110xxxx ...
incomplete = i < 3;
} else if ((c & 0xF8) == 0xF0) {
// 4-byte character: 11110xxx ...
incomplete = i < 4;
}
// else 1-byte character or invalid byte
break;
}
if (!incomplete) {
size_t pos = std::min(slot.sent_count, slot.generated_text.size());
const std::string str_test = slot.generated_text.substr(pos);
bool is_stop_full = false;
size_t stop_pos = FindStoppingStrings(str_test, token_str.size(),
StopType::kStopFull, slot);
if (stop_pos != std::string::npos) {
is_stop_full = true;
slot.generated_text.erase(slot.generated_text.begin() + pos + stop_pos,
slot.generated_text.end());
pos = std::min(slot.sent_count, slot.generated_text.size());
} else {
is_stop_full = false;
stop_pos = FindStoppingStrings(str_test, token_str.size(),
StopType::kStopPartial, slot);
}
// check if there is any token to predict
if (stop_pos == std::string::npos ||
(!slot.has_next_token && !is_stop_full && stop_pos > 0)) {
// no send the stop word in the response
result.text_to_send = slot.generated_text.substr(pos, std::string::npos);
slot.sent_count += result.text_to_send.size();
// add the token to slot queue and cache
}
slot.AddTokenString(result);
if (slot.params.stream) {
SendPartialResponse(slot, result);
} else {
slot.sent_token_probs_index++;
}
}
if (incomplete) {
slot.has_next_token = true;
}
// check the limits
if (slot.n_decoded > 2 && slot.has_next_token && !slot.HasBudget(params)) {
slot.stopped_limit = true;
slot.has_next_token = false;
}
if (llama_vocab_is_eog(vocab, result.tok)) {
slot.stopped_eos = true;
slot.has_next_token = false;
LOG_VERBOSE("eos token found", {});
}
LOG_VERBOSE(
"next token",
{
{"token", result.tok},
{"token_text", tokens_to_output_formatted_string(ctx, result.tok)},
{"has_next_token", slot.has_next_token},
{"n_remain", slot.n_remaining},
{"num_tokens_predicted", slot.n_decoded},
{"stopped_eos", slot.stopped_eos},
{"stopped_word", slot.stopped_word},
{"stopped_limit", slot.stopped_limit},
{"stopping_word", slot.stopping_word},
});
return slot.has_next_token; // continue
}
bool LlamaServerContext::ProcessImages(LlamaClientSlot& slot) const {
for (SlotImage& img : slot.images) {
if (!img.request_encode_image) {
continue;
}
if (!llava_image_embed_make_with_clip_img(
clp_ctx, params.cpuparams.n_threads, img.img_data,
&img.image_embedding, &img.image_tokens)) {
LOG_WARN << "Error processing the given image";
return false;
}
img.request_encode_image = false;
}
return slot.images.size() > 0;
}
void LlamaServerContext::SendError(TaskServer& task, std::string error) {
SendError(task.id, task.multitask_id, error);
}
void LlamaServerContext::SendError(LlamaClientSlot& slot,
const std::string& error) {
SendError(slot.task_id, slot.multitask_id, error);
}
void LlamaServerContext::SendError(int id_task, int id_multi,
const std::string& error) {
TaskResult res;
res.id = id_task;
res.multitask_id = id_multi;
res.stop = false;
res.error = true;
res.result_json = {{"content", error}};
LOG_ERROR << "Internel error catched " << error;
{
std::lock_guard<std::mutex> lock(mutex_results);
queue_results.push_back(res);
}
condition_results.notify_all();
}
void LlamaServerContext::AddMultiTask(int id, std::vector<int>& sub_ids) {
TaskMulti multi;
multi.id = id;
std::copy(
sub_ids.begin(), sub_ids.end(),
std::inserter(multi.subtasks_remaining, multi.subtasks_remaining.end()));
{
std::lock_guard<std::mutex> lock(mutex_tasks);
queue_multitasks.push_back(multi);
}
condition_tasks.notify_one();
}
void LlamaServerContext::UpdateMultiTask(int multitask_id, int subtask_id,
TaskResult& result) {
std::lock_guard<std::mutex> lock(mutex_tasks);
for (auto& multitask : queue_multitasks) {
if (multitask.id == multitask_id) {
multitask.subtasks_remaining.erase(subtask_id);
multitask.results.push_back(result);
condition_tasks.notify_one();
}
}
}
json LlamaServerContext::GetFormatedGeneration(LlamaClientSlot& slot) {
std::vector<std::string> samplers;
samplers.reserve(slot.sparams.samplers.size());
for (const auto& sampler : slot.sparams.samplers) {
samplers.emplace_back(common_sampler_type_to_str(sampler));
}
return json{
{"n_ctx", slot.n_ctx},
{"model", params.model_alias},
{"seed", slot.sparams.seed},
{"temperature", slot.sparams.temp},
{"dynatemp_range", slot.sparams.dynatemp_range},
{"dynatemp_exponent", slot.sparams.dynatemp_exponent},
{"top_k", slot.sparams.top_k},
{"top_p", slot.sparams.top_p},
{"min_p", slot.sparams.min_p},
{"typical_p", slot.sparams.typ_p},
{"repeat_last_n", slot.sparams.penalty_last_n},
{"repeat_penalty", slot.sparams.penalty_repeat},
{"presence_penalty", slot.sparams.penalty_present},
{"frequency_penalty", slot.sparams.penalty_freq},
{"mirostat", slot.sparams.mirostat},
{"mirostat_tau", slot.sparams.mirostat_tau},
{"mirostat_eta", slot.sparams.mirostat_eta},
{"stop", slot.params.antiprompt},
{"n_predict", slot.params.n_predict},
{"n_keep", params.n_keep},
{"ignore_eos", slot.sparams.ignore_eos},
{"stream", slot.params.stream},
//{"logit_bias", slot.sparams.logit_bias},
{"n_probs", slot.sparams.n_probs},
{"min_keep", slot.sparams.min_keep},
{"grammar", slot.sparams.grammar},
{"samplers", samplers},
};
}
void LlamaServerContext::SendPartialResponse(LlamaClientSlot& slot,
CompletionTokenOutput tkn) {
TaskResult res;
res.id = slot.task_id;
res.multitask_id = slot.multitask_id;
res.error = false;
res.stop = false;
res.result_json = json{{"content", tkn.text_to_send},
{"stop", false},
{"slot_id", slot.id},
{"multimodal", multimodal}};
if (slot.sparams.n_probs > 0) {
std::vector<CompletionTokenOutput> probs_output = {};
const std::vector<llama_token> to_send_toks =
common_tokenize(ctx, tkn.text_to_send, false);
size_t probs_pos = std::min(slot.sent_token_probs_index,
slot.generated_token_probs.size());
size_t probs_stop_pos =
std::min(slot.sent_token_probs_index + to_send_toks.size(),
slot.generated_token_probs.size());
if (probs_pos < probs_stop_pos) {
probs_output = std::vector<CompletionTokenOutput>(
slot.generated_token_probs.begin() + probs_pos,
slot.generated_token_probs.begin() + probs_stop_pos);
}
slot.sent_token_probs_index = probs_stop_pos;
res.result_json["completion_probabilities"] =
probs_vector_to_json(ctx, probs_output);
}
if (slot.oaicompat) {
res.result_json["oaicompat_token_ctr"] = slot.n_decoded;
res.result_json["model"] = slot.oaicompat_model;
}
{
std::lock_guard<std::mutex> lock(mutex_results);
queue_results.push_back(res);
}
condition_results.notify_all();
}
void LlamaServerContext::SendFinalResponse(LlamaClientSlot& slot) {
TaskResult res;
res.id = slot.task_id;
res.multitask_id = slot.multitask_id;
res.error = false;
res.stop = true;
res.result_json =
json{{"content", !slot.params.stream ? slot.generated_text : ""},
{"slot_id", slot.id},
{"stop", true},
{"model", params.model_alias},
{"tokens_predicted", slot.n_decoded},
{"tokens_evaluated", slot.num_prompt_tokens},
{"generation_settings", GetFormatedGeneration(slot)},
{"prompt", slot.prompt},
{"truncated", slot.truncated},
{"stopped_eos", slot.stopped_eos},
{"stopped_word", slot.stopped_word},
{"stopped_limit", slot.stopped_limit},
{"stopping_word", slot.stopping_word},
{"tokens_cached", slot.n_past},
{"timings", slot.GetFormatedTimings()}};
if (slot.sparams.n_probs > 0) {
std::vector<CompletionTokenOutput> probs = {};
if (!slot.params.stream && slot.stopped_word) {
const std::vector<llama_token> stop_word_toks =
common_tokenize(ctx, slot.stopping_word, false);
probs = std::vector<CompletionTokenOutput>(
slot.generated_token_probs.begin(),
slot.generated_token_probs.end() - 1);
} else {
probs = std::vector<CompletionTokenOutput>(
slot.generated_token_probs.begin(),
slot.generated_token_probs.begin() + slot.sent_token_probs_index);
}