diff --git a/common/arg.cpp b/common/arg.cpp index 95cfa4bfaf06..2bdd5cdb4d63 100644 --- a/common/arg.cpp +++ b/common/arg.cpp @@ -2978,6 +2978,14 @@ common_params_context common_params_parser_init(common_params & params, llama_ex params.train_dir = value; } ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_TRAIN_DIR")); + add_opt(common_arg( + {"--frame-costs"}, + "record each serving-loop frame's completed work and host time into a fixed ring, with totals on /metrics " + "and a summary line every 10 s (off unless set, so its own cost is measured against a run without it)", + [](common_params & params) { + params.frame_costs = true; + } + ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_FRAME_COSTS")); add_opt(common_arg( {"--lora"}, "FNAME", "path to LoRA adapter (use comma-separated values to load multiple adapters)", diff --git a/common/common.h b/common/common.h index 495ab6d1a4e7..b990b5c2a619 100644 --- a/common/common.h +++ b/common/common.h @@ -605,6 +605,7 @@ struct common_params { float val_split = 0.05f; // fraction of the data used for the validation set // llama-server /train: the ONLY directory it may write adapters into; empty disables the route std::string train_dir; + bool frame_costs = false; // record each serving-loop frame's work and host time (off unless asked) // embedding bool embedding = false; // get only sentence embedding diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 408d42e577dd..8bb52d774fa8 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -7,6 +7,11 @@ target_compile_features(test-server-checkpoint-policy PRIVATE cxx_std_17) add_test(NAME test-server-checkpoint-policy COMMAND test-server-checkpoint-policy) set_tests_properties(test-server-checkpoint-policy PROPERTIES LABELS "main") +add_executable(test-server-frame-costs test-server-frame-costs.cpp) +target_compile_features(test-server-frame-costs PRIVATE cxx_std_17) +add_test(NAME test-server-frame-costs COMMAND test-server-frame-costs) +set_tests_properties(test-server-frame-costs PROPERTIES LABELS "main") + add_executable(test-server-prefill test-server-prefill.cpp) target_compile_features(test-server-prefill PRIVATE cxx_std_17) add_test(NAME test-server-prefill COMMAND test-server-prefill) diff --git a/tests/test-server-frame-costs.cpp b/tests/test-server-frame-costs.cpp new file mode 100644 index 000000000000..0c1958e7fd8c --- /dev/null +++ b/tests/test-server-frame-costs.cpp @@ -0,0 +1,90 @@ +// what this catches: the engine's frame recorder (tools/server/server-frame-costs.h, CONTINUUM-ENGINE 4.13 step 1) +// claiming what it did not measure: host uptime before activation counted as idle; a mixed frame filed as prefill or +// decode; a failed or retried batch counted as plain work; a reader that fell behind not told what it lost; a window +// the ring overwrote presented as complete. Clocks start far from zero, as ggml_time_us does. Model-free. +#include "../tools/server/server-frame-costs.h" + +#include +#include +#include + +static void require(bool condition, const char * message) { + if (!condition) { + std::cerr << "FAILED: " << message << '\n'; + std::exit(1); + } +} + +static frame_cost frame(int64_t end_us, int64_t loop, int64_t batch, int64_t learn, int32_t gen, int32_t prompt, + frame_outcome outcome = frame_outcome::ok) { + frame_cost f; + f.end_us = end_us; + f.host_loop_us = loop; + f.host_batch_us = batch; + f.host_learn_us = learn; + f.gen_accepted = gen; + f.prompt_done = prompt; + f.sequences = 4; + f.max_context = 60'000; + f.outcome = outcome; + return f; +} + +static void a_window_never_reaches_before_activation() { + const int64_t t0 = 3'600'000'000; // an hour of host uptime before recording began + frame_costs<8> costs(t0); + costs.record(frame(t0 + 100'000, 60'000, 50'000, 0, 4, 0)); + const frame_window w = costs.window(0, t0 + 1'000'000); + require(w.wall_us == 1'000'000, "wall time starts at activation, not at the clock's origin"); + require(w.outside_loop_us() == 940'000, "outside-loop time is the measured interval minus loop time"); +} + +static void work_is_filed_by_what_completed() { + const int64_t t0 = 5'000'000; + frame_costs<8> costs(t0); + costs.record(frame(t0 + 100'000, 60'000, 50'000, 0, 4, 0)); // decode + costs.record(frame(t0 + 200'000, 230'000, 200'000, 0, 0, 2048)); // prefill + costs.record(frame(t0 + 400'000, 130'000, 100'000, 20'000, 3, 512)); // mixed, with learning after + costs.record(frame(t0 + 500'000, 40'000, 30'000, 0, 0, 0, frame_outcome::failed)); + costs.record(frame(t0 + 600'000, 70'000, 60'000, 0, 4, 0, frame_outcome::retried)); + const frame_window w = costs.window(t0, t0 + 1'000'000); + require(w.frames == 5, "every frame in the window"); + require(w.batch_us[(size_t) frame_kind::decode] == 110'000, "decode-only frames, including the retried one"); + require(w.batch_us[(size_t) frame_kind::prefill] == 200'000, "prefill-only frames"); + require(w.batch_us[(size_t) frame_kind::mixed] == 100'000, "a mixed frame stays mixed"); + require(w.batch_us[(size_t) frame_kind::none] == 30'000, "a failed frame completed nothing"); + require(w.failed == 1 && w.retried == 1, "outcomes counted"); + require(w.gen_accepted == 11 && w.prompt_done == 2560, "completed work only"); + require(w.host_learn_us == 20'000, "learning time kept apart"); + require(w.unclassified_us == 10'000 + 30'000 + 10'000 + 10'000 + 10'000, "loop time no named segment covers"); + require(std::fabs(w.gen_per_wall_s() - 11.0) < 1e-9, "accepted output over wall time"); + require(w.complete, "nothing overwritten"); +} + +static void a_reader_that_falls_behind_is_told_what_it_lost() { + const int64_t t0 = 9'000'000; + frame_costs<4> costs(t0); + for (int i = 1; i <= 6; ++i) { + costs.record(frame(t0 + i * 10, 5, 4, 0, 1, 0)); + } + std::vector out; + const frame_drain d = costs.drain(0, out); + require(d.dropped == 2 && out.size() == 4, "two overwritten, the newest four returned"); + require(out.front().seq == 2 && out.back().seq == 5 && d.next_seq == 6, "oldest first, sequence numbers intact"); + out.clear(); + costs.record(frame(t0 + 70, 5, 4, 0, 1, 0)); + const frame_drain again = costs.drain(d.next_seq, out); + require(again.dropped == 0 && out.size() == 1 && out.front().seq == 6, "a caught-up reader gets only what is new"); + + const frame_window w = costs.window(t0, t0 + 1000); + require(!w.complete && w.frames == 4, "a window the ring overwrote is marked incomplete"); + require(costs.window(t0 + 45, t0 + 1000).complete, "a window entirely within the ring is complete"); +} + +int main() { + a_window_never_reaches_before_activation(); + work_is_filed_by_what_completed(); + a_reader_that_falls_behind_is_told_what_it_lost(); + std::cout << "test-server-frame-costs: ok\n"; + return 0; +} diff --git a/tools/server/server-common.h b/tools/server/server-common.h index 6ea33aa2441c..a28d79ab7a9e 100644 --- a/tools/server/server-common.h +++ b/tools/server/server-common.h @@ -499,6 +499,28 @@ struct server_metrics { uint64_t n_decode = 0; uint64_t n_busy_slots = 0; + // serving-loop frames (CONTINUUM-ENGINE 4.13 step 1, server-frame-costs.h): cumulative totals; the per-frame ring + // lives in the server context because this struct is copied into every metrics result. Host time, not device time. + uint64_t n_frames = 0; + uint64_t n_frames_failed = 0; + uint64_t n_frame_slot_failures = 0; + uint64_t n_frame_gen_accepted = 0; + uint64_t t_frame_loop_us = 0; + uint64_t t_frame_batch_us = 0; + uint64_t t_frame_learn_us = 0; + uint64_t t_frame_record_us = 0; // the recorder's own cost, so its overhead is measured, not assumed + + template void add_frame(const Frame & f, int64_t record_us) { + ++n_frames; + n_frames_failed += f.outcome == decltype(f.outcome)::failed; + n_frame_slot_failures += (uint64_t) f.slot_failures; + n_frame_gen_accepted += (uint64_t) f.gen_accepted; + t_frame_loop_us += (uint64_t) f.host_loop_us; + t_frame_batch_us += (uint64_t) f.host_batch_us; + t_frame_learn_us += (uint64_t) f.host_learn_us; + t_frame_record_us += (uint64_t) record_us; + } + uint64_t n_draft_tokens = 0; // Total draft tokens generated uint64_t n_draft_accepted = 0; // Draft tokens actually accepted uint64_t n_draft_verif_steps = 0; // Total draft token verification steps by the target model diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index 29537a88f4cf..b51385e66335 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -3,6 +3,7 @@ #include "server-checkpoint-policy.h" #include "server-view-end.h" #include "server-mapped-file.h" +#include "server-frame-costs.h" #include #include #include "../../src/llama-ext.h" @@ -1664,6 +1665,11 @@ struct server_context_impl { }); metrics.init(); + if (params_base.frame_costs) { + frames = std::make_unique>(metrics.t_start); + frame_slot_stamp.assign(slots.size(), UINT64_MAX); + } + frames_reported_us = metrics.t_start; publish_ledger(); // readable before the loop's first boundary if (params_base.cache_idle_slots) { @@ -3395,6 +3401,7 @@ struct server_context_impl { try { callback(slot); } catch (const std::exception & e) { + ++frame_now.slot_failures; SLT_ERR(slot, "got exception: %s\n", e.what()); send_error(slot, std::string("got exception: ") + e.what(), ERROR_TYPE_SERVER); slot.release(); @@ -3407,6 +3414,7 @@ struct server_context_impl { try { callback(*slot); } catch (const std::exception & e) { + ++frame_now.slot_failures; SLT_ERR(*slot, "got exception: %s\n", e.what()); send_error(*slot, std::string("got exception: ") + e.what(), ERROR_TYPE_SERVER); slot->release(); @@ -3436,6 +3444,15 @@ struct server_context_impl { // time-fair interleave: after a prefill step, generating slots are owed decode-only time equal to that step int64_t t_decode_owed_us = 0; int32_t n_batch_gen = 0; // batch size before prompt tokens are added + // CONTINUUM-ENGINE 4.13 step 1: where each frame's device time went, and a window summary every 10 s + // created when serving starts, so no window reaches back into host uptime + std::unique_ptr> frames; + // the frame in progress: completion owners add to it (prompt tokens of a successful decode, drafts proposed and + // accepted); accepted output comes from n_tokens_generated, the one accepted-token counter + frame_cost frame_now; + int64_t frames_reported_us = 0; + // per-slot stamp of the last frame that counted it: the shape snapshot needs no per-frame allocation or clearing + std::vector frame_slot_stamp; server_prefill_order prefill_order; // #define DEBUG_TIMINGS #ifdef DEBUG_TIMINGS @@ -3459,6 +3476,9 @@ struct server_context_impl { #endif void update_slots() { + const int64_t t_loop_start = ggml_time_us(); + const int64_t gen_at_start = n_tokens_generated.load(std::memory_order_relaxed); + frame_now = {}; if (minds_on()) { minds_reap(); // a landed flash write frees her RAM copy; a failed one is written again } @@ -3505,11 +3525,24 @@ struct server_context_impl { } } + // from here the iteration is a frame: it is recorded on every way out, including a failed pre_decode + struct frame_guard { + server_context_impl * s; + int64_t t_loop_start; + int64_t gen_at_start; + ~frame_guard() { + if (s->frames) { + s->finish_frame(t_loop_start, gen_at_start); + } + } + } frame_guard_{ this, t_loop_start, gen_at_start }; + try { scoped_timer t(t_pre_decode, n_pre_decode); pre_decode(); batch.render(); } catch (const std::exception & e) { + frame_now.outcome = frame_outcome::failed; SRV_ERR("pre_decode() failed: %s\n", e.what()); abort_all_slots("pre_decode() failed: " + std::string(e.what())); @@ -3542,6 +3575,9 @@ struct server_context_impl { int32_t off_next = 0; int32_t n_batch = llama_n_batch(ctx_tgt); const bool has_prompt = batch.size() > n_batch_gen; + if (frames) { + frame_shape_before_decode(); + } const int64_t t_step_start = ggml_time_us(); for (int32_t off = 0; off < batch.size(); off = off_next) { const int32_t n_tokens = std::min(n_batch, batch.size() - off); @@ -3563,9 +3599,11 @@ struct server_context_impl { n_batch = llama_n_batch(ctx_tgt); } else { // try again with the updated n_batch + frame_now.outcome = frame_outcome::retried; continue; } } catch (const std::exception & e) { + frame_now.outcome = frame_outcome::failed; SRV_ERR("decode() failed: %s\n", e.what()); abort_all_slots("decode() failed: " + std::string(e.what())); break; // stop any further processing @@ -3575,6 +3613,7 @@ struct server_context_impl { scoped_timer t(t_post_decode, n_post_decode); post_decode(n_tokens, off, batch_view); } catch (const std::exception & e) { + frame_now.outcome = frame_outcome::failed; SRV_ERR("post_decode() failed: %s\n", e.what()); abort_all_slots("post_decode() failed: " + std::string(e.what())); break; // stop any further processing @@ -3587,7 +3626,58 @@ struct server_context_impl { // 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. + frame_now.host_batch_us = t_step; + const int64_t t_learn_start = ggml_time_us(); if (learning_at_start) { advance_learning(); } + frame_now.host_learn_us = ggml_time_us() - t_learn_start; + } + + void finish_frame(int64_t t_loop_start, int64_t gen_at_start) { + const int64_t t_end = ggml_time_us(); + frame_now.end_us = t_end; + frame_now.host_loop_us = t_end - t_loop_start; + frame_now.gen_accepted = (int32_t) (n_tokens_generated.load(std::memory_order_relaxed) - gen_at_start); + record_frame(); + } + + // the batch's shape before decode mutates anything: a slot its own completion releases is still counted + void frame_shape_before_decode() { + const int64_t t0 = ggml_time_us(); + const uint64_t stamp = frames->recorded(); // this frame's sequence number, once recorded + for (int32_t i = 0; i < batch.size(); ++i) { + const int id = batch.tokens[i].id_slot; + if (id >= 0 && (size_t) id < frame_slot_stamp.size() && frame_slot_stamp[id] != stamp) { + frame_slot_stamp[id] = stamp; + ++frame_now.sequences; + frame_now.max_context = std::max(frame_now.max_context, (int32_t) slots[id].prompt.n_tokens()); + } + } + frame_now.instrument_us += ggml_time_us() - t0; + } + + void record_frame() { + const int64_t t_record_start = ggml_time_us(); + frames->record(frame_now); + if (frame_now.end_us - frames_reported_us >= 10 * 1000 * 1000) { + // an export for people reading the log; the record itself is read through frames->drain + const frame_window w = frames->window(frames_reported_us, frame_now.end_us); + frames_reported_us = frame_now.end_us; + const double wall = std::max(1.0, (double) w.wall_us); + SRV_INF("frames%s: %" PRId64 " in %.1f s; host batch: decode %.1f%% prefill %.1f%% mixed %.1f%% none %.1f%%, " + "learn %.1f%%, unclassified %.1f%%, outside the loop %.1f%%; accepted %" PRId64 " tok (%.1f/s wall), " + "prompt %" PRId64 " tok, drafts %" PRId64 "/%" PRId64 "; retried %" PRId64 " failed %" PRId64 + " slot failures %" PRId64 "; widest %" PRId64 " seq, longest context %" PRId64 + "; recording cost %.3f%% of loop time\n", + w.complete ? "" : " (INCOMPLETE: the ring overwrote part of this window)", + w.frames, w.wall_us / 1e6, + 100.0 * w.batch_us[(size_t) frame_kind::decode] / wall, 100.0 * w.batch_us[(size_t) frame_kind::prefill] / wall, + 100.0 * w.batch_us[(size_t) frame_kind::mixed] / wall, 100.0 * w.batch_us[(size_t) frame_kind::none] / wall, + 100.0 * w.host_learn_us / wall, 100.0 * w.unclassified_us / wall, 100.0 * w.outside_loop_us() / wall, + w.gen_accepted, w.gen_per_wall_s(), w.prompt_done, w.draft_accepted, w.draft_proposed, + w.retried, w.failed, w.slot_failures, w.max_sequences, w.max_context, + 100.0 * w.instrument_us / std::max(1.0, (double) w.host_loop_us)); + } + metrics.add_frame(frame_now, frame_now.instrument_us + (ggml_time_us() - t_record_start)); } void pre_decode() { @@ -3799,6 +3889,7 @@ struct server_context_impl { } slot.stats.n_draft_tokens += draft.size(); + frame_now.draft_proposed += (int32_t) draft.size(); }); // update the batch with the sampled/drafted tokens @@ -4777,6 +4868,7 @@ struct server_context_impl { // update how many tokens out of those tested were accepted slot.stats.n_draft_accepted += n_accepted; + frame_now.draft_accepted += (int32_t) n_accepted; slot.stats.n_draft_verif_steps += 1; auto & n_accepted_per_pos = slot.n_accepted_per_pos; @@ -4894,6 +4986,7 @@ struct server_context_impl { } metrics_queue_prompt(n_prompt_tokens); + frame_now.prompt_done += (int32_t) n_prompt_tokens; // this decode succeeded: its prompt tokens are done if (has_output) { // the context is already synchronized, so the timings are correct diff --git a/tools/server/server-frame-costs.h b/tools/server/server-frame-costs.h new file mode 100644 index 000000000000..4368d3cc2106 --- /dev/null +++ b/tools/server/server-frame-costs.h @@ -0,0 +1,171 @@ +#pragma once + +// Continuum fork (CONTINUUM-ENGINE 4.13, step 1: measure before changing anything). One record per serving-loop +// iteration that submitted a batch, kept in a fixed ring (no allocation per frame) and read through a typed drain: +// every record carries a sequence number, and a reader that falls behind is told exactly how many it lost. +// +// What a record claims, and what it does not (Codex review of llama.cpp#142): +// - Work is what COMPLETED, taken from the owners that complete it: generated tokens are the accepted tokens +// (`n_tokens_generated`, incremented only for accepted output, after speculative verification); prompt tokens are +// those `metrics_post_decode` counted for a decode that succeeded. Draft proposals and accepted drafts are kept +// apart from both. A batch that was retried or failed says so in `outcome`. +// - The batch's shape (sequences, longest context) is snapshotted BEFORE decode, so a slot released by its own +// completion inside the frame is still counted. +// - Times are HOST elapsed, never device time: `host_batch_us` is decode + post-decode as the host saw them (sampling +// synchronizes the device), `host_learn_us` the learning work after the batch, `host_loop_us` the whole iteration. +// The rest of the iteration is `unclassified`, not idle; the time between iterations is outside the loop, not GPU idle. +// - A frame with both prompt and generated work is MIXED; it is never filed as a pure prefill or decode cost. + +#include +#include +#include +#include +#include + +enum class frame_outcome : uint8_t { + ok = 1, + retried = 2, // the engine shrank the batch and decoded again (no KV room at first) + failed = 3, // decode or post-decode threw; the frame's slots were aborted +}; + +enum class frame_kind : uint8_t { + decode = 1, // generated tokens only + prefill = 2, // prompt tokens only + mixed = 3, // both: its time is the pair's, never attributed to either alone + none = 4, // nothing completed (a failed or empty frame) +}; + +struct frame_cost { + uint64_t seq = 0; // assigned by the recorder + int64_t end_us = 0; // when the iteration ended (ggml_time_us) + int64_t host_loop_us = 0; + int64_t host_batch_us = 0; + int64_t host_learn_us = 0; + int32_t gen_accepted = 0; // accepted output tokens + int32_t prompt_done = 0; // prompt tokens of decodes that succeeded + int32_t draft_proposed = 0; + int32_t draft_accepted = 0; + int32_t sequences = 0; // distinct sequences in the batch, before decode + int32_t max_context = 0; // longest of them, before decode + int32_t slot_failures = 0; // slots whose own work threw and was released inside this frame + int64_t instrument_us = 0; // the shape snapshot's cost; the record's own write is added to the exported total + frame_outcome outcome = frame_outcome::ok; + + frame_kind kind() const { + if (gen_accepted > 0 && prompt_done > 0) { return frame_kind::mixed; } + if (gen_accepted > 0) { return frame_kind::decode; } + if (prompt_done > 0) { return frame_kind::prefill; } + return frame_kind::none; + } + int64_t unclassified_us() const { + const int64_t named = host_batch_us + host_learn_us; + return host_loop_us > named ? host_loop_us - named : 0; + } +}; + +struct frame_drain { + uint64_t next_seq = 0; // pass back as `after` next time + uint64_t dropped = 0; // records overwritten before this reader saw them +}; + +// Totals over the frames that ENDED in (from_us, to_us]; a frame crossing `from_us` belongs to the window it ends in. +struct frame_window { + int64_t wall_us = 0; // to_us - max(from_us, activation) + int64_t frames = 0; + int64_t host_loop_us = 0; + int64_t host_learn_us = 0; + int64_t unclassified_us = 0; + int64_t batch_us[5] = {}; // indexed by frame_kind + int64_t gen_accepted = 0; + int64_t prompt_done = 0; + int64_t draft_proposed = 0; + int64_t draft_accepted = 0; + int64_t retried = 0; + int64_t failed = 0; + int64_t slot_failures = 0; + int64_t instrument_us = 0; + int64_t max_sequences = 0; + int64_t max_context = 0; + bool complete = true; // false: the ring overwrote frames of this window; its totals undercount + + // wall time with no loop iteration running: outside the loop, NOT device idle + int64_t outside_loop_us() const { return wall_us > host_loop_us ? wall_us - host_loop_us : 0; } + // accepted output per second of wall time: the number the 80 tok/s goal is read against + double gen_per_wall_s() const { return wall_us > 0 ? 1e6 * (double) gen_accepted / (double) wall_us : 0.0; } +}; + +template +class frame_costs { + static_assert(N > 0 && (N & (N - 1)) == 0, "a power of two"); + +public: + // `activation_us` is when recording began: no window reaches before it, so host uptime is never counted. + explicit frame_costs(int64_t activation_us) : activation_us_(activation_us) {} + + int64_t activation_us() const { return activation_us_; } + + uint64_t record(frame_cost f) { + f.seq = next_seq_++; + ring_[f.seq & (N - 1)] = f; + return f.seq; + } + + // Copy every record with seq >= after into `out` (oldest first). + frame_drain drain(uint64_t after, std::vector & out) const { + frame_drain d; + const uint64_t oldest = next_seq_ > N ? next_seq_ - N : 0; + uint64_t from = after; + if (from < oldest) { + d.dropped = oldest - from; + from = oldest; + } + for (uint64_t s = from; s < next_seq_; ++s) { + out.push_back(ring_[s & (N - 1)]); + } + d.next_seq = next_seq_; + return d; + } + + frame_window window(int64_t from_us, int64_t to_us) const { + frame_window w; + const int64_t from = from_us > activation_us_ ? from_us : activation_us_; + w.wall_us = to_us > from ? to_us - from : 0; + const uint64_t oldest = next_seq_ > N ? next_seq_ - N : 0; + for (uint64_t s = next_seq_; s > oldest; --s) { + const frame_cost & f = ring_[(s - 1) & (N - 1)]; + if (f.end_us > to_us) { + continue; + } + if (f.end_us <= from) { + break; // records are in end order; everything older is before the window + } + ++w.frames; + w.host_loop_us += f.host_loop_us; + w.host_learn_us += f.host_learn_us; + w.unclassified_us += f.unclassified_us(); + w.batch_us[(size_t) f.kind()] += f.host_batch_us; + w.gen_accepted += f.gen_accepted; + w.prompt_done += f.prompt_done; + w.draft_proposed += f.draft_proposed; + w.draft_accepted += f.draft_accepted; + w.retried += f.outcome == frame_outcome::retried; + w.failed += f.outcome == frame_outcome::failed; + w.slot_failures += f.slot_failures; + w.instrument_us += f.instrument_us; + w.max_sequences = std::max(w.max_sequences, f.sequences); + w.max_context = std::max(w.max_context, f.max_context); + if (s - 1 == oldest && oldest > 0) { + // the oldest record the ring still holds is inside the window: older ones in it were overwritten + w.complete = false; + } + } + return w; + } + + uint64_t recorded() const { return next_seq_; } + +private: + std::array ring_{}; + uint64_t next_seq_ = 0; + int64_t activation_us_; +}; diff --git a/tools/server/server-task.cpp b/tools/server/server-task.cpp index 673bcf778824..c108a4f7c779 100644 --- a/tools/server/server-task.cpp +++ b/tools/server/server-task.cpp @@ -1603,6 +1603,38 @@ std::string server_task_result_metrics::to_metrics() { "spec_decode_num_drafts_total", "Speculative: Total speculative decoding verification steps", (double) metrics.n_draft_verif_steps + }, { + "frames_total", + "Serving-loop iterations that submitted a batch", + (double) metrics.n_frames + }, { + "frames_failed_total", + "Frames whose pre-decode, decode or post-decode failed", + (double) metrics.n_frames_failed + }, { + "frame_slot_failures_total", + "Slots whose own work threw and was released inside a frame", + (double) metrics.n_frame_slot_failures + }, { + "frame_tokens_accepted_total", + "Accepted output tokens, counted per frame", + (double) metrics.n_frame_gen_accepted + }, { + "frame_loop_seconds_total", + "Host time of the loop iterations that submitted a batch", + metrics.t_frame_loop_us / 1.e6 + }, { + "frame_batch_seconds_total", + "Host time of decode + post-decode (sampling synchronizes the device); not device busy time", + metrics.t_frame_batch_us / 1.e6 + }, { + "frame_learn_seconds_total", + "Host time of learning work after each batch", + metrics.t_frame_learn_us / 1.e6 + }, { + "frame_record_seconds_total", + "The frame recorder's own cost", + metrics.t_frame_record_us / 1.e6 }, }; diff --git a/tools/server/tests/unit/test_failed_fill.py b/tools/server/tests/unit/test_failed_fill.py index c7db18afde45..0dc497e1e5aa 100644 --- a/tools/server/tests/unit/test_failed_fill.py +++ b/tools/server/tests/unit/test_failed_fill.py @@ -82,6 +82,8 @@ def test_a_refused_checkpoint_copy_is_not_a_slot_failure(monkeypatch): def test_a_failed_fill_leaves_the_batch_and_its_prompt_clean(monkeypatch): global server server = configure(ServerPreset.tinyllama2()) + server.server_metrics = True + server.frame_costs = True start_with_fault(monkeypatch, "LLAMA_SERVER_TEST_FAIL_PROMPT_FILLS", 1) results = complete_both() @@ -90,6 +92,17 @@ def test_a_failed_fill_leaves_the_batch_and_its_prompt_clean(monkeypatch): good = results[1 - failed[0]] assert server.make_request("GET", "/health").status_code == 200 + # the frame recorder through a real slot failure: the failed slot is counted where it failed, the frame itself + # carried on (the other slot completed), and only the completed slot's output is counted as accepted + totals = {} + for line in server.make_request("GET", "/metrics").body.splitlines(): + if line.startswith("llamacpp:") and "{" not in line: + name, value = line.split(" ", 1) + totals[name] = float(value) + assert totals["llamacpp:frame_slot_failures_total"] == 1 + assert totals["llamacpp:frames_failed_total"] == 0 + assert totals["llamacpp:frame_tokens_accepted_total"] == good.body["timings"]["predicted_n"] + # the failed slot's memory holds none of the prompt, so nothing of it may be reused retry = complete(failed[0]) assert retry.status_code == 200, retry.body diff --git a/tools/server/tests/unit/test_metrics.py b/tools/server/tests/unit/test_metrics.py index 10cfc424b135..11f184d403cb 100644 --- a/tools/server/tests/unit/test_metrics.py +++ b/tools/server/tests/unit/test_metrics.py @@ -225,3 +225,36 @@ def test_metrics_embedding_prompt_is_counted(): assert metrics["llamacpp:prompt_tokens_total"][1] > 0 assert metrics["llamacpp:n_decode_total"][1] > 0 assert metrics["llamacpp:tokens_predicted_total"][1] == 0 + + +def test_frames_count_only_completed_work(): + # what this catches: the per-frame recorder (server-frame-costs.h) counting requested batch inputs instead of + # accepted output, or missing the frame in which a slot completes and is released (n_predict=1 ends in its first + # generated frame); its accepted total must equal the completion owner's own count + global server + server.frame_costs = True + server.start() + + n_predicted = 0 + for n_predict in [1, 4, 16]: + res = server.make_request("POST", "/completion", data={"prompt": "I believe", "n_predict": n_predict}) + assert res.status_code == 200 + n_predicted += res.body["timings"]["predicted_n"] + + metrics = parse_metrics(fetch_metrics(server)) + assert metrics["llamacpp:frame_tokens_accepted_total"][1] == n_predicted + assert metrics["llamacpp:frames_total"][1] > 0 + assert metrics["llamacpp:frames_failed_total"][1] == 0 + assert metrics["llamacpp:frame_loop_seconds_total"][1] >= metrics["llamacpp:frame_batch_seconds_total"][1] + + +def test_frames_are_off_unless_asked(): + # what this catches: the recorder running (and costing) in a server that did not ask for it, which would leave + # no clean run to measure its own cost against + global server + server.start() + res = server.make_request("POST", "/completion", data={"prompt": "I believe", "n_predict": 4}) + assert res.status_code == 200 + metrics = parse_metrics(fetch_metrics(server)) + assert metrics["llamacpp:frames_total"][1] == 0 + assert metrics["llamacpp:frame_tokens_accepted_total"][1] == 0 diff --git a/tools/server/tests/unit/test_speculative.py b/tools/server/tests/unit/test_speculative.py index 5837195006bc..6dacc6e38df1 100644 --- a/tools/server/tests/unit/test_speculative.py +++ b/tools/server/tests/unit/test_speculative.py @@ -131,3 +131,29 @@ def test_multi_requests_parallel(n_slots: int, n_requests: int): for res in results: assert res.status_code == 200 assert match_regex("(wise|kind|owl|answer)+", res.body["content"]) + + +def test_frames_count_accepted_tokens_not_drafts(): + # what this catches: the per-frame recorder counting draft proposals or verification inputs as output; with a + # draft model, rejected drafts must not appear in the accepted total, which equals what the requests received + global server + server.server_metrics = True + server.frame_costs = True + server.start() + n_predicted = 0 + for seed in [1, 2, 3]: + res = server.make_request("POST", "/completion", data={ + "prompt": "I believe the meaning of life is", "temperature": 0.8, "seed": seed, "n_predict": 24, + }) + assert res.status_code == 200 + n_predicted += res.body["timings"]["predicted_n"] + res = server.make_request("GET", "/metrics") + assert res.status_code == 200 + totals = {} + for line in res.body.splitlines(): + if line.startswith("llamacpp:") and "{" not in line: + name, value = line.split(" ", 1) + totals[name] = float(value) + assert totals["llamacpp:frame_tokens_accepted_total"] == n_predicted + assert totals["llamacpp:spec_decode_num_draft_tokens_total"] > totals["llamacpp:spec_decode_num_accepted_tokens_total"], \ + "some drafts were rejected, so the equality above is a real check" diff --git a/tools/server/tests/utils.py b/tools/server/tests/utils.py index cb66d76874f4..809a8768425b 100644 --- a/tools/server/tests/utils.py +++ b/tools/server/tests/utils.py @@ -85,6 +85,7 @@ class ServerProcess: server_embeddings: bool | None = False server_reranking: bool | None = False server_metrics: bool | None = False + frame_costs: bool | None = False kv_unified: bool | None = False swa_full: bool | None = False server_slots: bool | None = False @@ -197,6 +198,8 @@ def start(self, timeout_seconds: int = DEFAULT_HTTP_TIMEOUT) -> None: server_args.append("--embedding") if self.server_reranking: server_args.append("--reranking") + if self.frame_costs: + server_args.append("--frame-costs") if self.server_metrics: server_args.append("--metrics") if self.kv_unified: