diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index af5d3fff080e..bcdf26eb3cdd 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -19,6 +19,7 @@ #include "server-test-faults.h" #include "server-page-io.h" #include "server-page-job.h" +#include "server-engine-steps.h" #include "build-info.h" #include "common.h" @@ -896,6 +897,25 @@ struct server_context_impl { // update_slots pass; the trainer reads it between batches (see server-train.h) std::atomic n_busy_slots{0}; + // a captured step's working buffers (reused every step: no allocation once they reach the slot count) + 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_slots; + std::vector> step_counts; // per slot id: prompt, generated tokens + std::vector step_chosen; + std::vector step_work; + + // 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 @@ -3317,6 +3337,34 @@ 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. + // the step capture's buffers live on the context and are sized once to the slots: a captured + // step copies typed fields, never allocates, never builds JSON (server-engine-steps.h) + const bool capturing = batch.size() > 0 && engine_steps.active(); + const uint64_t step_id = capturing ? ++engine_step_id : 0; + step_slots.clear(); + if (capturing) { + step_counts.assign(slots.size(), { 0, 0 }); + for (const auto & t : batch.tokens) { + if (t.id_slot >= 0 && (size_t) t.id_slot < step_counts.size()) { + (t.is_prompt ? step_counts[t.id_slot].first : step_counts[t.id_slot].second)++; + } + } + step_chosen.clear(); + for (const auto & slot : slots) { + if (slot.id < 0 || (size_t) slot.id >= step_counts.size() || !slot.task) { + continue; + } + const auto & counts = step_counts[slot.id]; + if (counts.first == 0 && counts.second == 0) { + continue; + } + step_slots.push_back({ slot.id, slot.task->id, (int32_t) slot.prompt.n_tokens(), counts.first, counts.second, + (uint64_t) slot.stats.n_gen, (uint64_t) slot.stats.n_draft_accepted }); + step_chosen.push_back(slot.task->id); + } + engine_steps.push_began(t_step_start, step_id, step_chosen.data(), step_chosen.size()); + } for (int32_t off = 0; off < batch.size(); off = off_next) { const int32_t n_tokens = std::min(n_batch, batch.size() - off); try { @@ -3358,6 +3406,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(0, t_decode_owed_us - t_step); + if (capturing) { + step_work.clear(); + 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; + engine_step_work w; + w.task = s.task; + w.depth = s.depth; + w.prefilled = s.prefilled; + w.decoded = same ? (uint64_t) slot->stats.n_gen - s.n_gen : (uint64_t) s.generated; + w.accepted_known = same; + w.accepted = same ? (uint64_t) slot->stats.n_draft_accepted - s.n_accepted : 0; + step_work.push_back(w); + } + engine_steps.push_ended(ggml_time_us(), step_id, step_work.data(), step_work.size()); + } // 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. @@ -6375,6 +6441,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 { + 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, (size_t) params.n_parallel, 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(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(); diff --git a/tools/server/server-context.h b/tools/server/server-context.h index 78d544aba9e1..5adf0600478d 100644 --- a/tools/server/server-context.h +++ b/tools/server/server-context.h @@ -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_page_io, post_page_io_budget; // the KV page IO budget (server-page-io.h) server_http_context::handler_t get_train; diff --git a/tools/server/server-engine-steps.h b/tools/server/server-engine-steps.h new file mode 100644 index 000000000000..ced1db0f5593 --- /dev/null +++ b/tools/server/server-engine-steps.h @@ -0,0 +1,189 @@ +#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. +// +// The task loop only copies typed fields into a record the ring allocated when the subscriber opened +// it (inline room for every slot): no allocation, no JSON on the loop. The text frame is formatted at +// the edge, on the HTTP reader's thread (next_frame). + +#include +#include +#include +#include +#include +#include + +// One slot's share of a step. +struct engine_step_work { + int32_t task = 0; + int32_t depth = 0; // tokens in her context when the step began + int32_t prefilled = 0; + uint64_t decoded = 0; + bool accepted_known = false; // a task that finished in the step has its draft counters reset + uint64_t accepted = 0; +}; + +struct engine_step_record { + enum kind_t : uint8_t { began, ended, missed } kind = began; + int64_t at_us = 0; + uint64_t step = 0; + uint64_t seq = 0; + uint64_t count = 0; // missed: how many records were lost here + // capacity reserved once at open(); a push copies within it + std::vector chosen; + std::vector work; +}; + +struct engine_step_capture { + // Open a capture of at most `capacity` records for up to `n_slots` slots per step; refused while + // another is open. Every record's storage is allocated here, once. + bool open(size_t capacity, size_t n_slots, int64_t origin_us) { + std::lock_guard lock(mtx); + if (subscribed || capacity == 0) { + return false; + } + ring.assign(capacity, engine_step_record{}); + for (auto & r : ring) { + r.chosen.reserve(n_slots); + r.work.reserve(n_slots); + } + subscribed = true; + head = 0; + size = 0; + next_seq = 0; + lost = 0; + this->origin_us = origin_us; + return true; + } + + void close() { + std::lock_guard lock(mtx); + subscribed = false; + size = 0; + ready.notify_all(); + } + + bool active() { + std::lock_guard lock(mtx); + return subscribed; + } + + int64_t origin() { + std::lock_guard lock(mtx); + return origin_us; + } + + // Record a `began` step: the tasks it chose. + void push_began(int64_t at_us, uint64_t step, const int32_t * chosen, size_t n) { + std::lock_guard lock(mtx); + engine_step_record * r = claim(engine_step_record::began, at_us, step); + if (r != nullptr) { + r->chosen.assign(chosen, chosen + n); + } + } + + // Record an `ended` step: each chosen slot's work. + void push_ended(int64_t at_us, uint64_t step, const engine_step_work * work, size_t n) { + std::lock_guard lock(mtx); + engine_step_record * r = claim(engine_step_record::ended, at_us, step); + if (r != nullptr) { + r->work.assign(work, work + n); + } + } + + // The next record as one SSE frame, formatted here (the reader's thread), waiting at most + // `wait_s`; empty when none arrived. + std::string next_frame(int wait_s) { + std::unique_lock lock(mtx); + ready.wait_for(lock, std::chrono::seconds(wait_s), [&] { return size > 0 || !subscribed; }); + if (size == 0) { + return std::string(); + } + const engine_step_record & r = ring[head]; + std::string frame = "data: {\"kind\":\""; + frame += kind_name(r.kind); + frame += "\""; + if (r.kind == engine_step_record::missed) { + frame += ",\"count\":" + std::to_string(r.count); + } else { + frame += ",\"at_us\":" + std::to_string(r.at_us) + ",\"step\":" + std::to_string(r.step); + if (r.kind == engine_step_record::began) { + frame += ",\"chosen\":["; + for (size_t i = 0; i < r.chosen.size(); ++i) { + frame += (i ? "," : "") + std::to_string(r.chosen[i]); + } + frame += "]"; + } else { + frame += ",\"work\":["; + for (size_t i = 0; i < r.work.size(); ++i) { + const auto & w = r.work[i]; + frame += (i ? ",{" : "{"); + frame += "\"task\":" + std::to_string(w.task) + ",\"depth\":" + std::to_string(w.depth) + + ",\"prefilled\":" + std::to_string(w.prefilled) + ",\"decoded\":" + std::to_string(w.decoded) + + ",\"accepted_draft\":" + (w.accepted_known ? std::to_string(w.accepted) : std::string("null")) + "}"; + } + frame += "]"; + } + } + frame += ",\"seq\":" + std::to_string(r.seq) + "}\n\n"; + head = (head + 1) % ring.size(); + --size; + return frame; + } + +private: + static const char * kind_name(engine_step_record::kind_t kind) { + switch (kind) { + case engine_step_record::began: return "began"; + case engine_step_record::ended: return "ended"; + case engine_step_record::missed: return "missed"; + } + return "missed"; + } + + // The next free record, its header stamped; nullptr (and one more lost) when the ring is full. A + // `missed` record for earlier losses is placed first when room returns. Under mtx. + engine_step_record * claim(engine_step_record::kind_t kind, int64_t at_us, uint64_t step) { + if (!subscribed) { + return nullptr; + } + if (lost > 0 && size < ring.size()) { + engine_step_record & m = ring[(head + size++) % ring.size()]; + m.kind = engine_step_record::missed; + m.seq = next_seq++; + m.count = lost; + m.chosen.clear(); + m.work.clear(); + lost = 0; + } + if (size >= ring.size()) { + lost++; // published as one `missed` record when room returns; no sequence number spent + return nullptr; + } + engine_step_record & r = ring[(head + size++) % ring.size()]; + r.kind = kind; + r.at_us = at_us; + r.step = step; + r.seq = next_seq++; + r.count = 0; + r.chosen.clear(); + r.work.clear(); + ready.notify_one(); + return &r; + } + + std::mutex mtx; + std::condition_variable ready; + bool subscribed = false; + std::vector ring; + size_t head = 0; + size_t size = 0; + uint64_t next_seq = 0; + uint64_t lost = 0; + int64_t origin_us = 0; +}; diff --git a/tools/server/server.cpp b/tools/server/server.cpp index 7724d41bfa04..ed8d47bd1929 100644 --- a/tools/server/server.cpp +++ b/tools/server/server.cpp @@ -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; @@ -300,6 +301,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.get ("/page-io", ex_wrapper(routes.get_page_io)); ctx_http.post("/page-io/budget", ex_wrapper(routes.post_page_io_budget));