Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
276 changes: 249 additions & 27 deletions common/sampling.cpp

Large diffs are not rendered by default.

26 changes: 26 additions & 0 deletions common/sampling.h
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,10 @@ void common_sampler_free(struct common_sampler * gsmpl);
// if is_generated is true, the token is accepted by the sampling chain, the reasoning budget sampler, and the grammar sampler
void common_sampler_accept(struct common_sampler * gsmpl, llama_token token, bool is_generated);
void common_sampler_reset (struct common_sampler * gsmpl);

// Continuum fork: the ballpark sampling path's counters (CONTINUUM-ENGINE 4.7.13)
void common_sampler_coarse_stats(const struct common_sampler * gsmpl, size_t * cap, uint64_t * calls,
uint64_t * reseeds, uint64_t * widens, uint64_t * candidates);
struct common_sampler * common_sampler_clone (struct common_sampler * gsmpl);
void common_sampler_copy (const struct common_sampler * src, struct common_sampler * dst);

Expand All @@ -67,6 +71,28 @@ struct llama_sampler * common_sampler_get(const struct common_sampler * gsmpl);
//
llama_token common_sampler_sample(struct common_sampler * gsmpl, struct llama_context * ctx, int idx, bool grammar_first = false);

// One output row's sampling input, gathered from the context by the thread that owns it. Sampling from a
// row reads no context state, so the rows of one decode step sample on many lanes at once (continuum
// CONTINUUM-ENGINE 4.7.14). common_sampler_row_ith synchronizes the context first.
struct common_sampler_row {
const float * logits = nullptr;
const float * sampled_probs = nullptr;
const float * sampled_logits = nullptr;
const llama_token * sampled_ids = nullptr;
uint32_t n_sampled_probs = 0;
uint32_t n_sampled_logits = 0;
llama_token sampled_token = LLAMA_TOKEN_NULL; // a backend sampler's choice, if any
int32_t n_vocab = 0;
};

common_sampler_row common_sampler_row_ith(struct llama_context * ctx, int idx);

// common_sampler_sample over a gathered row: touches only `gsmpl`
llama_token common_sampler_sample_row(struct common_sampler * gsmpl, const common_sampler_row & row, bool grammar_first = false);

// common_sampler_sample_and_accept_n over gathered rows (rows.size() == draft.size() + 1): touches only `gsmpl`
std::vector<llama_token> common_sampler_sample_and_accept_rows(struct common_sampler * gsmpl, const std::vector<common_sampler_row> & rows, const llama_tokens & draft, bool grammar_first = false);

// generalized version of common_sampler_sample
//
// will cross-reference the sampled tokens with a batch of draft tokens and accept those that match
Expand Down
4 changes: 2 additions & 2 deletions common/speculative.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2677,8 +2677,8 @@ void common_speculative_draft(common_speculative * spec) {
}

