cui-llama.rn 1.1.2 → 1.1.4

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.
package/cpp/llama.h CHANGED
@@ -34,12 +34,15 @@
34
34
 
35
35
  #define LLAMA_DEFAULT_SEED 0xFFFFFFFF
36
36
 
37
+ // TODO: use everywhere in the implementation
38
+ #define LLAMA_TOKEN_NULL -1
39
+
37
40
  #define LLAMA_FILE_MAGIC_GGLA 0x67676c61u // 'ggla'
38
41
  #define LLAMA_FILE_MAGIC_GGSN 0x6767736eu // 'ggsn'
39
42
  #define LLAMA_FILE_MAGIC_GGSQ 0x67677371u // 'ggsq'
40
43
 
41
44
  #define LLAMA_SESSION_MAGIC LLAMA_FILE_MAGIC_GGSN
42
- #define LLAMA_SESSION_VERSION 8
45
+ #define LLAMA_SESSION_VERSION 9
43
46
 
44
47
  #define LLAMA_STATE_SEQ_MAGIC LLAMA_FILE_MAGIC_GGSQ
45
48
  #define LLAMA_STATE_SEQ_VERSION 2
@@ -54,8 +57,10 @@ extern "C" {
54
57
  // TODO: show sample usage
55
58
  //
56
59
 
60
+ // struct llama_vocab; // TODO: add in the future
57
61
  struct llama_model;
58
62
  struct llama_context;
63
+ struct llama_sampler;
59
64
 
60
65
  typedef int32_t llama_pos;
61
66
  typedef int32_t llama_token;
@@ -67,6 +72,7 @@ extern "C" {
67
72
  LLAMA_VOCAB_TYPE_BPE = 2, // GPT-2 tokenizer based on byte-level BPE
68
73
  LLAMA_VOCAB_TYPE_WPM = 3, // BERT tokenizer based on WordPiece
69
74
  LLAMA_VOCAB_TYPE_UGM = 4, // T5 tokenizer based on Unigram
75
+ LLAMA_VOCAB_TYPE_RWKV = 5, // RWKV tokenizer based on greedy tokenization
70
76
  };
71
77
 
72
78
  // pre-tokenization types
@@ -167,6 +173,8 @@ extern "C" {
167
173
  LLAMA_FTYPE_MOSTLY_Q4_0_4_4 = 33, // except 1d tensors
168
174
  LLAMA_FTYPE_MOSTLY_Q4_0_4_8 = 34, // except 1d tensors
169
175
  LLAMA_FTYPE_MOSTLY_Q4_0_8_8 = 35, // except 1d tensors
176
+ LLAMA_FTYPE_MOSTLY_TQ1_0 = 36, // except 1d tensors
177
+ LLAMA_FTYPE_MOSTLY_TQ2_0 = 37, // except 1d tensors
170
178
 
171
179
  LLAMA_FTYPE_GUESSED = 1024, // not specified in the model file
172
180
  };
@@ -199,6 +207,7 @@ extern "C" {
199
207
  LLAMA_SPLIT_MODE_ROW = 2, // split rows across GPUs
200
208
  };
201
209
 
210
+ // TODO: simplify (https://github.com/ggerganov/llama.cpp/pull/9294#pullrequestreview-2286561979)
202
211
  typedef struct llama_token_data {
203
212
  llama_token id; // token id
204
213
  float logit; // log-odds of the token
@@ -206,8 +215,10 @@ extern "C" {
206
215
  } llama_token_data;
207
216
 
208
217
  typedef struct llama_token_data_array {
218
+ // TODO: consider SoA
209
219
  llama_token_data * data;
210
220
  size_t size;
221
+ int64_t selected; // this is the index in the data array (i.e. not the token id)
211
222
  bool sorted;
212
223
  } llama_token_data_array;
213
224
 
@@ -268,9 +279,9 @@ extern "C" {
268
279
  enum llama_split_mode split_mode; // how to split the model across multiple GPUs
269
280
 
270
281
  // main_gpu interpretation depends on split_mode:
271
- // LLAMA_SPLIT_NONE: the GPU that is used for the entire model
272
- // LLAMA_SPLIT_ROW: the GPU that is used for small tensors and intermediate results
273
- // LLAMA_SPLIT_LAYER: ignored
282
+ // LLAMA_SPLIT_MODE_NONE: the GPU that is used for the entire model
283
+ // LLAMA_SPLIT_MODE_ROW: the GPU that is used for small tensors and intermediate results
284
+ // LLAMA_SPLIT_MODE_LAYER: ignored
274
285
  int32_t main_gpu;
275
286
 
276
287
  // proportion of the model (layers or rows) to offload to each GPU, size: llama_max_devices()
@@ -300,13 +311,12 @@ extern "C" {
300
311
  // NOTE: changing the default values of parameters marked as [EXPERIMENTAL] may cause crashes or incorrect results in certain configurations
301
312
  // https://github.com/ggerganov/llama.cpp/pull/7544
302
313
  struct llama_context_params {
303
- uint32_t seed; // RNG seed, -1 for random
304
314
  uint32_t n_ctx; // text context, 0 = from model
305
315
  uint32_t n_batch; // logical maximum batch size that can be submitted to llama_decode
306
316
  uint32_t n_ubatch; // physical maximum batch size
307
317
  uint32_t n_seq_max; // max number of sequences (i.e. distinct states for recurrent models)
308
- uint32_t n_threads; // number of threads to use for generation
309
- uint32_t n_threads_batch; // number of threads to use for batch processing
318
+ int32_t n_threads; // number of threads to use for generation
319
+ int32_t n_threads_batch; // number of threads to use for batch processing
310
320
 
311
321
  enum llama_rope_scaling_type rope_scaling_type; // RoPE scaling type, from `enum llama_rope_scaling_type`
312
322
  enum llama_pooling_type pooling_type; // whether to pool (sum) embedding results by sequence id
@@ -328,11 +338,13 @@ extern "C" {
328
338
  enum lm_ggml_type type_k; // data type for K cache [EXPERIMENTAL]
329
339
  enum lm_ggml_type type_v; // data type for V cache [EXPERIMENTAL]
330
340
 
331
- // Keep the booleans together to avoid misalignment during copy-by-value.
341
+ // Keep the booleans together and at the end of the struct to avoid misalignment during copy-by-value.
342
+ // TODO: move at the end of the struct
332
343
  bool logits_all; // the llama_decode() call computes all logits, not just the last one (DEPRECATED - set llama_batch.logits instead)
333
344
  bool embeddings; // if true, extract embeddings (together with logits)
334
345
  bool offload_kqv; // whether to offload the KQV ops (including the KV cache) to GPU
335
346
  bool flash_attn; // whether to use flash attention [EXPERIMENTAL]
347
+ //bool no_perf; // whether to measure performance timings, TODO: implement
336
348
 
337
349
  // Abort callback
338
350
  // if it returns true, execution of llama_decode() will be aborted
@@ -356,56 +368,14 @@ extern "C" {
356
368
  void * kv_overrides; // pointer to vector containing overrides
357
369
  } llama_model_quantize_params;
358
370
 
359
- // grammar types
360
- struct llama_grammar;
361
-
362
- // grammar element type
363
- enum llama_gretype {
364
- // end of rule definition
365
- LLAMA_GRETYPE_END = 0,
366
-
367
- // start of alternate definition for rule
368
- LLAMA_GRETYPE_ALT = 1,
369
-
370
- // non-terminal element: reference to rule
371
- LLAMA_GRETYPE_RULE_REF = 2,
372
-
373
- // terminal element: character (code point)
374
- LLAMA_GRETYPE_CHAR = 3,
375
-
376
- // inverse char(s) ([^a], [^a-b] [^abc])
377
- LLAMA_GRETYPE_CHAR_NOT = 4,
371
+ typedef struct llama_logit_bias {
372
+ llama_token token;
373
+ float bias;
374
+ } llama_logit_bias;
378
375
 
379
- // modifies a preceding LLAMA_GRETYPE_CHAR or LLAMA_GRETYPE_CHAR_ALT to
380
- // be an inclusive range ([a-z])
381
- LLAMA_GRETYPE_CHAR_RNG_UPPER = 5,
382
-
383
- // modifies a preceding LLAMA_GRETYPE_CHAR or
384
- // LLAMA_GRETYPE_CHAR_RNG_UPPER to add an alternate char to match ([ab], [a-zA])
385
- LLAMA_GRETYPE_CHAR_ALT = 6,
386
-
387
- // any character (.)
388
- LLAMA_GRETYPE_CHAR_ANY = 7,
389
- };
390
-
391
- typedef struct llama_grammar_element {
392
- enum llama_gretype type;
393
- uint32_t value; // Unicode code point or rule ID
394
- } llama_grammar_element;
395
-
396
- // performance timing information
397
- struct llama_timings {
398
- double t_start_ms;
399
- double t_end_ms;
400
- double t_load_ms;
401
- double t_sample_ms;
402
- double t_p_eval_ms;
403
- double t_eval_ms;
404
-
405
- int32_t n_sample;
406
- int32_t n_p_eval;
407
- int32_t n_eval;
408
- };
376
+ typedef struct llama_sampler_chain_params {
377
+ bool no_perf; // whether to measure performance timings
378
+ } llama_sampler_chain_params;
409
379
 
410
380
  // used in chat template
411
381
  typedef struct llama_chat_message {
@@ -417,8 +387,10 @@ extern "C" {
417
387
  struct llama_lora_adapter;
418
388
 
419
389
  // Helpers for getting default parameters
420
- LLAMA_API struct llama_model_params llama_model_default_params(void);
421
- LLAMA_API struct llama_context_params llama_context_default_params(void);
390
+ // TODO: update API to start accepting pointers to params structs (https://github.com/ggerganov/llama.cpp/discussions/9172)
391
+ LLAMA_API struct llama_model_params llama_model_default_params(void);
392
+ LLAMA_API struct llama_context_params llama_context_default_params(void);
393
+ LLAMA_API struct llama_sampler_chain_params llama_sampler_chain_default_params(void);
422
394
  LLAMA_API struct llama_model_quantize_params llama_model_quantize_default_params(void);
423
395
 
424
396
  // Initialize the llama + ggml backend
@@ -429,15 +401,23 @@ extern "C" {
429
401
  //optional:
430
402
  LLAMA_API void llama_numa_init(enum lm_ggml_numa_strategy numa);
431
403
 
404
+ // Optional: an auto threadpool gets created in ggml if not passed explicitly
405
+ LLAMA_API void llama_attach_threadpool(
406
+ struct llama_context * ctx,
407
+ lm_ggml_threadpool_t threadpool,
408
+ lm_ggml_threadpool_t threadpool_batch);
409
+ LLAMA_API void llama_detach_threadpool(struct llama_context * ctx);
410
+
432
411
  // Call once at the end of the program - currently only used for MPI
433
412
  LLAMA_API void llama_backend_free(void);
434
413
 
435
414
  LLAMA_API struct llama_model * llama_load_model_from_file(
436
415
  const char * path_model,
437
- struct llama_model_params params);
416
+ struct llama_model_params params);
438
417
 
439
418
  LLAMA_API void llama_free_model(struct llama_model * model);
440
419
 
420
+ // TODO: rename to llama_init_from_model
441
421
  LLAMA_API struct llama_context * llama_new_context_with_model(
442
422
  struct llama_model * model,
443
423
  struct llama_context_params params);
@@ -453,23 +433,22 @@ extern "C" {
453
433
  LLAMA_API bool llama_supports_mlock (void);
454
434
  LLAMA_API bool llama_supports_gpu_offload(void);
455
435
 
456
- LLAMA_API const struct llama_model * llama_get_model(const struct llama_context * ctx);
457
-
458
436
  LLAMA_API uint32_t llama_n_ctx (const struct llama_context * ctx);
459
437
  LLAMA_API uint32_t llama_n_batch (const struct llama_context * ctx);
460
438
  LLAMA_API uint32_t llama_n_ubatch (const struct llama_context * ctx);
461
439
  LLAMA_API uint32_t llama_n_seq_max (const struct llama_context * ctx);
462
440
 
463
- LLAMA_API enum llama_pooling_type llama_pooling_type(const struct llama_context * ctx);
464
-
465
- LLAMA_API enum llama_vocab_type llama_vocab_type (const struct llama_model * model);
466
- LLAMA_API enum llama_rope_type llama_rope_type (const struct llama_model * model);
467
-
468
441
  LLAMA_API int32_t llama_n_vocab (const struct llama_model * model);
469
442
  LLAMA_API int32_t llama_n_ctx_train(const struct llama_model * model);
470
443
  LLAMA_API int32_t llama_n_embd (const struct llama_model * model);
471
444
  LLAMA_API int32_t llama_n_layer (const struct llama_model * model);
472
445
 
446
+ LLAMA_API const struct llama_model * llama_get_model(const struct llama_context * ctx);
447
+
448
+ LLAMA_API enum llama_pooling_type llama_pooling_type(const struct llama_context * ctx);
449
+ LLAMA_API enum llama_vocab_type llama_vocab_type (const struct llama_model * model);
450
+ LLAMA_API enum llama_rope_type llama_rope_type (const struct llama_model * model);
451
+
473
452
  // Get the model's RoPE frequency scaling factor
474
453
  LLAMA_API float llama_rope_freq_scale_train(const struct llama_model * model);
475
454
 
@@ -697,7 +676,7 @@ extern "C" {
697
676
  //
698
677
 
699
678
  // Returns the *actual* size in bytes of the state
700
- // (rng, logits, embedding and kv_cache)
679
+ // (logits, embedding and kv_cache)
701
680
  // Only use when saving the state, not when restoring it, otherwise the size may be too small.
702
681
  LLAMA_API size_t llama_state_get_size(struct llama_context * ctx);
703
682
  LLAMA_API DEPRECATED(size_t llama_get_state_size(struct llama_context * ctx),
@@ -838,13 +817,13 @@ extern "C" {
838
817
  // Set the number of threads used for decoding
839
818
  // n_threads is the number of threads used for generation (single token)
840
819
  // n_threads_batch is the number of threads used for prompt and batch processing (multiple tokens)
841
- LLAMA_API void llama_set_n_threads(struct llama_context * ctx, uint32_t n_threads, uint32_t n_threads_batch);
820
+ LLAMA_API void llama_set_n_threads(struct llama_context * ctx, int32_t n_threads, int32_t n_threads_batch);
842
821
 
843
822
  // Get the number of threads used for generation of a single token.
844
- LLAMA_API uint32_t llama_n_threads(struct llama_context * ctx);
823
+ LLAMA_API int32_t llama_n_threads(struct llama_context * ctx);
845
824
 
846
825
  // Get the number of threads used for prompt and batch processing (multiple token).
847
- LLAMA_API uint32_t llama_n_threads_batch(struct llama_context * ctx);
826
+ LLAMA_API int32_t llama_n_threads_batch(struct llama_context * ctx);
848
827
 
849
828
  // Set whether the model is in embeddings mode or not
850
829
  // If true, embeddings will be returned but logits will not
@@ -1000,130 +979,113 @@ extern "C" {
1000
979
  int32_t length);
1001
980
 
1002
981
  //
1003
- // Grammar
982
+ // Sampling API
983
+ //
984
+ // Sample usage:
985
+ //
986
+ // // prepare the sampling chain at the start
987
+ // auto sparams = llama_sampler_chain_default_params();
988
+ //
989
+ // llama_sampler * smpl = llama_sampler_chain_init(sparams);
990
+ //
991
+ // llama_sampler_chain_add(smpl, llama_sampler_init_top_k(50));
992
+ // llama_sampler_chain_add(smpl, llama_sampler_init_top_p(0.9, 1));
993
+ // llama_sampler_chain_add(smpl, llama_sampler_init_temp (0.8));
994
+ //
995
+ // // typically, the chain should end with a sampler such as "greedy", "dist" or "mirostat"
996
+ // // this sampler will be responsible to select the actual token
997
+ // llama_sampler_chain_add(smpl, llama_sampler_init_dist(seed));
998
+ //
999
+ // ...
1000
+ //
1001
+ // // decoding loop:
1002
+ // while (...) {
1003
+ // ...
1004
+ //
1005
+ // llama_decode(ctx, batch);
1006
+ //
1007
+ // // sample from the logits of the last token in the batch
1008
+ // const llama_token id = llama_sampler_sample(smpl, ctx, -1);
1009
+ //
1010
+ // // accepting the token updates the internal state of certain samplers (e.g. grammar, repetition, etc.)
1011
+ // llama_sampler_accept(smpl, id);
1012
+ // ...
1013
+ // }
1014
+ //
1015
+ // llama_sampler_free(smpl);
1016
+ //
1017
+ // TODO: In the future, llama_sampler will be utilized to offload the sampling to the backends (e.g. GPU).
1018
+ // TODO: in the future, the entire sampling API that uses llama_model should start using llama_vocab
1004
1019
  //
1005
1020
 
1006
- /// Initialize a llama_grammar.
1007
- ///
1008
- /// @param rules The rule elements of the grammar to initialize.
1009
- /// @param n_rules The number of rules.
1010
- /// @param start_rule_index The index of the root rule (the starting point of the grammar).
1011
- /// @return The initialized llama_grammar or nullptr if initialization failed.
1012
- LLAMA_API struct llama_grammar * llama_grammar_init(
1013
- const llama_grammar_element ** rules,
1014
- size_t n_rules,
1015
- size_t start_rule_index);
1016
-
1017
- LLAMA_API void llama_grammar_free(struct llama_grammar * grammar);
1018
-
1019
- LLAMA_API struct llama_grammar * llama_grammar_copy(const struct llama_grammar * grammar);
1020
-
1021
- /// @details Apply constraints from grammar
1022
- LLAMA_API void llama_grammar_sample(
1023
- const struct llama_grammar * grammar,
1024
- const struct llama_context * ctx,
1025
- llama_token_data_array * candidates);
1026
- LLAMA_API DEPRECATED(void llama_sample_grammar(
1027
- struct llama_context * ctx,
1028
- llama_token_data_array * candidates,
1029
- const struct llama_grammar * grammar),
1030
- "use llama_grammar_sample instead");
1021
+ typedef void * llama_sampler_context_t;
1031
1022
 
1032
- /// @details Accepts the sampled token into the grammar
1033
- LLAMA_API void llama_grammar_accept_token(
1034
- struct llama_grammar * grammar,
1035
- struct llama_context * ctx,
1036
- llama_token token);
1023
+ // user code can implement the interface below in order to create custom llama_sampler
1024
+ struct llama_sampler_i {
1025
+ const char * (*name) (const struct llama_sampler * smpl); // can be NULL
1026
+ void (*accept)( struct llama_sampler * smpl, llama_token token); // can be NULL
1027
+ void (*apply) ( struct llama_sampler * smpl, llama_token_data_array * cur_p); // required
1028
+ void (*reset) ( struct llama_sampler * smpl); // can be NULL
1029
+ struct llama_sampler * (*clone) (const struct llama_sampler * smpl); // can be NULL if ctx is NULL
1030
+ void (*free) ( struct llama_sampler * smpl); // can be NULL if ctx is NULL
1037
1031
 
1038
- //
1039
- // Sampling functions
1040
- //
1032
+ // TODO: API for internal libllama usage for appending the sampling to an existing lm_ggml_cgraph
1033
+ //void (*apply_ggml) (struct llama_sampler * smpl, ...);
1034
+ };
1035
+
1036
+ struct llama_sampler {
1037
+ struct llama_sampler_i * iface;
1038
+ llama_sampler_context_t ctx;
1039
+ };
1041
1040
 
1042
- // Sets the current rng seed.
1043
- LLAMA_API void llama_set_rng_seed(struct llama_context * ctx, uint32_t seed);
1041
+ // mirror of llama_sampler_i:
1042
+ LLAMA_API const char * llama_sampler_name (const struct llama_sampler * smpl);
1043
+ LLAMA_API void llama_sampler_accept( struct llama_sampler * smpl, llama_token token);
1044
+ LLAMA_API void llama_sampler_apply ( struct llama_sampler * smpl, llama_token_data_array * cur_p);
1045
+ LLAMA_API void llama_sampler_reset ( struct llama_sampler * smpl);
1046
+ LLAMA_API struct llama_sampler * llama_sampler_clone (const struct llama_sampler * smpl);
1047
+ // important: do not free if the sampler has been added to a llama_sampler_chain (via llama_sampler_chain_add)
1048
+ LLAMA_API void llama_sampler_free ( struct llama_sampler * smpl);
1044
1049
 
1045
- /// @details Repetition penalty described in CTRL academic paper https://arxiv.org/abs/1909.05858, with negative logit fix.
1046
- /// @details Frequency and presence penalties described in OpenAI API https://platform.openai.com/docs/api-reference/parameter-details.
1047
- LLAMA_API void llama_sample_repetition_penalties(
1048
- struct llama_context * ctx,
1049
- llama_token_data_array * candidates,
1050
- const llama_token * last_tokens,
1051
- size_t penalty_last_n,
1052
- float penalty_repeat,
1053
- float penalty_freq,
1054
- float penalty_present);
1055
-
1056
- /// @details Apply classifier-free guidance to the logits as described in academic paper "Stay on topic with Classifier-Free Guidance" https://arxiv.org/abs/2306.17806
1057
- /// @param logits Logits extracted from the original generation context.
1058
- /// @param logits_guidance Logits extracted from a separate context from the same model. Other than a negative prompt at the beginning, it should have all generated and user input tokens copied from the main context.
1059
- /// @param scale Guidance strength. 1.0f means no guidance. Higher values mean stronger guidance.
1060
- LLAMA_API void llama_sample_apply_guidance(
1061
- struct llama_context * ctx,
1062
- float * logits,
1063
- float * logits_guidance,
1064
- float scale);
1050
+ // llama_sampler_chain
1051
+ // a type of llama_sampler that can chain multiple samplers one after another
1052
+
1053
+ LLAMA_API struct llama_sampler * llama_sampler_chain_init(struct llama_sampler_chain_params params);
1054
+
1055
+ // important: takes ownership of the sampler object and will free it when llama_sampler_free is called
1056
+ LLAMA_API void llama_sampler_chain_add( struct llama_sampler * chain, struct llama_sampler * smpl);
1057
+ LLAMA_API struct llama_sampler * llama_sampler_chain_get(const struct llama_sampler * chain, int32_t i);
1058
+ LLAMA_API int llama_sampler_chain_n (const struct llama_sampler * chain);
1059
+
1060
+ // available samplers:
1061
+
1062
+ LLAMA_API struct llama_sampler * llama_sampler_init_greedy (void);
1063
+ LLAMA_API struct llama_sampler * llama_sampler_init_dist (uint32_t seed);
1065
1064
 
1066
1065
  /// @details Sorts candidate tokens by their logits in descending order and calculate probabilities based on logits.
1067
- LLAMA_API void llama_sample_softmax(
1068
- struct llama_context * ctx,
1069
- llama_token_data_array * candidates);
1066
+ LLAMA_API struct llama_sampler * llama_sampler_init_softmax (void);
1070
1067
 
1071
1068
  /// @details Top-K sampling described in academic paper "The Curious Case of Neural Text Degeneration" https://arxiv.org/abs/1904.09751
1072
- LLAMA_API void llama_sample_top_k(
1073
- struct llama_context * ctx,
1074
- llama_token_data_array * candidates,
1075
- int32_t k,
1076
- size_t min_keep);
1069
+ LLAMA_API struct llama_sampler * llama_sampler_init_top_k (int32_t k);
1077
1070
 
1078
1071
  /// @details Nucleus sampling described in academic paper "The Curious Case of Neural Text Degeneration" https://arxiv.org/abs/1904.09751
1079
- LLAMA_API void llama_sample_top_p(
1080
- struct llama_context * ctx,
1081
- llama_token_data_array * candidates,
1082
- float p,
1083
- size_t min_keep);
1072
+ LLAMA_API struct llama_sampler * llama_sampler_init_top_p (float p, size_t min_keep);
1084
1073
 
1085
1074
  /// @details Minimum P sampling as described in https://github.com/ggerganov/llama.cpp/pull/3841
1086
- LLAMA_API void llama_sample_min_p(
1087
- struct llama_context * ctx,
1088
- llama_token_data_array * candidates,
1089
- float p,
1090
- size_t min_keep);
1091
-
1092
- /// @details XTC sampling
1093
- LLAMA_API void llama_sample_xtc(
1094
- struct llama_context * ctx,
1095
- llama_token_data_array * candidates,
1096
- float xtc_threshold,
1097
- float xtc_probability,
1098
- size_t min_keep,
1099
- std::mt19937 rng);
1075
+ LLAMA_API struct llama_sampler * llama_sampler_init_min_p (float p, size_t min_keep);
1076
+
1077
+ /// @details XTC sampling as described in https://github.com/oobabooga/text-generation-webui/pull/6335
1078
+ LLAMA_API struct llama_sampler * llama_sampler_init_xtc (float xtc_p, float xtc_t, size_t min_keep, uint32_t seed);
1100
1079
 
1101
1080
  /// @details Tail Free Sampling described in https://www.trentonbricken.com/Tail-Free-Sampling/.
1102
- LLAMA_API void llama_sample_tail_free(
1103
- struct llama_context * ctx,
1104
- llama_token_data_array * candidates,
1105
- float z,
1106
- size_t min_keep);
1081
+ LLAMA_API struct llama_sampler * llama_sampler_init_tail_free (float z, size_t min_keep);
1107
1082
 
1108
1083
  /// @details Locally Typical Sampling implementation described in the paper https://arxiv.org/abs/2202.00666.
1109
- LLAMA_API void llama_sample_typical(
1110
- struct llama_context * ctx,
1111
- llama_token_data_array * candidates,
1112
- float p,
1113
- size_t min_keep);
1084
+ LLAMA_API struct llama_sampler * llama_sampler_init_typical (float p, size_t min_keep);
1085
+ LLAMA_API struct llama_sampler * llama_sampler_init_temp (float t);
1114
1086
 
1115
- /// @details Dynamic temperature implementation described in the paper https://arxiv.org/abs/2309.02772.
1116
- LLAMA_API void llama_sample_entropy(
1117
- struct llama_context * ctx,
1118
- llama_token_data_array * candidates_p,
1119
- float min_temp,
1120
- float max_temp,
1121
- float exponent_val);
1122
-
1123
- LLAMA_API void llama_sample_temp(
1124
- struct llama_context * ctx,
1125
- llama_token_data_array * candidates,
1126
- float temp);
1087
+ /// @details Dynamic temperature implementation (a.k.a. entropy) described in the paper https://arxiv.org/abs/2309.02772.
1088
+ LLAMA_API struct llama_sampler * llama_sampler_init_temp_ext (float t, float delta, float exponent);
1127
1089
 
1128
1090
  /// @details Mirostat 1.0 algorithm described in the paper https://arxiv.org/abs/2007.14966. Uses tokens instead of words.
1129
1091
  /// @param candidates A vector of `llama_token_data` containing the candidate tokens, their probabilities (p), and log-odds (logit) for the current position in the generated text.
@@ -1131,36 +1093,57 @@ extern "C" {
1131
1093
  /// @param eta The learning rate used to update `mu` based on the error between the target and observed surprisal of the sampled word. A larger learning rate will cause `mu` to be updated more quickly, while a smaller learning rate will result in slower updates.
1132
1094
  /// @param m The number of tokens considered in the estimation of `s_hat`. This is an arbitrary value that is used to calculate `s_hat`, which in turn helps to calculate the value of `k`. In the paper, they use `m = 100`, but you can experiment with different values to see how it affects the performance of the algorithm.
1133
1095
  /// @param mu Maximum cross-entropy. This value is initialized to be twice the target cross-entropy (`2 * tau`) and is updated in the algorithm based on the error between the target and observed surprisal.
1134
- LLAMA_API llama_token llama_sample_token_mirostat(
1135
- struct llama_context * ctx,
1136
- llama_token_data_array * candidates,
1137
- float tau,
1138
- float eta,
1139
- int32_t m,
1140
- float * mu);
1096
+ LLAMA_API struct llama_sampler * llama_sampler_init_mirostat(
1097
+ int32_t n_vocab,
1098
+ uint32_t seed,
1099
+ float tau,
1100
+ float eta,
1101
+ int32_t m);
1141
1102
 
1142
1103
  /// @details Mirostat 2.0 algorithm described in the paper https://arxiv.org/abs/2007.14966. Uses tokens instead of words.
1143
1104
  /// @param candidates A vector of `llama_token_data` containing the candidate tokens, their probabilities (p), and log-odds (logit) for the current position in the generated text.
1144
1105
  /// @param tau The target cross-entropy (or surprise) value you want to achieve for the generated text. A higher value corresponds to more surprising or less predictable text, while a lower value corresponds to less surprising or more predictable text.
1145
1106
  /// @param eta The learning rate used to update `mu` based on the error between the target and observed surprisal of the sampled word. A larger learning rate will cause `mu` to be updated more quickly, while a smaller learning rate will result in slower updates.
1146
1107
  /// @param mu Maximum cross-entropy. This value is initialized to be twice the target cross-entropy (`2 * tau`) and is updated in the algorithm based on the error between the target and observed surprisal.
1147
- LLAMA_API llama_token llama_sample_token_mirostat_v2(
1148
- struct llama_context * ctx,
1149
- llama_token_data_array * candidates,
1150
- float tau,
1151
- float eta,
1152
- float * mu);
1153
-
1154
- /// @details Selects the token with the highest probability.
1155
- /// Does not compute the token probabilities. Use llama_sample_softmax() instead.
1156
- LLAMA_API llama_token llama_sample_token_greedy(
1157
- struct llama_context * ctx,
1158
- llama_token_data_array * candidates);
1108
+ LLAMA_API struct llama_sampler * llama_sampler_init_mirostat_v2(
1109
+ uint32_t seed,
1110
+ float tau,
1111
+ float eta);
1112
+
1113
+ LLAMA_API struct llama_sampler * llama_sampler_init_grammar(
1114
+ const struct llama_model * model,
1115
+ const char * grammar_str,
1116
+ const char * grammar_root);
1117
+
1118
+ LLAMA_API struct llama_sampler * llama_sampler_init_penalties(
1119
+ int32_t n_vocab, // llama_n_vocab()
1120
+ llama_token special_eos_id, // llama_token_eos()
1121
+ llama_token linefeed_id, // llama_token_nl()
1122
+ int32_t penalty_last_n, // last n tokens to penalize (0 = disable penalty, -1 = context size)
1123
+ float penalty_repeat, // 1.0 = disabled
1124
+ float penalty_freq, // 0.0 = disabled
1125
+ float penalty_present, // 0.0 = disabled
1126
+ bool penalize_nl, // consider newlines as a repeatable token
1127
+ bool ignore_eos); // ignore the end-of-sequence token
1128
+
1129
+ LLAMA_API struct llama_sampler * llama_sampler_init_logit_bias(
1130
+ int32_t n_vocab,
1131
+ int32_t n_logit_bias,
1132
+ const llama_logit_bias * logit_bias);
1133
+
1134
+ // Shorthand for:
1135
+ //
1136
+ // const auto * logits = llama_get_logits_ith(ctx, idx);
1137
+ // llama_token_data_array cur_p = { ... init from logits ... };
1138
+ // llama_sampler_apply(smpl, &cur_p);
1139
+ // return cur_p.data[cur_p.selected].id;
1140
+ //
1141
+ // At this point, this is mostly a convenience function.
1142
+ //
1143
+ LLAMA_API llama_token llama_sampler_sample(struct llama_sampler * smpl, struct llama_context * ctx, int32_t idx);
1159
1144
 
1160
- /// @details Randomly selects a token from the candidates based on their probabilities using the RNG of ctx.
1161
- LLAMA_API llama_token llama_sample_token(
1162
- struct llama_context * ctx,
1163
- llama_token_data_array * candidates);
1145
+ // TODO: extend in the future
1146
+ //LLAMA_API void llama_decode_with_sampler(struct llama_context * ctx, struct llama_sampler * smpl, struct llama_batch batch, ...);
1164
1147
 
1165
1148
  //
1166
1149
  // Model split
@@ -1176,12 +1159,6 @@ extern "C" {
1176
1159
  // Returns the split_prefix length.
1177
1160
  LLAMA_API int llama_split_prefix(char * split_prefix, size_t maxlen, const char * split_path, int split_no, int split_count);
1178
1161
 
1179
- // Performance information
1180
- LLAMA_API struct llama_timings llama_get_timings(struct llama_context * ctx);
1181
-
1182
- LLAMA_API void llama_print_timings(struct llama_context * ctx);
1183
- LLAMA_API void llama_reset_timings(struct llama_context * ctx);
1184
-
1185
1162
  // Print system information
1186
1163
  LLAMA_API const char * llama_print_system_info(void);
1187
1164
 
@@ -1189,65 +1166,42 @@ extern "C" {
1189
1166
  // If this is not called, or NULL is supplied, everything is output on stderr.
1190
1167
  LLAMA_API void llama_log_set(lm_ggml_log_callback log_callback, void * user_data);
1191
1168
 
1192
- LLAMA_API void llama_dump_timing_info_yaml(FILE * stream, const struct llama_context * ctx);
1193
-
1194
- #ifdef __cplusplus
1195
- }
1196
- #endif
1197
-
1198
- // Internal API to be implemented by llama.cpp and used by tests/benchmarks only
1199
- #ifdef LLAMA_API_INTERNAL
1200
-
1201
- #include <random>
1202
- #include <string>
1203
- #include <vector>
1204
-
1205
- struct lm_ggml_tensor;
1206
-
1207
- const std::vector<std::pair<std::string, struct lm_ggml_tensor *>> & llama_internal_get_tensor_map(
1208
- struct llama_context * ctx
1209
- );
1210
-
1211
- struct llama_partial_utf8 {
1212
- uint32_t value; // bit value so far (unshifted)
1213
- int n_remain; // num bytes remaining; -1 indicates invalid sequence
1214
- };
1215
-
1216
- struct llama_grammar_candidate {
1217
- size_t index;
1218
- const uint32_t * code_points;
1219
- llama_partial_utf8 partial_utf8;
1220
- };
1221
-
1222
- using llama_grammar_rule = std::vector< llama_grammar_element>;
1223
- using llama_grammar_stack = std::vector<const llama_grammar_element *>;
1224
-
1225
- using llama_grammar_rules = std::vector<llama_grammar_rule>;
1226
- using llama_grammar_stacks = std::vector<llama_grammar_stack>;
1227
- using llama_grammar_candidates = std::vector<llama_grammar_candidate>;
1169
+ //
1170
+ // Performance utils
1171
+ //
1172
+ // NOTE: Used by llama.cpp examples, avoid using in third-party apps. Instead, do your own performance measurements.
1173
+ //
1228
1174
 
1229
- const llama_grammar_rules & llama_grammar_get_rules (const struct llama_grammar * grammar);
1230
- llama_grammar_stacks & llama_grammar_get_stacks( struct llama_grammar * grammar);
1175
+ enum llama_perf_type {
1176
+ LLAMA_PERF_TYPE_CONTEXT = 0,
1177
+ LLAMA_PERF_TYPE_SAMPLER_CHAIN = 1,
1178
+ };
1231
1179
 
1232
- void llama_grammar_accept(
1233
- const llama_grammar_rules & rules,
1234
- const llama_grammar_stacks & stacks,
1235
- const uint32_t chr,
1236
- llama_grammar_stacks & new_stacks);
1180
+ LLAMA_API void llama_perf_print(const void * ctx, enum llama_perf_type type);
1181
+ LLAMA_API void llama_perf_reset( void * ctx, enum llama_perf_type type);
1237
1182
 
1238
- std::vector<llama_grammar_candidate> llama_grammar_reject_candidates_for_stack(
1239
- const llama_grammar_rules & rules,
1240
- const llama_grammar_stack & stack,
1241
- const llama_grammar_candidates & candidates);
1183
+ LLAMA_API void llama_perf_dump_yaml(FILE * stream, const struct llama_context * ctx);
1242
1184
 
1243
- std::pair<std::vector<uint32_t>, llama_partial_utf8> decode_utf8(
1244
- const std::string & src,
1245
- llama_partial_utf8 partial_start);
1185
+ // Keeps timings of samplers
1186
+ LLAMA_API struct llama_sampler_timings {int64_t t_sample_us; int32_t n_sample;};
1187
+ LLAMA_API struct llama_token_timings {
1188
+ double t_start_ms;
1189
+ double t_end_ms;
1190
+ double t_load_ms;
1191
+ double t_p_eval_ms;
1192
+ double t_eval_ms;
1246
1193
 
1247
- // Randomly selects a token from the candidates based on their probabilities using given std::mt19937.
1248
- // This is a temporary workaround in order to fix race conditions when sampling with multiple sequences.
1249
- llama_token llama_sample_token_with_rng(struct llama_context * ctx, llama_token_data_array * candidates, std::mt19937 & rng);
1194
+ int32_t n_p_eval;
1195
+ int32_t n_eval;
1196
+ };
1197
+
1198
+ // helper function for getting timings
1199
+ LLAMA_API struct llama_token_timings llama_get_token_timings(const void * v_ctx) ;
1200
+ LLAMA_API struct llama_sampler_timings llama_sampler_chain_timings(struct llama_sampler * chain);
1201
+ LLAMA_API struct llama_sampler_timings gpt_sampler_get_timigs(const struct gpt_sampler * gsmpl);
1202
+ #ifdef __cplusplus
1203
+ }
1204
+ #endif
1250
1205
 
1251
- #endif // LLAMA_API_INTERNAL
1252
1206
 
1253
1207
  #endif // LLAMA_H