Skip to content

Commit c3e9fc7

Browse files
sayapIwan Kawrakow
andcommitted
Fix logprobs
This commit is mostly a cherry-pick of ggml-org/llama.cpp#10783, plus optimization to do partial sort when sorting the logits. That mainline PR and friends were partially cherry-picked by ikawrakow#723, but wasn't really in a working state yet. A couple of additional changes: * Include timing information in response, which was (unintentionally?) done in mainline since ggml-org/llama.cpp#10643. * Also return the actual logprobs for accepted draft tokens. This is still a TODO in mainline [1]. Note that there is a TG performance penalty to return the logprobs, as we need to sort the logits. By doing partial sort, the penalty is quite small. Here are some numbers I got using the same prompt: This PR with partial sort: * no draft, no logprobs: 12.87 tok/s * no draft, with logprobs: 12.61 tok/s (2.0% drop) * with draft, no logprobs: 36.74 tok/s * with draft, with logprobs: 36.12 tok/s (1.7% drop) If cherry-pick the full sort from mainline PR: * no draft, no logprobs: 12.81 tok/s * no draft, with logprobs: 12.02 tok/s (6.2% drop) * with draft, no logprobs: 36.59 tok/s * with draft, with logprobs: 29.08 tok/s (20.5% drop) [1] https://github.com/ggml-org/llama.cpp/blob/b6548/tools/server/server.cpp#L4019 Co-authored-by: Iwan Kawrakow <[email protected]>
1 parent 6d2e7ca commit c3e9fc7

File tree

2 files changed

+111
-72
lines changed

2 files changed

+111
-72
lines changed

examples/server/server.cpp

