cui-llama.rn 1.4.1 → 1.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/README.md +4 -23
  2. package/android/build.gradle +12 -3
  3. package/android/src/main/CMakeLists.txt +13 -7
  4. package/android/src/main/java/com/rnllama/LlamaContext.java +27 -20
  5. package/android/src/main/java/com/rnllama/RNLlama.java +5 -1
  6. package/android/src/main/jni.cpp +8 -5
  7. package/android/src/main/jniLibs/arm64-v8a/librnllama.so +0 -0
  8. package/android/src/main/jniLibs/arm64-v8a/librnllama_v8.so +0 -0
  9. package/android/src/main/jniLibs/arm64-v8a/librnllama_v8_2.so +0 -0
  10. package/android/src/main/jniLibs/arm64-v8a/librnllama_v8_2_dotprod.so +0 -0
  11. package/android/src/main/jniLibs/arm64-v8a/librnllama_v8_2_dotprod_i8mm.so +0 -0
  12. package/android/src/main/jniLibs/arm64-v8a/librnllama_v8_2_i8mm.so +0 -0
  13. package/android/src/main/jniLibs/x86_64/librnllama.so +0 -0
  14. package/android/src/main/jniLibs/x86_64/librnllama_x86_64.so +0 -0
  15. package/cpp/README.md +1 -1
  16. package/cpp/common.cpp +0 -212
  17. package/cpp/common.h +3 -0
  18. package/cpp/rn-llama.cpp +822 -0
  19. package/cpp/rn-llama.h +123 -0
  20. package/ios/CMakeLists.txt +99 -0
  21. package/ios/RNLlama.h +5 -1
  22. package/ios/RNLlama.mm +2 -2
  23. package/ios/RNLlamaContext.h +8 -1
  24. package/ios/RNLlamaContext.mm +15 -11
  25. package/ios/rnllama.xcframework/Info.plist +74 -0
  26. package/jest/mock.js +3 -2
  27. package/lib/commonjs/NativeRNLlama.js.map +1 -1
  28. package/lib/commonjs/index.js +4 -2
  29. package/lib/commonjs/index.js.map +1 -1
  30. package/lib/module/NativeRNLlama.js.map +1 -1
  31. package/lib/module/index.js +4 -2
  32. package/lib/module/index.js.map +1 -1
  33. package/lib/typescript/NativeRNLlama.d.ts +5 -1
  34. package/lib/typescript/NativeRNLlama.d.ts.map +1 -1
  35. package/lib/typescript/index.d.ts.map +1 -1
  36. package/llama-rn.podspec +8 -2
  37. package/package.json +5 -2
  38. package/src/NativeRNLlama.ts +5 -1
  39. package/src/index.ts +9 -2