if (!result.empty()) {
SPC_DBG("called impl %s, hist size = %zu, call_count = %zu, gen = %zu\n",
common_speculative_type_to_str(impl.get()->type).c_str(), dp.prompt->size(),
SPC_DBG("called impl %s, n_past = %zu, call_count = %zu, gen = %zu\n",
common_speculative_type_to_str(impl.get()->type).c_str(), (size_t) dp.n_past,
impl.get()->n_call_draft, result.size());

// remember which implementation was used
Expand Down
75 changes: 58 additions & 17 deletions src/llama-sampler.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2954,26 +2954,66 @@ static void llama_sampler_penalties_apply(struct llama_sampler * smpl, llama_tok
return;
}

// Apply frequency and presence penalties to the cur_p
for (size_t i = 0; i < cur_p->size; ++i) {
const auto token_iter = ctx->token_count.find(cur_p->data[i].id);
if (token_iter == ctx->token_count.end()) {
continue;
// The academic publication that described this technique actually just only divided, but that would cause tokens with negative logits to become more likely, which is obviously wrong.
// This is common fix for this problem, which is to multiply by the penalty instead of dividing.
const auto penalize = [ctx](llama_token_data & d, int count) {
assert(count > 0 && count <= ctx->penalty_last_n);
if (d.logit <= 0) {
d.logit *= ctx->penalty_repeat;
} else {
d.logit /= ctx->penalty_repeat;
}
d.logit -= float(count) * ctx->penalty_freq + float(count > 0) * ctx->penalty_present;
};

const int count = token_iter->second;

assert(count > 0 && count <= ctx->penalty_last_n);
// Continuum fork (CONTINUUM-ENGINE 4.7.13): only tokens in the recent history can be penalized, at most
// penalty_last_n of them, so walk THEM, not the whole vocabulary. While the candidates are still in
// token-id order (data[id].id == id: penalties ran first, as in the default chain) each one is applied
// in place at data[id]: O(history) per token instead of O(vocab) hash lookups.
if (cur_p->size > ctx->token_count.size()) {
bool aligned = true;
for (const auto & [id, count] : ctx->token_count) {
if (id < 0 || (size_t) id >= cur_p->size || cur_p->data[id].id != id) {
aligned = false;
break;
}
}
if (aligned) {
for (const auto & [id, count] : ctx->token_count) {
penalize(cur_p->data[id], count);
}
cur_p->sorted = false;
return;
}
}

// The academic publication that described this technique actually just only divided, but that would cause tokens with negative logits to become more likely, which is obviously wrong.
// This is common fix for this problem, which is to multiply by the penalty instead of dividing.
if (cur_p->data[i].logit <= 0) {
cur_p->data[i].logit *= ctx->penalty_repeat;
} else {
cur_p->data[i].logit /= ctx->penalty_repeat;
// a candidate SUBSET still in token-id order (e.g. a ballpark cut, common/sampling.cpp): find each
// history token by binary search, O(history x log n), instead of a hash lookup per candidate
if (cur_p->size > 1) {
bool by_id = true;
for (size_t i = 1; i < cur_p->size; ++i) {
if (cur_p->data[i].id <= cur_p->data[i - 1].id) { by_id = false; break; }
}
if (by_id) {
const auto first = cur_p->data, last = cur_p->data + cur_p->size;
for (const auto & [id, count] : ctx->token_count) {
const auto it = std::lower_bound(first, last, id, [](const llama_token_data & d, llama_token v) { return d.id < v; });
if (it != last && it->id == id) {
penalize(*it, count);
}
}
cur_p->sorted = false;
return;
}
}

cur_p->data[i].logit -= float(count) * ctx->penalty_freq + float(count > 0) * ctx->penalty_present;
// candidates reordered or truncated by an earlier sampler: the array is the smaller side
for (size_t i = 0; i < cur_p->size; ++i) {
const auto token_iter = ctx->token_count.find(cur_p->data[i].id);
if (token_iter == ctx->token_count.end()) {
continue;
}
penalize(cur_p->data[i], token_iter->second);
}

cur_p->sorted = false;
Expand Down Expand Up @@ -3921,12 +3961,13 @@ static void llama_sampler_logit_bias_apply(struct llama_sampler * smpl, llama_to
return;
}

// search for the remaining candidates that were not found in the previous step
// search for the remaining candidates that were not found in the previous step. Every matching bias
// applies, as on the in-place path above: two biases on one token sum on both paths (Continuum fork:
// the subset path stopped at the first, which ballpark sampling exposed; Codex on #122)
for (size_t i = 0; i < cur_p->size; ++i) {
for (const auto & lb : ctx->to_search) {
if (cur_p->data[i].id == lb.token) {
cur_p->data[i].logit += lb.bias;
break;
}
}
}
Expand Down
2 changes: 2 additions & 0 deletions tests/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,8 @@ if (LLAMA_LLGUIDANCE)
endif ()

llama_build(test-recurrent-state-rollback.cpp)
llama_build_and_test(test-sampler-penalties.cpp)
llama_build(test-sampler-coarse.cpp) # needs -m <model>: ballpark sampling picks exactly the full path's token
llama_build_and_test(test-server-view-end.cpp)

# GGML_TENSOR_FLAG_GRAD: a leaf whose gradient the backward computes, never optimized (the walk reads the cached prefix K/V gradient)
Expand Down
Loading