Skip to content
Closed
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
4 changes: 4 additions & 0 deletions tests/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
107 changes: 107 additions & 0 deletions tests/test-server-continuation.cpp
Original file line number Diff line number Diff line change
@@ -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 = <think>, 40.. = words.

#include "server-continuation.h"

#include <cstdio>
#include <cstdlib>

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<std::pair<common_chat_role, size_t>> 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<continuation_response> 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<continuation_response> 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<continuation_response> 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;
}
4 changes: 4 additions & 0 deletions tools/server/server-common.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
1 change: 1 addition & 0 deletions tools/server/server-common.h
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
114 changes: 114 additions & 0 deletions tools/server/server-context.cpp
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#include <limits>
#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"
Expand Down Expand Up @@ -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<continuation_response> responses;
size_t n_sent_text = 0; // number of sent text character (i.e. handle partial UTF-8 on streaming)

std::vector<completion_token_output> generated_token_probs;
Expand Down Expand Up @@ -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
Expand All @@ -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)) {
Expand Down Expand Up @@ -2324,6 +2374,12 @@ struct server_context_impl {
}
auto res = std::make_unique<server_task_result_cmpl_final>();

// 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;
Expand Down Expand Up @@ -4981,6 +5037,8 @@ std::unique_ptr<server_res_generator> 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;
Expand All @@ -4991,6 +5049,29 @@ std::unique_ptr<server_res_generator> 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;
Expand Down Expand Up @@ -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<int64_t>() + 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

Expand Down Expand Up @@ -5651,6 +5764,7 @@ void server_routes::init_routes() {
auto res = create_response();
std::vector<raw_buffer> files;
json body = json::parse(req.body);
stub_her_response(body);
json body_parsed = oaicompat_chat_params_parse(
body,
meta->chat_params,
Expand Down
Loading