Lines changed: 69 additions & 68 deletions
Original file line numberDiff line numberDiff line change
@@ -556,6 +556,7 @@ struct slot_params {
556556
std::vector<std::string> antiprompt;
557557

558558
bool timings_per_token = false;
559+
bool post_sampling_probs = false;
559560
json input_prefix;
560561
json input_suffix;
561562

@@ -1545,6 +1546,8 @@ struct server_context {
15451546
slot.sparams.n_probs = json_value(data, "n_probs", default_sparams.n_probs);
15461547
slot.sparams.min_keep = json_value(data, "min_keep", default_sparams.min_keep);
15471548

1549+
slot.params.post_sampling_probs = json_value(data, "post_sampling_probs", default_params.post_sampling_probs);
1550+
15481551
// speculative decoding parameters
15491552
slot.params.speculative.n_max = json_value(data, "speculative.n_max", params.n_draft);
15501553
slot.params.speculative.n_min = json_value(data, "speculative.n_min", params.n_draft_min);
@@ -1947,26 +1950,7 @@ struct server_context {
19471950
}
19481951

19491952
// check if there is incomplete UTF-8 character at the end
1950-
bool incomplete = false;
1951-
for (unsigned i = 1; i < 5 && i <= slot.generated_text.size(); ++i) {
1952-
unsigned char c = slot.generated_text[slot.generated_text.size() - i];
1953-
if ((c & 0xC0) == 0x80) {
1954-
// continuation byte: 10xxxxxx
1955-
continue;
1956-
}
1957-
if ((c & 0xE0) == 0xC0) {
1958-
// 2-byte character: 110xxxxx ...
1959-
incomplete = i < 2;
1960-
} else if ((c & 0xF0) == 0xE0) {
1961-
// 3-byte character: 1110xxxx ...
1962-
incomplete = i < 3;
1963-
} else if ((c & 0xF8) == 0xF0) {
1964-
// 4-byte character: 11110xxx ...
1965-
incomplete = i < 4;
1966-
}
1967-
// else 1-byte character or invalid byte
1968-
break;
1969-
}
1953+
bool incomplete = validate_utf8(slot.generated_text) < slot.generated_text.size();
19701954

19711955
if (!incomplete) {
19721956
size_t pos = std::min(slot.n_sent_text, slot.generated_text.size());
@@ -2062,6 +2046,49 @@ struct server_context {
20622046
return slot.has_next_token; // continue
20632047
}
20642048

2049+
void populate_token_probs(const server_slot & slot, completion_token_output & result, bool post_sampling, bool special, int idx) {
2050+
size_t n_probs = slot.sparams.n_probs;
2051+
size_t n_vocab = llama_n_vocab(llama_get_model(ctx));
2052+
2053+
if (post_sampling) {
2054+
const auto * cur_p = llama_sampling_get_candidates(slot.ctx_sampling);
2055+
const size_t max_probs = cur_p->size;
2056+
2057+
// set probability for sampled token
2058+
for (size_t i = 0; i < max_probs; i++) {
2059+
if (cur_p->data[i].id == result.tok) {
2060+
result.prob = cur_p->data[i].p;
2061+
break;
2062+
}
2063+
}
2064+
2065+
// set probability for top n_probs tokens
2066+
result.probs.reserve(max_probs);
2067+
for (size_t i = 0; i < std::min(max_probs, n_probs); i++) {
2068+
result.probs.push_back({
2069+
cur_p->data[i].id,
2070+
llama_detokenize(ctx, {cur_p->data[i].id}, special),
2071+
cur_p->data[i].p
2072+
});
2073+
}
2074+
} else {
2075+
auto&&[sampled_token_p, cur] = get_token_probabilities(ctx, idx, result.tok, n_probs);
2076+
2077+
// set probability for sampled token
2078+
result.prob = sampled_token_p;
2079+
2080+
// set probability for top n_probs tokens
2081+
result.probs.reserve(n_probs);
2082+
for (size_t i = 0; i < std::min(n_vocab, n_probs); i++) {
2083+
result.probs.push_back({
2084+
cur[i].id,
2085+
llama_detokenize(ctx, {cur[i].id}, special),
2086+
cur[i].p
2087+
});
2088+
}
2089+
}
2090+
}
2091+
20652092
json get_formated_generation(const server_slot & slot) const {
20662093
const auto eos_bias = slot.sparams.logit_bias.find(llama_token_eos(model));
20672094
const bool ignore_eos = eos_bias != slot.sparams.logit_bias.end() && eos_bias->second < 0.0f && std::isinf(eos_bias->second);
@@ -2159,6 +2186,7 @@ struct server_context {
21592186
res.stop = false;
21602187
res.stream = slot.params.stream;
21612188
res.content = tkn.text_to_send;
2189+
res.post_sampling_probs = slot.params.post_sampling_probs;
21622190
res.oaicompat = slot.params.oaicompat;
21632191
res.oaicompat_model = slot.params.oaicompat_model;
21642192
res.oaicompat_cmpl_id = slot.params.oaicompat_cmpl_id;
@@ -2171,26 +2199,18 @@ struct server_context {
21712199
{"multimodal", false}
21722200
};
21732201
slot.update_chat_msg(res.oaicompat_msg_diffs);
2174-
if (slot.sparams.n_probs > 0) {
2175-
const std::vector<llama_token> to_send_toks = llama_tokenize(ctx, tkn.text_to_send, false);
2176-
const size_t probs_pos = std::min(slot.n_sent_token_probs, slot.generated_token_probs.size());
2177-
const size_t probs_stop_pos = std::min(slot.n_sent_token_probs + to_send_toks.size(), slot.generated_token_probs.size());
2178-
2179-
std::vector<completion_token_output> probs_output;
2180-
if (probs_pos < probs_stop_pos) {
2181-
probs_output = std::vector<completion_token_output>(
2182-
slot.generated_token_probs.begin() + probs_pos,
2183-
slot.generated_token_probs.begin() + probs_stop_pos);
2184-
}
2185-
slot.n_sent_token_probs = probs_stop_pos;
21862202

2187-
res.data["completion_probabilities"] = probs_vector_to_json(ctx, probs_output);
2203+
// populate res.probs_output
2204+
if (slot.sparams.n_probs > 0) {
2205+
res.probs_output = {tkn}; // copy the token probs
2206+
res.data["completion_probabilities"] = probs_vector_to_json(ctx, res.probs_output);
21882207
}
21892208

21902209
if (slot.oaicompat) {
21912210
res.data["oaicompat_token_ctr"] = slot.n_decoded;
21922211
res.data["model"] = slot.oaicompat_model;
21932212
}
2213+
21942214
// populate timings if this is final response or timings_per_token is enabled
21952215
if (slot.params.timings_per_token) {
21962216
res.timings = slot.get_timings();
@@ -2207,6 +2227,8 @@ struct server_context {
22072227
res.stop = true; // to do: set value
22082228
res.stream = slot.params.stream;
22092229
res.content = slot.generated_text;
2230+
res.timings = slot.get_timings();
2231+
res.post_sampling_probs = slot.params.post_sampling_probs;
22102232
res.oaicompat = slot.params.oaicompat;
22112233
res.oaicompat_model = slot.params.oaicompat_model;
22122234
res.oaicompat_cmpl_id = slot.params.oaicompat_cmpl_id;
@@ -2234,26 +2256,23 @@ struct server_context {
22342256
//{"oaicompat_chat_format", slot.params.oaicompat_chat_format},
22352257
};
22362258

2259+
// populate res.probs_output
22372260
if (slot.sparams.n_probs > 0) {
2238-
std::vector<completion_token_output> probs;
22392261
if (!slot.params.stream && slot.stopped_word) {
22402262
const std::vector<llama_token> stop_word_toks = llama_tokenize(ctx, slot.stopping_word, false);
22412263

22422264
size_t safe_offset = std::min(slot.generated_token_probs.size(), stop_word_toks.size());
2243-
probs = std::vector<completion_token_output>(
2265+
res.probs_output = std::vector<completion_token_output>(
22442266
slot.generated_token_probs.begin(),
22452267
slot.generated_token_probs.end() - safe_offset);
22462268
} else {
2247-
probs = std::vector<completion_token_output>(
2269+
res.probs_output = std::vector<completion_token_output>(
22482270
slot.generated_token_probs.begin(),
22492271
slot.generated_token_probs.end());
22502272
}
2251-
//res.generation_params = slot.params;
2252-
res.data["completion_probabilities"] = probs_vector_to_json(ctx, probs);
2273+
res.data["completion_probabilities"] = probs_vector_to_json(ctx, res.probs_output);
22532274
}
22542275

2255-
res.timings = slot.get_timings();
2256-
22572276
if (slot.oaicompat) {
22582277
res.data["oaicompat_token_ctr"] = slot.n_decoded;
22592278
res.data["model"] = slot.oaicompat_model;
@@ -3194,7 +3213,8 @@ struct server_context {
31943213
}
31953214

31963215
completion_token_output result;
3197-
const llama_token id = llama_sampling_sample(slot.ctx_sampling, ctx, NULL, slot.i_batch - i);
3216+
const int tok_idx = slot.i_batch - i;
3217+
const llama_token id = llama_sampling_sample(slot.ctx_sampling, ctx, NULL, tok_idx);
31983218

31993219
llama_sampling_accept(slot.ctx_sampling, ctx, id, true);
32003220

@@ -3210,35 +3230,12 @@ struct server_context {
32103230

32113231
slot.t_token_generation = (t_current - slot.t_start_generation) / 1e3;
32123232

3213-
llama_token_data_array cur_p = { slot.ctx_sampling->cur.data(), slot.ctx_sampling->cur.size(), false };
32143233
result.tok = id;
3234+
result.prob = 1.0f; // TODO: set it here instead of doing inside populate_token_probs
32153235
result.text_to_send = llama_token_to_piece(ctx, result.tok, accept_special_token(slot, result.tok));
32163236

3217-
const size_t n_probs = std::min(cur_p.size, (size_t) slot.sparams.n_probs);
3218-
if (n_probs > 0) {
3219-
const size_t n_valid = slot.ctx_sampling->n_valid;
3220-
3221-
// Make sure at least n_probs top tokens are at the front of the vector:
3222-
if (slot.sparams.temp == 0.0f && n_probs > n_valid) {
3223-
llama_sample_top_k(ctx, &cur_p, n_probs, 0);
3224-
}
3225-
3226-
if (slot.sparams.temp == 0.0f) {
3227-
// With greedy sampling the probabilities have possibly not been calculated.
3228-
for (size_t i = 0; i < n_probs; ++i) {
3229-
result.probs.push_back({
3230-
cur_p.data[i].id,llama_detokenize(ctx, {cur_p.data[i].id}, params.special),
3231-
i == 0 ? 1.0f : 0.0f
3232-
});
3233-
}
3234-
} else {
3235-
for (size_t i = 0; i < n_probs; ++i) {
3236-
result.probs.push_back({
3237-
cur_p.data[i].id, llama_detokenize(ctx, {cur_p.data[i].id}, params.special),
3238-
i >= n_valid ? 0.0f : cur_p.data[i].p // Tokens filtered out due to e.g. top_k have 0 probability.
3239-
});
3240-
}
3241-
}
3237+
if (slot.sparams.n_probs > 0) {
3238+
populate_token_probs(slot, result, slot.params.post_sampling_probs, params.special, tok_idx);
32423239
}
32433240

32443241
if (!process_token(result, slot)) {
@@ -3343,7 +3340,11 @@ struct server_context {
33433340

33443341
result.tok = ids[i];
33453342
result.text_to_send = llama_token_to_piece(ctx, result.tok, params.special);
3346-
// result.prob = 1.0f; // set later
3343+
result.prob = 1.0f; // set later
3344+
3345+
if (slot.sparams.n_probs > 0) {
3346+
populate_token_probs(slot, result, slot.params.post_sampling_probs, params.special, i);
3347+
}
33473348

33483349
if (!process_token(result, slot)) {
33493350
// release slot because of stop condition

examples/server/utils.hpp

Lines changed: 42 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -406,7 +406,6 @@ static json probs_vector_to_json(const llama_context * ctx, const std::vector<co
406406
return out;
407407
}
408408

409-
410409
//
411410
// OAI utils
412411
//
@@ -616,13 +615,12 @@ static json oaicompat_chat_params_parse(
616615

617616
// Handle "logprobs" field
618617
// TODO: The response format of this option is not yet OAI-compatible, but seems like no one really using it; We may need to fix it in the future
619-
if (body.contains("logprobs")) {
618+
if (json_value(body, "logprobs", false)) {
620619
if (has_tools && stream) {
621620
throw std::runtime_error("logprobs is not supported with tools + stream");
622621
}
623622
llama_params["n_probs"] = json_value(body, "top_logprobs", 20);
624-
}
625-
else if (body.contains("top_logprobs")) {
623+
} else if (body.contains("top_logprobs") && !body.at("top_logprobs").is_null()) {
626624
throw std::runtime_error("top_logprobs requires logprobs to be set to true");
627625
}
628626

@@ -715,3 +713,43 @@ static json format_error_response(const std::string & message, const enum error_
715713
{"type", type_str},
716714
};
717715
}
716+
717+
struct token_probabilities {
718+
float sampled_token_p;
719+
std::vector<llama_token_data> cur;
720+
};
721+
722+
static token_probabilities get_token_probabilities(llama_context * ctx, int idx, llama_token sampled_token_id, int n_sorted) {
723+
const auto * logits = llama_get_logits_ith(ctx, idx);
724+
const int n_vocab = llama_n_vocab(llama_get_model(ctx));
725+
n_sorted = std::min(n_sorted, n_vocab);
726+
727+
std::vector<std::pair<float, llama_token>> sorted(n_vocab);
728+
for (llama_token token_id = 0; token_id < n_vocab; token_id++) sorted[token_id] = {logits[token_id], token_id};
729+
730+
std::partial_sort(sorted.begin(), sorted.begin() + n_sorted, sorted.end(), std::greater<std::pair<float,llama_token>>{});
731+
732+
float max_l = sorted.front().first;
733+
float cum_sum = 0.0f;
734+
float sampled_token_p = 0.0f;
735+
bool sampled_token_found = false;
736+
std::vector<llama_token_data> cur(n_sorted);
737+
for (int i = 0; i < n_vocab; ++i) {
738+
float p = expf(sorted[i].first - max_l);
739+
cum_sum += p;
740+
if (i < n_sorted) {
741+
cur[i] = {sorted[i].second, sorted[i].first, p};
742+
}
743+
if (!sampled_token_found && sorted[i].second == sampled_token_id) {
744+
sampled_token_p = p;
745+
sampled_token_found = true;
746+
}
747+
}
748+
for (int i = n_sorted; i < n_vocab; ++i) cum_sum += expf(sorted[i].first - max_l);
749+
750+
float inv_cum_sum = 1/cum_sum;
751+
for (int i = 0; i < n_sorted; ++i) cur[i].p *= inv_cum_sum;
752+
sampled_token_p *= inv_cum_sum;
753+
754+
return {sampled_token_p, cur};
755+
}

0 commit comments

Comments
 (0)