Skip to content

Commit 61bdfd5

Browse files
ngxsonggerganov
andauthored
server : implement prompt processing progress report in stream mode (#15827)
* server : implement `return_progress` * add timings.cache_n * add progress.time_ms * add test * fix test for chat/completions * readme: add docs on timings * use ggml_time_us Co-authored-by: Georgi Gerganov <[email protected]> --------- Co-authored-by: Georgi Gerganov <[email protected]>
1 parent 01806e7 commit 61bdfd5

File tree

3 files changed

+152
-18
lines changed

3 files changed

+152
-18
lines changed

tools/server/README.md

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -512,6 +512,8 @@ These words will not be included in the completion, so make sure to add them to
512512

513513
`timings_per_token`: Include prompt processing and text generation speed information in each response. Default: `false`
514514

515+
`return_progress`: Include prompt processing progress in `stream` mode. The progress will be contained inside `prompt_progress` with 3 values: `total`, `cache` and `processed`. The overall progress is `processed/total`, while the actual timed progress is `(processed-cache)/(total-cache)`. Default: `false`
516+
515517
`post_sampling_probs`: Returns the probabilities of top `n_probs` tokens after applying sampling chain.
516518

517519
`response_fields`: A list of response fields, for example: `"response_fields": ["content", "generation_settings/n_predict"]`. If the specified field is missing, it will simply be omitted from the response without triggering an error. Note that fields with a slash will be unnested; for example, `generation_settings/n_predict` will move the field `n_predict` from the `generation_settings` object to the root of the response and give it a new name.
@@ -1276,6 +1278,34 @@ curl http://localhost:8080/v1/chat/completions \
12761278

12771279
**See our [Function calling](../../docs/function-calling.md) docs** for more details, supported native tool call styles (generic tool call style is used as fallback) / examples of use.
12781280

1281+
*Timings and context usage*
1282+
1283+
The response contains a `timings` object, for example:
1284+
1285+
```js
1286+
{
1287+
"choices": [],
1288+
"created": 1757141666,
1289+
"id": "chatcmpl-ecQULm0WqPrftUqjPZO1CFYeDjGZNbDu",
1290+
// ...
1291+
"timings": {
1292+
"cache_n": 236, // number of prompt tokens reused from cache
1293+
"prompt_n": 1, // number of prompt tokens being processed
1294+
"prompt_ms": 30.958,
1295+
"prompt_per_token_ms": 30.958,
1296+
"prompt_per_second": 32.301828283480845,
1297+
"predicted_n": 35, // number of predicted tokens
1298+
"predicted_ms": 661.064,
1299+
"predicted_per_token_ms": 18.887542857142858,
1300+
"predicted_per_second": 52.94494935437416
1301+
}
1302+
}
1303+
```
1304+
1305+
This provides information on the performance of the server. It also allows calculating the current context usage.
1306+
1307+
The total number of tokens in context is equal to `prompt_n + cache_n + predicted_n`
1308+
12791309
### POST `/v1/embeddings`: OpenAI-compatible embeddings API
12801310

12811311
This endpoint requires that the model uses a pooling different than type `none`. The embeddings are normalized using the Eucledian norm.

tools/server/server.cpp

Lines changed: 74 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -110,9 +110,10 @@ static bool server_task_type_need_logits(server_task_type task_type) {
110110
}
111111

112112
struct slot_params {
113-
bool stream = true;
114-
bool cache_prompt = true; // remember the prompt to avoid reprocessing all prompt
115-
bool return_tokens = false;
113+
bool stream = true;
114+
bool cache_prompt = true; // remember the prompt to avoid reprocessing all prompt
115+
bool return_tokens = false;
116+
bool return_progress = false;
116117

117118
int32_t n_keep = 0; // number of tokens to keep from initial prompt
118119
int32_t n_discard = 0; // number of tokens after n_keep that may be discarded when shifting context, 0 defaults to half
@@ -307,11 +308,11 @@ struct server_task {
307308

308309
// enabling this will output extra debug information in the HTTP responses from the server
309310
params.verbose = params_base.verbosity > 9;
310-
params.timings_per_token = json_value(data, "timings_per_token", false);
311311

312312
params.stream = json_value(data, "stream", false);
313313
params.cache_prompt = json_value(data, "cache_prompt", true);
314314
params.return_tokens = json_value(data, "return_tokens", false);
315+
params.return_progress = json_value(data, "return_progress", false);
315316
params.n_predict = json_value(data, "n_predict", json_value(data, "max_tokens", defaults.n_predict));
316317
params.n_indent = json_value(data, "n_indent", defaults.n_indent);
317318
params.n_keep = json_value(data, "n_keep", defaults.n_keep);
@@ -608,6 +609,8 @@ struct server_task {
608609
};
609610

610611
struct result_timings {
612+
int32_t cache_n = -1;
613+
611614
int32_t prompt_n = -1;
612615
double prompt_ms;
613616
double prompt_per_token_ms;
@@ -624,6 +627,8 @@ struct result_timings {
624627

625628
json to_json() const {
626629
json base = {
630+
{"cache_n", cache_n},
631+
627632
{"prompt_n", prompt_n},
628633
{"prompt_ms", prompt_ms},
629634
{"prompt_per_token_ms", prompt_per_token_ms},
@@ -644,6 +649,22 @@ struct result_timings {
644649
}
645650
};
646651

652+
struct result_prompt_progress {
653+
int32_t total = 0;
654+
int32_t cache = 0;
655+
int32_t processed = 0;
656+
int64_t time_ms = 0;
657+
658+
json to_json() const {
659+
return json {
660+
{"total", total},
661+
{"cache", cache},
662+
{"processed", processed},
663+
{"time_ms", time_ms},
664+
};
665+
}
666+
};
667+
647668
struct server_task_result {
648669
int id = -1;
649670
int id_slot = -1;
@@ -999,8 +1020,10 @@ struct server_task_result_cmpl_partial : server_task_result {
9991020
int32_t n_prompt_tokens;
10001021

10011022
bool post_sampling_probs;
1023+
bool is_progress = false;
10021024
completion_token_output prob_output;
10031025
result_timings timings;
1026+
result_prompt_progress progress;
10041027

10051028
// OAI-compat fields
10061029
bool verbose = false;
@@ -1045,6 +1068,9 @@ struct server_task_result_cmpl_partial : server_task_result {
10451068
if (timings.prompt_n > 0) {
10461069
res.push_back({"timings", timings.to_json()});
10471070
}
1071+
if (is_progress) {
1072+
res.push_back({"prompt_progress", progress.to_json()});
1073+
}
10481074
if (!prob_output.probs.empty()) {
10491075
res["completion_probabilities"] = completion_token_output::probs_vector_to_json({prob_output}, post_sampling_probs);
10501076
}
@@ -1082,6 +1108,9 @@ struct server_task_result_cmpl_partial : server_task_result {
10821108
if (timings.prompt_n >= 0) {
10831109
res.push_back({"timings", timings.to_json()});
10841110
}
1111+
if (is_progress) {
1112+
res.push_back({"prompt_progress", progress.to_json()});
1113+
}
10851114

10861115
return res;
10871116
}
@@ -1109,7 +1138,7 @@ struct server_task_result_cmpl_partial : server_task_result {
11091138
});
11101139
};
11111140
// We have to send an initial update to conform to openai behavior
1112-
if (first) {
1141+
if (first || is_progress) {
11131142
add_delta({
11141143
{"role", "assistant"},
11151144
{"content", nullptr},
@@ -1121,16 +1150,20 @@ struct server_task_result_cmpl_partial : server_task_result {
11211150
}
11221151

11231152
if (!deltas.empty()) {
1124-
GGML_ASSERT(deltas[deltas.size() - 1].at("choices").size() >= 1);
1153+
auto & last_json = deltas[deltas.size() - 1];
1154+
GGML_ASSERT(last_json.at("choices").size() >= 1);
11251155

11261156
if (prob_output.probs.size() > 0) {
1127-
deltas[deltas.size() - 1].at("choices").at(0)["logprobs"] = json {
1157+
last_json.at("choices").at(0)["logprobs"] = json {
11281158
{"content", completion_token_output::probs_vector_to_json({prob_output}, post_sampling_probs)},
11291159
};
11301160
}
11311161

11321162
if (timings.prompt_n >= 0) {
1133-
deltas[deltas.size() - 1].push_back({"timings", timings.to_json()});
1163+
last_json.push_back({"timings", timings.to_json()});
1164+
}
1165+
if (is_progress) {
1166+
last_json.push_back({"prompt_progress", progress.to_json()});
11341167
}
11351168
}
11361169

@@ -1404,6 +1437,7 @@ struct server_slot {
14041437

14051438
// n_prompt_tokens may not be equal to prompt_tokens.size(), because prompt maybe truncated
14061439
int32_t n_prompt_tokens = 0;
1440+
int32_t n_prompt_tokens_cache = 0;
14071441
int32_t n_prompt_tokens_processed = 0;
14081442

14091443
// input prompt tokens
@@ -1456,7 +1490,9 @@ struct server_slot {
14561490
void reset() {
14571491
SLT_DBG(*this, "%s", "\n");
14581492

1459-
n_prompt_tokens = 0;
1493+
n_prompt_tokens = 0;
1494+
n_prompt_tokens_cache = 0;
1495+
14601496
last_nl_pos = 0;
14611497
generated_text = "";
14621498
has_new_line = false;
@@ -1547,6 +1583,8 @@ struct server_slot {
15471583

15481584
result_timings get_timings() const {
15491585
result_timings timings;
1586+
timings.cache_n = n_prompt_tokens_cache;
1587+
15501588
timings.prompt_n = n_prompt_tokens_processed;
15511589
timings.prompt_ms = t_prompt_processing;
15521590
timings.prompt_per_token_ms = t_prompt_processing / n_prompt_tokens_processed;
@@ -2520,7 +2558,7 @@ struct server_context {
25202558

25212559
slot.add_token(result);
25222560
if (slot.params.stream) {
2523-
send_partial_response(slot, result);
2561+
send_partial_response(slot, result, false);
25242562
}
25252563
}
25262564

@@ -2712,13 +2750,24 @@ struct server_context {
27122750
return true;
27132751
}
27142752

2715-
void send_partial_response(server_slot & slot, const completion_token_output & tkn) {
2753+
void send_partial_response(server_slot & slot, const completion_token_output & tkn, bool is_progress) {
27162754
auto res = std::make_unique<server_task_result_cmpl_partial>();
27172755

2718-
res->id = slot.id_task;
2719-
res->index = slot.index;
2720-
res->content = tkn.text_to_send;
2721-
res->tokens = { tkn.tok };
2756+
res->id = slot.id_task;
2757+
res->index = slot.index;
2758+
2759+
if (is_progress) {
2760+
res->is_progress = true;
2761+
res->progress.total = slot.n_prompt_tokens;
2762+
res->progress.cache = slot.n_prompt_tokens_cache;
2763+
res->progress.processed = slot.cache_tokens.size();
2764+
res->progress.time_ms = (ggml_time_us() - slot.t_start_process_prompt / 1000);
2765+
} else {
2766+
res->content = tkn.text_to_send;
2767+
res->tokens = { tkn.tok };
2768+
2769+
slot.update_chat_msg(res->oaicompat_msg_diffs);
2770+
}
27222771

27232772
res->n_decoded = slot.n_decoded;
27242773
res->n_prompt_tokens = slot.n_prompt_tokens;
@@ -2729,8 +2778,6 @@ struct server_context {
27292778
res->oaicompat_model = slot.params.oaicompat_model;
27302779
res->oaicompat_cmpl_id = slot.params.oaicompat_cmpl_id;
27312780

2732-
slot.update_chat_msg(res->oaicompat_msg_diffs);
2733-
27342781
// populate res.probs_output
27352782
if (slot.params.sampling.n_probs > 0) {
27362783
res->prob_output = tkn; // copy the token probs
@@ -3557,6 +3604,7 @@ struct server_context {
35573604
slot.n_past--;
35583605
}
35593606

3607+
slot.n_prompt_tokens_cache = slot.n_past;
35603608
slot.n_prompt_tokens_processed = 0;
35613609
}
35623610

@@ -3573,7 +3621,8 @@ struct server_context {
35733621
llama_memory_seq_rm(llama_get_memory(ctx), slot.id, -1, -1);
35743622

35753623
// there is no common part left
3576-
slot.n_past = 0;
3624+
slot.n_past = 0;
3625+
slot.n_prompt_tokens_cache = 0;
35773626
}
35783627

35793628
SLT_INF(slot, "kv cache rm [%d, end)\n", slot.n_past);
@@ -3767,6 +3816,13 @@ struct server_context {
37673816
n_batch = llama_n_batch(ctx);
37683817

37693818
for (auto & slot : slots) {
3819+
// optionally send prompt processing progress
3820+
if (slot.state == SLOT_STATE_PROCESSING_PROMPT || slot.state == SLOT_STATE_DONE_PROMPT) {
3821+
if (slot.params.stream && slot.params.return_progress) {
3822+
send_partial_response(slot, {}, true);
3823+
}
3824+
}
3825+
37703826
if (slot.i_batch < (int) i || slot.i_batch >= (int) (i + n_tokens)) {
37713827
continue; // continue loop of slots
37723828
}

tools/server/tests/unit/test_chat_completion.py

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -402,3 +402,51 @@ def test_context_size_exceeded():
402402
assert server.n_ctx is not None
403403
assert server.n_slots is not None
404404
assert res.body["error"]["n_ctx"] == server.n_ctx // server.n_slots
405+
406+
407+
@pytest.mark.parametrize(
408+
"n_batch,batch_count,reuse_cache",
409+
[
410+
(64, 15, False),
411+
(64, 1, True),
412+
]
413+
)
414+
def test_return_progresssss(n_batch, batch_count, reuse_cache):
415+
global server
416+
server.n_batch = n_batch
417+
server.n_ctx = 2048
418+
server.n_slots = 1
419+
server.start()
420+
def make_cmpl_request():
421+
return server.make_stream_request("POST", "/chat/completions", data={
422+
"max_tokens": 10,
423+
"messages": [
424+
{"role": "user", "content": "This is a test" * 100},
425+
],
426+
"stream": True,
427+
"return_progress": True,
428+
})
429+
if reuse_cache:
430+
# make a first request to populate the cache
431+
res0 = make_cmpl_request()
432+
for _ in res0:
433+
pass # discard the output
434+
435+
res = make_cmpl_request()
436+
last_progress = None
437+
total_batch_count = 0
438+
for data in res:
439+
cur_progress = data.get("prompt_progress", None)
440+
if cur_progress is None:
441+
continue
442+
if last_progress is not None:
443+
assert cur_progress["total"] == last_progress["total"]
444+
assert cur_progress["cache"] == last_progress["cache"]
445+
assert cur_progress["processed"] > last_progress["processed"]
446+
total_batch_count += 1
447+
last_progress = cur_progress
448+
449+
assert last_progress is not None
450+
assert last_progress["total"] > 0
451+
assert last_progress["processed"] == last_progress["total"]
452+
assert total_batch_count == batch_count

0 commit comments

Comments
 (0)