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
102 changes: 102 additions & 0 deletions tools/server/server-context.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
#include "server-learn-ledger.h"
#include "server-learn-residency.h"
#include "server-test-faults.h"
#include "server-engine-steps.h"

#include "build-info.h"
#include "common.h"
Expand Down Expand Up @@ -888,6 +889,10 @@ struct server_context_impl {
// update_slots pass; the trainer reads it between batches (see server-train.h)
std::atomic<int> n_busy_slots{0};

// every step the task loop runs, for the one subscriber of `GET /engine/steps` (4.10 P5)
engine_step_capture engine_steps;
uint64_t engine_step_id = 0;

// The most one sequence may hold: llama_n_ctx_seq capped at the model's training context.
// ONE value, set at load: every slot is sized from it and context_geometry reports it, so
// the report never names a size the slots refuse (it said 524288 while each slot capped at
Expand Down Expand Up @@ -3645,6 +3650,37 @@ struct server_context_impl {
int32_t n_batch = llama_n_batch(ctx_tgt);
const bool has_prompt = batch.size() > n_batch_gen;
const int64_t t_step_start = ggml_time_us();
// The step capture: what this step runs, and each slot's depth and counters before it.
struct step_slot {
int32_t id_slot;
int task;
int32_t depth;
int32_t prefilled;
int32_t generated;
uint64_t n_gen;
uint64_t n_accepted;
};
std::vector<step_slot> step_slots;
const bool capturing = batch.size() > 0 && engine_steps.active();
const uint64_t step_id = capturing ? ++engine_step_id : 0;
if (capturing) {
std::map<int32_t, std::pair<int32_t, int32_t>> by_slot; // prompt, generated tokens
for (const auto & t : batch.tokens) {
auto & counts = by_slot[t.id_slot];
(t.is_prompt ? counts.first : counts.second)++;
}
json chosen = json::array();
for (const auto & slot : slots) {
const auto it = by_slot.find(slot.id);
if (it == by_slot.end() || !slot.task) {
continue;
}
step_slots.push_back({ slot.id, slot.task->id, (int32_t) slot.prompt.n_tokens(), it->second.first, it->second.second,
(uint64_t) slot.stats.n_gen, (uint64_t) slot.stats.n_draft_accepted });
chosen.push_back(slot.task->id);
}
engine_steps.push({ { "kind", "began" }, { "at_us", t_step_start }, { "step", step_id }, { "chosen", chosen } });
}
for (int32_t off = 0; off < batch.size(); off = off_next) {
const int32_t n_tokens = std::min(n_batch, batch.size() - off);
try {
Expand Down Expand Up @@ -3686,6 +3722,24 @@ struct server_context_impl {
// a prefill step adds its duration to the decode time owed; a decode-only step pays it back
const int64_t t_step = ggml_time_us() - t_step_start;
t_decode_owed_us = has_prompt ? t_decode_owed_us + t_step : std::max<int64_t>(0, t_decode_owed_us - t_step);
if (capturing) {
json work = json::array();
for (const auto & s : step_slots) {
const auto slot = std::find_if(slots.begin(), slots.end(), [&](const server_slot & candidate) { return candidate.id == s.id_slot; });
// a task that finished in this step was released and its counters reset: its
// decoded count is the tokens it generated in the batch, its accepted drafts unknown
const bool same = slot != slots.end() && slot->task && slot->task->id == s.task;
json entry = {
{ "task", s.task },
{ "depth", s.depth },
{ "prefilled", s.prefilled },
{ "decoded", same ? (uint64_t) slot->stats.n_gen - s.n_gen : (uint64_t) s.generated },
};
entry["accepted_draft"] = same ? json((uint64_t) slot->stats.n_draft_accepted - s.n_accepted) : json(nullptr);
work.push_back(entry);
}
engine_steps.push({ { "kind", "ended" }, { "at_us", ggml_time_us() }, { "step", step_id }, { "work", work } });
}
// Completion-triggered learning can begin inside post_decode. Its entry
// preparation is already one measured blocking segment; do not append a
// graph segment before the queued NEXT_RESPONSE lets serving run again.
Expand Down Expand Up @@ -6703,6 +6757,54 @@ void server_routes::init_routes() {
return res;
};

// The engine-step stream (continuum 4.10 P5): every step the task loop runs, to ONE subscriber,
// never through the learning events above. The subscriber names the ring's bound (`capacity`, its
// memory to spend; none is refused, never defaulted); the stream opens with the engine's identity
// and its clock origin; a run the ring could not keep arrives as a `missed` record in position.
this->get_engine_steps = [this](const server_http_req & req) -> std::unique_ptr<server_res_generator> {
const std::string asked = req.get_param("capacity");
const long long capacity = asked.empty() ? 0 : std::atoll(asked.c_str());
const int64_t origin_us = ggml_time_us();
if (capacity <= 0 || !ctx_server.engine_steps.open((size_t) capacity, origin_us)) {
auto res = create_response();
res->error(format_error_response(capacity <= 0 ? "\"capacity\" (the ring's bound, in records) is required"
: "another subscriber holds the engine-step stream",
ERROR_TYPE_INVALID_REQUEST));
return res;
}
struct step_stream : server_res_generator {
engine_step_capture & steps;
step_stream(server_queue & tasks, server_response & results, int sleep_idle_seconds, engine_step_capture & steps)
: server_res_generator(tasks, results, sleep_idle_seconds, true), steps(steps) {}
void on_complete() override {
steps.close();
server_res_generator::on_complete();
}
};
auto res = std::make_unique<step_stream>(queue_tasks, queue_results, params.sleep_idle_seconds, ctx_server.engine_steps);
res->set_req(&req); // its connection ends the stream (should_stop)
res->status = 200;
res->content_type = "text/event-stream";
res->data = "data: " + safe_json_to_str({ { "kind", "opened" }, { "engine", ctx_server.learning_engine_identity() }, { "origin_us", origin_us } }) + "\n\n";
const int keepalive = params.sse_ping_interval > 0 ? params.sse_ping_interval : 1;
res->set_next([res_this = res.get(), keepalive](std::string & output) -> bool {
if (res_this->should_stop()) {
return false;
}
if (!res_this->data.empty()) {
output = std::move(res_this->data);
res_this->data.clear();
return true;
}
output = res_this->steps.next_frame(keepalive);
if (output.empty()) {
output = ":\n\n"; // keepalive
}
return true;
});
return res;
};

// a read answers from the loop's last publication, never queued behind the chunk it reports on
this->get_learn_grants = [this](const server_http_req &) {
auto res = create_response();
Expand Down
1 change: 1 addition & 0 deletions tools/server/server-context.h
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,7 @@ struct server_routes {
server_http_context::handler_t post_learn_residency, release_learn_residency, revoke_learn_residency;
server_http_context::handler_t get_learn_grants, post_learn_grants, revoke_learn_grant, post_learn_preflight;
server_http_context::handler_t get_learn_events;
server_http_context::handler_t get_engine_steps;
server_http_context::handler_t post_prompt_cache_limit;
server_http_context::handler_t get_train;
server_http_context::handler_t post_train;
Expand Down
91 changes: 91 additions & 0 deletions tools/server/server-engine-steps.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
#pragma once

// The engine's step capture (continuum CONTINUUM-ENGINE 4.10 P5 slice 1): every step the task loop
// runs, published to ONE subscriber on its own stream (`GET /engine/steps`), never through the
// learning events stream. The subscriber sets the ring's bound when it subscribes (its memory to
// spend); with no subscriber nothing is recorded. Writing never blocks the task loop: a full ring
// counts what it could not keep and publishes that count in position as a `missed` record, so the
// reader knows exactly where its capture has a hole.

#include <chrono>
#include <condition_variable>
#include <cstdint>
#include <deque>
#include <mutex>
#include <string>

#include "server-common.h"

struct engine_step_capture {
// Open a capture of at most `capacity` records; refused while another is open.
bool open(size_t capacity, int64_t origin_us) {
std::lock_guard<std::mutex> lock(mtx);
if (subscribed || capacity == 0) {
return false;
}
subscribed = true;
bound = capacity;
next_seq = 0;
lost = 0;
records.clear();
this->origin_us = origin_us;
return true;
}

void close() {
std::lock_guard<std::mutex> lock(mtx);
subscribed = false;
records.clear();
}

bool active() {
std::lock_guard<std::mutex> lock(mtx);
return subscribed;
}

int64_t origin() {
std::lock_guard<std::mutex> lock(mtx);
return origin_us;
}

// Record one step record (its `seq` is stamped here). Never blocks; counts loss when full.
void push(json record) {
std::lock_guard<std::mutex> lock(mtx);
if (!subscribed) {
return;
}
if (lost > 0 && records.size() < bound) {
records.push_back({{"kind", "missed"}, {"seq", next_seq++}, {"count", lost}});
lost = 0;
}
if (records.size() >= bound) {
lost++; // published as one `missed` record when room returns; no sequence number spent
return;
}
record["seq"] = next_seq++;
records.push_back(std::move(record));
ready.notify_one();
}

// The next record as one SSE frame, waiting at most `wait_s`; empty when none arrived.
std::string next_frame(int wait_s) {
std::unique_lock<std::mutex> lock(mtx);
ready.wait_for(lock, std::chrono::seconds(wait_s), [&] { return !records.empty() || !subscribed; });
if (records.empty()) {
return std::string();
}
std::string frame = "data: " + records.front().dump() + "\n\n";
records.pop_front();
return frame;
}

private:
std::mutex mtx;
std::condition_variable ready;
bool subscribed = false;
size_t bound = 0;
uint64_t next_seq = 0;
uint64_t lost = 0;
int64_t origin_us = 0;
std::deque<json> records;
};
2 changes: 2 additions & 0 deletions tools/server/server.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,7 @@ int llama_server(common_params & params, int argc, char ** argv) {
routes.post_learn = models_routes->proxy_post;
routes.get_learn_grants = models_routes->proxy_get;
routes.get_learn_events = models_routes->proxy_get;
routes.get_engine_steps = models_routes->proxy_get;
routes.post_learn_grants = models_routes->proxy_post;
routes.post_learn_preflight = models_routes->proxy_post;
routes.post_prompt_cache_limit = models_routes->proxy_post;
Expand Down Expand Up @@ -298,6 +299,7 @@ int llama_server(common_params & params, int argc, char ** argv) {
ctx_http.post("/learn/preflight", ex_wrapper(routes.post_learn_preflight));
ctx_http.post("/learn/grants", ex_wrapper(routes.post_learn_grants));
ctx_http.get ("/learn/events", ex_wrapper(routes.get_learn_events));
ctx_http.get ("/engine/steps", ex_wrapper(routes.get_engine_steps));
ctx_http.post("/prompt-cache/limit", ex_wrapper(routes.post_prompt_cache_limit));
ctx_http.post("/learn/grants/revoke", ex_wrapper(routes.revoke_learn_grant));
ctx_http.get ("/train", ex_wrapper(routes.get_train));
Expand Down