MCPcopy Create free account
hub / github.com/appdevforall/CodeOnTheGo / common_sampler_sample

Function common_sampler_sample

subprojects/llama.cpp/common/sampling.cpp:449–519  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

447}
448
449llama_token common_sampler_sample(struct common_sampler * gsmpl, struct llama_context * ctx, int idx, bool grammar_first) {
450 llama_synchronize(ctx);
451
452 // start measuring sampling time after the llama_context synchronization in order to not measure any ongoing async operations
453 const auto tm = gsmpl->tm();
454
455 llama_token id = LLAMA_TOKEN_NULL;
456
457 auto & grmr = gsmpl->grmr;
458 auto & chain = gsmpl->chain;
459 auto & cur_p = gsmpl->cur_p; // initialized by set_logits
460
461 // Check if a backend sampler has already sampled a token in which case we
462 // return that token id directly.
463 {
464 id = llama_get_sampled_token_ith(ctx, idx);
465
466 if (id != LLAMA_TOKEN_NULL) {
467 LOG_DBG("%s: Backend sampler selected token: '%d'. Will not run any CPU samplers\n", __func__, id);
468
469 GGML_ASSERT(!gsmpl->grmr && "using grammar in combination with backend sampling is not supported");
470
471 // TODO: simplify
472 gsmpl->cur.resize(1);
473 gsmpl->cur[0] = { id, 0.0f, 1.0f };
474 cur_p = { gsmpl->cur.data(), gsmpl->cur.size(), 0, true };
475
476 return id;
477 }
478 }
479
480 gsmpl->set_logits(ctx, idx);
481
482 if (grammar_first) {
483 llama_sampler_apply(grmr, &cur_p);
484 }
485
486 llama_sampler_apply(chain, &cur_p);
487
488 id = cur_p.data[cur_p.selected].id;
489
490 if (grammar_first) {
491 return id;
492 }
493
494 // check if it the sampled token fits the grammar (grammar-based rejection sampling)
495 {
496 llama_token_data single_token_data = { id, 1.0f, 0.0f };
497 llama_token_data_array single_token_data_array = { &single_token_data, 1, -1, false };
498
499 llama_sampler_apply(grmr, &single_token_data_array);
500
501 const bool is_valid = single_token_data_array.data[0].logit != -INFINITY;
502 if (is_valid) {
503 return id;
504 }
505 }
506

Callers 7

mainFunction · 0.85
generate_responseFunction · 0.85
mainFunction · 0.85
update_slotsMethod · 0.85
mainFunction · 0.85
draftMethod · 0.85

Calls 8

llama_synchronizeFunction · 0.85
llama_sampler_applyFunction · 0.85
tmMethod · 0.80
set_logitsMethod · 0.80
sizeMethod · 0.65
resizeMethod · 0.45
dataMethod · 0.45

Tested by 2

mainFunction · 0.68
draftMethod · 0.68