-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathllama_webgpu_core.cpp
More file actions
1606 lines (1334 loc) · 37.6 KB
/
llama_webgpu_core.cpp
File metadata and controls
1606 lines (1334 loc) · 37.6 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 <algorithm>
#include <atomic>
#include <cerrno>
#include <cctype>
#include <cmath>
#include <cstdlib>
#include <cstdint>
#include <cstring>
#include <cstdio>
#include <regex>
#include <string>
#include <vector>
#include <unistd.h>
#include <emscripten/emscripten.h>
#include <emscripten/threading.h>
#include <emscripten/wasmfs.h>
#include "ggml-backend.h"
#include "llama.h"
#include "mtmd-helper.h"
#include "mtmd.h"
namespace {
struct runtime_state {
llama_model * model = nullptr;
llama_context * ctx = nullptr;
const llama_vocab * vocab = nullptr;
mtmd_context * mm_ctx = nullptr;
uint32_t n_ctx = 0;
};
runtime_state g_state;
bool g_backend_initialized = false;
bool g_has_webgpu = false;
bool g_generation_active = false;
bool g_cancel_requested = false;
llama_sampler * g_active_sampler = nullptr;
std::atomic<int32_t> g_log_level{3};
std::atomic<int32_t> g_last_non_cont_level{GGML_LOG_LEVEL_NONE};
std::string g_last_error;
std::string g_last_output;
std::string g_last_piece;
std::string g_last_tokens_json = "[]";
std::string g_last_detokenized;
std::string g_last_embedding_json = "[]";
std::string g_backend_json = "[]";
std::string g_model_meta_json = "{}";
bool g_model_uses_gpu_ops = false;
std::vector<llama_token> g_cached_prompt_tokens;
std::vector<mtmd_bitmap *> g_pending_media;
std::string to_lower(std::string value) {
std::transform(
value.begin(),
value.end(),
value.begin(),
[](unsigned char c) { return static_cast<char>(std::tolower(c)); });
return value;
}
std::string escape_json(const std::string & value) {
std::string escaped;
escaped.reserve(value.size() + 8);
for (const char c : value) {
switch (c) {
case '\\':
escaped += "\\\\";
break;
case '"':
escaped += "\\\"";
break;
case '\n':
escaped += "\\n";
break;
case '\r':
escaped += "\\r";
break;
case '\t':
escaped += "\\t";
break;
default:
escaped += c;
break;
}
}
return escaped;
}
void set_error(const std::string & message) {
g_last_error = message;
}
void clear_error() {
g_last_error.clear();
}
void webgpu_log_callback(
ggml_log_level level,
const char * text,
void * user_data) {
(void) user_data;
const int32_t configured = g_log_level.load(std::memory_order_relaxed);
if (configured <= 0 || text == nullptr) {
return;
}
int32_t effective = 0;
if (level == GGML_LOG_LEVEL_CONT) {
effective = g_last_non_cont_level.load(std::memory_order_relaxed);
} else {
effective = static_cast<int32_t>(level);
g_last_non_cont_level.store(effective, std::memory_order_relaxed);
}
if (effective == GGML_LOG_LEVEL_NONE) {
return;
}
if (effective >= configured) {
std::fputs(text, stderr);
std::fflush(stderr);
}
}
void apply_log_level_callback() {
llama_log_set(webgpu_log_callback, nullptr);
ggml_log_set(webgpu_log_callback, nullptr);
}
void clear_pending_media() {
for (mtmd_bitmap * bitmap : g_pending_media) {
if (bitmap != nullptr) {
mtmd_bitmap_free(bitmap);
}
}
g_pending_media.clear();
}
void ensure_backend_initialized() {
if (!g_backend_initialized) {
llama_backend_init();
g_backend_initialized = true;
}
apply_log_level_callback();
}
void end_generation_state() {
if (g_active_sampler != nullptr) {
llama_sampler_free(g_active_sampler);
g_active_sampler = nullptr;
}
g_generation_active = false;
g_last_piece.clear();
g_cancel_requested = false;
}
void free_runtime() {
end_generation_state();
clear_pending_media();
if (g_state.mm_ctx != nullptr) {
mtmd_free(g_state.mm_ctx);
g_state.mm_ctx = nullptr;
}
if (g_state.ctx != nullptr) {
llama_free(g_state.ctx);
g_state.ctx = nullptr;
}
if (g_state.model != nullptr) {
llama_model_free(g_state.model);
g_state.model = nullptr;
}
g_state.vocab = nullptr;
g_state.n_ctx = 0;
g_last_output.clear();
g_last_piece.clear();
g_last_tokens_json = "[]";
g_last_detokenized.clear();
g_last_embedding_json = "[]";
g_model_meta_json = "{}";
g_model_uses_gpu_ops = false;
g_cached_prompt_tokens.clear();
}
std::vector<std::string> collect_backend_labels() {
std::vector<std::string> labels;
const size_t count = ggml_backend_dev_count();
labels.reserve(count);
for (size_t i = 0; i < count; ++i) {
ggml_backend_dev_t dev = ggml_backend_dev_get(i);
if (dev == nullptr) {
continue;
}
const char * dev_name = ggml_backend_dev_name(dev);
if (dev_name == nullptr) {
continue;
}
std::string label = dev_name;
ggml_backend_reg_t reg = ggml_backend_dev_backend_reg(dev);
if (reg != nullptr) {
const char * reg_name = ggml_backend_reg_name(reg);
if (reg_name != nullptr && std::strlen(reg_name) > 0) {
const std::string reg_str = reg_name;
const std::string dev_str = dev_name;
if (to_lower(reg_str) == to_lower(dev_str)) {
label = reg_str;
} else {
label = reg_str + " (" + dev_str + ")";
}
}
}
labels.push_back(label);
}
return labels;
}
void refresh_backend_probe() {
clear_error();
ensure_backend_initialized();
ggml_backend_load_all();
const std::vector<std::string> labels = collect_backend_labels();
std::string json = "[";
for (size_t i = 0; i < labels.size(); ++i) {
if (i > 0) {
json += ",";
}
json += '"';
json += escape_json(labels[i]);
json += '"';
}
json += "]";
g_backend_json = json;
g_has_webgpu = false;
for (const std::string & label : labels) {
const std::string lowered = to_lower(label);
if (lowered.find("webgpu") != std::string::npos ||
lowered.find("wgpu") != std::string::npos) {
g_has_webgpu = true;
break;
}
}
}
std::string read_model_meta_string(
const llama_model * model,
const int32_t index,
const bool read_key) {
size_t buf_size = read_key ? 1024 : 65536;
for (int attempt = 0; attempt < 6; ++attempt) {
std::vector<char> buf(buf_size, '\0');
const int32_t rc = read_key
? llama_model_meta_key_by_index(model, index, buf.data(), buf.size())
: llama_model_meta_val_str_by_index(model, index, buf.data(), buf.size());
if (rc < 0) {
buf_size *= 2;
continue;
}
if (static_cast<size_t>(rc) >= buf_size) {
buf_size = static_cast<size_t>(rc) + 1;
continue;
}
return std::string(buf.data());
}
return "";
}
void rebuild_model_metadata_json() {
if (g_state.model == nullptr) {
g_model_meta_json = "{}";
return;
}
const int32_t count = llama_model_meta_count(g_state.model);
if (count <= 0) {
g_model_meta_json = "{}";
return;
}
std::string json = "{";
bool wrote_any = false;
for (int32_t i = 0; i < count; ++i) {
const std::string key = read_model_meta_string(g_state.model, i, true);
const std::string value = read_model_meta_string(g_state.model, i, false);
if (key.empty()) {
continue;
}
if (wrote_any) {
json += ",";
}
wrote_any = true;
json += '"';
json += escape_json(key);
json += "\":";
json += '"';
json += escape_json(value);
json += '"';
}
json += "}";
g_model_meta_json = json;
}
bool ensure_loaded() {
if (g_state.model == nullptr || g_state.ctx == nullptr || g_state.vocab == nullptr) {
set_error("Model is not loaded");
return false;
}
return true;
}
bool tokenize_text(
const std::string & text,
const bool add_special,
std::vector<llama_token> & out) {
if (!ensure_loaded()) {
return false;
}
int32_t capacity = static_cast<int32_t>(text.size()) + 8;
if (capacity < 32) {
capacity = 32;
}
out.assign(static_cast<size_t>(capacity), 0);
int32_t n_tokens = llama_tokenize(
g_state.vocab,
text.c_str(),
static_cast<int32_t>(text.size()),
out.data(),
static_cast<int32_t>(out.size()),
add_special,
true);
if (n_tokens < 0) {
const int32_t required = -n_tokens;
out.assign(static_cast<size_t>(required), 0);
n_tokens = llama_tokenize(
g_state.vocab,
text.c_str(),
static_cast<int32_t>(text.size()),
out.data(),
static_cast<int32_t>(out.size()),
add_special,
true);
}
if (n_tokens < 0) {
set_error("Prompt tokenization failed");
return false;
}
out.resize(static_cast<size_t>(n_tokens));
return true;
}
bool decode_tokens(const std::vector<llama_token> & tokens) {
if (!ensure_loaded()) {
return false;
}
if (tokens.empty()) {
set_error("Cannot decode empty token sequence");
return false;
}
int32_t max_batch = static_cast<int32_t>(llama_n_batch(g_state.ctx));
if (max_batch <= 0) {
max_batch = 512;
}
for (size_t offset = 0; offset < tokens.size(); offset += static_cast<size_t>(max_batch)) {
const int32_t count = static_cast<int32_t>(
std::min(tokens.size() - offset, static_cast<size_t>(max_batch)));
llama_token * ptr = const_cast<llama_token *>(tokens.data() + offset);
const int rc = llama_decode(g_state.ctx, llama_batch_get_one(ptr, count));
if (rc != 0) {
set_error("llama_decode failed while processing prompt");
return false;
}
}
return true;
}
std::string token_to_piece(const llama_token token, const bool special) {
if (!ensure_loaded()) {
return "";
}
std::vector<char> buf(256, '\0');
int32_t n =
llama_token_to_piece(g_state.vocab, token, buf.data(), buf.size(), 0, special);
if (n < 0) {
buf.assign(static_cast<size_t>(-n) + 8, '\0');
n = llama_token_to_piece(g_state.vocab, token, buf.data(), buf.size(), 0, special);
}
if (n < 0) {
return "";
}
return std::string(buf.data(), static_cast<size_t>(n));
}
bool should_abort_callback(void * /*data*/) {
return g_cancel_requested;
}
std::string serialize_tokens_json(const std::vector<llama_token> & tokens) {
std::string json = "[";
for (size_t i = 0; i < tokens.size(); ++i) {
if (i > 0) {
json += ",";
}
json += std::to_string(tokens[i]);
}
json += "]";
return json;
}
std::string serialize_embedding_json(const std::vector<float> & embedding) {
std::string json = "[";
for (size_t i = 0; i < embedding.size(); ++i) {
if (i > 0) {
json += ",";
}
json += std::to_string(static_cast<double>(embedding[i]));
}
json += "]";
return json;
}
void normalize_embedding_inplace(std::vector<float> & embedding) {
double norm_squared = 0.0;
for (const float value : embedding) {
const double dv = static_cast<double>(value);
norm_squared += dv * dv;
}
if (norm_squared <= 0.0) {
return;
}
const double scale = 1.0 / std::sqrt(norm_squared);
for (float & value : embedding) {
value = static_cast<float>(static_cast<double>(value) * scale);
}
}
void parse_token_list(const char * token_text, std::vector<llama_token> & out_tokens) {
out_tokens.clear();
if (token_text == nullptr) {
return;
}
const char * p = token_text;
while (*p != '\0') {
while (*p != '\0' &&
!std::isdigit(static_cast<unsigned char>(*p)) &&
*p != '-' &&
*p != '+') {
++p;
}
if (*p == '\0') {
break;
}
char * end = nullptr;
const long value = std::strtol(p, &end, 10);
if (end == p) {
++p;
continue;
}
out_tokens.push_back(static_cast<llama_token>(value));
p = end;
}
}
void replace_all_inplace(
std::string & text,
const std::string & from,
const std::string & to) {
if (from.empty()) {
return;
}
size_t start = 0;
while (true) {
const size_t pos = text.find(from, start);
if (pos == std::string::npos) {
break;
}
text.replace(pos, from.size(), to);
start = pos + to.size();
}
}
size_t count_occurrences(const std::string & text, const std::string & pattern) {
if (pattern.empty()) {
return 0;
}
size_t count = 0;
size_t start = 0;
while (true) {
const size_t pos = text.find(pattern, start);
if (pos == std::string::npos) {
break;
}
++count;
start = pos + pattern.size();
}
return count;
}
std::string normalize_media_markers(const std::string & prompt, const size_t media_count) {
const char * marker_ptr = mtmd_default_marker();
const std::string marker = marker_ptr == nullptr
? std::string("<__media__>")
: std::string(marker_ptr);
std::string normalized = prompt;
replace_all_inplace(normalized, "<image>", marker);
replace_all_inplace(normalized, "[IMG]", marker);
replace_all_inplace(normalized, "<|image|>", marker);
replace_all_inplace(normalized, "<img>", marker);
replace_all_inplace(normalized, "<|img|>", marker);
replace_all_inplace(
normalized,
"<|vision_start|><|image_pad|><|vision_end|>",
marker);
replace_all_inplace(
normalized,
"<|vision_start|><|video_pad|><|vision_end|>",
marker);
replace_all_inplace(normalized, "<audio>", marker);
replace_all_inplace(normalized, "<|audio|>", marker);
normalized = std::regex_replace(normalized, std::regex("<\\|image_\\d+\\|>"), marker);
normalized = std::regex_replace(normalized, std::regex("<\\|audio_\\d+\\|>"), marker);
if (media_count == 0) {
return normalized;
}
const size_t marker_count = count_occurrences(normalized, marker);
if (marker_count >= media_count) {
return normalized;
}
const size_t missing = media_count - marker_count;
std::string marker_block;
for (size_t i = 0; i < missing; ++i) {
if (!marker_block.empty()) {
marker_block += ' ';
}
marker_block += marker;
}
const size_t user_cap_pos = normalized.find("User:");
if (user_cap_pos != std::string::npos) {
normalized.replace(user_cap_pos, 5, "User: " + marker_block + " ");
return normalized;
}
const size_t user_pos = normalized.find("user:");
if (user_pos != std::string::npos) {
normalized.replace(user_pos, 5, "user: " + marker_block + " ");
return normalized;
}
return marker_block + "\n" + normalized;
}
bool decode_multimodal_prompt(const std::string & prompt) {
if (g_state.mm_ctx == nullptr) {
set_error(
"Multimodal projector is not loaded. Call loadMultimodalProjector first.");
clear_pending_media();
return false;
}
mtmd_input_chunks * chunks = mtmd_input_chunks_init();
if (chunks == nullptr) {
set_error("Failed to allocate multimodal input chunks");
clear_pending_media();
return false;
}
const std::string normalized_prompt =
normalize_media_markers(prompt, g_pending_media.size());
mtmd_input_text input_text {};
input_text.text = normalized_prompt.c_str();
const llama_token bos = llama_vocab_bos(g_state.vocab);
const llama_token eos = llama_vocab_eos(g_state.vocab);
input_text.add_special = bos != eos && bos != -1;
input_text.parse_special = true;
std::vector<const mtmd_bitmap *> bitmaps;
bitmaps.reserve(g_pending_media.size());
for (const mtmd_bitmap * bitmap : g_pending_media) {
bitmaps.push_back(bitmap);
}
const int32_t tokenize_rc = mtmd_tokenize(
g_state.mm_ctx,
chunks,
&input_text,
bitmaps.data(),
bitmaps.size());
if (tokenize_rc != 0) {
if (tokenize_rc == 1) {
set_error(
"Multimodal marker count does not match number of provided media parts");
} else if (tokenize_rc == 2) {
set_error("Failed to preprocess multimodal media content");
} else {
set_error("mtmd_tokenize failed while processing multimodal prompt");
}
mtmd_input_chunks_free(chunks);
clear_pending_media();
return false;
}
llama_pos new_n_past = 0;
int32_t n_batch = static_cast<int32_t>(llama_n_batch(g_state.ctx));
if (n_batch <= 0) {
n_batch = 512;
}
const int32_t eval_rc = mtmd_helper_eval_chunks(
g_state.mm_ctx,
g_state.ctx,
chunks,
0,
0,
n_batch,
true,
&new_n_past);
mtmd_input_chunks_free(chunks);
clear_pending_media();
if (eval_rc != 0) {
set_error("mtmd_helper_eval_chunks failed while ingesting multimodal prompt");
return false;
}
return true;
}
llama_sampler * create_sampler(
const float temp,
const int32_t top_k,
const float top_p,
const float repeat_penalty,
const char * grammar,
const uint32_t seed) {
llama_sampler_chain_params sparams = llama_sampler_chain_default_params();
llama_sampler * sampler = llama_sampler_chain_init(sparams);
if (sampler == nullptr) {
return nullptr;
}
if (repeat_penalty != 1.0f) {
llama_sampler_chain_add(
sampler,
llama_sampler_init_penalties(64, repeat_penalty, 0.0f, 0.0f));
}
if (top_k > 0) {
llama_sampler_chain_add(sampler, llama_sampler_init_top_k(top_k));
}
if (top_p < 1.0f) {
llama_sampler_chain_add(sampler, llama_sampler_init_top_p(top_p, 1));
}
if (grammar != nullptr && std::strlen(grammar) > 0) {
llama_sampler * grammar_sampler =
llama_sampler_init_grammar(g_state.vocab, grammar, "root");
if (grammar_sampler == nullptr) {
llama_sampler_free(sampler);
return nullptr;
}
llama_sampler_chain_add(sampler, grammar_sampler);
}
llama_sampler_chain_add(sampler, llama_sampler_init_temp(temp));
llama_sampler_chain_add(sampler, llama_sampler_init_dist(seed));
return sampler;
}
int32_t begin_generation_impl(
const char * prompt,
float temp,
int32_t top_k,
float top_p,
float repeat_penalty,
const char * grammar,
uint32_t seed) {
clear_error();
g_last_output.clear();
g_last_piece.clear();
if (!ensure_loaded()) {
return -1;
}
if (prompt == nullptr) {
set_error("Prompt is null");
return -2;
}
if (temp < 0.0f) {
temp = 0.0f;
}
if (top_k < 0) {
top_k = 0;
}
if (top_p <= 0.0f || top_p > 1.0f) {
top_p = 1.0f;
}
if (repeat_penalty <= 0.0f) {
repeat_penalty = 1.0f;
}
end_generation_state();
g_cancel_requested = false;
const std::string prompt_text = prompt;
if (!g_pending_media.empty()) {
llama_memory_clear(llama_get_memory(g_state.ctx), false);
g_cached_prompt_tokens.clear();
if (!decode_multimodal_prompt(prompt_text)) {
return -3;
}
} else {
std::vector<llama_token> prompt_tokens;
if (!tokenize_text(prompt_text, true, prompt_tokens)) {
return -3;
}
size_t prefix = 0;
const size_t max_prefix =
std::min(g_cached_prompt_tokens.size(), prompt_tokens.size());
while (prefix < max_prefix &&
g_cached_prompt_tokens[prefix] == prompt_tokens[prefix]) {
prefix++;
}
if (prefix == prompt_tokens.size() && prefix > 0) {
prefix--;
}
if (prefix == 0) {
llama_memory_clear(llama_get_memory(g_state.ctx), false);
} else {
const bool removed = llama_memory_seq_rm(
llama_get_memory(g_state.ctx),
0,
static_cast<llama_pos>(prefix),
-1);
if (!removed) {
prefix = 0;
llama_memory_clear(llama_get_memory(g_state.ctx), false);
}
}
if (prefix < prompt_tokens.size()) {
std::vector<llama_token> eval_tokens(
prompt_tokens.begin() + prefix,
prompt_tokens.end());
if (!decode_tokens(eval_tokens)) {
g_cached_prompt_tokens.clear();
return -4;
}
}
g_cached_prompt_tokens = prompt_tokens;
}
g_active_sampler =
create_sampler(temp, top_k, top_p, repeat_penalty, grammar, seed);
if (g_active_sampler == nullptr) {
if (grammar != nullptr && std::strlen(grammar) > 0) {
set_error("Failed to initialize sampler chain (invalid grammar)");
} else {
set_error("Failed to initialize sampler chain");
}
return -5;
}
g_generation_active = true;
return 0;
}
int32_t next_token_impl() {
clear_error();
if (!ensure_loaded()) {
return -1;
}
if (!g_generation_active || g_active_sampler == nullptr) {
set_error("Generation is not active");
return -2;
}
if (g_cancel_requested) {
end_generation_state();
return 0;
}
const llama_token token = llama_sampler_sample(g_active_sampler, g_state.ctx, -1);
if (token == LLAMA_TOKEN_NULL) {
set_error("Sampler returned LLAMA_TOKEN_NULL");
end_generation_state();
return -3;
}
if (llama_vocab_is_eog(g_state.vocab, token)) {
end_generation_state();
return 0;
}
if (llama_vocab_is_control(g_state.vocab, token)) {
end_generation_state();
return 0;
}
g_last_piece = token_to_piece(token, false);
g_last_output += g_last_piece;
llama_token token_for_decode = token;
const int rc = llama_decode(g_state.ctx, llama_batch_get_one(&token_for_decode, 1));
if (rc != 0) {
if (g_cancel_requested) {
end_generation_state();
return 0;
}
set_error("llama_decode failed while generating tokens");
end_generation_state();
return -4;
}
return 1;
}
int32_t load_model_internal(
const char * model_path,
int32_t n_ctx,
int32_t n_threads,
int32_t n_threads_batch,
int32_t n_batch,
int32_t n_ubatch,
int32_t n_gpu_layers,
bool use_mmap) {
llama_model_params mparams = llama_model_default_params();
mparams.n_gpu_layers = n_gpu_layers;
mparams.use_mmap = use_mmap;
mparams.use_mlock = false;
mparams.vocab_only = false;
g_state.model = llama_model_load_from_file(model_path, mparams);
if (g_state.model == nullptr) {
set_error("llama_model_load_from_file failed");
return -2;
}
llama_context_params cparams = llama_context_default_params();
if (n_ctx > 0) {
cparams.n_ctx = static_cast<uint32_t>(n_ctx);
}
if (n_threads > 0) {
cparams.n_threads = n_threads;
}
if (n_threads_batch > 0) {
cparams.n_threads_batch = n_threads_batch;
} else if (n_threads > 0) {
cparams.n_threads_batch = n_threads;
}
if (n_batch > 0) {
cparams.n_batch = static_cast<uint32_t>(n_batch);
}
if (n_ubatch > 0) {
cparams.n_ubatch = static_cast<uint32_t>(n_ubatch);
}
if (cparams.n_batch == 0 || cparams.n_batch > cparams.n_ctx) {
cparams.n_batch = std::min<uint32_t>(cparams.n_ctx, 1024U);
}
if (cparams.n_ubatch == 0 || cparams.n_ubatch > cparams.n_batch) {
cparams.n_ubatch = std::min<uint32_t>(cparams.n_batch, 512U);
}
const bool enable_gpu_ops = n_gpu_layers > 0;
g_model_uses_gpu_ops = enable_gpu_ops;
cparams.offload_kqv = enable_gpu_ops;
cparams.op_offload = enable_gpu_ops;
cparams.no_perf = true;
g_state.ctx = llama_init_from_model(g_state.model, cparams);
if (g_state.ctx == nullptr) {
set_error("llama_init_from_model failed");
free_runtime();
return -3;
}
g_state.vocab = llama_model_get_vocab(g_state.model);
g_state.n_ctx = llama_n_ctx(g_state.ctx);
llama_set_abort_callback(g_state.ctx, should_abort_callback, nullptr);
rebuild_model_metadata_json();
return 0;
}
} // namespace
extern "C" {
EMSCRIPTEN_KEEPALIVE int32_t llamadart_webgpu_probe() {
refresh_backend_probe();
return g_has_webgpu ? 1 : 0;
}
EMSCRIPTEN_KEEPALIVE int32_t llamadart_webgpu_supports_pthreads() {
#if defined(__EMSCRIPTEN_PTHREADS__)
return 1;
#else
return 0;
#endif
}
EMSCRIPTEN_KEEPALIVE const char * llamadart_webgpu_backends_json() {
refresh_backend_probe();
return g_backend_json.c_str();
}
EMSCRIPTEN_KEEPALIVE const char * llamadart_webgpu_last_error() {
return g_last_error.c_str();
}
EMSCRIPTEN_KEEPALIVE void llamadart_webgpu_set_log_level(int32_t level) {
if (level < 0) {
level = 0;
} else if (level > 4) {
level = 4;
}