@@ -0,0 +1,822 @@
1
+ #include "rn-llama.h"
2
+
3
+ namespace rnllama {
4
+
5
+ const std::vector<lm_ggml_type> kv_cache_types = {
6
+ LM_GGML_TYPE_F32,
7
+ LM_GGML_TYPE_F16,
8
+ LM_GGML_TYPE_BF16,
9
+ LM_GGML_TYPE_Q8_0,
10
+ LM_GGML_TYPE_Q4_0,
11
+ LM_GGML_TYPE_Q4_1,
12
+ LM_GGML_TYPE_IQ4_NL,
13
+ LM_GGML_TYPE_Q5_0,
14
+ LM_GGML_TYPE_Q5_1,
15
+ };
16
+
17
+ lm_ggml_type kv_cache_type_from_str(const std::string & s) {
18
+ for (const auto & type : kv_cache_types) {
19
+ if (lm_ggml_type_name(type) == s) {
20
+ return type;
21
+ }
22
+ }
23
+ throw std::runtime_error("Unsupported cache type: " + s);
24
+ }
25
+
26
+ static void llama_batch_clear(llama_batch *batch) {
27
+ batch->n_tokens = 0;
28
+ }
29
+
30
+ static void llama_batch_add(llama_batch *batch, llama_token id, llama_pos pos, std::vector<llama_seq_id> seq_ids, bool logits) {
31
+ batch->token [batch->n_tokens] = id;
32
+ batch->pos [batch->n_tokens] = pos;
33
+ batch->n_seq_id[batch->n_tokens] = seq_ids.size();
34
+ for (size_t i = 0; i < seq_ids.size(); i++) {
35
+ batch->seq_id[batch->n_tokens][i] = seq_ids[i];
36
+ }
37
+ batch->logits [batch->n_tokens] = logits ? 1 : 0;
38
+ batch->n_tokens += 1;
39
+ }
40
+
41
+ // NOTE: Edit from https://github.com/ggerganov/llama.cpp/blob/master/examples/server/server.cpp
42
+
43
+ static void log(const char *level, const char *function, int line,
44
+ const char *format, ...)
45
+ {
46
+ va_list args;
47
+ #if defined(__ANDROID__)
48
+ char prefix[256];
49
+ snprintf(prefix, sizeof(prefix), "%s:%d %s", function, line, format);
50
+
51
+ va_start(args, format);
52
+ android_LogPriority priority;
53
+ if (strcmp(level, "ERROR") == 0) {
54
+ priority = ANDROID_LOG_ERROR;
55
+ } else if (strcmp(level, "WARNING") == 0) {
56
+ priority = ANDROID_LOG_WARN;
57
+ } else if (strcmp(level, "INFO") == 0) {
58
+ priority = ANDROID_LOG_INFO;
59
+ } else {
60
+ priority = ANDROID_LOG_DEBUG;
61
+ }
62
+ __android_log_vprint(priority, "RNLlama", prefix, args);
63
+ va_end(args);
64
+ #else
65
+ printf("[%s] %s:%d ", level, function, line);
66
+ va_start(args, format);
67
+ vprintf(format, args);
68
+ va_end(args);
69
+ printf("\n");
70
+ #endif
71
+ }
72
+
73
+ #if RNLLAMA_VERBOSE != 1
74
+ #define LOG_VERBOSE(MSG, ...)
75
+ #else
76
+ #define LOG_VERBOSE(MSG, ...) \
77
+ do \
78
+ { \
79
+ if (rnllama_verbose) \
80
+ { \
81
+ log("VERBOSE", __func__, __LINE__, MSG, ##__VA_ARGS__); \
82
+ } \
83
+ } while (0)
84
+ #endif
85
+
86
+ #define LOG_ERROR(MSG, ...) log("ERROR", __func__, __LINE__, MSG, ##__VA_ARGS__)
87
+ #define LOG_WARNING(MSG, ...) log("WARNING", __func__, __LINE__, MSG, ##__VA_ARGS__)
88
+ #define LOG_INFO(MSG, ...) log("INFO", __func__, __LINE__, MSG, ##__VA_ARGS__)
89
+
90
+ static size_t common_part(const std::vector<llama_token> &a, const std::vector<llama_token> &b)
91
+ {
92
+ size_t i;
93
+ for (i = 0; i < a.size() && i < b.size() && a[i] == b[i]; i++)
94
+ {
95
+ }
96
+ return i;
97
+ }
98
+
99
+ static bool ends_with(const std::string &str, const std::string &suffix)
100
+ {
101
+ return str.size() >= suffix.size() &&
102
+ 0 == str.compare(str.size() - suffix.size(), suffix.size(), suffix);
103
+ }
104
+
105
+ static size_t find_partial_stop_string(const std::string &stop,
106
+ const std::string &text)
107
+ {
108
+ if (!text.empty() && !stop.empty())
109
+ {
110
+ const char text_last_char = text.back();
111
+ for (int64_t char_index = stop.size() - 1; char_index >= 0; char_index--)
112
+ {
113
+ if (stop[char_index] == text_last_char)
114
+ {
115
+ const std::string current_partial = stop.substr(0, char_index + 1);
116
+ if (ends_with(text, current_partial))
117
+ {
118
+ return text.size() - char_index - 1;
119
+ }
120
+ }
121
+ }
122
+ }
123
+ return std::string::npos;
124
+ }
125
+
126
+ // format incomplete utf-8 multibyte character for output
127
+ std::string tokens_to_output_formatted_string(const llama_context *ctx, const llama_token token)
128
+ {
129
+ std::string out = token == -1 ? "" : common_token_to_piece(ctx, token);
130
+ // if the size is 1 and first bit is 1, meaning it's a partial character
131
+ // (size > 1 meaning it's already a known token)
132
+ if (out.size() == 1 && (out[0] & 0x80) == 0x80)
133
+ {
134
+ std::stringstream ss;
135
+ ss << std::hex << (out[0] & 0xff);
136
+ std::string res(ss.str());
137
+ out = "byte: \\x" + res;
138
+ }
139
+ return out;
140
+ }
141
+
142
+ std::string tokens_to_str(llama_context *ctx, const std::vector<llama_token>::const_iterator begin, const std::vector<llama_token>::const_iterator end)
143
+ {
144
+ std::string ret;
145
+ for (auto it = begin; it != end; ++it)
146
+ {
147
+ ret += common_token_to_piece(ctx, *it);
148
+ }
149
+ return ret;
150
+ }
151
+
152
+ llama_rn_context::~llama_rn_context() {
153
+ if (ctx_sampling != nullptr) {
154
+ common_sampler_free(ctx_sampling);
155
+ }
156
+ }
157
+
158
+ void llama_rn_context::rewind() {
159
+ is_interrupted = false;
160
+ params.antiprompt.clear();
161
+ params.sampling.grammar.clear();
162
+ num_prompt_tokens = 0;
163
+ num_tokens_predicted = 0;
164
+ generated_text = "";
165
+ generated_text.reserve(params.n_ctx);
166
+ generated_token_probs.clear();
167
+ truncated = false;
168
+ stopped_eos = false;
169
+ stopped_word = false;
170
+ stopped_limit = false;
171
+ stopping_word = "";
172
+ incomplete = false;
173
+ n_remain = 0;
174
+ n_past = 0;
175
+ params.sampling.n_prev = n_ctx;
176
+ }
177
+
178
+ bool llama_rn_context::initSampling() {
179
+ if (ctx_sampling != nullptr) {
180
+ common_sampler_free(ctx_sampling);
181
+ }
182
+ ctx_sampling = common_sampler_init(model, params.sampling);
183
+ return ctx_sampling != nullptr;
184
+ }
185
+
186
+ bool llama_rn_context::loadModel(common_params &params_)
187
+ {
188
+ params = params_;
189
+ llama_init = common_init_from_params(params);
190
+ model = llama_init.model.get();
191
+ ctx = llama_init.context.get();
192
+ if (model == nullptr)
193
+ {
194
+ LOG_ERROR("unable to load model: %s", params_.model.c_str());
195
+ return false;
196
+ }
197
+ n_ctx = llama_n_ctx(ctx);
198
+
199
+ // We can uncomment for debugging or after this fix: https://github.com/ggerganov/llama.cpp/pull/11101
200
+ // LOG_INFO("%s\n", common_params_get_system_info(params).c_str());
201
+
202
+ return true;
203
+ }
204
+
205
+ bool llama_rn_context::validateModelChatTemplate() const {
206
+ const char * tmpl = llama_model_chat_template(model);
207
+ llama_chat_message chat[] = {{"user", "test"}};
208
+ int32_t chat_res = llama_chat_apply_template(tmpl, chat, 1, true, nullptr, 0);
209
+ return chat_res > 0;
210
+ }
211
+
212
+ void llama_rn_context::truncatePrompt(std::vector<llama_token> &prompt_tokens) {
213
+ const int n_left = n_ctx - params.n_keep;
214
+ const int n_block_size = n_left / 2;
215
+ const int erased_blocks = (prompt_tokens.size() - params.n_keep - n_block_size) / n_block_size;
216
+
217
+ // Keep n_keep tokens at start of prompt (at most n_ctx - 4)
218
+ std::vector<llama_token> new_tokens(prompt_tokens.begin(), prompt_tokens.begin() + params.n_keep);
219
+
220
+ new_tokens.insert(new_tokens.end(), prompt_tokens.begin() + params.n_keep + erased_blocks * n_block_size, prompt_tokens.end());
221
+
222
+ LOG_VERBOSE("input truncated, n_ctx: %d, n_keep: %d, n_left: %d, new_tokens: %s, num_prompt_tokens: %d",
223
+ n_ctx,
224
+ params.n_keep,
225
+ n_left,
226
+ tokens_to_str(ctx, new_tokens.cbegin(), new_tokens.cend()).c_str(),
227
+ new_tokens.size()
228
+ );
229
+
230
+ truncated = true;
231
+ prompt_tokens = new_tokens;
232
+ }
233
+
234
+ void llama_rn_context::loadPrompt() {
235
+ std::vector<llama_token> prompt_tokens = ::common_tokenize(ctx, params.prompt, true, true);
236
+ num_prompt_tokens = prompt_tokens.size();
237
+
238
+ // LOG tokens
239
+ std::stringstream ss;
240
+ ss << "\n" << __func__ << ": prompt_tokens = ";
241
+ for (auto& token : prompt_tokens) {
242
+ ss << token << " ";
243
+ }
244
+ LOG_INFO("%s\n", ss.str().c_str());
245
+
246
+ if (params.n_keep < 0)
247
+ {
248
+ params.n_keep = (int)num_prompt_tokens;
249
+ }
250
+ params.n_keep = std::min(n_ctx - 4, params.n_keep);
251
+
252
+ // if input prompt is too big, truncate like normal
253
+ if (num_prompt_tokens >= (size_t) n_ctx)
254
+ {
255
+ truncatePrompt(prompt_tokens);
256
+ num_prompt_tokens = prompt_tokens.size();
257
+
258
+ LM_GGML_ASSERT(num_prompt_tokens < (size_t) n_ctx);
259
+ }
260
+
261
+ // do context shifitng
262
+ if(!params.embedding){
263
+ purge_missing_tokens(ctx, embd, prompt_tokens, params.n_predict, params.n_ctx);
264
+ }
265
+
266
+
267
+ // push the prompt into the sampling context (do not apply grammar)
268
+ for (auto & token : prompt_tokens)
269
+ {
270
+ common_sampler_accept(ctx_sampling, token, false);
271
+ }
272
+
273
+ // compare the evaluated prompt with the new prompt
274
+ n_past = common_part(embd, prompt_tokens);
275
+
276
+ embd = prompt_tokens;
277
+ if (n_past == num_prompt_tokens)
278
+ {
279
+ // we have to evaluate at least 1 token to generate logits.
280
+ n_past--;
281
+ }
282
+
283
+ // since #3228 we now have to manually manage the KV cache
284
+ llama_kv_cache_seq_rm(ctx, 0, n_past, -1);
285
+
286
+ LOG_VERBOSE("prompt ingested, n_past: %d, cached: %s, to_eval: %s",
287
+ n_past,
288
+ tokens_to_str(ctx, embd.cbegin(), embd.cbegin() + n_past).c_str(),
289
+ tokens_to_str(ctx, embd.cbegin() + n_past, embd.cend()).c_str()
290
+ );
291
+
292
+ has_next_token = true;
293
+ }
294
+
295
+ void llama_rn_context::beginCompletion() {
296
+ // number of tokens to keep when resetting context
297
+ n_remain = params.n_predict;
298
+ llama_perf_context_reset(ctx);
299
+ is_predicting = true;
300
+ }
301
+
302
+ completion_token_output llama_rn_context::nextToken()
303
+ {
304
+ completion_token_output result;
305
+ result.tok = -1;
306
+
307
+ if (embd.size() >= (size_t)params.n_ctx)
308
+ {
309
+ // Shift context
310
+
311
+ const int n_left = n_past - params.n_keep - 1;
312
+ const int n_discard = n_left/2;
313
+
314
+ llama_kv_cache_seq_rm (ctx, 0, params.n_keep + 1 , params.n_keep + n_discard + 1);
315
+ llama_kv_cache_seq_add(ctx, 0, params.n_keep + 1 + n_discard, n_past, -n_discard);
316
+
317
+ for (size_t i = params.n_keep + 1 + n_discard; i < embd.size(); i++)
318
+ {
319
+ embd[i - n_discard] = embd[i];
320
+ }
321
+ embd.resize(embd.size() - n_discard);
322
+
323
+ n_past -= n_discard;
324
+
325
+ LOG_VERBOSE("input truncated, n_ctx: %d, n_keep: %d, n_left: %d, new_tokens: %s",
326
+ params.n_ctx,
327
+ params.n_keep,
328
+ n_left
329
+ );
330
+ }
331
+
332
+ bool tg = true;
333
+ while (n_past < embd.size())
334
+ {
335
+ int n_eval = (int)embd.size() - n_past;
336
+ tg = n_eval == 1;
337
+ if (n_eval > params.n_batch)
338
+ {
339
+ n_eval = params.n_batch;
340
+ }
341
+ if (llama_decode(ctx, llama_batch_get_one(&embd[n_past], n_eval)))
342
+ {
343
+ LOG_ERROR("failed to eval, n_eval: %d, n_past: %d, n_threads: %d, embd: %s",
344
+ n_eval,
345
+ n_past,
346
+ params.cpuparams.n_threads,
347
+ tokens_to_str(ctx, embd.cbegin() + n_past, embd.cend()).c_str()
348
+ );
349
+ has_next_token = false;
350
+ return result;
351
+ }
352
+ n_past += n_eval;
353
+
354
+ if(is_interrupted) {
355
+ LOG_INFO("Decoding Interrupted");
356
+ embd.resize(n_past);
357
+ has_next_token = false;
358
+ return result;
359
+ }
360
+ }
361
+
362
+ const llama_vocab* vocab = llama_model_get_vocab(model);
363
+
364
+ if (params.n_predict == 0)
365
+ {
366
+ has_next_token = false;
367
+ result.tok = llama_vocab_eos(vocab);
368
+ return result;
369
+ }
370
+
371
+ {
372
+ // out of user input, sample next token
373
+ std::vector<llama_token_data> candidates;
374
+ candidates.reserve(llama_vocab_n_tokens(vocab));
375
+
376
+ result.tok = common_sampler_sample(ctx_sampling, ctx, -1);
377
+
378
+ llama_token_data_array cur_p = *common_sampler_get_candidates(ctx_sampling);
379
+
380
+ const int32_t n_probs = params.sampling.n_probs;
381
+
382
+ // deprecated
383
+ /*if (params.sampling.temp <= 0 && n_probs > 0)
384
+ {
385
+ // For llama_sample_token_greedy we need to sort candidates
386
+ llama_sampler_init_softmax();
387
+
388
+ }*/
389
+
390
+
391
+ for (size_t i = 0; i < std::min(cur_p.size, (size_t)n_probs); ++i)
392
+ {
393
+ result.probs.push_back({cur_p.data[i].id, cur_p.data[i].p});
394
+ }
395
+
396
+ common_sampler_accept(ctx_sampling, result.tok, true);
397
+ if (tg) {
398
+ num_tokens_predicted++;
399
+ }
400
+ }
401
+
402
+ // add it to the context
403
+ embd.push_back(result.tok);
404
+ // decrement remaining sampling budget
405
+ --n_remain;
406
+
407
+ if (!embd.empty() && embd.back() == llama_vocab_eos(vocab))
408
+ {
409
+ // stopping_word = llama_token_to_piece(ctx, embd.back());
410
+ has_next_token = false;
411
+ stopped_eos = true;
412
+ LOG_VERBOSE("eos token found", "");
413
+ return result;
414
+ }
415
+
416
+ has_next_token = params.n_predict == -1 || n_remain != 0;
417
+ return result;
418
+ }
419
+
420
+ size_t llama_rn_context::findStoppingStrings(const std::string &text, const size_t last_token_size,
421
+ const stop_type type)
422
+ {
423
+ size_t stop_pos = std::string::npos;
424
+ for (const std::string &word : params.antiprompt)
425
+ {
426
+ size_t pos;
427
+ if (type == STOP_FULL)
428
+ {
429
+ const size_t tmp = word.size() + last_token_size;
430
+ const size_t from_pos = text.size() > tmp ? text.size() - tmp : 0;
431
+ pos = text.find(word, from_pos);
432
+ }
433
+ else
434
+ {
435
+ pos = find_partial_stop_string(word, text);
436
+ }
437
+ if (pos != std::string::npos &&
438
+ (stop_pos == std::string::npos || pos < stop_pos))
439
+ {
440
+ if (type == STOP_FULL)
441
+ {
442
+ stopping_word = word;
443
+ stopped_word = true;
444
+ has_next_token = false;
445
+ }
446
+ stop_pos = pos;
447
+ }
448
+ }
449
+ return stop_pos;
450
+ }
451
+
452
+ completion_token_output llama_rn_context::doCompletion()
453
+ {
454
+ const completion_token_output token_with_probs = nextToken();
455
+
456
+ const std::string token_text = token_with_probs.tok == -1 ? "" : common_token_to_piece(ctx, token_with_probs.tok);
457
+ generated_text += token_text;
458
+
459
+ if (params.sampling.n_probs > 0)
460
+ {
461
+ generated_token_probs.push_back(token_with_probs);
462
+ }
463
+
464
+ // check if there is incomplete UTF-8 character at the end
465
+ for (unsigned i = 1; i < 5 && i <= generated_text.size(); ++i) {
466
+ unsigned char c = generated_text[generated_text.size() - i];
467
+ if ((c & 0xC0) == 0x80) {
468
+ // continuation byte: 10xxxxxx
469
+ continue;
470
+ }
471
+ if ((c & 0xE0) == 0xC0) {
472
+ // 2-byte character: 110xxxxx ...
473
+ incomplete = i < 2;
474
+ } else if ((c & 0xF0) == 0xE0) {
475
+ // 3-byte character: 1110xxxx ...
476
+ incomplete = i < 3;
477
+ } else if ((c & 0xF8) == 0xF0) {
478
+ // 4-byte character: 11110xxx ...
479
+ incomplete = i < 4;
480
+ }
481
+ // else 1-byte character or invalid byte
482
+ break;
483
+ }
484
+
485
+ if (incomplete && !has_next_token)
486
+ {
487
+ has_next_token = true;
488
+ n_remain++;
489
+ }
490
+
491
+ if (!has_next_token && n_remain == 0)
492
+ {
493
+ stopped_limit = true;
494
+ }
495
+
496
+ LOG_VERBOSE("next token, token: %s, token_text: %s, has_next_token: %d, n_remain: %d, num_tokens_predicted: %d, stopped_eos: %d, stopped_word: %d, stopped_limit: %d, stopping_word: %s",
497
+ common_token_to_piece(ctx, token_with_probs.tok),
498
+ tokens_to_output_formatted_string(ctx, token_with_probs.tok).c_str(),
499
+ has_next_token,
500
+ n_remain,
501
+ num_tokens_predicted,
502
+ stopped_eos,
503
+ stopped_word,
504
+ stopped_limit,
505
+ stopping_word.c_str()
506
+ );
507
+ return token_with_probs;
508
+ }
509
+
510
+ std::vector<float> llama_rn_context::getEmbedding(common_params &embd_params)
511
+ {
512
+ static const int n_embd = llama_model_n_embd(llama_get_model(ctx));
513
+ if (!embd_params.embedding)
514
+ {
515
+ LOG_WARNING("embedding disabled, embedding: %s", embd_params.embedding);
516
+ return std::vector<float>(n_embd, 0.0f);
517
+ }
518
+ float *data;
519
+
520
+ const enum llama_pooling_type pooling_type = llama_pooling_type(ctx);
521
+ printf("pooling_type: %d\n", pooling_type);
522
+ if (pooling_type == LLAMA_POOLING_TYPE_NONE) {
523
+ data = llama_get_embeddings(ctx);
524
+ } else {
525
+ data = llama_get_embeddings_seq(ctx, 0);
526
+ }
527
+
528
+ if (!data) {
529
+ return std::vector<float>(n_embd, 0.0f);
530
+ }
531
+ std::vector<float> embedding(data, data + n_embd), out(data, data + n_embd);
532
+ common_embd_normalize(embedding.data(), out.data(), n_embd, embd_params.embd_normalize);
533
+ return out;
534
+ }
535
+
536
+ std::string llama_rn_context::bench(int pp, int tg, int pl, int nr)
537
+ {
538
+ if (is_predicting) {
539
+ LOG_ERROR("cannot benchmark while predicting", "");
540
+ return std::string("[]");
541
+ }
542
+
543
+ is_predicting = true;
544
+
545
+ double pp_avg = 0;
546
+ double tg_avg = 0;
547
+
548
+ double pp_std = 0;
549
+ double tg_std = 0;
550
+
551
+ // TODO: move batch into llama_rn_context (related https://github.com/mybigday/llama.rn/issues/30)
552
+ llama_batch batch = llama_batch_init(
553
+ std::min(pp, params.n_ubatch), // max n_tokens is limited by n_ubatch
554
+ 0, // No embeddings
555
+ 1 // Single sequence
556
+ );
557
+
558
+ for (int i = 0; i < nr; i++)
559
+ {
560
+ llama_batch_clear(&batch);
561
+
562
+ const int n_tokens = pp;
563
+
564
+ for (int i = 0; i < n_tokens; i++)
565
+ {
566
+ llama_batch_add(&batch, 0, i, {0}, false);
567
+ }
568
+ batch.logits[batch.n_tokens - 1] = 1; // true
569
+
570
+ llama_kv_cache_clear(ctx);
571
+
572
+ const int64_t t_pp_start = llama_time_us();
573
+ if (llama_decode(ctx, batch) != 0)
574
+ {
575
+ LOG_ERROR("llama_decode() failed during prompt", "");
576
+ }
577
+ const int64_t t_pp_end = llama_time_us();
578
+ llama_kv_cache_clear(ctx);
579
+
580
+ if (is_interrupted) break;
581
+
582
+ const int64_t t_tg_start = llama_time_us();
583
+
584
+ for (int i = 0; i < tg; i++)
585
+ {
586
+ llama_batch_clear(&batch);
587
+
588
+ for (int j = 0; j < pl; j++)
589
+ {
590
+ llama_batch_add(&batch, 0, i, {j}, true);
591
+ }
592
+
593
+ if (llama_decode(ctx, batch) != 0)
594
+ {
595
+ LOG_ERROR("llama_decode() failed during text generation", "");
596
+ }
597
+ if (is_interrupted) break;
598
+ }
599
+
600
+ const int64_t t_tg_end = llama_time_us();
601
+
602
+ llama_kv_cache_clear(ctx);
603
+
604
+ const double t_pp = (t_pp_end - t_pp_start) / 1000000.0;
605
+ const double t_tg = (t_tg_end - t_tg_start) / 1000000.0;
606
+
607
+ const double speed_pp = pp / t_pp;
608
+ const double speed_tg = (pl * tg) / t_tg;
609
+
610
+ pp_avg += speed_pp;
611
+ tg_avg += speed_tg;
612
+
613
+ pp_std += speed_pp * speed_pp;
614
+ tg_std += speed_tg * speed_tg;
615
+ }
616
+
617
+ pp_avg /= nr;
618
+ tg_avg /= nr;
619
+
620
+ if (nr > 1) {
621
+ pp_std = sqrt(pp_std / (nr - 1) - pp_avg * pp_avg * nr / (nr - 1));
622
+ tg_std = sqrt(tg_std / (nr - 1) - tg_avg * tg_avg * nr / (nr - 1));
623
+ } else {
624
+ pp_std = 0;
625
+ tg_std = 0;
626
+ }
627
+
628
+ if (is_interrupted) llama_kv_cache_clear(ctx);
629
+ is_predicting = false;
630
+
631
+ char model_desc[128];
632
+ llama_model_desc(model, model_desc, sizeof(model_desc));
633
+ return std::string("[\"") + model_desc + std::string("\",") +
634
+ std::to_string(llama_model_size(model)) + std::string(",") +
635
+ std::to_string(llama_model_n_params(model)) + std::string(",") +
636
+ std::to_string(pp_avg) + std::string(",") +
637
+ std::to_string(pp_std) + std::string(",") +
638
+ std::to_string(tg_avg) + std::string(",") +
639
+ std::to_string(tg_std) +
640
+ std::string("]");
641
+ }
642
+
643
+ int llama_rn_context::applyLoraAdapters(std::vector<common_adapter_lora_info> lora) {
644
+ for (auto &la : lora) {
645
+ la.ptr = llama_adapter_lora_init(model, la.path.c_str());
646
+ if (la.ptr == nullptr) {
647
+ LOG_ERROR("failed to apply lora adapter '%s'\n", la.path.c_str());
648
+ return -1;
649
+ }
650
+ }
651
+ this->lora = lora;
652
+ common_set_adapter_lora(ctx, lora);
653
+ return 0;
654
+ }
655
+
656
+ void llama_rn_context::removeLoraAdapters() {
657
+ this->lora.clear();
658
+ common_set_adapter_lora(ctx, this->lora); // apply empty list
659
+ }
660
+
661
+ std::vector<common_adapter_lora_info> llama_rn_context::getLoadedLoraAdapters() {
662
+ return this->lora;
663
+ }
664
+ std::vector<int> llama_rn_context::longest_common_subseq(const std::vector<int> x, const std::vector<int> y){
665
+ int m = x.size(), n = y.size();
666
+
667
+ //int LCSuff[m+1][n+1];
668
+ std::vector<std::vector<int>> LCSuff(m+1, std::vector<int>(n+1));
669
+
670
+ for (int j = 0; j <= n; j++)
671
+ LCSuff[0][j] = 0;
672
+ for (int i = 0; i <= m; i++)
673
+ LCSuff[i][0] = 0;
674
+
675
+ for (int i = 1; i <= m; i++)
676
+ {
677
+ for (int j = 1; j <= n; j++)
678
+ {
679
+ if (x[i - 1] == y[j - 1])
680
+ LCSuff[i][j] = LCSuff[i - 1][j - 1] + 1;
681
+ else
682
+ LCSuff[i][j] = 0;
683
+ }
684
+ }
685
+
686
+ std::vector<int> longest;
687
+ for (int i = 1; i <= m; i++)
688
+ {
689
+ for (int j = 1; j <= n; j++)
690
+ {
691
+ if (LCSuff[i][j] > longest.size())
692
+ {
693
+ auto off1 = ((i - LCSuff[i][j] + 1) - 1);
694
+ auto off2 = off1 + LCSuff[i][j];
695
+ longest.clear();
696
+ // std::vector<int>().swap(longest);
697
+ longest = std::vector<int>(x.begin() + off1, x.begin() + off2);
698
+ // x.substr((i - LCSuff[i][j] + 1) - 1, LCSuff[i][j]);
699
+ }
700
+ }
701
+ }
702
+ return longest;
703
+ }
704
+
705
+ bool llama_rn_context::arr_start_with(const std::vector<int> targetArray, const std::vector<int> searchSeq)
706
+ {
707
+ int ss = searchSeq.size();
708
+ if(targetArray.size()<ss)
709
+ {
710
+ return false;
711
+ }
712
+ for(int i=0;i<ss;++i)
713
+ {
714
+ if(targetArray[i]!=searchSeq[i])
715
+ {
716
+ return false;
717
+ }
718
+ }
719
+ return true;
720
+ }
721
+
722
+ int llama_rn_context::arr_find_index_of(const std::vector<int> targetArray, const std::vector<int> searchSeq)
723
+ {
724
+ int ss = searchSeq.size();
725
+ int tas = targetArray.size();
726
+ if(tas<ss)
727
+ {
728
+ return -1;
729
+ }
730
+ for(int i=0;i<tas;++i)
731
+ {
732
+ int srch = 0;
733
+ bool fail = false;
734
+ for(int srch=0;srch<ss;++srch)
735
+ {
736
+ if ((i + srch) >= tas || targetArray[i + srch] != searchSeq[srch])
737
+ {
738
+ fail = true;
739
+ break;
740
+ }
741
+ }
742
+ if(!fail)
743
+ {
744
+ return i;
745
+ }
746
+ }
747
+ return -1;
748
+ }
749
+
750
+ void llama_rn_context::purge_missing_tokens(llama_context * ctx, std::vector<int> &current_context_tokens, std::vector<int> &new_context_tokens, const int genamt, const int nctx)
751
+ {
752
+ //scan from start old and new ctx, until first mismatch found, save as p0
753
+ //check remaining old and new ctx for longest common subseq, which needs to be at 256 tokens
754
+ //test: longest common subseq (LCQ) MUST start within 0 tokens from end of memory, otherwise purge fails
755
+ //if passed, save beginning of LCQ from old ctx as p1
756
+ //remove all tokens from old ctx between p0 and p1, updating both arrays and kv, then continue as normal
757
+
758
+ const int short_fall_threshold = 200 + (nctx/30); //dont trigger shifting if the distance between trimstart and currhead < this
759
+ const int stack_allowance = 60 + (nctx/50); //in case the end text is slightly modified, be forgiving
760
+
761
+ int trimstart = 0;
762
+ int new_tokens_len = new_context_tokens.size();
763
+ bool purge_needed = true;
764
+
765
+ for (int i = 0; i < current_context_tokens.size(); ++i)
766
+ {
767
+ if (current_context_tokens[i] == new_context_tokens[i])
768
+ {
769
+ trimstart += 1;
770
+ }
771
+ else
772
+ {
773
+ break;
774
+ }
775
+ if ((i + 2) >= new_tokens_len)
776
+ {
777
+ purge_needed = false;
778
+ break; //no surgery required
779
+ }
780
+ }
781
+
782
+
783
+
784
+ if(!purge_needed || new_tokens_len < 6 || current_context_tokens.size() < 6 || new_tokens_len - trimstart < short_fall_threshold)
785
+ {
786
+ LOG_INFO("Fall Threshold: %d out of %d\n", new_tokens_len - trimstart, short_fall_threshold);
787
+ return; //no purge is needed
788
+ }
789
+
790
+ //at least this many tokens need to match, otherwise don't bother trimming
791
+ const int lc_tok_threshold = std::max(std::min((new_tokens_len - trimstart) - (genamt+stack_allowance), (int)(nctx*0.45)), short_fall_threshold - stack_allowance);
792
+
793
+ auto curr_ctx_without_memory = std::vector<int>(current_context_tokens.begin() + trimstart, current_context_tokens.end());
794
+ auto new_ctx_without_memory = std::vector<int>(new_context_tokens.begin() + trimstart, new_context_tokens.end());
795
+
796
+ auto shared = longest_common_subseq(curr_ctx_without_memory, new_ctx_without_memory);
797
+
798
+ if (shared.size() > lc_tok_threshold && arr_start_with(new_ctx_without_memory, shared)) // enough tokens in common
799
+ {
800
+ int found = arr_find_index_of(current_context_tokens,shared);
801
+ if(found>=0 && found > trimstart)
802
+ {
803
+
804
+ //extract the unwanted tokens out from context and KV
805
+ int diff = found - trimstart;
806
+ llama_kv_cache_seq_rm(ctx, 0, trimstart, trimstart + diff);
807
+ llama_kv_cache_seq_add(ctx, 0, trimstart + diff, -1, -diff);
808
+
809
+ for (size_t i = trimstart + diff; i < current_context_tokens.size() - 1; i++)
810
+ {
811
+ current_context_tokens[i - diff] = current_context_tokens[i];
812
+ }
813
+
814
+ LOG_INFO("\n[Context Shifting: Erased %d tokens at position %d]", diff, trimstart + 1);
815
+
816
+ current_context_tokens.resize(current_context_tokens.size() - diff);
817
+ }
818
+ }
819
+
820
+ }
821
+
822
+ }