Repository navigation
Expand file tree
/
Copy pathserver-decision.cpp
More file actions
1783 lines (1637 loc) · 73.5 KB
/
Copy pathserver-decision.cpp
File metadata and controls
1783 lines (1637 loc) · 73.5 KB
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 "server-decision.h"
#include "../../src/llama-ext.h" // staging API: llama_decision_order
#include <algorithm>
#include <cctype>
#include <cmath>
#include <stdexcept>
static const char * decision_question_type_name(server_decision_question_type type) {
switch (type) {
case SERVER_DECISION_QUESTION_CHOICE: return "choice";
case SERVER_DECISION_QUESTION_SCORE: return "score";
case SERVER_DECISION_QUESTION_NOUL: return "noul";
}
return "";
}
// lev reads noul from a rating scale: 0 = certainly no, 8 = certainly yes
static const size_t DECISION_LEV_N_RATINGS = 9;
// h2o-lightning follows serve_config.json and h2o_lightning_shim.py of the model repo
// a longer state keeps its head and its tail
static const size_t DECISION_H2O_MAX_STATE_TOKENS = 32000;
// the recursive functions of this file walk request JSON, a deeper value would overflow the stack
static const int RECURSIVE_LIMIT = 128;
static std::string decision_meta_str(const llama_model * model, const std::string & key) {
char buf[256];
const int32_t n = llama_model_meta_val_str(model, key.c_str(), buf, sizeof(buf));
return n < 0 ? "" : std::string(buf);
}
//
// model-specific setup
//
void server_decision_context::init(const llama_model * model) {
*this = server_decision_context(); // the model can be reloaded
const common_decision_type model_type = common_get_decision_type(model);
if (model_type == COMMON_DECISION_TYPE_NONE) {
return;
}
const std::string prefix = decision_meta_str(model, "general.architecture") + ".decision.";
const std::string type_name = decision_meta_str(model, prefix + "type");
vocab = llama_model_get_vocab(model);
const char * tmpl_src = llama_model_chat_template(model, "systemone");
if (tmpl_src == nullptr) {
throw std::runtime_error("decision model has no \"systemone\" template");
}
tmpl = std::make_shared<const common_chat_template>(tmpl_src, "", "");
const std::string prefix_temp = prefix + "temperature.";
for (int32_t i = 0; i < llama_model_meta_count(model); i++) {
char key[256];
char val[64];
if (llama_model_meta_key_by_index(model, i, key, sizeof(key)) < 0 || !string_starts_with(key, prefix_temp)) {
continue;
}
if (llama_model_meta_val_str_by_index(model, i, val, sizeof(val)) < 0) {
continue;
}
const float temp = std::strtof(val, nullptr);
if (temp <= 0.0f) {
throw std::runtime_error(string_format("invalid decision temperature: %s = %s", key, val));
}
temperatures[key + prefix_temp.size()] = temp;
}
// "<n_levels>.<level>" -> offset
const std::string prefix_bias = prefix + "score_bias.";
for (int32_t i = 0; i < llama_model_meta_count(model); i++) {
char key[256];
char val[64];
if (llama_model_meta_key_by_index(model, i, key, sizeof(key)) < 0 || !string_starts_with(key, prefix_bias)) {
continue;
}
if (llama_model_meta_val_str_by_index(model, i, val, sizeof(val)) < 0) {
continue;
}
const auto parts = string_split<std::string>(key + prefix_bias.size(), '.');
const size_t n = parts.size() == 2 ? std::strtoul(parts[0].c_str(), nullptr, 10) : 0;
const size_t level = parts.size() == 2 ? std::strtoul(parts[1].c_str(), nullptr, 10) : 0;
if (n < 2 || n > 255 || level >= n) {
throw std::runtime_error(string_format("invalid decision score bias: %s", key));
}
auto & bias = score_bias[n];
bias.resize(n, 0.0f);
bias[level] = std::strtof(val, nullptr);
}
if (model_type == COMMON_DECISION_TYPE_OPENJEV) {
// one letter per option, each must be a single token
const std::string letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
for (const char c : letters) {
const auto toks = common_tokenize(vocab, std::string(1, c), false, false);
if (toks.size() != 1) {
throw std::runtime_error(string_format("decision label '%c' is not a single token", c));
}
labels.push_back(toks[0]);
}
n_options_max = labels.size();
noul_true_first = true;
} else if (model_type == COMMON_DECISION_TYPE_LEV || model_type == COMMON_DECISION_TYPE_GRANITE_SWITCH || model_type == COMMON_DECISION_TYPE_NIMBLE || model_type == COMMON_DECISION_TYPE_PPLX_DECIDER || model_type == COMMON_DECISION_TYPE_VLLM_D3) {
// label codes are A..Z then AA..ZZ, only the ones that are a single token are used
std::vector<std::string> codes;
for (char a = 'A'; a <= 'Z'; a++) {
codes.push_back(std::string(1, a));
}
for (char a = 'A'; a <= 'Z'; a++) {
for (char b = 'A'; b <= 'Z'; b++) {
codes.push_back(std::string{a, b});
}
}
for (const auto & code : codes) {
const auto toks = common_tokenize(vocab, code, false, false);
if (toks.size() == 1 && labels.size() < 255) {
labels.push_back(toks[0]);
label_texts.push_back(code);
}
}
n_options_max = labels.size();
if (model_type == COMMON_DECISION_TYPE_VLLM_D3) {
canonical_legend = true;
}
if (model_type == COMMON_DECISION_TYPE_GRANITE_SWITCH) {
noul_true_first = true;
}
} else if (model_type == COMMON_DECISION_TYPE_KEV) {
// the hidden state of an option is read at the token that ends it
const auto toks = common_tokenize(vocab, "<|box_end|>", false, true);
if (toks.size() != 1) {
throw std::runtime_error("decision model has no <|box_end|> token");
}
token_marker = toks[0];
n_options_max = 255;
} else if (model_type == COMMON_DECISION_TYPE_LAYA) {
token_marker = llama_vocab_mask(vocab);
token_sep = llama_vocab_sep(vocab);
if (token_marker == LLAMA_TOKEN_NULL || token_sep == LLAMA_TOKEN_NULL) {
throw std::runtime_error("decision model has no mask or sep token");
}
text_marker = common_token_to_piece(vocab, token_marker, true);
const std::string val = decision_meta_str(model, prefix + "max_head_tokens");
max_head_tokens = std::strtoul(val.c_str(), nullptr, 10);
if (max_head_tokens == 0) {
throw std::runtime_error("decision model has no valid max_head_tokens");
}
n_options_max = 255;
} else if (model_type == COMMON_DECISION_TYPE_CLEF) {
n_options_max = 255;
noul_true_first = true;
choice_sorted = true;
} else if (model_type == COMMON_DECISION_TYPE_VLLM_DECISION2) {
n_options_max = 255;
noul_criteria_order = true;
strict_payload = true;
canonical_legend = true;
} else if (model_type == COMMON_DECISION_TYPE_LFM2_D1 || model_type == COMMON_DECISION_TYPE_LFM3_D1 || model_type == COMMON_DECISION_TYPE_LFM3_D1_OMNI) {
n_options_max = 255;
noul_true_first = true;
if (model_type != COMMON_DECISION_TYPE_LFM2_D1) {
// the texts of the special tokens are broken in the input
init_quoted_spellings(LLAMA_TOKEN_ATTR_CONTROL, 2);
}
} else if (model_type == COMMON_DECISION_TYPE_LFM2_D1_OMNI) {
token_marker = llama_vocab_mask(vocab);
if (token_marker == LLAMA_TOKEN_NULL) {
throw std::runtime_error("decision model has no mask token");
}
n_options_max = 255;
} else if (model_type == COMMON_DECISION_TYPE_H2O_LIGHTNING) {
// the answer is read at the token of a label, its text is given to the template
for (uint32_t i = 0; llama_model_decision_label(model, i) != nullptr; i++) {
const std::string text = llama_model_decision_label(model, i);
const auto toks = common_tokenize(vocab, text, false, false);
if (toks.size() != 1 || std::find(labels.begin(), labels.end(), toks[0]) != labels.end()) {
throw std::runtime_error(string_format("decision label \"%s\" is not a single distinct token", text.c_str()));
}
labels.push_back(toks[0]);
label_texts.push_back(text);
}
if (labels.empty()) {
throw std::runtime_error("decision model has no labels");
}
// the texts of the control and user-defined tokens are quoted in the input, so that they stay text
init_quoted_spellings(LLAMA_TOKEN_ATTR_CONTROL | LLAMA_TOKEN_ATTR_USER_DEFINED, 1);
n_options_max = labels.size();
noul_true_first = true;
} else if (model_type == COMMON_DECISION_TYPE_MINICPM_OCR_JEV) {
// the classes come from the GGUF classifier labels, the request API is binary: [inconsistent, consistent]
const uint32_t n_classes = llama_model_n_cls_out(model);
if (n_classes != 2 || llama_model_n_embd_out(model) != (int32_t) n_classes) {
throw std::runtime_error(string_format("decision model must have 2 classifier labels and output one score per class, got %u labels and %d scores",
n_classes, llama_model_n_embd_out(model)));
}
n_options_max = n_classes;
choice_sorted = true;
} else {
throw std::runtime_error("unsupported decision model type: " + type_name);
}
type = model_type;
SRV_INF("decision model type: %s\n", type_name.c_str());
}
void server_decision_context::init_quoted_spellings(uint32_t attrs, size_t min_size) {
for (llama_token id = 0; id < llama_vocab_n_tokens(vocab); id++) {
if (llama_vocab_get_attr(vocab, id) & attrs) {
const std::string text = llama_vocab_get_text(vocab, id);
if (text.size() >= min_size) {
quoted_spellings.push_back(text);
}
}
}
std::stable_sort(quoted_spellings.begin(), quoted_spellings.end(), [](const std::string & a, const std::string & b) {
return a.size() > b.size();
});
for (const auto & spelling : quoted_spellings) {
if (quoted_first.find(spelling[0]) == std::string::npos) {
quoted_first += spelling[0];
}
}
}
//
// request parsing
//
// lfm3-d1-omni: a spoken question, its instructions are an input_audio part
static bool decision_is_spoken(const json & instructions) {
return instructions.is_object() && json_value(instructions, "type", std::string()) == "input_audio";
}
static bool decision_is_payload(const json & val) {
return val.is_string() || val.is_object() || val.is_array();
}
std::vector<server_decision_question> server_decision_context::parse_questions(const json & body) const {
// lfm2-d1, lfm2-d1-omni, lfm3-d1 and vllm-d3 accept a null state, for example to ask about images only
const bool null_state = type == COMMON_DECISION_TYPE_LFM2_D1 || type == COMMON_DECISION_TYPE_LFM2_D1_OMNI || type == COMMON_DECISION_TYPE_VLLM_D3 || type == COMMON_DECISION_TYPE_LFM3_D1 || type == COMMON_DECISION_TYPE_LFM3_D1_OMNI;
if (!body.contains("state") || (body.at("state").is_null() && !null_state)) {
throw std::invalid_argument("\"state\" must be provided");
}
if (strict_payload && !decision_is_payload(body.at("state"))) {
throw std::invalid_argument("\"state\" must be text, an object or an array");
}
if (!body.contains("questions") || !body.at("questions").is_object() || body.at("questions").empty()) {
throw std::invalid_argument("\"questions\" must be a non-empty object");
}
if (type == COMMON_DECISION_TYPE_MINICPM_OCR_JEV && body.at("questions").size() != 1) {
throw std::invalid_argument("this model answers exactly one question");
}
std::vector<server_decision_question> questions;
for (const auto & [id, q] : body.at("questions").items()) {
auto err = [&id = id](const std::string & msg) {
return std::invalid_argument("questions." + id + ": " + msg);
};
if (!q.is_object()) {
throw err("must be an object");
}
// the vllm-d3 prompt has a default question
// h2o-lightning: the instructions can be left out, the template has a default, and the type defaults to choice
const bool is_h2o = type == COMMON_DECISION_TYPE_H2O_LIGHTNING;
const json instructions = q.contains("instructions") ? q.at("instructions") : (is_h2o ? json(std::string()) : json());
// minicpm-ocr-jev answers one fixed question, the prompt is entirely in the template
const bool is_ocr_jev = type == COMMON_DECISION_TYPE_MINICPM_OCR_JEV;
if (instructions.is_null() && type != COMMON_DECISION_TYPE_VLLM_D3 && !is_h2o && !is_ocr_jev) {
throw err("\"instructions\" must be provided");
}
if (strict_payload && (!decision_is_payload(instructions) || instructions == "")) {
throw err("\"instructions\" must be non-empty text, an object or an array");
}
if (type == COMMON_DECISION_TYPE_LFM3_D1 && decision_is_spoken(instructions)) {
throw err("spoken instructions need a model with audio input");
}
server_decision_question question;
question.id = id;
question.instructions = instructions;
const std::string type_name = json_value(q, "type", std::string(is_h2o ? "choice" : ""));
const json criteria = q.contains("criteria") ? q.at("criteria") : json();
if (type_name == "choice") {
question.type = SERVER_DECISION_QUESTION_CHOICE;
if (!criteria.is_object() || criteria.empty()) {
throw err("\"criteria\" must be a non-empty object");
}
for (const auto & [key, description] : criteria.items()) {
if (strict_payload && (key.empty() || !(description.is_null() || decision_is_payload(description)))) {
throw err("option keys must be non-empty, descriptions must be null, text, an object or an array");
}
question.options.push_back({key, description});
}
if (strict_payload && question.options.size() < 2) {
throw err("\"criteria\" must have at least 2 options");
}
if (choice_sorted) {
std::sort(question.options.begin(), question.options.end(), [](const auto & a, const auto & b) {
return a.key < b.key;
});
}
} else if (type_name == "score") {
question.type = SERVER_DECISION_QUESTION_SCORE;
// h2o-lightning: from 1 level, the maximum is n_options_max
if (is_h2o && (!criteria.is_array() || criteria.empty())) {
throw err("\"criteria\" must be a non-empty array");
}
if (!is_h2o && (!criteria.is_array() || criteria.size() < 2 || criteria.size() > 10)) {
throw err("\"criteria\" must be an array of 2 to 10 levels");
}
for (size_t i = 0; i < criteria.size(); i++) {
if (strict_payload && !decision_is_payload(criteria.at(i))) {
throw err("level descriptions must be text, an object or an array");
}
question.options.push_back({std::to_string(i), criteria.at(i)});
}
} else if (type_name == "noul") {
question.type = SERVER_DECISION_QUESTION_NOUL;
if (!criteria.is_null() && !criteria.is_object()) {
throw err("\"criteria\" must be an object");
}
if (strict_payload && criteria.is_object()) {
for (const auto & [key, description] : criteria.items()) {
if ((key != "false" && key != "true") || !decision_is_payload(description)) {
throw err("\"criteria\" may only describe \"false\" and \"true\" with text, an object or an array");
}
}
}
for (const char * key : {"false", "true"}) {
json description;
if (criteria.is_object() && criteria.contains(key)) {
description = criteria.at(key);
} else if (criteria.is_object() && (type == COMMON_DECISION_TYPE_LFM2_D1_OMNI || is_h2o)) {
// lfm2-d1-omni and h2o-lightning also read the descriptions under "no" and "yes"
const char * alias = std::string(key) == "true" ? "yes" : "no";
description = criteria.contains(alias) ? criteria.at(alias) : json();
}
question.options.push_back({key, description});
}
if (noul_true_first || (noul_criteria_order && criteria.is_object() && criteria.size() == 2 && criteria.begin().key() == "true")) {
std::swap(question.options[0], question.options[1]);
}
} else {
throw err("\"type\" must be one of: choice, score, noul");
}
// the classes are fixed: "0" is inconsistent, "1" is consistent
if (type == COMMON_DECISION_TYPE_MINICPM_OCR_JEV) {
// the task text is in the template, an instructions from the request would be dropped
if (!instructions.is_null()) {
throw err("\"instructions\" is not used by this model, the task is part of its prompt");
}
if (question.type == SERVER_DECISION_QUESTION_CHOICE) {
const auto & opts = question.options;
if (opts.size() != 2 || opts[0].key != "0" || opts[1].key != "1" || !opts[0].description.is_null() || !opts[1].description.is_null()) {
throw err("\"criteria\" must be {\"0\": null, \"1\": null}");
}
} else if (question.type == SERVER_DECISION_QUESTION_NOUL) {
if (!criteria.is_null()) {
throw err("\"criteria\" is not supported for a noul question");
}
} else {
throw err("only choice and noul questions are supported");
}
}
if (question.options.size() > n_options_max) {
throw err(string_format("too many options (%zu), this model supports at most %zu", question.options.size(), n_options_max));
}
questions.push_back(std::move(question));
}
return questions;
}
//
// images
//
static const size_t DECISION_MAX_IMAGES = 8;
// any media, mtmd tells an audio clip or a video from an image by its content
static void decision_load_image(const json & url, std::vector<raw_buffer> & files) {
if (!url.is_string() || !string_starts_with(url.get<std::string>(), "data:")) {
throw std::invalid_argument("media must be data URLs (data:image/..., data:audio/... or data:video/...;base64,...)");
}
if (files.size() >= DECISION_MAX_IMAGES) {
throw std::invalid_argument(string_format("too many images, the maximum is %zu", DECISION_MAX_IMAGES));
}
handle_media(files, url.get<std::string>(), "");
}
// audio is base64 data, as a data URL or not (OpenAI input_audio)
static void decision_load_audio(const json & data, std::vector<raw_buffer> & files) {
if (!data.is_string() || string_starts_with(data.get<std::string>(), "http") || string_starts_with(data.get<std::string>(), "file://")) {
throw std::invalid_argument("audio must be base64 data");
}
if (files.size() >= DECISION_MAX_IMAGES) {
throw std::invalid_argument(string_format("too many media files, the maximum is %zu", DECISION_MAX_IMAGES));
}
handle_media(files, data.get<std::string>(), "");
}
json server_decision_context::parse_state(const json & body, std::vector<raw_buffer> & files) const {
if (type == COMMON_DECISION_TYPE_MINICPM_OCR_JEV && !body.at("state").is_string()) {
throw std::invalid_argument("\"state\" must be the OCR text");
}
if (body.contains("videos") && !body.at("videos").is_null() && !body.at("videos").empty()) {
throw std::invalid_argument("\"videos\" is not supported");
}
// "images" is an alias of "files"
for (const char * key : {"files", "images"}) {
if (!body.contains(key) || body.at(key).is_null()) {
continue;
}
if (!body.at(key).is_array()) {
throw std::invalid_argument(string_format("\"%s\" must be an array", key));
}
for (const auto & url : body.at(key)) {
decision_load_image(url, files);
}
}
// the prompt has the original image, then the image rendered from the OCR text
if (type == COMMON_DECISION_TYPE_MINICPM_OCR_JEV && files.size() != 2) {
throw std::invalid_argument(string_format("this model needs exactly 2 images (the original, then the rendered one), got %zu", files.size()));
}
const json & state = body.at("state");
const bool is_wrapped = state.is_object() && state.contains("messages");
const json & messages = is_wrapped ? state.at("messages") : state;
if (!messages.is_array()) {
return state;
}
// chat messages: take the image and audio parts out of the content
json messages_out = json::array();
for (const auto & msg : messages) {
if (!msg.is_object() || !msg.contains("content") || !msg.at("content").is_array()) {
messages_out.push_back(msg);
continue;
}
json content = json::array();
for (const auto & part : msg.at("content")) {
if (part.is_object() && json_value(part, "type", std::string()) == "image_url" && part.contains("image_url")) {
const json & image_url = part.at("image_url");
decision_load_image(image_url.is_object() && image_url.contains("url") ? image_url.at("url") : image_url, files);
} else if (part.is_object() && json_value(part, "type", std::string()) == "input_audio" && part.contains("input_audio")) {
const json input_audio = json_value(part, "input_audio", json::object());
decision_load_audio(input_audio.contains("data") ? input_audio.at("data") : json_value(input_audio, "url", json()), files);
} else if (is_lfm3_d1() && part.is_object() && json_value(part, "type", std::string()) == "video_url" && part.contains("video_url")) {
const json & video_url = part.at("video_url");
decision_load_image(video_url.is_object() && video_url.contains("url") ? video_url.at("url") : video_url, files);
} else {
content.push_back(part);
}
}
json msg_out = msg;
msg_out["content"] = content;
messages_out.push_back(msg_out);
}
if (!is_wrapped) {
return messages_out;
}
json state_out = state;
state_out["messages"] = messages_out;
return state_out;
}
//
// prompt
//
// replace text in all strings of a JSON value
static json decision_replace_text(const json & val, const std::string & search, const std::string & replace, int depth = 0) {
if (depth >= RECURSIVE_LIMIT) {
throw std::invalid_argument("JSON is nested more than " + std::to_string(RECURSIVE_LIMIT) + " levels deep");
}
if (val.is_string()) {
std::string str = val.get<std::string>();
string_replace_all(str, search, replace);
return str;
}
if (val.is_array()) {
json out = json::array();
for (const auto & item : val) {
out.push_back(decision_replace_text(item, search, replace, depth + 1));
}
return out;
}
if (val.is_object()) {
json out = json::object();
for (const auto & [key, item] : val.items()) {
out[key] = decision_replace_text(item, search, replace, depth + 1);
}
return out;
}
return val;
}
// sort the keys of all objects of a JSON value
static json decision_sort_keys(const json & val, int depth = 0) {
if (depth >= RECURSIVE_LIMIT) {
throw std::invalid_argument("JSON is nested more than " + std::to_string(RECURSIVE_LIMIT) + " levels deep");
}
if (val.is_array()) {
json out = json::array();
for (const auto & item : val) {
out.push_back(decision_sort_keys(item, depth + 1));
}
return out;
}
if (val.is_object()) {
std::map<std::string, json> sorted;
for (const auto & [key, item] : val.items()) {
sorted[key] = decision_sort_keys(item, depth + 1);
}
json out = json::object();
for (const auto & [key, item] : sorted) {
out[key] = item;
}
return out;
}
return val;
}
// kev flattens a JSON value into text, the keys of an object are kept as labels (kev/api.py: render)
static std::string decision_kev_render(const json & val, int indent = 0, int depth = 0) {
if (depth >= RECURSIVE_LIMIT) {
throw std::invalid_argument("JSON is nested more than " + std::to_string(RECURSIVE_LIMIT) + " levels deep");
}
const std::string pad(2 * indent, ' ');
if (val.is_null()) {
return "";
}
if (val.is_string()) {
return val.get<std::string>();
}
if (val.is_boolean()) {
return val.get<bool>() ? "True" : "False";
}
if (val.is_array()) {
std::string out;
for (const auto & item : val) {
const std::string text = decision_kev_render(item, indent + 1, depth + 1);
out += (out.empty() ? "" : "\n") + pad + "- " + text.substr(std::min(text.size(), text.find_first_not_of(" \t\n\r")));
}
return out;
}
if (val.is_object()) {
std::string out;
for (const auto & [key, item] : val.items()) {
const bool is_nested = item.is_object() || item.is_array();
out += (out.empty() ? "" : "\n") + pad + key + (is_nested ? ":\n" : ": ") + decision_kev_render(item, is_nested ? indent + 1 : 0, depth + 1);
}
return out;
}
return val.dump();
}
// same result as std::regex_replace with <\|([A-Za-z0-9_]+)\|>
// std::regex is not used: libstdc++ recurses for each char, a long input overflows the stack
std::string server_decision_escape_special_tokens(const std::string & text) {
const auto is_name = [](char c) {
return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '_';
};
std::string out;
size_t n_done = 0; // the chars of text that are in out
for (size_t i = text.find("<|"); i != std::string::npos; i = text.find("<|", std::max(i + 1, n_done))) {
size_t j = i + 2;
while (j < text.size() && is_name(text[j])) {
j++;
}
if (j > i + 2 && text.compare(j, 2, "|>") == 0) {
out.append(text, n_done, i - n_done);
out += "<\xC2\xA6";
out.append(text, i + 2, j - i - 2);
out += "\xC2\xA6>";
n_done = j + 2;
}
}
if (n_done == 0) {
return text;
}
out.append(text, n_done, std::string::npos);
return out;
}
// kev text input: special tokens written in the text must not be parsed as such
static std::string decision_kev_text(const json & val) {
return server_decision_escape_special_tokens(decision_kev_render(val));
}
// lfm2-d1-omni, lfm3-d1: special tokens written in the input must not be parsed as such, in keys too
template <typename F>
static json decision_escape(const json & val, const F & escape, int depth = 0) {
if (depth >= RECURSIVE_LIMIT) {
throw std::invalid_argument("JSON is nested more than " + std::to_string(RECURSIVE_LIMIT) + " levels deep");
}
if (val.is_string()) {
return escape(val.get<std::string>());
}
if (val.is_array()) {
json out = json::array();
for (const auto & item : val) {
out.push_back(decision_escape(item, escape, depth + 1));
}
return out;
}
if (val.is_object()) {
json out = json::object();
for (const auto & [key, item] : val.items()) {
out[escape(key)] = decision_escape(item, escape, depth + 1);
}
return out;
}
return val;
}
std::string server_decision_context::d1_break(const std::string & text) const {
static const std::string zwsp = "\xE2\x80\x8B";
std::string cur = text;
// again for a match that overlapped the one broken before it
for (bool changed = true; changed;) {
changed = false;
std::string out;
for (size_t i = 0; i < cur.size();) {
const std::string * hit = nullptr;
if (quoted_first.find(cur[i]) != std::string::npos) {
for (const auto & spelling : quoted_spellings) {
if (cur.compare(i, spelling.size(), spelling) == 0) {
hit = &spelling;
break;
}
}
}
if (hit == nullptr) {
out += cur[i++];
continue;
}
// after the first character, its UTF-8 bytes
const unsigned char c = (*hit)[0];
const size_t n = c < 0x80 ? 1 : c < 0xE0 ? 2 : c < 0xF0 ? 3 : 4;
out += hit->substr(0, n) + zwsp + hit->substr(n);
i += hit->size();
changed = true;
}
cur = std::move(out);
}
return cur;
}
//
// h2o-lightning: the texts are rendered the way the reference shim renders them with Python (json.dumps, str.lstrip)
//
// one code point of UTF-8 text at s[i], i moves past it; an invalid byte is read as is
static uint32_t decision_utf8_next(const std::string & s, size_t & i) {
const unsigned char c = s[i];
size_t n = c < 0x80 ? 1 : (c >> 5) == 0x6 ? 2 : (c >> 4) == 0xe ? 3 : (c >> 3) == 0x1e ? 4 : 1;
if (i + n > s.size()) {
n = 1;
}
uint32_t cp = n == 1 ? c : n == 2 ? (c & 0x1f) : n == 3 ? (c & 0x0f) : (c & 0x07);
for (size_t k = 1; k < n; k++) {
cp = (cp << 6) | (s[i + k] & 0x3f);
}
i += n;
return cp;
}
// str.isspace() of Python
static bool decision_py_isspace(uint32_t cp) {
return (cp >= 0x09 && cp <= 0x0d) || (cp >= 0x1c && cp <= 0x20) || cp == 0x85 || cp == 0xa0 || cp == 0x1680 ||
(cp >= 0x2000 && cp <= 0x200a) || cp == 0x2028 || cp == 0x2029 || cp == 0x202f || cp == 0x205f || cp == 0x3000;
}
static std::string decision_py_rstrip(const std::string & s) {
size_t end = 0;
for (size_t i = 0; i < s.size();) {
if (!decision_py_isspace(decision_utf8_next(s, i))) {
end = i;
}
}
return s.substr(0, end);
}
static std::string decision_py_lstrip(const std::string & s) {
size_t i = 0;
while (i < s.size()) {
size_t next = i;
if (!decision_py_isspace(decision_utf8_next(s, next))) {
break;
}
i = next;
}
return s.substr(i);
}
// a code point as JSON escapes, a surrogate pair above the BMP
static std::string decision_py_escape_cp(uint32_t cp) {
if (cp < 0x10000) {
return string_format("\\u%04x", cp);
}
cp -= 0x10000;
return string_format("\\u%04x\\u%04x", 0xd800 + (cp >> 10), 0xdc00 + (cp & 0x3ff));
}
// repr() of a Python float: the shortest digits that read back the same, in exponent form below 1e-4 and from 1e16
static std::string decision_py_float(double v) {
char buf[64];
// the fewest digits that read back the same
for (int prec = 0; prec < 17; prec++) {
snprintf(buf, sizeof(buf), "%.*e", prec, v);
if (std::strtod(buf, nullptr) == v) {
break;
}
}
const std::string sci(buf); // for example "-1.25e+03"
const size_t pos_e = sci.find('e');
const int exp = std::atoi(sci.c_str() + pos_e + 1);
std::string sign;
std::string digits;
for (size_t i = 0; i < pos_e; i++) {
if (sci[i] == '-') {
sign = "-";
} else if (sci[i] != '.') {
digits += sci[i];
}
}
const int n = (int) digits.size();
if (exp < -4 || exp >= 16) {
return sign + digits.substr(0, 1) + (n > 1 ? "." + digits.substr(1) : "") + string_format("e%c%02d", exp < 0 ? '-' : '+', std::abs(exp));
}
if (exp >= n - 1) {
return sign + digits + std::string(exp - (n - 1), '0') + ".0";
}
if (exp >= 0) {
return sign + digits.substr(0, exp + 1) + "." + digits.substr(exp + 1);
}
return sign + "0." + std::string(-exp - 1, '0') + digits;
}
static void decision_py_str(std::string & out, const std::string & s, bool ensure_ascii) {
out += '"';
for (size_t i = 0; i < s.size();) {
const unsigned char c = s[i];
switch (c) {
case '"': out += "\\\""; i++; continue;
case '\\': out += "\\\\"; i++; continue;
case '\b': out += "\\b"; i++; continue;
case '\f': out += "\\f"; i++; continue;
case '\n': out += "\\n"; i++; continue;
case '\r': out += "\\r"; i++; continue;
case '\t': out += "\\t"; i++; continue;
default: break;
}
if (c < 0x20 || (ensure_ascii && c == 0x7f)) {
out += string_format("\\u%04x", c);
i++;
} else if (c < 0x80 || !ensure_ascii) {
out += (char) c;
i++;
} else {
out += decision_py_escape_cp(decision_utf8_next(s, i));
}
}
out += '"';
}
// json.dumps() of Python: indent < 0 is no indent, keys stay in their order
static void decision_py_dump(std::string & out, const json & val, int indent, int level, const std::string & item_sep, const std::string & key_sep, bool ensure_ascii) {
if (level >= RECURSIVE_LIMIT) {
throw std::invalid_argument("JSON is nested more than " + std::to_string(RECURSIVE_LIMIT) + " levels deep");
}
const auto newline = [&](int lvl) {
return indent < 0 ? std::string() : "\n" + std::string(indent * lvl, ' ');
};
if (val.is_null()) {
out += "null";
} else if (val.is_boolean()) {
out += val.get<bool>() ? "true" : "false";
} else if (val.is_number_float()) {
out += decision_py_float(val.get<double>());
} else if (val.is_number()) {
out += val.dump();
} else if (val.is_string()) {
decision_py_str(out, val.get<std::string>(), ensure_ascii);
} else if (val.is_array()) {
if (val.empty()) {
out += "[]";
return;
}
out += "[" + newline(level + 1);
for (size_t i = 0; i < val.size(); i++) {
if (i > 0) {
out += item_sep + newline(level + 1);
}
decision_py_dump(out, val.at(i), indent, level + 1, item_sep, key_sep, ensure_ascii);
}
out += newline(level) + "]";
} else if (val.is_object()) {
if (val.empty()) {
out += "{}";
return;
}
out += "{" + newline(level + 1);
bool first = true;
for (const auto & [key, item] : val.items()) {
if (!first) {
out += item_sep + newline(level + 1);
}
first = false;
decision_py_str(out, key, ensure_ascii);
out += key_sep;
decision_py_dump(out, item, indent, level + 1, item_sep, key_sep, ensure_ascii);
}
out += newline(level) + "}";
}
}
static std::string decision_py_dumps(const json & val, int indent, const std::string & item_sep, const std::string & key_sep, bool ensure_ascii) {
std::string out;
decision_py_dump(out, val, indent, 0, item_sep, key_sep, ensure_ascii);
return out;
}
// a state longer than max_state_tokens keeps its head and its tail around a "..." line
std::string server_decision_context::h2o_cut_state(const std::string & text) const {
// a byte-level BPE never has more tokens than bytes
const size_t max_state_tokens = DECISION_H2O_MAX_STATE_TOKENS;
if (text.size() <= max_state_tokens) {
return text;
}
const llama_tokens tokens = common_tokenize(vocab, text, false, true);
if (tokens.size() <= max_state_tokens) {
return text;
}
// each half is the text of its token pieces, a cut inside a character gives U+FFFD as in a JSON response of the server
const size_t half = max_state_tokens / 2;
auto text_of = [&](llama_tokens::const_iterator begin, llama_tokens::const_iterator end) {
std::string out;
for (auto it = begin; it != end; ++it) {
out += common_token_to_piece(vocab, *it, true);
}
return json::parse(json::make(out).dump_safe()).get<std::string>();
};
return text_of(tokens.begin(), tokens.begin() + half) + "\n...\n" + text_of(tokens.end() - half, tokens.end());
}
// the special token texts written in the input are quoted with JSON escapes, so they stay text
std::string server_decision_context::h2o_quote(const std::string & text) const {
std::string out;
for (size_t i = 0; i < text.size();) {
bool is_quoted = false;
if (quoted_first.find(text[i]) == std::string::npos) {
out += text[i++];
continue;
}
for (const auto & spelling : quoted_spellings) {
if (text.compare(i, spelling.size(), spelling) == 0) {
std::string quoted = spelling;
string_replace_all(quoted, "<", "\\u003c");
string_replace_all(quoted, ">", "\\u003e");
out += quoted;
i += spelling.size();
is_quoted = true;
break;
}
}
if (!is_quoted) {
out += text[i++];
}
}
return out;
}
json server_decision_context::prepare_state(const json & state) const {
if (type != COMMON_DECISION_TYPE_H2O_LIGHTNING) {
return state;
}
// done once per request: compact JSON, the cut, the quoting
return h2o_quote(h2o_cut_state(state.is_string() ? state.get<std::string>() : decision_py_dumps(state, -1, ",", ":", false)));
}
json server_decision_context::render_h2o(const json & state, const server_decision_question & question) const {
// the instructions are JSON with an indent of 1, the descriptions are default JSON, the state is from prepare_state()
const std::string instructions = decision_py_lstrip(question.instructions.is_string() ?
question.instructions.get<std::string>() : decision_py_dumps(question.instructions, 1, ",", ": ", true));
json options = json::array();
for (size_t i = 0; i < question.options.size(); i++) {
const auto & opt = question.options[i];
json description; // null if not provided, the template has a default, except a score level that is shown as JSON null
if (question.type == SERVER_DECISION_QUESTION_SCORE && opt.description.is_null()) {
description = "null";
} else if (!opt.description.is_null()) {
description = h2o_quote(opt.description.is_string() ? opt.description.get<std::string>() : decision_py_dumps(opt.description, -1, ", ", ": ", false));
}
const std::string key = h2o_quote(opt.key);
// the user turn is stripped like Python's str.strip(), the template only trims ASCII whitespace
// so the text that ends the turn is stripped here, a space keeps a description that is only whitespace
if (i + 1 == question.options.size()) {
const bool is_key = question.type == SERVER_DECISION_QUESTION_CHOICE && description.is_null();
if (is_key || description.is_string()) {
const std::string text = is_key ? key : description.get<std::string>();
const std::string stripped = decision_py_rstrip(text);
if (stripped != text) {
description = stripped.empty() ? " " : stripped;
}
}
}
json option = json::object();
option["label"] = label_texts[i];
option["key"] = key;
option["description"] = description;
options.push_back(option);
}
json inp = json::object();
inp["type"] = decision_question_type_name(question.type);
inp["state"] = state;
inp["instructions"] = h2o_quote(instructions);
inp["options"] = options;
return inp;
}
// given to the lfm2-d1-omni template: text between the pieces of the prompt, and at the start of the pieces that are cut to a token budget
static const std::string D1OMNI_MARKER = "<<d1omni:";
static const std::string D1OMNI_SEP = "<<d1omni:sep>>";
static const std::string D1OMNI_MARK_STATE = "<<d1omni:state>>";
static const std::string D1OMNI_MARK_QUESTION = "<<d1omni:question>>";
static const std::string D1OMNI_MARK_OPTION = "<<d1omni:option>>";
// max_length, image_text_length and audio_text_length of the model config, the converter checks them
static const size_t D1OMNI_MAX_TOKENS = 16384;
static const size_t D1OMNI_MAX_TOKENS_IMAGE = 896;
static const size_t D1OMNI_MAX_TOKENS_AUDIO = 15360;
size_t server_decision_context::n_variants(const server_decision_question & question) const {
// lev shows the options of a choice in 2 orders, to cancel the preference for the first label
if (type == COMMON_DECISION_TYPE_LEV && question.type == SERVER_DECISION_QUESTION_CHOICE && question.options.size() > 1) {
return 2;
}
return 1;
}
size_t server_decision_context::n_outputs(const server_decision_question & question) const {
if (type == COMMON_DECISION_TYPE_LEV && question.type == SERVER_DECISION_QUESTION_NOUL) {
return DECISION_LEV_N_RATINGS;
}
return question.options.size();
}
// label codes follow prompt.py of the model repo
void server_decision_context::d1_labels(const server_decision_question & question, std::vector<std::string> & texts, std::vector<llama_tokens> & groups) const {
const size_t n_options = question.options.size();
auto get_single_tokens = [&](const std::vector<std::string> & forms) {
llama_tokens out;
for (const auto & form : forms) {
const auto toks = common_tokenize(vocab, form, false, false);
if (toks.size() == 1 && std::find(out.begin(), out.end(), toks[0]) == out.end()) {
out.push_back(toks[0]);
}
}
return out;
};
if (question.type != SERVER_DECISION_QUESTION_CHOICE) {
for (const auto & opt : question.options) {
llama_tokens group;
if (question.type == SERVER_DECISION_QUESTION_SCORE) {
group = get_single_tokens({opt.key});
} else if (opt.key == "true") {
group = get_single_tokens({"yes", "Yes", "YES"});
} else {
group = get_single_tokens({"no", "No", "NO"});
}
if (group.empty()) {
throw std::runtime_error("decision label is not a single token: " + opt.key);
}
texts.push_back(opt.key);
groups.push_back(group);
}
return;
}