Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions include/llama.h
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand Down
1 change: 1 addition & 0 deletions src/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions src/llama-adapter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -587,6 +587,7 @@ void llama_adapter_lora_free(llama_adapter_lora * adapter) {
if (adapter->model != nullptr) {
std::unique_lock<std::shared_mutex> 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;
}

Expand Down
5 changes: 5 additions & 0 deletions src/llama-context.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand Down Expand Up @@ -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__);
}
Expand Down Expand Up @@ -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();

Expand Down Expand Up @@ -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();

Expand Down Expand Up @@ -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;
Expand Down
18 changes: 18 additions & 0 deletions src/llama-context.h
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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<std::vector<llama_seq_id>> seqs; // per ubatch row
Expand Down Expand Up @@ -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<ggml_backend_buffer_type_t, llama_memory_breakdown_data> & 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;
Expand Down
169 changes: 169 additions & 0 deletions src/llama-graph-slots.cpp
Original file line number Diff line number Diff line change
@@ -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 <algorithm>

// 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<llama_graph_slot> & 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<llama_graph_slot>();
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<llm_graph_result>(sched_params_cur.max_nodes);
}
made->loras = std::make_unique<llama_adapter_loras>();
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<llama_adapter_loras>(*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<ggml_backend_buffer_type_t, llama_memory_breakdown_data> & 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);
}
47 changes: 47 additions & 0 deletions src/llama-graph-slots.h
Original file line number Diff line number Diff line change
@@ -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 <array>
#include <cstdint>
#include <memory>
#include <unordered_map>
#include <vector>

struct llama_graph_slot {
std::vector<uint64_t> 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<llm_graph_result_ptr, 2> 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<std::unique_ptr<llama_graph_slot>> 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<llama_seq_id, uint64_t> named; // whom each sequence serves, as its owner named her
std::vector<uint64_t> key; // this step's, reused across steps
};
11 changes: 10 additions & 1 deletion src/llama-lived-routing.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<int64_t>(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) {
Expand All @@ -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();
Expand Down Expand Up @@ -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 ----
Expand Down
2 changes: 2 additions & 0 deletions src/llama-model.h
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
#include "llama-vocab.h"

#include <map>
#include <atomic>
#include <memory>
#include <string>
#include <unordered_map>
Expand Down Expand Up @@ -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<uint64_t> 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<const ggml_tensor *> can_prefetch;
Expand Down
1 change: 1 addition & 0 deletions tests/continuum-tests.cmake
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Loading
Loading