From 0c2b2bf711116c8f73198ae0cb7ff26d8a659586 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Fri, 27 Nov 2026 21:29:32 -0600 Subject: [PATCH] A decode's outputs stay readable while the next decode is queued; a mind's slot orders its inputs by its own events A context has one output buffer and reads it only after synchronize(), which waits for everything queued, so a caller serving several minds could not queue mind B's step before reading mind A's. With the output ring on (llama_set_output_ring), each decode takes the spare buffer by pointer swap before reserving its outputs and records an event once its output copies are queued; a ticket (llama_output_ticket) reads that decode's logits after waiting on its event alone (llama_ticket_logits). Off by default. Queuing was still serialized one level down: a scheduler of one copy has no events, so every split input from the CPU (the token embedding) waited for the Metal backend to drain, A's step included. ggml_backend_sched_use_events gives such a scheduler events, so each input waits for this scheduler's own last use of its backend; graph slots use it, a slot's last use being that mind's previous step. Measured on the M5 (Qwen3.6-35B-A3B Q4_K_M, Q4_0 K/V, FA, core stopped, 03:24-03:27Z), test-output-ring: two minds, each her own stream and graph slot, one token each in turn, 192 steps, serial against pipelined (B queued before A is read): minds at 1.2k/1.9k: 14.07 / 14.05 -> 13.56 / 13.60 ms/step (96-97%); again 14.17 -> 13.52 (95%), submit 1.35 ms minds at 30k/30.7k: 18.34 -> 17.89 ms/step (98%), submit 1.45 ms logits bit-identical at every step (max |diff| 0) Without the scheduler events the pipelined arm was slower than serial (contended: 27.05 -> 30.11 ms/step). The live core is GPU-bound now (a 10 s sample at 03:30Z: the persona-scheduler thread 95% in settle, 5% in submit), so this plumbing's value is what it enables (a decode read by ticket, inputs ordered by events: batched decode), not the 2-5% it saves alone. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- ggml/include/ggml-backend.h | 5 ++ ggml/src/ggml-backend.cpp | 19 +++++ include/llama.h | 14 ++++ src/CMakeLists.txt | 1 + src/llama-context.cpp | 2 + src/llama-context.h | 7 ++ src/llama-graph-slots.cpp | 1 + src/llama-output-ring.cpp | 94 +++++++++++++++++++++ src/llama-output-ring.h | 33 ++++++++ tests/continuum-tests.cmake | 1 + tests/test-output-ring.cpp | 159 ++++++++++++++++++++++++++++++++++++ 11 files changed, 336 insertions(+) create mode 100644 src/llama-output-ring.cpp create mode 100644 src/llama-output-ring.h create mode 100644 tests/test-output-ring.cpp diff --git a/ggml/include/ggml-backend.h b/ggml/include/ggml-backend.h index 9fb78f1f7a13..2a5316b52e20 100644 --- a/ggml/include/ggml-backend.h +++ b/ggml/include/ggml-backend.h @@ -409,6 +409,11 @@ extern "C" { GGML_API bool ggml_backend_sched_alloc_graph_admitted(ggml_backend_sched_t sched, struct ggml_cgraph * graph, const size_t * max_new, size_t * sizes, ggml_backend_sched_allocation_callback callback, void * user_data); GGML_API bool ggml_backend_sched_alloc_graph_within(ggml_backend_sched_t sched, struct ggml_cgraph * graph, const size_t * max_new, size_t * sizes); // returns success + // Continuum: a scheduler of one copy that orders its split inputs by its own events instead of waiting for its + // backends to drain, so a graph of its own can be queued behind other work still on the device (a mind's graph + // slot, queued while another mind's step computes). False when no backend of it records events (each such backend + // keeps its drain). + GGML_API bool ggml_backend_sched_use_events(ggml_backend_sched_t sched); GGML_API enum ggml_status ggml_backend_sched_graph_compute(ggml_backend_sched_t sched, struct ggml_cgraph * graph); GGML_API enum ggml_status ggml_backend_sched_graph_compute_async(ggml_backend_sched_t sched, struct ggml_cgraph * graph); GGML_API void ggml_backend_sched_synchronize(ggml_backend_sched_t sched); diff --git a/ggml/src/ggml-backend.cpp b/ggml/src/ggml-backend.cpp index 62f2c6558ff8..23b62c743395 100644 --- a/ggml/src/ggml-backend.cpp +++ b/ggml/src/ggml-backend.cpp @@ -3301,6 +3301,25 @@ bool ggml_backend_sched_alloc_graph_admitted(ggml_backend_sched_t sched, struct return true; } +// Continuum (ggml-backend.h): events for a scheduler of one copy. Each split input then waits for this scheduler's +// own last use of its backend, never for everything queued on the device; with one copy that use is this +// scheduler's previous graph. +bool ggml_backend_sched_use_events(ggml_backend_sched_t sched) { + GGML_ASSERT(sched); + if (sched->n_copies > 1) { + return true; // a pipeline-parallel scheduler has them already + } + // a backend whose device records none (the CPU) keeps its drain: it runs synchronously anyway + bool any = false; + for (int b = 0; b < sched->n_backends; b++) { + if (sched->events[b][0] == NULL) { + sched->events[b][0] = ggml_backend_event_new(sched->backends[b]->device); + } + any = any || sched->events[b][0] != NULL; + } + return any; +} + bool ggml_backend_sched_alloc_graph_within(ggml_backend_sched_t sched, struct ggml_cgraph * graph, const size_t * max_new, size_t * sizes) { return ggml_backend_sched_alloc_graph_admitted(sched, graph, max_new, sizes, nullptr, nullptr); diff --git a/include/llama.h b/include/llama.h index 5272ca6b9d31..e439c57d66e7 100644 --- a/include/llama.h +++ b/include/llama.h @@ -2241,6 +2241,20 @@ extern "C" { // hers. Name her when she is bound to the sequence; an unnamed sequence is keyed by its id. LLAMA_API void llama_set_graph_slot_key(struct llama_context * ctx, llama_seq_id seq, uint64_t key); + // Keep each decode's logits readable while the next decode is queued behind it (Continuum; + // llama-output-ring.h): two output buffers swapped by pointer per decode, and an event per decode, + // so a caller serving several minds queues mind B's step before reading mind A's. false, leaving + // it off, when the output device records no events. + LLAMA_API bool llama_set_output_ring(struct llama_context * ctx, bool on); + + // The last decode's ticket with the ring on (-1 before any decode, or with it off). + LLAMA_API int64_t llama_output_ticket(const struct llama_context * ctx); + + // Row j of the outputs decode `ticket` produced, in the order it produced them, once they landed: + // waits for that decode alone, never for one queued after it. NULL once the ticket is no longer + // held (the decode after next has begun) or j is past its outputs. + LLAMA_API float * llama_ticket_logits(struct llama_context * ctx, int64_t ticket, int32_t j); + // The bytes the lived-routing table holds, for the owner of this context's memory. LLAMA_API size_t llama_lived_routing_bytes(const struct llama_context * ctx); diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index b4220c0b7a0b..31c372b28508 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -21,6 +21,7 @@ set(LLAMA_CORE_SOURCES llama-persona-file.cpp llama-context-opt.cpp llama-graph-slots.cpp + llama-output-ring.cpp llama-context-opt-measure.cpp llama-context-learn.cpp llama-context-learn-tiles.cpp diff --git a/src/llama-context.cpp b/src/llama-context.cpp index f7ff9a356edb..4624b7e571f4 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -2346,6 +2346,7 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { // reserve output buffer (none for outputs that only feed a training loss) const bool host_outputs = opt_host_outputs(); // Continuum + output_ring_swap(); // Continuum: the latest decode's outputs stay readable while this one writes (llama-output-ring.cpp) if (output_reserve(host_outputs ? n_outputs_all : 0) < (host_outputs ? n_outputs_all : 0)) { LLAMA_LOG_ERROR("%s: could not reserve space for batch with %d outputs\n", __func__, n_outputs_all); return -2; @@ -2612,6 +2613,7 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { // set to total number of outputs in the batch, for use in llama_get_logits_ith n_outputs = host_outputs ? n_outputs_all : 0; + output_ring_record(); // Continuum: this decode's outputs readable by its ticket once they land (llama-output-ring.cpp) // set output mappings if (n_outputs > 0) { diff --git a/src/llama-context.h b/src/llama-context.h index 3177e396e5f0..d51504568b72 100644 --- a/src/llama-context.h +++ b/src/llama-context.h @@ -10,6 +10,7 @@ #include "llama-moe-cache.h" #include "llama-lived-routing.h" #include "llama-graph-slots.h" +#include "llama-output-ring.h" #include "ggml-cpp.h" #include "ggml-opt.h" @@ -252,6 +253,9 @@ struct llama_context { void set_graph_slots(size_t n); // each mind's decode graph kept across a switch (llama-graph-slots.cpp) size_t graph_slots_bytes() const; void set_graph_slot_key(llama_seq_id seq, uint64_t key); + bool set_output_ring(bool on); // Continuum: each decode's outputs readable by ticket (llama-output-ring.cpp) + int64_t output_ticket() const; + float * ticket_logits(int64_t ticket, int32_t j); llama_lived_routing lived_routing; struct routing_pending { std::vector> seqs; // per ubatch row @@ -566,6 +570,9 @@ struct llama_context { // Continuum: the minds' decode schedulers, swapped in for a step (llama-graph-slots.cpp) llama_graph_slots graph_slots; + llama_output_ring output_ring; // Continuum (llama-output-ring.cpp) + void output_ring_swap(); + void output_ring_record(); void graph_slot_swap(llama_graph_slot & slot); void graph_slot_enter(const llama_ubatch & ubatch); void graph_slot_leave(); diff --git a/src/llama-graph-slots.cpp b/src/llama-graph-slots.cpp index dfa9a627133d..acde8c585f73 100644 --- a/src/llama-graph-slots.cpp +++ b/src/llama-graph-slots.cpp @@ -78,6 +78,7 @@ void llama_context::graph_slot_enter(const llama_ubatch & ubatch) { sched_params_cur.max_nodes, sched_params_cur.parallel, sched_params_cur.op_offload)); ggml_backend_sched_set_copy_callback(made->sched.get(), sched_copy_experts, this); ggml_backend_sched_set_realloc_callback(made->sched.get(), sched_graph_realloc, this); + ggml_backend_sched_use_events(made->sched.get()); // her inputs wait for her own last step, never for every mind's queued one for (auto & res : made->gf_res_prev) { res = std::make_unique(sched_params_cur.max_nodes); } diff --git a/src/llama-output-ring.cpp b/src/llama-output-ring.cpp new file mode 100644 index 000000000000..afa51969913e --- /dev/null +++ b/src/llama-output-ring.cpp @@ -0,0 +1,94 @@ +// Continuum: a decode's outputs kept readable while the next decode is queued behind it (llama-output-ring.h) + +#include "llama-output-ring.h" + +#include "llama-context.h" +#include "llama-model.h" + +#include + +bool llama_context::set_output_ring(bool on) { + synchronize(); + auto & ring = output_ring; + ring.on = false; + ring.spare.reset(); + for (auto & slot : ring.slots) { + slot = llama_output_ticket_slot{}; + } + if (!on) { + return true; + } + // the output copies run on the output device's backend, so its events say when they landed + ggml_backend_dev_t dev = model.dev_output(); + for (auto & backend : backends) { + if (ggml_backend_get_device(backend.get()) == dev) { + ring.backend = backend.get(); + } + } + if (ring.backend == nullptr) { + return false; + } + for (auto & slot : ring.slots) { + slot.event.reset(ggml_backend_event_new(dev)); + if (!slot.event) { + return false; + } + } + ring.on = true; + return true; +} + +// before a decode reserves its outputs: it writes the spare, so the latest decode's outputs stay where they are and +// become the one before; what the decode before that held is overwritten +void llama_context::output_ring_swap() { + auto & ring = output_ring; + if (!ring.on) { + return; + } + buf_output.swap(ring.spare); + std::swap(ring.slots[0], ring.slots[1]); + ring.slots[0].ticket = -1; // being written +} + +// once the decode's output copies are queued +void llama_context::output_ring_record() { + auto & ring = output_ring; + if (!ring.on) { + return; + } + auto & slot = ring.slots[0]; + slot.ticket = ring.decodes++; + slot.n_outputs = n_outputs; + slot.logits = logits.data; + ggml_backend_event_record(slot.event.get(), ring.backend); +} + +int64_t llama_context::output_ticket() const { + return output_ring.on ? output_ring.slots[0].ticket : -1; +} + +float * llama_context::ticket_logits(int64_t ticket, int32_t j) { + for (auto & slot : output_ring.slots) { + if (ticket < 0 || slot.ticket != ticket) { + continue; + } + if (j < 0 || j >= slot.n_outputs || slot.logits == nullptr) { + return nullptr; + } + ggml_backend_event_synchronize(slot.event.get()); // this decode's outputs only, never one queued after it + return slot.logits + (size_t) j * model.vocab.n_tokens(); + } + return nullptr; +} + +bool llama_set_output_ring(llama_context * ctx, bool on) { + return ctx->set_output_ring(on); +} + +int64_t llama_output_ticket(const llama_context * ctx) { + return ctx->output_ticket(); +} + +float * llama_ticket_logits(llama_context * ctx, int64_t ticket, int32_t j) { + return ctx->ticket_logits(ticket, j); +} diff --git a/src/llama-output-ring.h b/src/llama-output-ring.h new file mode 100644 index 000000000000..f2740d539a1e --- /dev/null +++ b/src/llama-output-ring.h @@ -0,0 +1,33 @@ +#pragma once + +// Continuum: a decode's outputs kept readable while the next decode is queued behind it. +// +// A context has one output buffer and reads it only after synchronize(), which waits for everything queued, so a +// caller serving several minds could not queue mind B's step until it had read mind A's: on the M5 (Qwen3.6-35B-A3B, +// 2026-11-28) each token was ~5.5 ms of submit with the GPU idle, then ~15.5 ms of GPU, strictly in turn. +// +// With the ring on, the context keeps two output buffers. Each decode takes the spare by pointer swap before it +// reserves its outputs, so the previous decode's outputs stay where they are, and records an event once its own +// output copies are queued. A ticket names one decode: its logits are read after waiting on that decode's event +// alone, so A is sampled while B computes. A ticket is readable until the decode after next begins. + +#include "ggml-backend.h" +#include "ggml-cpp.h" + +#include +#include + +struct llama_output_ticket_slot { + int64_t ticket = -1; // the decode it holds, or -1 + int32_t n_outputs = 0; + float * logits = nullptr; // its rows, in the order the decode produced them + ggml_backend_event_ptr event; // recorded once its output copies were queued +}; + +struct llama_output_ring { + bool on = false; + ggml_backend_t backend = nullptr; // where the output copies run, so where the events are recorded + ggml_backend_buffer_ptr spare; // the previous decode's buffer while the context writes the other + std::array slots; // [the latest decode, the one before] + int64_t decodes = 0; +}; diff --git a/tests/continuum-tests.cmake b/tests/continuum-tests.cmake index 65e14882e6a8..54b329f133ae 100644 --- a/tests/continuum-tests.cmake +++ b/tests/continuum-tests.cmake @@ -60,6 +60,7 @@ if (NOT WIN32 OR NOT BUILD_SHARED_LIBS) # hybrid model (-m), on a GPU backend as well as the CPU (a hybrid passed on the CPU while Metal tore its state) llama_build(test-walk-exact.cpp) llama_build(test-graph-slots.cpp) + llama_build(test-output-ring.cpp) llama_build_and_test(test-server-tokens-range.cpp) target_include_directories(test-server-tokens-range PRIVATE ${PROJECT_SOURCE_DIR}/tools/server ${PROJECT_SOURCE_DIR}/tools/mtmd) target_link_libraries(test-server-tokens-range PRIVATE server-context) diff --git a/tests/test-output-ring.cpp b/tests/test-output-ring.cpp new file mode 100644 index 000000000000..31c8b6d8ddd0 --- /dev/null +++ b/tests/test-output-ring.cpp @@ -0,0 +1,159 @@ +// Continuum: a decode's outputs kept readable while the next decode is queued behind it (src/llama-output-ring.h). +// +// Two minds, each her own stream at her own depth, each with her graph kept (graph slots), decode one token each in +// turn, teacher-forced so both arms see the same inputs. Serial: decode A, read A, decode B, read B, as the Core +// serves today (each read waits for everything queued). Pipelined: B's step is queued before A's outputs are read, so +// A is read, and her next step encoded, while B computes. What this catches: +// - a ticket that reads another decode's outputs (the ring's swap or its record misplaced): every step's logits +// must be bit-identical to the serial arm's; +// - a ticket read that waits for the decode queued after it (no overlap): it prints ms/step for both arms. + +#include "arg.h" +#include "common.h" +#include "llama.h" + +#include +#include +#include +#include +#include +#include + +static constexpr uint32_t N_MINDS = 2; +static constexpr uint32_t N_GEN = 96; + +// each mind at her own depth: OUTPUT_RING_DEPTH (default 1200) for the first, 700 more for each after +static uint32_t depth_of(uint32_t m) { + const char * set = getenv("OUTPUT_RING_DEPTH"); + return (set ? (uint32_t) std::stoul(set) : 1200) + 700 * m; +} + +struct arm_result { + std::vector> logits; // [step][n_vocab], minds interleaved A, B, A, B, ... + double ms_per_step = 0.0; + double submit_ms_per_step = 0.0; // how long each decode call blocked the caller +}; + +static arm_result run_arm(const common_params & params, llama_model * model, const std::vector & tokens, bool pipelined) { + auto cparams = common_context_params_to_llama(params); + cparams.n_seq_max = N_MINDS; + cparams.n_ctx = N_MINDS * (depth_of(N_MINDS - 1) + 4096); + cparams.n_batch = 2048; + cparams.n_ubatch = 2048; + cparams.kv_unified = false; + cparams.flash_attn_type = LLAMA_FLASH_ATTN_TYPE_ENABLED; + cparams.type_k = GGML_TYPE_Q4_0; + cparams.type_v = GGML_TYPE_Q4_0; + llama_context * ctx = llama_init_from_model(model, cparams); + GGML_ASSERT(ctx != nullptr); + llama_set_graph_slots(ctx, N_MINDS); + GGML_ASSERT(llama_set_output_ring(ctx, true)); + + llama_batch_ext * batch = llama_batch_ext_init(ctx); + GGML_ASSERT(batch != nullptr); + auto put = [&](llama_token t, llama_pos p, llama_seq_id s, bool out) { + const int32_t i = llama_batch_ext_add_token(batch, s, t); + GGML_ASSERT(i >= 0 && llama_batch_ext_set_pos(batch, i, &p) && llama_batch_ext_set_output_logits(batch, i, out)); + }; + auto decode = [&]() { + GGML_ASSERT(llama_process(ctx, LLAMA_PROCESS_TYPE_DECODE, batch) == 0); + llama_batch_ext_clear(batch); + return llama_output_ticket(ctx); + }; + const int32_t n_vocab = llama_vocab_n_tokens(llama_model_get_vocab(model)); + + llama_pos pos[N_MINDS]; + for (uint32_t m = 0; m < N_MINDS; ++m) { // each at her own depth, prefilled a batch at a time + const uint32_t n = depth_of(m); + for (uint32_t from = 0; from < n; from += 2048) { + const uint32_t to = std::min(n, from + 2048); + for (uint32_t i = from; i < to; ++i) { + put(tokens[(i + 97 * m) % tokens.size()], (llama_pos) i, (llama_seq_id) m, i + 1 == n); + } + const int64_t ticket = decode(); + if (to == n) { + (void) llama_ticket_logits(ctx, ticket, 0); + } + } + pos[m] = (llama_pos) n; + } + + arm_result r; + double submit_ms = 0.0; + auto step = [&](uint32_t m) { + put(tokens[(size_t) (pos[m] + 31 * m) % tokens.size()], pos[m], (llama_seq_id) m, true); + ++pos[m]; + const auto t = std::chrono::steady_clock::now(); + const int64_t ticket = decode(); + submit_ms += std::chrono::duration(std::chrono::steady_clock::now() - t).count(); + return ticket; + }; + auto keep = [&](int64_t ticket) { + const float * l = llama_ticket_logits(ctx, ticket, 0); + GGML_ASSERT(l != nullptr); + r.logits.emplace_back(l, l + n_vocab); + }; + const auto t0 = std::chrono::steady_clock::now(); + if (!pipelined) { + for (uint32_t g = 0; g < N_GEN; ++g) { + for (uint32_t m = 0; m < N_MINDS; ++m) { + keep(step(m)); + } + } + } else { + // one step always queued behind the one computing: B's goes in before A's is read, and A's next before B's + int64_t held = step(0); + for (uint32_t g = 0; g < N_GEN; ++g) { + const int64_t b = step(1); + keep(held); + held = g + 1 < N_GEN ? step(0) : -1; + keep(b); + } + } + const double ms = std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); + r.ms_per_step = ms / (N_GEN * N_MINDS); + r.submit_ms_per_step = submit_ms / (N_GEN * N_MINDS); + llama_batch_ext_free(batch); + llama_free(ctx); + return r; +} + +int main(int argc, char ** argv) { + common_params params; + if (!common_params_parse(argc, argv, params, LLAMA_EXAMPLE_COMMON)) { + return 1; + } + llama_backend_init(); + llama_model * model = llama_model_load_from_file(params.model.path.c_str(), common_model_params_to_llama(params)); + GGML_ASSERT(model != nullptr); + + std::string text; + uint32_t lcg = 12345; + static const char * words[] = { "room", "card", "claim", "review", "patch", "lease", "board", "turn" }; + while (text.size() < 32768) { + lcg = lcg * 1664525u + 1013904223u; + text += words[(lcg >> 16) % 8]; + text += (lcg >> 8) % 7 == 0 ? ".\n" : " "; + } + const std::vector tokens = common_tokenize(llama_model_get_vocab(model), text, true, false); + GGML_ASSERT(tokens.size() > 4096); // the prompt wraps: depth is what is measured, not novelty + + const arm_result serial = run_arm(params, model, tokens, false); + const arm_result pipelined = run_arm(params, model, tokens, true); + + float max_diff = 0.0f; + for (size_t s = 0; s < serial.logits.size(); ++s) { + for (size_t i = 0; i < serial.logits[s].size(); ++i) { + max_diff = std::max(max_diff, std::fabs(serial.logits[s][i] - pipelined.logits[s][i])); + } + } + printf("output ring: %u minds at %u and %u, %u steps: serial %.2f ms/step (submit %.2f), pipelined %.2f ms/step (submit %.2f; %.0f%% of serial), max |logit diff| %g\n", + N_MINDS, depth_of(0), depth_of(1), N_GEN * N_MINDS, serial.ms_per_step, serial.submit_ms_per_step, pipelined.ms_per_step, pipelined.submit_ms_per_step, 100.0 * pipelined.ms_per_step / serial.ms_per_step, max_diff); + const bool ok = max_diff == 0.0f && serial.logits.size() == pipelined.logits.size(); + if (!ok) { + printf("FAIL: a ticket read another decode's outputs\n"); + } + llama_model_free(model); + llama_backend_free(); + return ok ? 0 : 1; +}