diff --git a/include/llama.h b/include/llama.h index e7bd1a1bbabf..5272ca6b9d31 100644 --- a/include/llama.h +++ b/include/llama.h @@ -2226,6 +2226,21 @@ extern "C" { // Pin a span from what serving recorded; false, pinning nothing, when a position was never served. LLAMA_API bool llama_pin_lived_routing(struct llama_context * ctx, llama_seq_id seq, llama_pos pos0, int32_t n_pos); + // Keep each mind's decode graph built and allocated across a switch to another (Continuum): up to + // `n` decode steps of one token per sequence, each keyed by its sequences and adapter set, keep + // their own scheduler and graph, so a mind returning to the engine reuses its graph instead of + // rebuilding, re-splitting and re-allocating it. The owner sets n from the minds it keeps + // resident; 0 (the default) keeps none. Call between decodes. + LLAMA_API void llama_set_graph_slots(struct llama_context * ctx, size_t n); + + // The compute buffer bytes the kept graphs hold beside the context's own. + LLAMA_API size_t llama_graph_slots_bytes(const struct llama_context * ctx); + + // Name whom sequence `seq` serves (Continuum): her steps keep their graph in her own slot, so a + // mind returning to a stream another mind used finds hers, and a change of her shape rebuilds only + // 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); + // 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 bc539ac173a0..b4220c0b7a0b 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -20,6 +20,7 @@ set(LLAMA_CORE_SOURCES llama-context-api.cpp llama-persona-file.cpp llama-context-opt.cpp + llama-graph-slots.cpp llama-context-opt-measure.cpp llama-context-learn.cpp llama-context-learn-tiles.cpp diff --git a/src/llama-adapter.cpp b/src/llama-adapter.cpp index fb8ab80a6c86..5baae9c00f87 100644 --- a/src/llama-adapter.cpp +++ b/src/llama-adapter.cpp @@ -587,6 +587,7 @@ void llama_adapter_lora_free(llama_adapter_lora * adapter) { if (adapter->model != nullptr) { std::unique_lock lock(adapter->model->loras_mutex); adapter->model->loras.erase(adapter); + adapter->model->lora_frees.fetch_add(1, std::memory_order_release); // Continuum (llama-graph-slots.h) adapter->model = nullptr; } diff --git a/src/llama-context.cpp b/src/llama-context.cpp index 7be338bac8e5..f7ff9a356edb 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -810,6 +810,7 @@ void llama_context::sched_reserve() { const size_t max_nodes = this->graph_max_nodes(); sched_max_nodes = max_nodes; // Continuum + graph_slots_drop(); // Continuum: every slot was made for the scheduler being replaced (llama-graph-slots.cpp) LLAMA_LOG_DEBUG("%s: max_nodes = %zu\n", __func__, max_nodes); @@ -1079,6 +1080,7 @@ bool llama_context::memory_update(bool optimize) { } gf_res_prev_active = nullptr; + graph_slots_forget(); // Continuum (llama-graph-slots.cpp) if (!mctx->apply()) { LLAMA_LOG_ERROR("%s: failed to apply memory update\n", __func__); } @@ -1846,6 +1848,7 @@ llm_graph_result * llama_context::process_ubatch(const llama_ubatch & ubatch, ll return nullptr; } + graph_slot_enter(ubatch); // Continuum: this mind's own slot, where her kept graph is (llama-graph-slots.cpp) auto * res = get_gf_res_prev(); auto * gf = res->get_gf(); @@ -2390,6 +2393,7 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { ggml_backend_event_wait(h_nextn_backend, ev_h_nextn_read.get()); } + graph_slot_scope slot_scope{*this}; // Continuum: slots serve this decode only; the context's own scheduler is back when it returns do { const auto & ubatch = mctx->get_ubatch(); @@ -4185,6 +4189,7 @@ llama_memory_breakdown llama_context::memory_breakdown() const { reported.push_back(buft); ret[buft].compute += ggml_backend_sched_get_buffer_size(sched.get(), backend); opt_breakdown_serving(ret, backend); // Continuum + graph_slots_breakdown(ret, backend); // Continuum (llama-graph-slots.cpp) } } return ret; diff --git a/src/llama-context.h b/src/llama-context.h index 9e6cec35603f..3177e396e5f0 100644 --- a/src/llama-context.h +++ b/src/llama-context.h @@ -9,6 +9,7 @@ #include "llama-memory.h" #include "llama-moe-cache.h" #include "llama-lived-routing.h" +#include "llama-graph-slots.h" #include "ggml-cpp.h" #include "ggml-opt.h" @@ -248,6 +249,9 @@ struct llama_context { void routing_queue(const llm_graph_result * res, const llama_ubatch & ubatch); // after a serving ubatch computes void routing_settle(); // at synchronize void drop_reusable_graphs(); // no cached graph is reused across a change it cannot see + 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); llama_lived_routing lived_routing; struct routing_pending { std::vector> seqs; // per ubatch row @@ -560,6 +564,20 @@ struct llama_context { bool sched_need_reserve = true; size_t sched_max_nodes = 0; // Continuum: the node budget the scheduler was reserved for (set_adapters_lora) + // Continuum: the minds' decode schedulers, swapped in for a step (llama-graph-slots.cpp) + llama_graph_slots graph_slots; + void graph_slot_swap(llama_graph_slot & slot); + void graph_slot_enter(const llama_ubatch & ubatch); + void graph_slot_leave(); + void graph_slots_drop(); + void graph_slots_forget(); + void graph_slots_breakdown(std::map & ret, ggml_backend_t backend) const; + struct graph_slot_scope { // slots serve decode() only, and never outlive it + llama_context & ctx; + explicit graph_slot_scope(llama_context & c) : ctx(c) { ctx.graph_slots.in_decode = true; } + ~graph_slot_scope() { ctx.graph_slot_leave(); ctx.graph_slots.in_decode = false; } + }; + // whether the reserve graph has a logits tensor, set in sched_reserve() // true until then, because the first output_reserve() runs before any graph is reserved bool graph_has_logits = true; diff --git a/src/llama-graph-slots.cpp b/src/llama-graph-slots.cpp new file mode 100644 index 000000000000..dfa9a627133d --- /dev/null +++ b/src/llama-graph-slots.cpp @@ -0,0 +1,169 @@ +// Continuum: each mind's decode graph kept built and allocated across a switch (llama-graph-slots.h) + +#include "llama-graph-slots.h" + +#include "llama-context.h" +#include "llama-model.h" + +#include + +// the context and the slot exchange scheduler, graph results, active graph and adapter set: entering and leaving are +// the same four pointer swaps +void llama_context::graph_slot_swap(llama_graph_slot & slot) { + sched.swap(slot.sched); + gf_res_prev.swap(slot.gf_res_prev); + std::swap(gf_res_prev_active, slot.gf_res_prev_active); + loras.swap(slot.loras); +} + +void llama_context::graph_slot_leave() { + if (graph_slots.active) { + graph_slot_swap(*graph_slots.active); + graph_slots.active = nullptr; + } +} + +// a slot is freed only once the backends finished with its buffers (its last step may still be in flight) +static void graph_slot_free(std::unique_ptr & slot) { + ggml_backend_sched_synchronize(slot->sched.get()); + slot.reset(); +} + +// whom a sequence serves: the owner's name for her, or the sequence itself when the owner named no one +static uint64_t graph_slot_key(const llama_graph_slots & gs, llama_seq_id seq) { + const auto it = gs.named.find(seq); + return it != gs.named.end() ? it->second : (UINT64_C(1) << 63) | (uint64_t) (uint32_t) seq; +} + +// Each mind's steps keep their graph in her own slot (keyed by whom the ubatch's sequences serve). Whether her kept +// graph serves this step is the graph's own reuse check (its K/V extent, adapter set, pin and every other input), +// never a key derived here; when it cannot, her step rebuilds in her slot, and no other mind's graph is touched. +void llama_context::graph_slot_enter(const llama_ubatch & ubatch) { + auto & gs = graph_slots; + + // one token per sequence, nothing to learn, and no live owner holding this context's scheduler or its graph + const bool step = gs.in_decode && gs.capacity > 0 && ubatch.n_tokens == ubatch.n_seqs_unq && ubatch.n_labels() == 0 && + !opt_serving_continuation && !(opt_reply && opt_reply->graph_meta); + if (!step) { + graph_slot_leave(); + return; + } + + gs.key.clear(); + for (uint32_t s = 0; s < ubatch.n_seqs_unq; ++s) { + gs.key.push_back(graph_slot_key(gs, ubatch.seq_id_unq[s])); + } + if (gs.active && gs.active->key == gs.key) { // the next ubatch of the same decode + gs.active->used = ++gs.clock; + return; + } + graph_slot_leave(); + + // a slot made before an adapter was freed may name an address a new adapter now holds + const uint64_t frees = model.lora_frees.load(std::memory_order_acquire); + for (auto & slot : gs.slots) { + if (slot->lora_frees != frees) { + graph_slot_free(slot); + } + } + gs.slots.erase(std::remove(gs.slots.begin(), gs.slots.end(), nullptr), gs.slots.end()); + + auto own = std::find_if(gs.slots.begin(), gs.slots.end(), [&](const auto & slot) { return slot->key == gs.key; }); + llama_graph_slot * slot = nullptr; + if (own != gs.slots.end()) { + slot = own->get(); + } else if (gs.slots.size() < gs.capacity) { + auto made = std::make_unique(); + made->sched.reset(ggml_backend_sched_new(backend_ptrs.data(), backend_buft.data(), backend_ptrs.size(), + 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); + for (auto & res : made->gf_res_prev) { + res = std::make_unique(sched_params_cur.max_nodes); + } + made->loras = std::make_unique(); + made->lora_frees = frees; + gs.slots.push_back(std::move(made)); + slot = gs.slots.back().get(); + } else { // a mind with no slot takes the one served longest ago + slot = std::min_element(gs.slots.begin(), gs.slots.end(), [](const auto & a, const auto & b) { return a->used < b->used; })->get(); + } + + // her kept graph wears the set it was built with; a step wearing another (by value: addresses and scales, never + // dereferenced) rebuilds with a copy of the set it wears + const bool same_set = slot->key == gs.key && *slot->loras == *loras; + if (!same_set) { + slot->key = gs.key; + slot->loras = std::make_unique(*loras); + slot->gf_res_prev_active = nullptr; + } + slot->used = ++gs.clock; + gs.active = slot; + graph_slot_swap(*slot); +} + +void llama_context::set_graph_slot_key(llama_seq_id seq, uint64_t key) { + graph_slots.named[seq] = key; +} + +// the scheduler was re-reserved (its node budget or parameters changed): every slot was made for the old one +void llama_context::graph_slots_drop() { + graph_slot_leave(); + for (auto & slot : graph_slots.slots) { + graph_slot_free(slot); + } + graph_slots.slots.clear(); +} + +// no slot's graph may be reused across a change it cannot see; the schedulers and their buffers stay +void llama_context::graph_slots_forget() { + for (auto & slot : graph_slots.slots) { + for (auto & res : slot->gf_res_prev) { + res->reset(); + } + slot->gf_res_prev_active = nullptr; + } +} + +void llama_context::set_graph_slots(size_t n) { + graph_slot_leave(); + graph_slots.capacity = n; + auto & slots = graph_slots.slots; + while (slots.size() > n) { + auto lru = std::min_element(slots.begin(), slots.end(), [](const auto & a, const auto & b) { return a->used < b->used; }); + graph_slot_free(*lru); + slots.erase(lru); + } +} + +size_t llama_context::graph_slots_bytes() const { + size_t bytes = 0; + for (const auto & slot : graph_slots.slots) { + ggml_backend_sched * s = slot.get() == graph_slots.active ? sched.get() : slot->sched.get(); + for (auto * backend : backend_ptrs) { + bytes += ggml_backend_sched_get_buffer_size(s, backend); + } + } + return bytes; +} + +// every slot's compute buffers, counted beside the context's own +void llama_context::graph_slots_breakdown(std::map & ret, ggml_backend_t backend) const { + for (const auto & slot : graph_slots.slots) { + ggml_backend_sched * s = slot.get() == graph_slots.active ? sched.get() : slot->sched.get(); + ret[ggml_backend_sched_get_buffer_type(s, backend)].compute += + ggml_backend_sched_get_buffer_size(s, backend); + } +} + +void llama_set_graph_slots(llama_context * ctx, size_t n) { + ctx->set_graph_slots(n); +} + +size_t llama_graph_slots_bytes(const llama_context * ctx) { + return ctx->graph_slots_bytes(); +} + +void llama_set_graph_slot_key(llama_context * ctx, llama_seq_id seq, uint64_t key) { + ctx->set_graph_slot_key(seq, key); +} diff --git a/src/llama-graph-slots.h b/src/llama-graph-slots.h new file mode 100644 index 000000000000..5b7a9a3dc951 --- /dev/null +++ b/src/llama-graph-slots.h @@ -0,0 +1,47 @@ +#pragma once + +// Continuum: each mind's decode graph stays built and allocated across a switch to another mind. +// +// A backend scheduler holds the split and the allocation of ONE graph (ggml_backend_sched: splits, graph copy, galloc), +// so a context serving several minds one step at a time rebuilt, re-split and re-allocated its graph at every switch: +// on the M5 (Qwen3.6-35B-A3B, four residents) 0 of 74 decode steps reused a graph, with 78 switches in that turn. +// +// A slot is a second scheduler with its own graph results. Entering a slot SWAPS the context's scheduler, graph results, +// active graph and adapter set with the slot's, so every use of the context's scheduler is unchanged; leaving swaps them +// back. A swap is a pointer exchange, never a copy. A slot is active only inside decode(), for ubatches of one token per +// sequence; prefill and training run on the context's own scheduler, reserved for the worst case. +// +// The slot keeps the adapter set its graphs were built with, so the graph's own reuse check (llm_graph_params::allow_reuse, +// which compares the set by pointer) holds when the mind returns. An adapter freed on the model may come back at the same +// address, so a slot built before any free is dropped rather than compared (llama_model::lora_frees). + +#include "llama-adapter.h" +#include "llama-graph.h" + +#include "ggml-cpp.h" + +#include +#include +#include +#include +#include + +struct llama_graph_slot { + std::vector key; // whom its ubatch's sequences serve + llama_adapter_loras_ptr loras; // the set its graphs were built with + ggml_backend_sched_ptr sched; + std::array gf_res_prev; // per output shape, as the context's own + llm_graph_result * gf_res_prev_active = nullptr; + uint64_t lora_frees = 0; // the model's adapter frees when the slot was made + uint64_t used = 0; // the step it last served, for eviction +}; + +struct llama_graph_slots { + size_t capacity = 0; // set by the owner from the minds it keeps resident + std::vector> slots; + llama_graph_slot * active = nullptr; + bool in_decode = false; // slots serve decode() only (llama_context::graph_slot_scope) + uint64_t clock = 0; + std::unordered_map named; // whom each sequence serves, as its owner named her + std::vector key; // this step's, reused across steps +}; diff --git a/src/llama-lived-routing.cpp b/src/llama-lived-routing.cpp index bd6a08e3541f..be7972588e09 100644 --- a/src/llama-lived-routing.cpp +++ b/src/llama-lived-routing.cpp @@ -127,6 +127,14 @@ ggml_tensor * llama_route_experts(const llm_graph_context & graph, int32_t il, g // ---- the context ---- +// The most tokens a graph of this context is built for: a ubatch, rounded up to a multiple of the sequences as +// graph_reserve rounds it (three streams reserve 2049 of a 2048 ubatch; the M5, 2026-11-28 06:32Z aborted at the +// capture's bound on exactly that). +static int64_t capture_rows(const llama_cparams & cparams) { + const int64_t seqs = std::max(1, cparams.n_seq_max); + return ((int64_t) cparams.n_ubatch + seqs - 1) / seqs * seqs; +} + llama_routing_capture llama_context::set_routing_capture(bool on) { const auto & hp = model.hparams; if (on && hp.n_expert == 0) { @@ -145,7 +153,7 @@ llama_routing_capture llama_context::set_routing_capture(bool on) { ggml_init_params params = { /*.mem_size =*/ ggml_tensor_overhead(), /*.mem_buffer =*/ nullptr, /*.no_alloc =*/ true }; lived_routing.capture_ctx.reset(ggml_init(params)); lived_routing.capture_dev = ggml_new_tensor_2d(lived_routing.capture_ctx.get(), GGML_TYPE_I32, lived_routing.n_used, - (int64_t) lived_routing.n_layer * cparams.n_ubatch); + (int64_t) lived_routing.n_layer * capture_rows(cparams)); ggml_set_name(lived_routing.capture_dev, "lived_routing_capture"); ggml_backend_dev_t dev = model.dev_output(); auto * buft = dev ? ggml_backend_dev_buffer_type(dev) : ggml_backend_cpu_buffer_type(); @@ -290,6 +298,7 @@ void llama_context::drop_reusable_graphs() { res->reset(); } gf_res_prev_active = nullptr; + graph_slots_forget(); // Continuum: each mind's kept graph too (llama-graph-slots.cpp) } // ---- the API ---- diff --git a/src/llama-model.h b/src/llama-model.h index 18fa1f8187b3..ae97ad6c7e64 100644 --- a/src/llama-model.h +++ b/src/llama-model.h @@ -8,6 +8,7 @@ #include "llama-vocab.h" #include +#include #include #include #include @@ -1008,6 +1009,7 @@ struct llama_model { // guards `loras`: an adapter can be loaded or freed on one thread (e.g. a training context // in llama-server /train) while another context on the same model sizes its graph from it mutable std::shared_mutex loras_mutex; + std::atomic lora_frees{0}; // Continuum: adapters freed so far; a kept graph made before one is dropped (llama-graph-slots.h) // which tensors can be prefetched - driven by TENSOR_READ_LAZY std::unordered_set can_prefetch; diff --git a/tests/continuum-tests.cmake b/tests/continuum-tests.cmake index f5e8b0ff41cd..65e14882e6a8 100644 --- a/tests/continuum-tests.cmake +++ b/tests/continuum-tests.cmake @@ -59,6 +59,7 @@ if (NOT WIN32 OR NOT BUILD_SHARED_LIBS) # the exact walk trains on the window's whole gradient whatever the chunking: run on a pure-attention AND a # 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_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-graph-slots.cpp b/tests/test-graph-slots.cpp new file mode 100644 index 000000000000..48908968520e --- /dev/null +++ b/tests/test-graph-slots.cpp @@ -0,0 +1,223 @@ +// Continuum: each mind's decode graph kept across switches (src/llama-graph-slots.h). +// +// Four minds share one context, each at her own depth, three different adapter sets among them, and +// decode one token each in turn, as the lane serves residents. The same teacher-forced steps run twice, on two contexts: +// with no slots (every switch rebuilds, re-splits and re-allocates) and with one slot per mind. What this catches: +// - a kept graph that serves a mind's step with another mind's K/V, adapter set or shape: the logits must be +// bit-identical to the rebuilt graph's at every step; +// - a slot that does not keep its graph: with slots, every step after a mind's first reuses its graph. +// It prints ms/step for both, the graphs reused, and the bytes the slots hold. + +#include "arg.h" +#include "common.h" +#include "llama.h" + +#include +#include +#include +#include +#include +#include + +static constexpr uint32_t N_MINDS = 4; +static constexpr uint32_t N_GEN = 48; + +struct arm_result { + std::vector> logits; // [step][n_vocab] + double ms_per_step = 0.0; + int32_t reused = 0; + size_t slot_bytes = 0; + bool attached = false; +}; + +static uint64_t persona_id(uint32_t m) { return 0xA000 + m; } + +// One stream is the Core's shape: one mind is on the context at a time, bound into its one sequence by her blocks +// (llama_persona_bind) and saved out after her step, and each is named to the slots by her persona id. Many streams: +// each mind is her own sequence and the slots know her by it. +static arm_result run_arm(const common_params & params, llama_model * model, const std::vector & tokens, + llama_adapter_lora * a, llama_adapter_lora * b, uint32_t slots, bool one_stream) { + auto cparams = common_context_params_to_llama(params); + cparams.n_seq_max = one_stream ? 1 : N_MINDS; + cparams.n_ctx = (one_stream ? 1 : N_MINDS) * 2048; + 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; + cparams.no_perf = false; + llama_context * ctx = llama_init_from_model(model, cparams); + GGML_ASSERT(ctx != nullptr); + llama_set_graph_slots(ctx, slots); + const auto capture = llama_set_routing_capture(ctx, true); // as serving runs: each graph also records its routing + GGML_ASSERT(capture == LLAMA_ROUTING_CAPTURE_RECORDING || capture == LLAMA_ROUTING_CAPTURE_NO_EXPERTS); + + // mind 0 and 2 wear a, mind 1 wears b, mind 3 serves the base + float one = 1.0f; + llama_adapter_lora * genes[N_MINDS] = { a, b, a, nullptr }; + auto wear = [&](uint32_t m) { + GGML_ASSERT(llama_set_adapters_lora(ctx, genes[m] ? &genes[m] : nullptr, genes[m] ? 1 : 0, &one) == 0); + }; + llama_persona * persona[N_MINDS] = {}; + // her storage is memory this test owns (the block layer's role: her mapped file), attached once, so binding her + // points the stream at it and saving her points it away: the Core's move on a device that views host memory + const size_t storage = one_stream ? llama_persona_storage_bytes(ctx) : 0; + const bool attaches = storage > 0 && llama_persona_storage_viewable(ctx); + const size_t page = 1u << 16; + std::vector> memory(attaches ? N_MINDS : 0, std::vector(storage + 2 * page)); + auto aligned = [&](std::vector & m) { return reinterpret_cast((reinterpret_cast(m.data()) + page - 1) & ~(uintptr_t) (page - 1)); }; + auto seq_of = [&](uint32_t m) { return one_stream ? (llama_seq_id) 0 : (llama_seq_id) m; }; + auto bind = [&](uint32_t m) { + if (one_stream) { + GGML_ASSERT(llama_persona_bind(ctx, 0, persona[m]) == 0); + llama_set_graph_slot_key(ctx, 0, persona_id(m)); + } + }; + auto park = [&](uint32_t m) { + if (one_stream) { + GGML_ASSERT(llama_persona_save(ctx, 0, persona[m]) == 0); + } + }; + + 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); + }; + llama_pos pos[N_MINDS]; + for (uint32_t m = 0; m < N_MINDS; ++m) { // each at its own depth, so each has its own n_kv + const uint32_t n = 260 + 256 * m; // its N_GEN steps stay inside one 256-cell block: n_kv never changes + if (one_stream) { + persona[m] = llama_persona_init(ctx, persona_id(m), 1); + GGML_ASSERT(persona[m] != nullptr); + if (attaches) { // bound fresh before her first token, she decodes straight into her storage + GGML_ASSERT(llama_persona_storage_attach(ctx, persona[m], aligned(memory[m]), storage + page) == 0); + GGML_ASSERT(llama_persona_bind(ctx, 0, persona[m]) == 0); + } + llama_set_graph_slot_key(ctx, 0, persona_id(m)); + } + wear(m); + for (uint32_t i = 0; i < n; ++i) { + put(tokens[(i + 97 * m) % tokens.size()], (llama_pos) i, seq_of(m), i + 1 == n); + } + decode(); + (void) llama_get_logits_ith(ctx, -1); + park(m); + pos[m] = (llama_pos) n; + } + llama_perf_context_reset(ctx); + + arm_result r; + const int32_t n_vocab = llama_vocab_n_tokens(llama_model_get_vocab(model)); + const auto t0 = std::chrono::steady_clock::now(); + for (uint32_t g = 0; g < N_GEN; ++g) { + for (uint32_t m = 0; m < N_MINDS; ++m) { + bind(m); + wear(m); + put(tokens[(size_t) (pos[m] + 31 * m) % tokens.size()], pos[m], seq_of(m), true); + decode(); + const float * l = llama_get_logits_ith(ctx, -1); + r.logits.emplace_back(l, l + n_vocab); + park(m); + ++pos[m]; + } + } + const double ms = std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); + r.ms_per_step = ms / (N_GEN * N_MINDS); + r.reused = llama_perf_context(ctx).n_reused; + r.slot_bytes = llama_graph_slots_bytes(ctx); + r.attached = attaches; + llama_batch_ext_free(batch); + for (auto * p : persona) { + llama_persona_free(p); + } + 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); + + const std::string init = "test-graph-slots." + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()) + ".gguf"; + GGML_ASSERT(common_lora_write_fresh(model, init, 8, 16, { "attn_q", "attn_v" }, 42)); + llama_adapter_lora * a = llama_adapter_lora_init(model, init.c_str()); + llama_adapter_lora * b = llama_adapter_lora_init(model, init.c_str()); + GGML_ASSERT(a != nullptr && b != nullptr); + std::remove(init.c_str()); + + std::string text; + uint32_t lcg = 12345; + static const char * words[] = { "room", "card", "claim", "review", "patch", "lease", "board", "turn" }; + while (text.size() < 16384) { + 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() > 2048); + + // what this catches (the M5, 2026-11-28 06:32Z): a context whose streams do not divide its ubatch (three of 2048) + // reserves a graph rounded up past the ubatch (2049), and the routing capture sized for exactly the ubatch aborted + // at its bound in sched_reserve, before any decode + { + auto cparams = common_context_params_to_llama(params); + cparams.n_seq_max = 3; + cparams.n_ctx = 3 * 2048; + cparams.n_batch = 2048; + cparams.n_ubatch = 2048; + cparams.kv_unified = false; + llama_context * ctx = llama_init_from_model(model, cparams); + GGML_ASSERT(ctx != nullptr); + const auto capture = llama_set_routing_capture(ctx, true); + GGML_ASSERT(capture == LLAMA_ROUTING_CAPTURE_RECORDING || capture == LLAMA_ROUTING_CAPTURE_NO_EXPERTS); + // a setting changed after the capture is on: the decode re-reserves its graphs with the capture in them, as + // serving's does (the abort's path: decode, sched_reserve, graph_reserve) + llama_set_embeddings(ctx, true); + llama_batch_ext * batch = llama_batch_ext_init(ctx); + GGML_ASSERT(batch != nullptr); + const llama_pos at = 0; + const int32_t i = llama_batch_ext_add_token(batch, 0, tokens[0]); + GGML_ASSERT(i >= 0 && llama_batch_ext_set_pos(batch, i, &at) && llama_batch_ext_set_output_logits(batch, i, true)); + GGML_ASSERT(llama_process(ctx, LLAMA_PROCESS_TYPE_DECODE, batch) == 0); + llama_batch_ext_free(batch); + llama_free(ctx); + printf("graph-slots: three streams reserve and decode with routing captured\n"); + } + + bool ok = true; + for (const bool one_stream : { false, true }) { + const arm_result rebuilt = run_arm(params, model, tokens, a, b, 0, one_stream); + const arm_result kept = run_arm(params, model, tokens, a, b, N_MINDS, one_stream); + float max_diff = 0.0f; + for (size_t s = 0; s < rebuilt.logits.size(); ++s) { + for (size_t i = 0; i < rebuilt.logits[s].size(); ++i) { + max_diff = std::max(max_diff, std::fabs(rebuilt.logits[s][i] - kept.logits[s][i])); + } + } + const int32_t steps = (int32_t) (N_GEN * N_MINDS); + printf("graph slots, %s: %u minds, %d steps: rebuilt %.2f ms/step (%d reused), kept %.2f ms/step (%d reused), " + "slots hold %.1f MiB, max |logit diff| %g\n", one_stream ? (kept.attached ? "one stream, attached storage (the Core)" : "one stream, row copies") : "a stream each", + N_MINDS, steps, rebuilt.ms_per_step, rebuilt.reused, kept.ms_per_step, kept.reused, + kept.slot_bytes / 1024.0 / 1024.0, max_diff); + if (max_diff != 0.0f) { printf("FAIL: a kept graph served different logits\n"); ok = false; } + if (kept.reused < steps - (int32_t) N_MINDS) { printf("FAIL: a slot rebuilt a mind's graph it kept\n"); ok = false; } + } + + llama_adapter_lora_free(a); + llama_adapter_lora_free(b); + llama_model_free(model); + llama_backend_free(); + return ok ? 0 : 1; +}