diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 408d42e577dd..df231045e8ba 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -189,6 +189,10 @@ endif () llama_build(test-recurrent-state-rollback.cpp) llama_build_and_test(test-server-view-end.cpp) +# a persona's next request continues the tokens her slot holds (CONTINUUM-ENGINE 4.14) +llama_build_and_test(test-server-continuation.cpp) +target_include_directories(test-server-continuation PRIVATE ${PROJECT_SOURCE_DIR}/tools/server) + # GGML_TENSOR_FLAG_GRAD: a leaf whose gradient the backward computes, never optimized (the walk reads the cached prefix K/V gradient) llama_build_and_test(test-grad-leaf.cpp) diff --git a/tests/test-server-continuation.cpp b/tests/test-server-continuation.cpp new file mode 100644 index 000000000000..1b078e4f6a8c --- /dev/null +++ b/tests/test-server-continuation.cpp @@ -0,0 +1,107 @@ +// A persona's next request carries only what is new, and continues the tokens her slot holds +// (tools/server/server-continuation.h). Synthetic tokens: 1 = <|im_start|>user, +// 2 = <|im_start|>assistant, 9 = <|im_end|> (end of turn), 3 = "\n", 7 = , 40.. = words. + +#include "server-continuation.h" + +#include +#include + +static bool is_eot(llama_token t) { return t == 9; } + +static common_chat_msg_spans spans_of(const llama_tokens & tokens) { + common_chat_msg_spans spans; + std::vector> at; + for (size_t i = 0; i < tokens.size(); i++) { + if (tokens[i] == 1) at.emplace_back(COMMON_CHAT_ROLE_USER, i); + if (tokens[i] == 2) at.emplace_back(COMMON_CHAT_ROLE_ASSISTANT, i); + } + for (size_t k = 0; k < at.size(); k++) { + const size_t end = k + 1 < at.size() ? at[k + 1].second : tokens.size(); + spans.add(at[k].first, at[k].second, end - at[k].second); + } + return spans; +} + +// The server's rendering of a continuing request: the stub (a user line, an assistant turn), then +// the request's new messages and the generation prompt; its delta starts at the stub's end of turn. +static llama_tokens delta_of(const llama_tokens & new_messages) { + llama_tokens rendered = { 1, 30, 9, 3, 2, 31, 9, 3 }; + rendered.insert(rendered.end(), new_messages.begin(), new_messages.end()); + rendered.insert(rendered.end(), { 2, 3, 7 }); + const auto d = delta_after_stub(rendered, spans_of(rendered), is_eot); + if (d.miss != continuation_miss::none) { + fprintf(stderr, "delta missed: %s\n", continuation_miss_name(d.miss)); + exit(1); + } + return llama_tokens(rendered.begin() + d.from, rendered.end()); +} + +#define CHECK(cond) do { if (!(cond)) { fprintf(stderr, "%s:%d: %s\n", __FILE__, __LINE__, #cond); exit(1); } } while (0) + +int main() { + // what this catches: the stub itself (or anything before its end of turn) entering her tokens. + { + const llama_tokens delta = delta_of({ 1, 70, 9, 3 }); + CHECK((delta == llama_tokens{ 9, 3, 1, 70, 9, 3, 2, 3, 7 })); // her turn's glue, the new turn, the generation prompt + } + // what this catches: Codex's act-3 miss. Three consecutive acts, each generating reasoning the + // caller never sends back: every act continues from her own tokens, nothing of hers is + // re-rendered or compared, and her slot after act 3 is exactly what she generated plus what was new. + { + llama_tokens slot = { 1, 40, 9, 3, 2, 3, 7 }; // act 1's prompt + std::vector lineage; + llama_tokens expect = slot; + for (llama_token act = 1; act <= 3; act++) { + const size_t served = slot.size(); + const llama_tokens generated = { (llama_token) (50 + act), (llama_token) (60 + act) }; // her reasoning, then her call + slot.insert(slot.end(), generated.begin(), generated.end()); + expect.insert(expect.end(), generated.begin(), generated.end()); + lineage.push_back({ "act-" + std::to_string(act), served, slot.size() }); + // Her next request: only her result and the room's new line. + const llama_tokens delta = delta_of({ 1, (llama_token) (70 + act), 9, 3 }); + const auto c = continue_from(slot, lineage, "act-" + std::to_string(act), delta); + CHECK(c.miss == continuation_miss::none); + CHECK(c.kept == slot.size() && c.generated == 2); + expect.insert(expect.end(), delta.begin(), delta.end()); + CHECK(c.tokens == expect); + slot = c.tokens; // served: her slot holds the continued prompt, her next generation follows it + } + } + // what this catches: a warm pass during her tool (one token generated after her response's + // glue) making her real request miss, or its token leaking into her prompt. + { + llama_tokens slot = { 1, 40, 9, 3, 2, 3, 7, 51, 61 }; + std::vector lineage = { { "act-1", 7, slot.size() } }; + slot.insert(slot.end(), { 9, 3, 2, 3, 7, 80 }); + lineage.push_back({ "warm-1", slot.size() - 1, slot.size() }); + const llama_tokens delta = delta_of({ 1, 71, 9, 3 }); + const auto c = continue_from(slot, lineage, "act-1", delta); + CHECK(c.miss == continuation_miss::none && c.kept == 9); + llama_tokens expect = { 1, 40, 9, 3, 2, 3, 7, 51, 61 }; + expect.insert(expect.end(), delta.begin(), delta.end()); + CHECK(c.tokens == expect); + } + const llama_tokens held = { 1, 40, 9, 3, 2, 3, 7, 51, 61 }; + const std::vector act = { { "act-1", 7, held.size() } }; + // what this catches: a request naming no response treated as a continuation. + CHECK(continue_from(held, act, "", { 9 }).miss == continuation_miss::not_requested); + // what this catches: another response's tokens standing in for the one the request continues. + CHECK(continue_from(held, act, "act-2", { 9 }).miss == continuation_miss::other_response); + // what this catches: a lineage that outlived its tokens (the slot was cut shorter than her response). + CHECK(continue_from(llama_tokens(held.begin(), held.begin() + 5), act, "act-1", { 9 }).miss == continuation_miss::other_response); + // what this catches: a response that generated nothing treated as holding her response. + CHECK(continue_from(held, { { "act-1", held.size(), held.size() } }, "act-1", { 9 }).miss == continuation_miss::not_generated); + // what this catches: a template with no assistant delimiter cut at a guessed point. + { + const llama_tokens no_assistant = { 1, 30, 9, 3, 1, 70, 9, 3 }; + CHECK(delta_after_stub(no_assistant, spans_of(no_assistant), is_eot).miss == continuation_miss::no_stub); + } + // what this catches: a stub turn with no end of turn cut at a guessed point. + { + const llama_tokens open = { 1, 30, 9, 3, 2, 31, 1, 70 }; + CHECK(delta_after_stub(open, spans_of(open), is_eot).miss == continuation_miss::no_end_of_turn); + } + fprintf(stderr, "test-server-continuation: ok\n"); + return 0; +} diff --git a/tools/server/server-common.cpp b/tools/server/server-common.cpp index eadc271dc706..e603183fc6cd 100644 --- a/tools/server/server-common.cpp +++ b/tools/server/server-common.cpp @@ -48,6 +48,10 @@ json format_error_response(const std::string & message, const enum error_type ty type_str = "unavailable_error"; code = 503; break; + case ERROR_TYPE_CONTINUATION_REFUSED: + type_str = "continuation_refused"; + code = 409; + break; case ERROR_TYPE_EXCEED_CONTEXT_SIZE: type_str = "exceed_context_size_error"; code = 400; diff --git a/tools/server/server-common.h b/tools/server/server-common.h index 24bbb7a0bd57..61b7aebb49ca 100644 --- a/tools/server/server-common.h +++ b/tools/server/server-common.h @@ -61,6 +61,7 @@ enum error_type { ERROR_TYPE_UNAVAILABLE, // custom error ERROR_TYPE_NOT_SUPPORTED, // custom error ERROR_TYPE_EXCEED_CONTEXT_SIZE, // custom error + ERROR_TYPE_CONTINUATION_REFUSED, // Continuum fork: a request's continuation does not hold (server-continuation.h) }; // thin wrapper around common_grammar_trigger with (de)serialization functions diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index 15831cececbc..22b6b0f83ca7 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -1,6 +1,7 @@ #include #include "server-context.h" #include "server-checkpoint-policy.h" +#include "server-continuation.h" #include "server-view-end.h" #include "../../src/llama-ext.h" #include "server-train.h" @@ -302,6 +303,11 @@ struct server_slot { std::string generated_text; std::string debug_generated_text; llama_tokens generated_tokens; + + // Continuum fork: the responses her slot's tokens hold, for the request that continues one + // (server-continuation.h). Valid only while every task since was a continuation of them: any other + // task clears it at launch, and a response is added at its final result. + std::vector responses; size_t n_sent_text = 0; // number of sent text character (i.e. handle partial UTF-8 on streaming) std::vector generated_token_probs; @@ -1924,6 +1930,46 @@ struct server_context_impl { return output; } + // A request that continues her last response is served from the tokens her slot holds: her + // generated tokens stay, and only what follows her response is new (server-continuation.h). + // Runs after the adapter check, so a slot cleared for an adapter change never continues. A + // continuation that does not hold is REFUSED, typed, and her held tokens and lineage are kept: + // serving it as sent would recompute what she already holds. A cold start is the caller's own + // decision (a request that names no continuation). Returns false when it refused. + bool continue_her_response(server_slot & slot, server_task & task) { + if (task.params.continues.empty()) { + slot.responses.clear(); // a new lineage: what this task does to her tokens is not a continuation + return true; + } + const auto refuse = [&](continuation_miss miss) { + SLT_WRN(slot, "continuation of %s refused (%s): her held tokens are kept\n", task.params.continues.c_str(), + continuation_miss_name(miss)); + send_error(task, string_format("continuation of %s refused (%s): her slot keeps her held tokens; a cold start is a request that names no continuation", + task.params.continues.c_str(), continuation_miss_name(miss)), + ERROR_TYPE_CONTINUATION_REFUSED); + return false; + }; + if (task.tokens.has_mtmd || slot.prompt.tokens.has_mtmd) { + return refuse(continuation_miss::has_media); + } + // The task's tokens are only its delta (cut at launch from the stub's rendering). + const llama_tokens & delta = task.tokens.get_tokens(); + const continuation c = continue_from(slot.prompt.tokens.get_tokens(), slot.responses, task.params.continues, delta); + if (c.miss != continuation_miss::none) { + return refuse(c.miss); + } + for (auto & span : task.params.message_spans.spans) { + span.pos += c.kept; + } + if (task.params.view_end_pos >= 0) { + task.params.view_end_pos += (int32_t) c.kept; + } + SLT_INF(slot, "continuing %s: %zu held tokens (%zu generated) kept, %zu new\n", + task.params.continues.c_str(), c.kept, c.generated, delta.size()); + task.tokens = server_tokens(c.tokens, false); + return true; + } + bool launch_slot_with_task(server_slot & slot, server_task && task) { page_slot_reassigned(slot); // a restore buffered for this slot is dropped, never applied over it (server-context-page.inc) // process per-request lora adapters @@ -1945,6 +1991,10 @@ struct server_context_impl { } } + if (!continue_her_response(slot, task)) { + return false; + } + // if using alora, make sure it's only a single one requested and active size_t alora_invocation_start = task.tokens.size(); if (lora_all_alora(slot.lora)) { @@ -2324,6 +2374,12 @@ struct server_context_impl { } auto res = std::make_unique(); + // Her slot now holds this response after the prompt she was served: the next request that + // names it continues from these tokens (server-continuation.h). + if (!slot.task->is_child() && !slot.task->params.request_id.empty() && slot.stats.n_gen > 0) { + slot.responses.push_back({ slot.task->params.request_id, (size_t) slot.task->n_tokens(), (size_t) slot.prompt.n_tokens() }); + } + res->id = slot.task->id; res->id_slot = slot.id; res->learned = slot.learned; @@ -4981,6 +5037,8 @@ std::unique_ptr server_routes::handle_completions_impl( data); task.params.message_spans = task.tokens.find_message_spans(delimiters); + task.params.request_id = json_value(data, "request_id", std::string()); + task.params.continues = json_value(data, "continues", std::string()); // Continuum fork: where the caller's view ends, so the prompt is checkpointed there. if (data.contains("view_messages") && data.contains("messages")) { std::string refusal; @@ -4991,6 +5049,29 @@ std::unique_ptr server_routes::handle_completions_impl( data.at("view_messages").dump().c_str(), refusal.c_str()); } } + if (!task.params.continues.empty()) { + const continuation_delta d = task.tokens.has_mtmd + ? continuation_delta{ continuation_miss::has_media, 0 } + : delta_after_stub(task.tokens.get_tokens(), task.params.message_spans, + [&](llama_token tok) { return llama_vocab_is_eog(ctx_server.vocab, tok); }); + if (d.miss != continuation_miss::none) { + res->error(format_error_response(string_format("continuation of %s refused (%s): her slot keeps her held tokens", + task.params.continues.c_str(), continuation_miss_name(d.miss)), + ERROR_TYPE_CONTINUATION_REFUSED)); + return res; + } + const llama_tokens & rendered = task.tokens.get_tokens(); + task.tokens = server_tokens(llama_tokens(rendered.begin() + d.from, rendered.end()), false); + // Her view end moves with the cut; one inside the stub names nothing of hers. + task.params.view_end_pos = task.params.view_end_pos >= (int32_t) d.from ? task.params.view_end_pos - (int32_t) d.from : -1; + common_chat_msg_spans kept; + for (const auto & span : task.params.message_spans.spans) { + if (span.pos >= d.from) { + kept.add(span.role, span.pos - d.from, span.len); + } + } + task.params.message_spans = kept; + } task.id_slot = json_value(data, "id_slot", -1); sse_ping_interval = task.params.sse_ping_interval; @@ -5212,6 +5293,38 @@ server_routes::server_routes(const common_params & params, server_context & ctx_ }); } +// A continuing request (`continues`) carries only the messages after her held response. They are +// rendered behind a short stub of that response, never the response itself: a user line, then an +// assistant turn whose tool calls are the ones the new tool results answer (a template may require +// a tool result to follow its call). The delta is cut at the stub's end-of-turn (server-continuation.h). +static void stub_her_response(json & body) { + if (json_value(body, "continues", std::string()).empty() || !body.contains("messages") || !body.at("messages").is_array()) { + return; + } + json calls = json::array(); + for (const auto & msg : body.at("messages")) { + if (json_value(msg, "role", std::string()) == "tool") { + calls.push_back({ { "id", json_value(msg, "tool_call_id", std::string()) }, + { "type", "function" }, + { "function", { { "name", "continue" }, { "arguments", "{}" } } } }); + } + } + json stub = json::array(); + stub.push_back({ { "role", "user" }, { "content", "." } }); + json assistant = { { "role", "assistant" }, { "content", "." } }; + if (!calls.empty()) { + assistant["tool_calls"] = calls; + } + stub.push_back(assistant); + for (const auto & msg : body.at("messages")) { + stub.push_back(msg); + } + body["messages"] = stub; + if (body.contains("view_messages") && body.at("view_messages").is_number_integer()) { + body["view_messages"] = body.at("view_messages").get() + 2; // the stub's two messages lead + } +} + static json get_res_model_info(const server_context_meta & meta) { // note: do NOT use ctx_server here, otherwise it's not possible to use this during sleep @@ -5651,6 +5764,7 @@ void server_routes::init_routes() { auto res = create_response(); std::vector files; json body = json::parse(req.body); + stub_her_response(body); json body_parsed = oaicompat_chat_params_parse( body, meta->chat_params, diff --git a/tools/server/server-continuation.h b/tools/server/server-continuation.h new file mode 100644 index 000000000000..b7f9d943e2ac --- /dev/null +++ b/tools/server/server-continuation.h @@ -0,0 +1,128 @@ +#pragma once + +#include "chat.h" +#include "common.h" +#include "llama.h" + +#include +#include +#include +#include + +// Continuum fork: a persona's next request continues the tokens her slot already holds, and carries +// only what is new (CONTINUUM-ENGINE 4.14, "her token history is the engine's"). +// +// After her act her slot holds [the prompt she was served][the tokens she generated]: her reasoning, +// her words and her call, exactly as sampled, without the end-of-turn token that stopped her. A +// request that names the request her response answered (`continues`) carries ONLY the messages after +// that response. The server renders them behind a short stub of her response (a user line, then an +// assistant turn whose tool calls the new tool results answer), never her response itself, and takes +// the tokens from the end-of-turn that closes the stub: the template's own glue that closes her turn, +// then the new messages. Her request is then her held tokens up to her response's end plus that delta. +// Nothing she holds is re-rendered, re-tokenized, compared or recomputed. +// +// Anything that does not hold exactly is a typed miss, and the request is refused with it +// (`continuation_refused`): her held tokens and lineage are kept. A cold start is the caller's own +// request that names no continuation. + +enum class continuation_miss { + none, // continued + not_requested, // the request names no response it continues + other_response, // her slot's lineage holds no response by that id + has_media, // a multimodal prompt is not continued + no_stub, // the template's delimiters found no assistant turn for the stub + no_end_of_turn, // the stub's assistant turn carries no end-of-turn token + not_generated, // the response it names generated nothing +}; + +inline const char * continuation_miss_name(continuation_miss miss) { + switch (miss) { + case continuation_miss::none: return "none"; + case continuation_miss::not_requested: return "not_requested"; + case continuation_miss::other_response: return "other_response"; + case continuation_miss::has_media: return "has_media"; + case continuation_miss::no_stub: return "no_stub"; + case continuation_miss::no_end_of_turn: return "no_end_of_turn"; + case continuation_miss::not_generated: return "not_generated"; + } + return "unknown"; +} + +// One response her slot holds: the caller's id for the request it answered, where the prompt she was +// served for it ends and where her response ends in the slot's tokens. A slot holds a lineage of them: +// a continuation keeps every earlier one as its prefix, any other request starts a new lineage. +struct continuation_response { + std::string id; + size_t n_served = 0; + size_t n_end = 0; +}; + +// Where a continuing request's new tokens start in its rendering (the stub, then its new messages): +// at the end-of-turn closing the stub's assistant turn, which closes her held response in her tokens. +struct continuation_delta { + continuation_miss miss = continuation_miss::none; + size_t from = 0; +}; + +inline continuation_delta delta_after_stub(const llama_tokens & tokens, const common_chat_msg_spans & spans, + const std::function & is_end_of_turn) { + continuation_delta out; + const common_chat_msg_span * stub = nullptr; + for (const auto & span : spans.spans) { + if (span.role == COMMON_CHAT_ROLE_ASSISTANT) { + stub = &span; + break; + } + } + if (stub == nullptr) { + out.miss = continuation_miss::no_stub; + return out; + } + for (size_t i = stub->pos + stub->len; i > stub->pos; --i) { + if (is_end_of_turn(tokens[i - 1])) { + out.from = i - 1; + return out; + } + } + out.miss = continuation_miss::no_end_of_turn; + return out; +} + +struct continuation { + continuation_miss miss = continuation_miss::not_requested; + llama_tokens tokens; // her held tokens up to her response's end, then the delta + size_t kept = 0; // her held tokens kept: the prompt she was served and her response + size_t generated = 0; // of those, the tokens she generated +}; + +// Her request: the held tokens of the response it continues, then its delta. `responses` is her slot's +// lineage, oldest first; a continuation of an earlier one (her real request after a warm pass that +// continued the same response) keeps only that response's tokens, and the prompt cache finds the rest. +inline continuation continue_from(const llama_tokens & held, const std::vector & responses, + const std::string & continues, const llama_tokens & delta) { + continuation out; + if (continues.empty()) { + return out; + } + const continuation_response * answered = nullptr; + for (const auto & r : responses) { + if (r.id == continues) { + answered = &r; + } + } + if (answered == nullptr || answered->n_end > held.size()) { + out.miss = continuation_miss::other_response; + return out; + } + if (answered->n_end <= answered->n_served) { + out.miss = continuation_miss::not_generated; + return out; + } + out.miss = continuation_miss::none; + out.kept = answered->n_end; + out.generated = answered->n_end - answered->n_served; + out.tokens.reserve(answered->n_end + delta.size()); + out.tokens.insert(out.tokens.end(), held.begin(), held.begin() + answered->n_end); + out.tokens.insert(out.tokens.end(), delta.begin(), delta.end()); + return out; +} diff --git a/tools/server/server-task.h b/tools/server/server-task.h index c757135afcc0..b3ff51ad2f26 100644 --- a/tools/server/server-task.h +++ b/tools/server/server-task.h @@ -175,6 +175,12 @@ struct task_params { // is checkpointed exactly there and a saved page keeps that checkpoint. -1 = not given. int32_t view_end_pos = -1; + // Continuum fork: the caller's own id for this request (`request_id`), and the id of the request + // whose response this one continues (`continues`): her slot's held tokens stand for that response + // and everything before it (server-continuation.h). Named by the caller, never by this server. + std::string request_id; + std::string continues; + // Embeddings int32_t embd_normalize = 2; // (-1=none, 0=max absolute int16, 1=taxicab, 2=Euclidean/L2, >2=p-norm)