forked from go-skynet/go-llama.cpp
-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathwrapper.cpp
More file actions
1538 lines (1282 loc) · 57.8 KB
/
wrapper.cpp
File metadata and controls
1538 lines (1282 loc) · 57.8 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 "wrapper.h"
#include "llama.cpp/include/llama.h"
#include "llama.cpp/ggml/include/ggml.h"
#include "llama.cpp/common/common.h"
#include "llama.cpp/common/sampling.h"
#include "llama.cpp/common/speculative.h"
#include "llama.cpp/common/chat.h"
// Use angle-bracket form so this resolves via -I paths in both modes:
// dev (-I./llama.cpp/vendor → submodule) and consumer
// (-I./cgo_headers/llama.cpp/thirdparty → vendored copy). The vendored copy
// can't live under a directory named "vendor" because Go's module zip excludes
// any nested vendor/ subtree.
#include <nlohmann/json.hpp>
#include <string>
#include <vector>
#include <memory>
#include <cstring>
// CUDA backend header for GPU info
#ifdef GGML_USE_CUDA
#include "llama.cpp/ggml/include/ggml-cuda.h"
#endif
// Global error handling
static std::string g_last_error;
// Global log level control
static ggml_log_level g_min_log_level = GGML_LOG_LEVEL_INFO;
// Log callback that respects LLAMA_LOG environment variable
static void llama_log_callback(ggml_log_level level, const char * text, void * /*user_data*/) {
if (level >= g_min_log_level) {
fprintf(stderr, "%s", text);
}
}
extern "C" {
// Initialise logging based on LLAMA_LOG environment variable
// Supported values: none, debug, info (default), warn, error
void llama_wrapper_init_logging() {
const char* log_level = std::getenv("LLAMA_LOG");
if (log_level != nullptr) {
std::string level_str(log_level);
if (level_str == "none") {
g_min_log_level = GGML_LOG_LEVEL_NONE;
} else if (level_str == "debug") {
g_min_log_level = GGML_LOG_LEVEL_DEBUG;
} else if (level_str == "info") {
g_min_log_level = GGML_LOG_LEVEL_INFO;
} else if (level_str == "warn") {
g_min_log_level = GGML_LOG_LEVEL_WARN;
} else if (level_str == "error") {
g_min_log_level = GGML_LOG_LEVEL_ERROR;
}
}
llama_log_set(llama_log_callback, nullptr);
}
// Forward declarations of Go callback functions
extern bool goTokenCallback(uintptr_t handle, const char* token);
extern bool goProgressCallback(float progress, void* user_data);
// Separate wrappers for model and context
struct llama_wrapper_model_t {
llama_model* model;
int n_gpu_layers; // Number of GPU layers requested (for stats reporting)
};
struct llama_wrapper_context_t {
llama_context* ctx;
llama_model* model; // Reference to parent model
std::vector<int> cached_tokens; // Cache for prefix matching optimisation
};
const char* llama_wrapper_last_error() {
return g_last_error.c_str();
}
void llama_wrapper_free_result(char* result) {
if (result) {
free(result);
}
}
// Static no-op callback for silent loading
static bool silent_progress_callback(float progress, void* user_data) {
(void)progress;
(void)user_data;
return true; // Continue loading
}
// Convert our params to llama.cpp model params
static struct llama_model_params convert_model_params(llama_wrapper_model_params params) {
struct llama_model_params model_params = llama_model_default_params();
// Only set n_gpu_layers if not -1 (which means "use default/all layers")
// llama.cpp default is 999 which effectively means all layers
if (params.n_gpu_layers != -1) {
model_params.n_gpu_layers = params.n_gpu_layers;
}
model_params.main_gpu = params.main_gpu ? atoi(params.main_gpu) : 0;
model_params.use_mmap = params.mmap;
model_params.use_mlock = params.mlock;
model_params.no_host = false; // Use host buffers (b6709 added field)
// Configure progress callback
if (params.disable_progress_callback) {
model_params.progress_callback = silent_progress_callback;
model_params.progress_callback_user_data = nullptr;
} else if (params.progress_callback) {
model_params.progress_callback = params.progress_callback;
model_params.progress_callback_user_data = params.progress_callback_user_data;
}
// Otherwise NULL → llama.cpp installs default dot printer
return model_params;
}
// Convert our params to llama.cpp context params
static struct llama_context_params convert_context_params(llama_wrapper_model_params params) {
struct llama_context_params ctx_params = llama_context_default_params();
ctx_params.n_ctx = params.n_ctx > 0 ? params.n_ctx : 2048;
ctx_params.n_batch = params.n_batch > 0 ? params.n_batch : 512;
// n_ubatch: 0 means match n_batch. Encoder-only models (nomic, BERT) require
// n_ubatch >= longest sequence length, since the whole input must fit in one
// forward pass.
ctx_params.n_ubatch = params.n_ubatch > 0 ? params.n_ubatch : ctx_params.n_batch;
ctx_params.n_threads = params.n_threads > 0 ? params.n_threads : 4;
ctx_params.n_threads_batch = params.n_threads_batch > 0 ? params.n_threads_batch : ctx_params.n_threads;
ctx_params.n_seq_max = params.n_parallel > 0 ? params.n_parallel : 1;
ctx_params.embeddings = params.embeddings;
// Set KV cache quantization type
if (params.kv_cache_type != nullptr) {
std::string cache_type(params.kv_cache_type);
if (cache_type == "f16") {
ctx_params.type_k = GGML_TYPE_F16;
ctx_params.type_v = GGML_TYPE_F16;
} else if (cache_type == "q8_0") {
ctx_params.type_k = GGML_TYPE_Q8_0;
ctx_params.type_v = GGML_TYPE_Q8_0;
} else if (cache_type == "q4_0") {
ctx_params.type_k = GGML_TYPE_Q4_0;
ctx_params.type_v = GGML_TYPE_Q4_0;
}
// If unrecognized, leave as default (f16)
}
// Set Flash Attention mode
if (params.flash_attn != nullptr) {
std::string fa_mode(params.flash_attn);
if (fa_mode == "enabled") {
ctx_params.flash_attn_type = LLAMA_FLASH_ATTN_TYPE_ENABLED;
} else if (fa_mode == "disabled") {
ctx_params.flash_attn_type = LLAMA_FLASH_ATTN_TYPE_DISABLED;
} else if (fa_mode == "auto") {
ctx_params.flash_attn_type = LLAMA_FLASH_ATTN_TYPE_AUTO;
}
// If unrecognized, leave as default (auto)
}
return ctx_params;
}
void* llama_wrapper_model_load(const char* model_path, llama_wrapper_model_params params) {
if (!model_path) {
g_last_error = "Model path cannot be null";
return nullptr;
}
try {
// Initialize llama backend
llama_backend_init();
// Load model (weights only)
auto model_params = convert_model_params(params);
llama_model* model = llama_model_load_from_file(model_path, model_params);
if (!model) {
g_last_error = "Failed to load model from: " + std::string(model_path);
return nullptr;
}
// Create wrapper (model only, no context)
auto wrapper = new llama_wrapper_model_t();
wrapper->model = model;
// Store n_gpu_layers for stats reporting
// If -1 was passed (meaning "use default"), llama.cpp uses 999 layers
wrapper->n_gpu_layers = (params.n_gpu_layers == -1) ? 999 : params.n_gpu_layers;
return wrapper;
} catch (const std::exception& e) {
g_last_error = "Exception loading model: " + std::string(e.what());
return nullptr;
}
}
void llama_wrapper_model_free(void* model) {
if (!model) return;
auto wrapper = static_cast<llama_wrapper_model_t*>(model);
if (wrapper->model) {
llama_model_free(wrapper->model);
wrapper->model = nullptr; // Prevent double-free
}
delete wrapper;
}
void* llama_wrapper_context_create(void* model, llama_wrapper_model_params params) {
if (!model) {
g_last_error = "Model cannot be null";
return nullptr;
}
try {
auto model_wrapper = static_cast<llama_wrapper_model_t*>(model);
// Create context from model
auto ctx_params = convert_context_params(params);
llama_context* ctx = llama_init_from_model(model_wrapper->model, ctx_params);
if (!ctx) {
g_last_error = "Failed to create context";
return nullptr;
}
// Create context wrapper
auto ctx_wrapper = new llama_wrapper_context_t();
ctx_wrapper->ctx = ctx;
ctx_wrapper->model = model_wrapper->model; // Keep reference to parent model
return ctx_wrapper;
} catch (const std::exception& e) {
g_last_error = "Exception creating context: " + std::string(e.what());
return nullptr;
}
}
void llama_wrapper_context_free(void* ctx) {
if (!ctx) return;
auto wrapper = static_cast<llama_wrapper_context_t*>(ctx);
if (wrapper->ctx) {
llama_free(wrapper->ctx);
wrapper->ctx = nullptr; // Prevent double-free
}
delete wrapper;
}
// Get model's native maximum context length from GGUF metadata
int llama_wrapper_get_model_context_length(void* model) {
if (!model) {
return 32768; // Fallback if model is null
}
auto model_wrapper = static_cast<llama_wrapper_model_t*>(model);
// Query model's native context length from GGUF metadata
int n_ctx_train = llama_model_n_ctx_train(model_wrapper->model);
// Return model's training context, or reasonable fallback
return (n_ctx_train > 0) ? n_ctx_train : 32768;
}
// Get model's embedding dimension
int llama_wrapper_model_n_embd(void* model) {
if (!model) {
return -1; // Error if model is null
}
auto model_wrapper = static_cast<llama_wrapper_model_t*>(model);
return llama_model_n_embd(model_wrapper->model);
}
// Helper function to find common prefix length between two token vectors
static int findCommonPrefix(const std::vector<int>& a, const std::vector<int>& b) {
int commonLen = 0;
size_t minLen = std::min(a.size(), b.size());
for (size_t i = 0; i < minLen; i++) {
if (a[i] != b[i]) {
break;
}
commonLen++;
}
return commonLen;
}
char* llama_wrapper_generate_with_tokens(void* ctx, const int* tokens, int n_tokens, int prefix_len, llama_wrapper_generate_params params) {
if (!ctx || !tokens) {
g_last_error = "Context and tokens cannot be null";
return nullptr;
}
auto wrapper = static_cast<llama_wrapper_context_t*>(ctx);
if (!wrapper->ctx) {
g_last_error = "Context has been freed";
return nullptr;
}
try {
// Convert C tokens to vector
std::vector<llama_token> prompt_tokens(tokens, tokens + n_tokens);
if (prompt_tokens.empty()) {
g_last_error = "Token array is empty";
return nullptr;
}
// Check context size with safety margin BEFORE manipulating KV cache
int available_ctx = llama_n_ctx(wrapper->ctx);
if (available_ctx <= 0) {
g_last_error = "Invalid context size";
return nullptr;
}
// Check if prompt fits with room for at least a few generated tokens
int tokens_needed = (int)prompt_tokens.size() + params.max_tokens;
if (tokens_needed > available_ctx) {
char err_msg[256];
snprintf(err_msg, sizeof(err_msg),
"Prompt too long for context size: need %d tokens (%d prompt + %d generation) but context is only %d tokens",
tokens_needed, (int)prompt_tokens.size(), params.max_tokens > 0 ? params.max_tokens : 128, available_ctx);
g_last_error = err_msg;
return nullptr;
}
if ((int)prompt_tokens.size() >= available_ctx - 1) {
g_last_error = "Prompt too long for context size (need at least 1 token for generation)";
return nullptr;
}
// Clear KV cache from divergence point onwards
// For full cache hits, we'll refresh the last prompt token, so clear from prefix_len - 1
// For partial matches, clear from prefix_len as usual
int clear_from = (prefix_len == n_tokens && n_tokens > 0) ? prefix_len - 1 : prefix_len;
// Only clear if clear_from is valid and within context bounds
if (clear_from >= 0 && clear_from < available_ctx) {
llama_memory_seq_rm(llama_get_memory(wrapper->ctx), 0, clear_from, -1);
}
// Create sampling parameters - use the struct directly instead of calling a function
common_params_sampling sampling_params;
// Basic sampling
sampling_params.seed = params.seed;
sampling_params.temp = params.temperature;
sampling_params.top_k = params.top_k;
sampling_params.top_p = params.top_p;
sampling_params.min_p = params.min_p;
sampling_params.typ_p = params.typ_p;
sampling_params.top_n_sigma = params.top_n_sigma;
sampling_params.min_keep = params.min_keep;
// Repetition penalties
sampling_params.penalty_last_n = params.penalty_last_n;
sampling_params.penalty_repeat = params.penalty_repeat;
sampling_params.penalty_freq = params.penalty_freq;
sampling_params.penalty_present = params.penalty_present;
// DRY sampling
sampling_params.dry_multiplier = params.dry_multiplier;
sampling_params.dry_base = params.dry_base;
sampling_params.dry_allowed_length = params.dry_allowed_length;
sampling_params.dry_penalty_last_n = params.dry_penalty_last_n;
// Convert dry_sequence_breakers from C array to std::vector
sampling_params.dry_sequence_breakers.clear();
for (int i = 0; i < params.dry_sequence_breakers_count; i++) {
sampling_params.dry_sequence_breakers.push_back(std::string(params.dry_sequence_breakers[i]));
}
// Dynamic temperature
sampling_params.dynatemp_range = params.dynatemp_range;
sampling_params.dynatemp_exponent = params.dynatemp_exponent;
// XTC sampling
sampling_params.xtc_probability = params.xtc_probability;
sampling_params.xtc_threshold = params.xtc_threshold;
// Mirostat sampling
sampling_params.mirostat = params.mirostat;
sampling_params.mirostat_tau = params.mirostat_tau;
sampling_params.mirostat_eta = params.mirostat_eta;
// Other parameters
sampling_params.n_prev = params.n_prev;
sampling_params.n_probs = params.n_probs;
sampling_params.ignore_eos = params.ignore_eos;
// Initialise sampler
common_sampler* sampler = common_sampler_init(wrapper->model, sampling_params);
if (!sampler) {
g_last_error = "Failed to initialise sampler";
return nullptr;
}
// Validate generation parameters
// Reject negative max_tokens (0 is allowed and means "use default")
if (params.max_tokens < 0) {
common_sampler_free(sampler);
g_last_error = "Invalid max_tokens value (must be >= 0)";
return nullptr;
}
int n_predict = params.max_tokens > 0 ? params.max_tokens : 128;
// After clearing cache from prefix_len onwards, cache ends at prefix_len - 1
// Next position to use is prefix_len
int n_past = prefix_len;
// Process prompt tokens from prefix_len onwards using explicit positions
if (prefix_len < n_tokens) {
int tokens_to_process = n_tokens - prefix_len;
int n_batch = llama_n_batch(wrapper->ctx);
// Process tokens in chunks that respect n_batch limit
for (int chunk_start = 0; chunk_start < tokens_to_process; chunk_start += n_batch) {
int chunk_size = std::min(n_batch, tokens_to_process - chunk_start);
llama_batch batch = llama_batch_init(chunk_size, 0, 1);
common_batch_clear(batch);
// Add tokens for this chunk with explicit positions
for (int i = 0; i < chunk_size; i++) {
int token_idx = prefix_len + chunk_start + i;
int position = prefix_len + chunk_start + i;
// Only the very last token of the entire prompt needs logits
bool needs_logits = (chunk_start + i == tokens_to_process - 1);
common_batch_add(batch, prompt_tokens[token_idx], position, { 0 }, needs_logits);
}
if (llama_decode(wrapper->ctx, batch) != 0) {
if (params.debug) {
fprintf(stderr, "WARNING: prompt decode failed for chunk starting at %d\n", chunk_start);
}
llama_batch_free(batch);
common_sampler_free(sampler);
g_last_error = "Failed to decode prompt";
return nullptr;
}
llama_batch_free(batch);
}
n_past = n_tokens; // Position now at end of prompt
} else if (prefix_len == n_tokens && n_tokens > 0) {
// Full cache hit - refresh last token's logits to ensure determinism
// This is critical: without this, we sample from stale logits from the previous generation
// The last prompt token is at position n_tokens - 1 (0-indexed positions)
llama_batch batch = llama_batch_init(512, 0, 1);
common_batch_clear(batch);
common_batch_add(batch, prompt_tokens[n_tokens - 1], n_tokens - 1, { 0 }, true);
if (llama_decode(wrapper->ctx, batch) != 0) {
if (params.debug) {
fprintf(stderr, "WARNING: logit refresh failed\n");
}
llama_batch_free(batch);
common_sampler_free(sampler);
g_last_error = "Failed to refresh logits for cached prompt";
return nullptr;
}
llama_batch_free(batch);
n_past = n_tokens; // Set position to end of prompt for generation
}
// If n_tokens == 0, nothing to decode
// Generation loop - follows simple.cpp pattern
std::string result;
int n_decode = 0;
if (params.debug) {
fprintf(stderr, "DEBUG: Starting generation loop, n_predict=%d, n_past=%d\n", n_predict, n_past);
}
// Main generation loop - decode first, then sample
for (int n_gen = 0; n_gen < n_predict; n_gen++) {
if (params.debug && n_gen == 0) {
fprintf(stderr, "DEBUG: First iteration, about to sample\n");
}
// Sample the next token (using logits from previous decode or prompt)
llama_token new_token_id = common_sampler_sample(sampler, wrapper->ctx, -1);
if (params.debug && n_gen == 0) {
fprintf(stderr, "DEBUG: Sampled token: %d\n", new_token_id);
}
// Check for EOS
if (llama_vocab_is_eog(llama_model_get_vocab(wrapper->model), new_token_id)) {
if (params.debug) {
fprintf(stderr, "INFO: End of generation token encountered\n");
}
break;
}
if (params.debug && n_gen == 0) {
fprintf(stderr, "DEBUG: About to convert token to text\n");
}
// Convert token to text
std::string token_str = common_token_to_piece(wrapper->ctx, new_token_id);
if (params.debug && n_gen == 0) {
fprintf(stderr, "DEBUG: Token text: '%s'\n", token_str.c_str());
}
// Call callback if provided
if (params.callback_handle != 0) {
if (!goTokenCallback(params.callback_handle, token_str.c_str())) {
if (params.debug) {
fprintf(stderr, "INFO: Generation stopped by callback\n");
}
break;
}
}
result += token_str;
// Check stop words
for (int j = 0; j < params.stop_words_count; j++) {
if (result.find(params.stop_words[j]) != std::string::npos) {
if (params.debug) {
fprintf(stderr, "INFO: Stop word found, ending generation\n");
}
goto generation_done;
}
}
if (params.debug && n_gen == 0) {
// Query actual cache state before decode
int cache_pos = llama_memory_seq_pos_max(llama_get_memory(wrapper->ctx), 0);
fprintf(stderr, "DEBUG: About to decode token, n_past=%d, cache_pos_max=%d\n", n_past, cache_pos);
}
// Decode the sampled token to get logits for next iteration
// Allocate enough space for the batch (minimum 512 tokens as per llama.cpp examples)
llama_batch gen_batch = llama_batch_init(512, 0, 1);
common_batch_clear(gen_batch);
common_batch_add(gen_batch, new_token_id, n_past, { 0 }, true);
if (params.debug && n_gen == 0) {
fprintf(stderr, "DEBUG: Batch token=%d, pos=%d, n_tokens=%d\n", new_token_id, n_past, gen_batch.n_tokens);
}
// Increment position for next iteration
n_past++;
if (params.debug && n_gen == 0) {
fprintf(stderr, "DEBUG: Batch prepared, calling llama_decode\n");
}
if (llama_decode(wrapper->ctx, gen_batch) != 0) {
if (params.debug) {
fprintf(stderr, "WARNING: decode failed, stopping generation\n");
}
llama_batch_free(gen_batch);
break;
}
if (params.debug && n_gen == 0) {
fprintf(stderr, "DEBUG: Decode succeeded, freeing batch\n");
}
llama_batch_free(gen_batch);
n_decode += 1;
if (params.debug && n_gen == 0) {
fprintf(stderr, "DEBUG: First iteration complete\n");
}
}
generation_done:
common_sampler_free(sampler);
// Return allocated string (caller must free)
char* c_result = (char*)malloc(result.length() + 1);
if (c_result) {
memcpy(c_result, result.c_str(), result.length());
c_result[result.length()] = '\0';
} else {
g_last_error = "Failed to allocate memory for result";
}
return c_result;
} catch (const std::exception& e) {
g_last_error = "Exception during generation: " + std::string(e.what());
return nullptr;
}
}
// Simple wrapper that tokenises the prompt and handles prefix caching automatically
char* llama_wrapper_generate(void* ctx, llama_wrapper_generate_params params) {
if (!ctx) {
g_last_error = "Context cannot be null";
return nullptr;
}
auto wrapper = static_cast<llama_wrapper_context_t*>(ctx);
if (!wrapper->ctx) {
g_last_error = "Context has been freed";
return nullptr;
}
try {
// Tokenise the prompt
std::vector<llama_token> prompt_tokens = common_tokenize(wrapper->ctx, params.prompt, true, true);
if (prompt_tokens.empty()) {
g_last_error = "Failed to tokenize prompt";
return nullptr;
}
// Convert to int vector for comparison
std::vector<int> tokens_int(prompt_tokens.begin(), prompt_tokens.end());
// Find common prefix with cached tokens (only if prefix caching enabled)
int prefix_len = params.enable_prefix_caching
? findCommonPrefix(wrapper->cached_tokens, tokens_int)
: 0;
// Update cache to new token sequence (only if prefix caching enabled)
if (params.enable_prefix_caching) {
wrapper->cached_tokens = tokens_int;
} else {
wrapper->cached_tokens.clear(); // Ensure cache is empty when disabled
}
// Call token-based generation with prefix caching
return llama_wrapper_generate_with_tokens(ctx, tokens_int.data(), tokens_int.size(), prefix_len, params);
} catch (const std::exception& e) {
g_last_error = "Exception during generation: " + std::string(e.what());
return nullptr;
}
}
char* llama_wrapper_generate_draft_with_tokens(void* ctx_target, void* ctx_draft, const int* tokens, int n_tokens, int target_prefix_len, int draft_prefix_len, llama_wrapper_generate_params params) {
if (!ctx_target || !ctx_draft || !tokens) {
g_last_error = "Target, draft contexts and tokens cannot be null";
return nullptr;
}
auto wrapper_tgt = static_cast<llama_wrapper_context_t*>(ctx_target);
auto wrapper_dft = static_cast<llama_wrapper_context_t*>(ctx_draft);
if (!wrapper_tgt->ctx) {
g_last_error = "Target context has been freed";
return nullptr;
}
if (!wrapper_dft->ctx) {
g_last_error = "Draft context has been freed";
return nullptr;
}
try {
// Clear target KV cache from divergence point
// Sequence ID 0 is the default sequence for single-sequence inference
// For speculative generation with full cache hits, we need to refresh the second-to-last token
// (since we decode all but last token), so clear from that position
int target_clear_from = (target_prefix_len == n_tokens && n_tokens > 1) ? n_tokens - 2 : target_prefix_len;
llama_memory_seq_rm(llama_get_memory(wrapper_tgt->ctx), 0, target_clear_from, -1);
// Note: draft KV cache is managed internally by common_speculative (b8635+)
// Convert C tokens to vector
std::vector<llama_token> prompt_tokens(tokens, tokens + n_tokens);
if (prompt_tokens.empty()) {
g_last_error = "Token array is empty";
return nullptr;
}
// Set up speculative parameters.
// b9002+: common_params_speculative uses a nested draft substructure
// (params.draft.* instead of the flat fields used pre-b9002).
// common_speculative_init checks !params.draft.mparams.path.empty() to
// decide whether the draft implementation should be registered, so the
// path field must be set even though we're passing the model directly.
common_params_speculative spec_params;
spec_params.type = COMMON_SPECULATIVE_TYPE_DRAFT;
// Configure draft model parameters
spec_params.draft.n_max = params.n_draft > 0 ? params.n_draft : 16;
spec_params.draft.p_min = 0.75f;
spec_params.draft.model = wrapper_dft->model;
spec_params.draft.mparams.path = "draft";
// Draft context parameters
spec_params.draft.cparams = llama_context_default_params();
spec_params.draft.cparams.n_ctx = llama_n_ctx(wrapper_dft->ctx);
spec_params.draft.cparams.n_batch = llama_n_batch(wrapper_dft->ctx);
spec_params.draft.cparams.n_threads = llama_n_threads(wrapper_dft->ctx);
spec_params.draft.cparams.n_threads_batch = llama_n_threads_batch(wrapper_dft->ctx);
// Initialize speculative sampling
common_speculative* spec = common_speculative_init(spec_params, wrapper_tgt->ctx);
if (!spec) {
g_last_error = "Failed to initialize speculative sampling";
return nullptr;
}
// Create sampling parameters
common_params_sampling sampling_params;
// Basic sampling
sampling_params.seed = params.seed;
sampling_params.temp = params.temperature;
sampling_params.top_k = params.top_k;
sampling_params.top_p = params.top_p;
sampling_params.min_p = params.min_p;
sampling_params.typ_p = params.typ_p;
sampling_params.top_n_sigma = params.top_n_sigma;
sampling_params.min_keep = params.min_keep;
// Repetition penalties
sampling_params.penalty_last_n = params.penalty_last_n;
sampling_params.penalty_repeat = params.penalty_repeat;
sampling_params.penalty_freq = params.penalty_freq;
sampling_params.penalty_present = params.penalty_present;
// DRY sampling
sampling_params.dry_multiplier = params.dry_multiplier;
sampling_params.dry_base = params.dry_base;
sampling_params.dry_allowed_length = params.dry_allowed_length;
sampling_params.dry_penalty_last_n = params.dry_penalty_last_n;
// Convert dry_sequence_breakers from C array to std::vector
sampling_params.dry_sequence_breakers.clear();
for (int i = 0; i < params.dry_sequence_breakers_count; i++) {
sampling_params.dry_sequence_breakers.push_back(std::string(params.dry_sequence_breakers[i]));
}
// Dynamic temperature
sampling_params.dynatemp_range = params.dynatemp_range;
sampling_params.dynatemp_exponent = params.dynatemp_exponent;
// XTC sampling
sampling_params.xtc_probability = params.xtc_probability;
sampling_params.xtc_threshold = params.xtc_threshold;
// Mirostat sampling
sampling_params.mirostat = params.mirostat;
sampling_params.mirostat_tau = params.mirostat_tau;
sampling_params.mirostat_eta = params.mirostat_eta;
// Other parameters
sampling_params.n_prev = params.n_prev;
sampling_params.n_probs = params.n_probs;
sampling_params.ignore_eos = params.ignore_eos;
// Initialise sampler
common_sampler* sampler = common_sampler_init(wrapper_tgt->model, sampling_params);
if (!sampler) {
common_speculative_free(spec);
g_last_error = "Failed to initialise sampler";
return nullptr;
}
// Evaluate prompt (all but last token), but only process tokens after the target prefix
// If target_prefix_len is at or past the last token, we don't need to decode anything
if (prompt_tokens.size() > 1 && target_prefix_len < (int)prompt_tokens.size() - 1) {
// Process tokens from target_prefix_len to size - 1
int tokens_to_process = prompt_tokens.size() - 1 - target_prefix_len;
int n_batch = llama_n_batch(wrapper_tgt->ctx);
// Process tokens in chunks that respect n_batch limit
for (int chunk_start = 0; chunk_start < tokens_to_process; chunk_start += n_batch) {
int chunk_size = std::min(n_batch, tokens_to_process - chunk_start);
llama_batch batch = llama_batch_init(chunk_size, 0, 1);
common_batch_clear(batch);
// Add tokens for this chunk with explicit positions
for (int i = 0; i < chunk_size; i++) {
int token_idx = target_prefix_len + chunk_start + i;
// Only the very last token of the entire prompt needs logits
bool needs_logits = (chunk_start + i == tokens_to_process - 1);
common_batch_add(batch, prompt_tokens[token_idx], token_idx, { 0 }, needs_logits);
}
if (llama_decode(wrapper_tgt->ctx, batch) != 0) {
llama_batch_free(batch);
common_sampler_free(sampler);
common_speculative_free(spec);
g_last_error = "Failed to decode prompt";
return nullptr;
}
llama_batch_free(batch);
}
} else if (target_prefix_len == (int)prompt_tokens.size() && prompt_tokens.size() > 1) {
// Full cache hit - refresh the second-to-last token to ensure determinism
// This matches the pattern where we decode all but the last token
llama_batch batch = llama_batch_init(512, 0, 1);
common_batch_clear(batch);
common_batch_add(batch, prompt_tokens[prompt_tokens.size() - 2], prompt_tokens.size() - 2, { 0 }, true);
if (llama_decode(wrapper_tgt->ctx, batch) != 0) {
if (params.debug) {
fprintf(stderr, "WARNING: speculative prompt logit refresh failed\n");
}
llama_batch_free(batch);
common_sampler_free(sampler);
common_speculative_free(spec);
g_last_error = "Failed to refresh logits for cached speculative prompt";
return nullptr;
}
llama_batch_free(batch);
}
// Generation variables
std::string result;
llama_token last_token = prompt_tokens.back();
llama_tokens prompt_tgt(prompt_tokens.begin(), prompt_tokens.end() - 1);
int n_past = prompt_tokens.size() - 1;
int n_predict = params.max_tokens > 0 ? params.max_tokens : 128;
llama_batch batch_tgt = llama_batch_init(llama_n_batch(wrapper_tgt->ctx), 0, 1);
// Generation loop
while (result.length() < (size_t)n_predict) {
// Generate draft tokens
llama_tokens draft = common_speculative_draft(spec, spec_params, prompt_tgt, last_token);
// Prepare batch with last token and draft
common_batch_clear(batch_tgt);
common_batch_add(batch_tgt, last_token, n_past, { 0 }, true);
for (size_t i = 0; i < draft.size(); ++i) {
common_batch_add(batch_tgt, draft[i], n_past + i + 1, { 0 }, true);
}
// Evaluate on target model
if (llama_decode(wrapper_tgt->ctx, batch_tgt) != 0) {
if (params.debug) {
fprintf(stderr, "WARNING: target decode failed, stopping\n");
}
break;
}
// Sample and accept tokens
const auto ids = common_sampler_sample_and_accept_n(sampler, wrapper_tgt->ctx, draft);
if (ids.empty()) {
break;
}
// Process accepted tokens - track actual count in case of early termination
size_t tokens_processed = 0;
bool early_termination = false;
for (size_t i = 0; i < ids.size(); ++i) {
const llama_token id = ids[i];
// Check for EOS
if (llama_vocab_is_eog(llama_model_get_vocab(wrapper_tgt->model), id)) {
early_termination = true;
break;
}
const std::string token_str = common_token_to_piece(wrapper_tgt->ctx, id);
// Call callback if provided
if (params.callback_handle != 0) {
if (!goTokenCallback(params.callback_handle, token_str.c_str())) {
early_termination = true;
break;
}
}
result += token_str;
prompt_tgt.push_back(id);
tokens_processed++;
// Check stop words
for (int j = 0; j < params.stop_words_count; j++) {
if (result.find(params.stop_words[j]) != std::string::npos) {
early_termination = true;
goto early_exit;
}
}
}
early_exit:
// Update position tracking based on tokens actually processed
if (early_termination) {
n_past += tokens_processed;
if (params.debug) {
fprintf(stderr, "DEBUG: Early termination after processing %zu/%zu tokens\n",
tokens_processed, ids.size());
}
} else {
n_past += ids.size();
}
// Clean up any unaccepted/unprocessed tokens from KV cache
// This removes everything from position n_past onwards, ensuring the cache
// only contains tokens we've actually processed and accepted
llama_memory_seq_rm(llama_get_memory(wrapper_tgt->ctx), 0, n_past, -1);
// Update last token for next iteration
if (tokens_processed > 0) {
// Use the last token we actually processed
last_token = prompt_tgt[prompt_tgt.size() - 1];
}
// Break if early termination
if (early_termination) {
break;
}
}
llama_batch_free(batch_tgt);
common_sampler_free(sampler);
common_speculative_free(spec);
// Return allocated string
char* c_result = (char*)malloc(result.length() + 1);
if (c_result) {
memcpy(c_result, result.c_str(), result.length());
c_result[result.length()] = '\0';
} else {
g_last_error = "Failed to allocate memory for result";
}
return c_result;
} catch (const std::exception& e) {
g_last_error = "Exception during speculative generation: " + std::string(e.what());
return nullptr;
}
}
// Simple wrapper that tokenises the prompt and handles prefix caching automatically for both models
char* llama_wrapper_generate_draft(void* ctx_target, void* ctx_draft, llama_wrapper_generate_params params) {
if (!ctx_target || !ctx_draft) {
g_last_error = "Target and draft contexts cannot be null";
return nullptr;
}
auto wrapper_tgt = static_cast<llama_wrapper_context_t*>(ctx_target);
auto wrapper_dft = static_cast<llama_wrapper_context_t*>(ctx_draft);
if (!wrapper_tgt->ctx) {
g_last_error = "Target context has been freed";
return nullptr;
}
if (!wrapper_dft->ctx) {
g_last_error = "Draft context has been freed";
return nullptr;
}
try {
// Tokenise the prompt
std::vector<llama_token> prompt_tokens = common_tokenize(wrapper_tgt->ctx, params.prompt, true, true);
if (prompt_tokens.empty()) {
g_last_error = "Failed to tokenize prompt";
return nullptr;
}
// Convert to int vector for comparison
std::vector<int> tokens_int(prompt_tokens.begin(), prompt_tokens.end());
// Find common prefix for both contexts (only if prefix caching enabled)
int target_prefix_len = params.enable_prefix_caching
? findCommonPrefix(wrapper_tgt->cached_tokens, tokens_int)
: 0;
int draft_prefix_len = params.enable_prefix_caching
? findCommonPrefix(wrapper_dft->cached_tokens, tokens_int)
: 0;
// Update both caches to new token sequence (only if prefix caching enabled)
if (params.enable_prefix_caching) {
wrapper_tgt->cached_tokens = tokens_int;
wrapper_dft->cached_tokens = tokens_int;
} else {
wrapper_tgt->cached_tokens.clear(); // Ensure cache is empty when disabled
wrapper_dft->cached_tokens.clear();
}
// Call token-based speculative generation with prefix caching
return llama_wrapper_generate_draft_with_tokens(ctx_target, ctx_draft, tokens_int.data(), tokens_int.size(), target_prefix_len, draft_prefix_len, params);
} catch (const std::exception& e) {
g_last_error = "Exception during speculative generation: " + std::string(e.what());
return nullptr;
}
}
int llama_wrapper_tokenize(void* ctx, const char* text, int* tokens, int max_tokens) {
if (!ctx || !text || !tokens) {
g_last_error = "Invalid parameters for tokenization";
return -1;
}
auto wrapper = static_cast<llama_wrapper_context_t*>(ctx);
try {
std::vector<llama_token> token_vec = common_tokenize(wrapper->ctx, text, true, true);
int count = std::min((int)token_vec.size(), max_tokens);
for (int i = 0; i < count; i++) {
tokens[i] = token_vec[i];
}
return count;
} catch (const std::exception& e) {
g_last_error = "Exception during tokenization: " + std::string(e.what());
return -1;