From 0d2e3d9813b8eccb100720bc65fbef27685c6e8b Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sat, 28 Nov 2026 07:31:25 -0600 Subject: [PATCH 1/4] One decode serves minds wearing different adapters, each adapter on her own rows A context applied ONE adapter set to every row of a ubatch, so minds bound in streams of one context shared a step only while they wore the same adapters. On the M5 (2026-11-28, Qwen3.6-35B-A3B) every resident wore her own, and a turn chose a batch 85 times and batched nothing. A sequence now names its own set (llama_set_seq_adapters_lora), once, when its owner binds a mind to it; an empty set is the base. A sequence that names none wears the context's set, and a context that never names one builds upstream's graph. At graph build the ubatch's rows are grouped by the set they wear and each adapter's delta is added to its group's rows only: consecutive rows are a view, interleaved rows are gathered and written back by index (correct, slower, counted by llama_seq_adapters_gathered). Rows never move, so output indices hold; base rows are in no group. The groups (sets, scales, rows, the model's adapter frees) are part of the graph's identity, so a set rebound under another scale rebuilds the graph and the same step again reuses it. Decode refuses a token shared by sequences wearing different sets, and a set named before an adapter was freed. Organized as the fork's other additions: the data model and the graph in llama-adapter-seq.{h,cpp}; upstream code gains one-line hooks (the three LoRA sites, graph_params, decode, graph_max_nodes) and two lines in llm_graph_params. test-seq-adapters, against upstream stepping one mind at a time under the context's set (Codex's cases: rows swapped with sequence ids kept, a rebind at another scale on a warm graph, the base after an adapted owner; interleaved groups; the shared-token refusal), on both KV layouts: - qwen35-0.8b CPU: bit-exact in every phase (adapter effect 1.4-2.0); Metal: within 1.0-1.6x the kernels' own difference between one row and four (<=1.8e-3), 0 argmax flips of 24 per phase - a random qwen35moe with every expert weight adapted (build_lora_mm_id): exact on CPU, <=1.2e-7 on Metal - graph reuse after each phase's first step equal to upstream's batch with no adapter, every phase Found on the way: upstream adds a context set's adapters in its hash map's order, and on a hybrid one ulp at a step moved the next step's logits by 0.19 on the CPU, so the test takes upstream in both orders. And with kv_unified off (the Core's layout) split_equal takes a ubatch's sequences only in consecutive increasing ids: a batch out of that order is split into several ubatches and reuses no graph (phases 1 and 5, upstream's path too). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- include/llama.h | 21 +++ src/CMakeLists.txt | 1 + src/llama-adapter-seq.cpp | 300 +++++++++++++++++++++++++++++++ src/llama-adapter-seq.h | 83 +++++++++ src/llama-context.cpp | 5 + src/llama-context.h | 8 + src/llama-graph.cpp | 4 + src/llama-graph.h | 15 ++ tests/continuum-tests.cmake | 2 + tests/test-seq-adapters.cpp | 348 ++++++++++++++++++++++++++++++++++++ 10 files changed, 787 insertions(+) create mode 100644 src/llama-adapter-seq.cpp create mode 100644 src/llama-adapter-seq.h create mode 100644 tests/test-seq-adapters.cpp diff --git a/include/llama.h b/include/llama.h index e439c57d66e7..46a6593c81cf 100644 --- a/include/llama.h +++ b/include/llama.h @@ -2241,6 +2241,27 @@ 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); + // Give sequence `seq` its own adapter set (Continuum), so one decode serves sequences wearing different + // adapters: each adapter's delta is added to its own sequences' rows only. Name it when a mind is bound to the + // sequence, never per step; n_adapters 0 (or every scale 0) is the base model, no adapter. The adapters must be + // loaded on the context's model. A sequence that names none wears the context's set (llama_set_adapters_lora). + // Returns 0, -1 for a sequence outside the context or missing adapters, -2 for an adapter not on the model. + // A token shared by sequences wearing different sets is refused by decode; an adapter freed after a set was + // named refuses decode until the set is named again. + LLAMA_API int32_t llama_set_seq_adapters_lora( + struct llama_context * ctx, + llama_seq_id seq, + struct llama_adapter_lora ** adapters, + size_t n_adapters, + const float * scales); + + // Return sequence `seq` to the context's set: when her mind is released from it. + LLAMA_API void llama_clear_seq_adapters_lora(struct llama_context * ctx, llama_seq_id seq); + + // The ubatches whose sequences' sets interleaved, so their rows were gathered and written back by index + // instead of viewed: the fast path's misses, for a probe. Order a batch's sequences by set to avoid them. + LLAMA_API uint64_t llama_seq_adapters_gathered(const struct llama_context * ctx); + // 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 diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 31c372b28508..1c716f6d7184 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-adapter-seq.cpp llama-output-ring.cpp llama-context-opt-measure.cpp llama-context-learn.cpp diff --git a/src/llama-adapter-seq.cpp b/src/llama-adapter-seq.cpp new file mode 100644 index 000000000000..bcb9c05342e8 --- /dev/null +++ b/src/llama-adapter-seq.cpp @@ -0,0 +1,300 @@ +// Continuum: an adapter set per sequence (llama-adapter-seq.h). + +#include "llama-adapter-seq.h" + +#include "llama-context.h" +#include "llama-graph.h" +#include "llama-impl.h" +#include "llama-model.h" + +#include +#include +#include + +// +// the sets +// + +llama_adapter_set llama_adapter_set_of(const llama_adapter_loras & loras, const llama_adapter_lora * shadow) { + llama_adapter_set set; + set.adapters.reserve(loras.size()); + for (const auto & [adapter, scale] : loras) { + if (adapter != shadow && scale != 0.0f) { + set.adapters.emplace_back(adapter, scale); + } + } + std::sort(set.adapters.begin(), set.adapters.end()); + return set; +} + +bool llama_adapter_seq_groups::gathered() const { + return std::any_of(groups.begin(), groups.end(), [](const llama_adapter_seq_group & group) { return !group.consecutive(); }); +} + +llama_adapter_set llama_adapter_seq_sets::wears(llama_seq_id seq, const llama_adapter_set & context_set) const { + const auto it = by_seq.find(seq); + return it == by_seq.end() ? context_set : it->second.set; +} + +llama_adapter_seq_groups llama_adapter_seq_sets::group(const llama_ubatch & ubatch, const llama_adapter_set & context_set, uint64_t lora_frees) const { + llama_adapter_seq_groups out; + if (by_seq.empty()) { + return out; + } + bool named = false; + for (uint32_t s = 0; s < ubatch.n_seqs_unq; ++s) { + named = named || by_seq.count(ubatch.seq_id_unq[s]) > 0; + } + if (!named) { + return out; + } + out.named = true; + out.lora_frees = lora_frees; + // a row's set is its first sequence's: decode refused a token whose sequences wear different sets (refuses) + for (uint32_t i = 0; i < ubatch.n_tokens; ++i) { + llama_adapter_set set = wears(ubatch.seq_id[i][0], context_set); + if (set.adapters.empty()) { + continue; // the base: no delta, no group + } + auto it = std::find_if(out.groups.begin(), out.groups.end(), [&](const llama_adapter_seq_group & group) { return group.set == set; }); + if (it == out.groups.end()) { + out.groups.push_back({ std::move(set), (int32_t) i, 1, {} }); + continue; + } + if (it->consecutive() && it->begin + it->n == (int32_t) i) { + ++it->n; + continue; + } + if (it->consecutive()) { // its rows interleave with another group's: list them + for (int32_t r = it->begin; r < it->begin + it->n; ++r) { + it->rows.push_back(r); + } + } + it->rows.push_back((int32_t) i); + ++it->n; + } + if (out.gathered()) { + ++gathered; + } + return out; +} + +const char * llama_adapter_seq_sets::refuses(const llama_batch_ext & batch, const llama_adapter_set & context_set, uint64_t lora_frees) const { + if (by_seq.empty()) { + return nullptr; + } + for (const auto & [seq, named] : by_seq) { + if (named.lora_frees != lora_frees && !named.set.adapters.empty()) { + return "a sequence's adapter set was named before an adapter was freed; name it again"; + } + } + for (const auto & token : batch.tokens) { + if (token.seq_ids.size() < 2) { + continue; + } + const llama_adapter_set first = wears(*token.seq_ids.begin(), context_set); + for (const llama_seq_id seq : token.seq_ids) { + if (wears(seq, context_set) != first) { + return "a token is shared by sequences that wear different adapter sets; submit it once per set"; + } + } + } + return nullptr; +} + +// +// the context +// + +int32_t llama_context::set_seq_adapters_lora(llama_seq_id seq, llama_adapter_lora ** adapters, size_t n_adapters, const float * scales) { + if (seq < 0 || (uint32_t) seq >= cparams.n_seq_max) { + LLAMA_LOG_ERROR("%s: sequence %d is outside the context's %u\n", __func__, seq, cparams.n_seq_max); + return -1; + } + llama_adapter_seq_sets::named named; + { + std::shared_lock lock(model.loras_mutex); // an adapter may load or free on another thread + for (size_t i = 0; i < n_adapters; ++i) { + if (model.loras.count(adapters[i]) == 0) { + LLAMA_LOG_ERROR("%s: adapter %zu is not loaded on this model\n", __func__, i); + return -2; + } + if (scales[i] != 0.0f) { + named.set.adapters.emplace_back(adapters[i], scales[i]); + } + } + named.lora_frees = model.lora_frees.load(std::memory_order_acquire); + } + std::sort(named.set.adapters.begin(), named.set.adapters.end()); + seq_adapters.by_seq[seq] = std::move(named); + // groups add each set's deltas: the scheduler's node budget is re-reserved only if they could exceed it + sched_need_reserve = sched_need_reserve || graph_max_nodes() > sched_max_nodes; + return 0; +} + +void llama_context::clear_seq_adapters_lora(llama_seq_id seq) { + seq_adapters.by_seq.erase(seq); +} + +llama_adapter_set llama_context::seq_adapters_context_set() const { + return llama_adapter_set_of(*loras, opt_shadow); +} + +bool llama_context::seq_adapters_refuse(const llama_batch_ext & batch) const { + const char * why = seq_adapters.refuses(batch, seq_adapters_context_set(), model.lora_frees.load(std::memory_order_acquire)); + if (why != nullptr) { + LLAMA_LOG_ERROR("%s: %s\n", __func__, why); + } + return why != nullptr; +} + +void llama_context::seq_adapters_graph_params(llm_graph_params & params, const llama_ubatch & ubatch) const { + params.seq_groups = seq_adapters.group(ubatch, seq_adapters_context_set(), model.lora_frees.load(std::memory_order_acquire)); +} + +uint32_t llama_context::seq_adapters_max_nodes() const { + if (seq_adapters.by_seq.empty()) { + return 0; + } + // every group may wear every adapter, each delta adding the views of its rows and its add into them. Called by + // graph_max_nodes under its shared lock on model.loras_mutex (a second shared lock on one thread is undefined) + uint32_t per_set = 0; + for (const auto & lora : model.loras) { + per_set += lora->get_n_nodes() * 2u; + } + return per_set * cparams.n_seq_max; +} + +// +// the graph +// + +namespace { + +// the rows of an interleaved group, set from its list +class llm_graph_input_seq_rows : public llm_graph_input_i { +public: + explicit llm_graph_input_seq_rows(std::vector rows) : rows(std::move(rows)) {} + + void set_input(const llama_ubatch * ubatch) override { + GGML_UNUSED(ubatch); + ggml_backend_tensor_set(tensor, rows.data(), 0, rows.size() * sizeof(int32_t)); + } + + // the graph is reused only under the same groups (llm_graph_params::allow_reuse), so the same rows + bool can_reuse(const llm_graph_params & params) override { + GGML_UNUSED(params); + return true; + } + + std::vector rows; + ggml_tensor * tensor = nullptr; +}; + +// t's rows [begin, begin + n), its tokens its outermost dimension +ggml_tensor * rows_view(ggml_context * ctx, ggml_tensor * t, int64_t n_tokens, int32_t begin, int32_t n) { + const int d = ggml_n_dims(t) - 1; + GGML_ASSERT(t->ne[d] == n_tokens && "an adapter group's rows are its tensor's outermost dimension"); + switch (d) { + case 0: return ggml_view_1d(ctx, t, n, begin * t->nb[0]); + case 1: return ggml_view_2d(ctx, t, t->ne[0], n, t->nb[1], begin * t->nb[1]); + default: return ggml_view_3d(ctx, t, t->ne[0], t->ne[1], n, t->nb[1], t->nb[2], begin * t->nb[2]); + } +} + +} // namespace + +// one delta per adapter of each group that wears one, on that group's rows; `term` builds an adapter's delta on rows +// [begin, begin + n) of its inputs (all of them when n is the ubatch's) +template +ggml_tensor * llm_graph_context::seq_lora_apply(ggml_tensor * res, ggml_tensor * w, Term term) const { + for (const auto & group : seq_groups.groups) { + for (const auto & [adapter, scale] : group.set.adapters) { + llama_adapter_lora_weight * lw = adapter->get_weight(w); + if (lw == nullptr) { + continue; + } + if (group.n == (int32_t) n_tokens) { + res = ggml_add(ctx0, res, term(adapter, lw, scale, 0, group.n)); + } else if (group.consecutive()) { + const int d = ggml_n_dims(res) - 1; + res = ggml_acc(ctx0, res, term(adapter, lw, scale, group.begin, group.n), res->nb[1], res->nb[2], res->nb[3], group.begin * res->nb[d]); + } else { + res = seq_rows_add(res, term(adapter, lw, scale, 0, (int32_t) n_tokens), group.rows); + } + } + } + // the training shadow is the context's, on the labelled rows whatever set they wear + for (const auto & [adapter, scale] : *loras) { + llama_adapter_lora_weight * lw = adapter == shadow && lora_on(adapter) ? adapter->get_weight(w) : nullptr; + if (lw != nullptr) { + res = shadow_add(res, term(adapter, lw, scale, 0, (int32_t) n_tokens)); + } + } + return res; +} + +// base plus term on the listed rows only, as shadow_add: gathered, added, written back into a copy of base, so every +// other row is base byte for byte +ggml_tensor * llm_graph_context::seq_rows_add(ggml_tensor * base, ggml_tensor * term, const std::vector & rows) const { + auto inp = std::make_unique(rows); + inp->tensor = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, (int64_t) rows.size()); + ggml_set_input(inp->tensor); + ggml_tensor * idx = inp->tensor; + res->add_input(std::move(inp)); + + GGML_ASSERT(ggml_is_contiguous(base)); + const int64_t n = ggml_nelements(base) / n_tokens; + ggml_tensor * b2 = ggml_n_dims(base) <= 2 ? base : ggml_reshape_2d(ctx0, base, n, n_tokens); + ggml_tensor * t2 = ggml_n_dims(term) <= 2 ? term : ggml_reshape_2d(ctx0, ggml_cont(ctx0, term), n, n_tokens); + ggml_tensor * sel = ggml_add(ctx0, ggml_get_rows(ctx0, b2, idx), ggml_get_rows(ctx0, t2, idx)); + ggml_tensor * updated = ggml_set_rows(ctx0, ggml_dup(ctx0, b2), sel, idx); + return ggml_n_dims(base) <= 2 ? updated : ggml_reshape(ctx0, updated, base); +} + +ggml_tensor * llm_graph_context::seq_lora_mm(ggml_tensor * w, ggml_tensor * cur, ggml_tensor * out) const { + return seq_lora_apply(out, w, [&](llama_adapter_lora * adapter, llama_adapter_lora_weight * lw, float scale, int32_t begin, int32_t n) { + ggml_tensor * x = n == (int32_t) n_tokens ? cur : rows_view(ctx0, cur, n_tokens, begin, n); + ggml_tensor * ab = ggml_mul_mat(ctx0, lw->b, ggml_mul_mat(ctx0, lw->a, x)); + return ggml_scale(ctx0, ab, lw->get_scale(adapter->alpha, scale)); + }); +} + +ggml_tensor * llm_graph_context::seq_lora_mm_id(ggml_tensor * w, ggml_tensor * cur, ggml_tensor * ids, ggml_tensor * out) const { + return seq_lora_apply(out, w, [&](llama_adapter_lora * adapter, llama_adapter_lora_weight * lw, float scale, int32_t begin, int32_t n) { + const bool all = n == (int32_t) n_tokens; + ggml_tensor * x = all ? cur : rows_view(ctx0, cur, n_tokens, begin, n); + ggml_tensor * id = all ? ids : rows_view(ctx0, ids, n_tokens, begin, n); + ggml_tensor * ab = ggml_mul_mat_id(ctx0, lw->b, ggml_mul_mat_id(ctx0, lw->a, x, id), id); + // as build_lora_mm_id: the rank is B's input width + const float rank = (float) lw->b->ne[0]; + return ggml_scale(ctx0, ab, adapter->alpha ? scale * adapter->alpha / rank : scale); + }); +} + +ggml_tensor * llm_graph_context::seq_lora_embd(ggml_tensor * tok_embd, ggml_tensor * ids, ggml_tensor * cur) const { + return seq_lora_apply(cur, tok_embd, [&](llama_adapter_lora * adapter, llama_adapter_lora_weight * lw, float scale, int32_t begin, int32_t n) { + ggml_tensor * id = n == (int32_t) n_tokens ? ids : rows_view(ctx0, ids, n_tokens, begin, n); + return ggml_scale(ctx0, ggml_mul_mat(ctx0, lw->b, ggml_get_rows(ctx0, lw->a, id)), lw->get_scale(adapter->alpha, scale)); + }); +} + +// +// the API +// + +int32_t llama_set_seq_adapters_lora(llama_context * ctx, llama_seq_id seq, llama_adapter_lora ** adapters, size_t n_adapters, const float * scales) { + if (n_adapters > 0 && (adapters == nullptr || scales == nullptr)) { + LLAMA_LOG_ERROR("%s: %zu adapters with no adapters or scales\n", __func__, n_adapters); + return -1; + } + return ctx->set_seq_adapters_lora(seq, adapters, n_adapters, scales); +} + +void llama_clear_seq_adapters_lora(llama_context * ctx, llama_seq_id seq) { + ctx->clear_seq_adapters_lora(seq); +} + +uint64_t llama_seq_adapters_gathered(const llama_context * ctx) { + return ctx->seq_adapters.gathered; +} diff --git a/src/llama-adapter-seq.h b/src/llama-adapter-seq.h new file mode 100644 index 000000000000..d0e4f85aec03 --- /dev/null +++ b/src/llama-adapter-seq.h @@ -0,0 +1,83 @@ +#pragma once + +// Continuum: an adapter set per sequence, so one step decodes minds wearing different adapters. +// +// A context applies ONE adapter set (llama_set_adapters_lora) to every row of a ubatch, so minds bound in streams of one +// context could share a step only while they wore the same adapters: on the M5 (2026-11-28, Qwen3.6-35B-A3B) every +// resident wore her own three, and the lane chose a batch 85 times in a turn and batched nothing. +// +// A sequence may name its own set (llama_set_seq_adapters_lora), once, when its owner binds a mind to it; an empty set +// is the base model. A sequence that names none wears the context's set, so a context that never names one builds the +// graph upstream builds. At graph build the ubatch's rows are grouped by the set they wear, and each adapter's delta is +// computed on its group's rows only: a group of consecutive rows is a view (no copy); rows that interleave with another +// group's are gathered and written back by index, correct and slower, and counted (llama_seq_adapters_gathered). +// Rows never move, so the caller's output indices hold. The training shadow stays the context's: it adds to the +// labelled rows whatever set they wear. + +#include "llama-adapter.h" +#include "llama-batch.h" + +#include +#include +#include +#include + +// an adapter set by value: each adapter with its scale, ordered by address, no zero scale +struct llama_adapter_set { + std::vector> adapters; + + bool operator==(const llama_adapter_set & other) const { return adapters == other.adapters; } + bool operator!=(const llama_adapter_set & other) const { return !(*this == other); } +}; + +// the rows of one ubatch that wear one set: [begin, begin + n) when consecutive, else each row listed +struct llama_adapter_seq_group { + llama_adapter_set set; + int32_t begin = 0; + int32_t n = 0; + std::vector rows; // empty when consecutive + + bool consecutive() const { return rows.empty(); } + bool operator==(const llama_adapter_seq_group & other) const { + return set == other.set && begin == other.begin && n == other.n && rows == other.rows; + } +}; + +// a ubatch's groups, part of its graph's identity (llm_graph_params::allow_reuse): a step with the same rows under the +// same sets and scales reuses its graph, and a set rebound under another scale rebuilds it. Rows on the base model are +// in no group (they add nothing, so they never interleave). Empty when no row's sequence names a set of its own: the +// graph is upstream's. +struct llama_adapter_seq_groups { + bool named = false; // some row's sequence names a set + std::vector groups; + uint64_t lora_frees = 0; // the model's adapter frees when grouped: an address freed and reused is another adapter + + bool empty() const { return !named; } + bool gathered() const; + bool operator==(const llama_adapter_seq_groups & other) const { + return named == other.named && groups == other.groups && lora_frees == other.lora_frees; + } +}; + +// what a context holds: each sequence's own set, as its owner named it +struct llama_adapter_seq_sets { + struct named { + llama_adapter_set set; + uint64_t lora_frees = 0; // the model's adapter frees when it was named + }; + std::unordered_map by_seq; + mutable uint64_t gathered = 0; // ubatches whose groups interleaved + + // the set a row of `seq` wears: her own, or the context's (without the training shadow, which is added apart) + llama_adapter_set wears(llama_seq_id seq, const llama_adapter_set & context_set) const; + + // a ubatch's groups; empty when none of its sequences names a set + llama_adapter_seq_groups group(const llama_ubatch & ubatch, const llama_adapter_set & context_set, uint64_t lora_frees) const; + + // why a batch cannot be decoded, or nullptr: a token shared by sequences that wear different sets (each set needs + // its own evaluation of the token, so the caller submits it once per set), or a set named before an adapter was freed + const char * refuses(const llama_batch_ext & batch, const llama_adapter_set & context_set, uint64_t lora_frees) const; +}; + +// the context's set as a value, without the training shadow +llama_adapter_set llama_adapter_set_of(const llama_adapter_loras & loras, const llama_adapter_lora * shadow); diff --git a/src/llama-context.cpp b/src/llama-context.cpp index 4624b7e571f4..58f46c86f90a 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -2183,6 +2183,9 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { if (adapters_restore_uncertain(__func__)) { // Continuum return -1; } + if (seq_adapters_refuse(batch_inp)) { // Continuum: a token under two sequences' different sets (llama-adapter-seq.cpp) + return -1; + } if (!memory) { LLAMA_LOG_DEBUG("%s: cannot decode batches with this context (calling encode() instead)\n", __func__); @@ -2961,6 +2964,7 @@ uint32_t llama_context::graph_max_nodes() const { for (const auto & lora : model.loras) { res += lora->get_n_nodes(); } + res += seq_adapters_max_nodes(); // Continuum: each sequence's set adds its deltas, under the lock above (llama-adapter-seq.cpp) // the MoE cache adds a lookup to each MoE layer, and a second expert path with a CPU share (up to ~16 tensors per layer), // which the per-tensor estimates above do not cover for models with few tensors per layer @@ -3139,6 +3143,7 @@ llm_graph_params llama_context::graph_params( /*.res =*/ res, }; opt_graph_params(params, ubatch); // Continuum: the shadow, its rows and the streams (llama-context-opt.cpp) + seq_adapters_graph_params(params, ubatch); // Continuum: each sequence's adapter set (llama-adapter-seq.cpp) return params; } diff --git a/src/llama-context.h b/src/llama-context.h index d51504568b72..0c7002c05755 100644 --- a/src/llama-context.h +++ b/src/llama-context.h @@ -253,6 +253,14 @@ 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); + // Continuum: each sequence's own adapter set (llama-adapter-seq.cpp) + int32_t set_seq_adapters_lora(llama_seq_id seq, llama_adapter_lora ** adapters, size_t n_adapters, const float * scales); + void clear_seq_adapters_lora(llama_seq_id seq); + llama_adapter_set seq_adapters_context_set() const; + bool seq_adapters_refuse(const llama_batch_ext & batch) const; + void seq_adapters_graph_params(llm_graph_params & params, const llama_ubatch & ubatch) const; + uint32_t seq_adapters_max_nodes() const; + llama_adapter_seq_sets seq_adapters; 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); diff --git a/src/llama-graph.cpp b/src/llama-graph.cpp index 9f2aa41af816..c2a825a7220a 100644 --- a/src/llama-graph.cpp +++ b/src/llama-graph.cpp @@ -1732,6 +1732,7 @@ llm_graph_context::llm_graph_context(const llm_graph_params & params) : moe_cache (params.moe_cache), shadow (params.shadow), // Continuum n_shadow_rows (params.n_shadow_rows), + seq_groups (params.seq_groups), // Continuum hdmd (model.hdmd.rot.empty() ? nullptr : &model.hdmd), layer_inp_dev (params.layer_inp_dev), layer_inp_src (params.layer_inp_src), @@ -1844,6 +1845,7 @@ ggml_tensor * llm_graph_context::build_lora_mm( res = ggml_mul(ctx0, res, w_s); } + if (!seq_groups.empty()) { return seq_lora_mm(w, cur, res); } // Continuum: each sequence's set (llama-adapter-seq.cpp) for (const auto & lora : *loras) { llama_adapter_lora_weight * lw = lora.first->get_weight(w); if (lw == nullptr || !lora_on(lora.first)) { @@ -1932,6 +1934,7 @@ ggml_tensor * llm_graph_context::build_lora_mm_id( s = ggml_get_rows(ctx0, s, ids); res = ggml_mul(ctx0, res, s); } + if (!seq_groups.empty()) { return seq_lora_mm_id(w, cur, ids, res); } // Continuum: each sequence's set (llama-adapter-seq.cpp) for (const auto & lora : *loras) { llama_adapter_lora_weight * lw = lora.first->get_weight(w); if (lw == nullptr || !lora_on(lora.first)) { @@ -2824,6 +2827,7 @@ ggml_tensor * llm_graph_context::build_inp_embd(ggml_tensor * tok_embd, float to } // apply lora for embedding tokens if needed + if (!seq_groups.empty()) { cur = seq_lora_embd(tok_embd, ids, cur); } else // Continuum: each sequence's set (llama-adapter-seq.cpp) for (const auto & lora : *loras) { llama_adapter_lora_weight * lw = lora.first->get_weight(tok_embd); if (lw == nullptr || !lora_on(lora.first)) { diff --git a/src/llama-graph.h b/src/llama-graph.h index 0deff3325406..894c4be689cb 100644 --- a/src/llama-graph.h +++ b/src/llama-graph.h @@ -4,6 +4,7 @@ #include "llama-batch.h" #include "llama-hparams.h" #include "llama-adapter.h" +#include "llama-adapter-seq.h" // Continuum #include #include @@ -915,6 +916,8 @@ struct llm_graph_params { // the physical attention stream of each of the ubatch's unique sequences (seq_id_unq order): the graph's K/V // views are built at these streams, so a graph is reused only when they match std::vector streams = {}; + // the ubatch's rows grouped by the adapter set each sequence wears (llama-adapter-seq.h); empty: the context's set + llama_adapter_seq_groups seq_groups = {}; // return true if the "other" params would result in a graph with the same topology as with the current params // having the same topology allows us to reuse the graph in some cases @@ -999,6 +1002,7 @@ struct llm_graph_params { cparams.training == other.cparams.training && // Continuum: a training graph and its shadow shadow == other.shadow && n_shadow_rows == other.n_shadow_rows && + seq_groups == other.seq_groups && // Continuum (llama-adapter-seq.h) cross == other.cross; } }; @@ -1206,6 +1210,7 @@ struct llm_graph_context { // Continuum (llama-graph-train.cpp) const llama_adapter_lora * shadow; const uint32_t n_shadow_rows; + const llama_adapter_seq_groups seq_groups; // Continuum (llama-adapter-seq.cpp) mutable ggml_tensor * inp_train_rows = nullptr; // build_inp_train_rows, once per graph mutable llm_graph_input_training_rows * inp_training_rows = nullptr; // the in-place training attention's K/V grad sinks (tap k, chunk k, tap v, chunk v), set by @@ -1599,6 +1604,16 @@ struct llm_graph_context { // whether an attached adapter's term is in this graph: every one but the shadow always, the // shadow only when the ubatch has labelled rows bool lora_on(const llama_adapter_lora * adapter) const; + + // Continuum: each sequence's own adapter set (llama-adapter-seq.cpp). Where any row's sequence names one, these + // replace upstream's loop over the context's set in build_lora_mm, build_lora_mm_id and the token embedding: each + // group's adapters add to its own rows, and the training shadow to the labelled rows + ggml_tensor * seq_lora_mm(ggml_tensor * w, ggml_tensor * cur, ggml_tensor * out) const; + ggml_tensor * seq_lora_mm_id(ggml_tensor * w, ggml_tensor * cur, ggml_tensor * ids, ggml_tensor * out) const; + ggml_tensor * seq_lora_embd(ggml_tensor * tok_embd, ggml_tensor * ids, ggml_tensor * cur) const; + template + ggml_tensor * seq_lora_apply(ggml_tensor * res, ggml_tensor * w, Term term) const; + ggml_tensor * seq_rows_add(ggml_tensor * base, ggml_tensor * term, const std::vector & rows) const; // base plus the shadow's term, on the labelled rows only (Cormac, 2026-10-14): those rows of // base and of the term are gathered and added, and written back into a copy of base; every // other row is base, byte for byte. A multiplied 0/1 mask was not: an untrained layer's inf or diff --git a/tests/continuum-tests.cmake b/tests/continuum-tests.cmake index 54b329f133ae..5f7ab58bf98c 100644 --- a/tests/continuum-tests.cmake +++ b/tests/continuum-tests.cmake @@ -60,6 +60,8 @@ 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) + # one decode serves minds wearing different adapters, each on her own rows (src/llama-adapter-seq.h): -m a model + llama_build(test-seq-adapters.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) diff --git a/tests/test-seq-adapters.cpp b/tests/test-seq-adapters.cpp new file mode 100644 index 000000000000..5dad755ec9f9 --- /dev/null +++ b/tests/test-seq-adapters.cpp @@ -0,0 +1,348 @@ +// Continuum: an adapter set per sequence (src/llama-adapter-seq.h). +// +// Four minds share one context, each in her own sequence at her own depth, each wearing her own adapters (two distinct +// nonzero adapters, both at once, and the base). The same teacher-forced tokens are decoded several ways: the +// REFERENCE steps one mind at a time under upstream's context-wide set (llama_set_adapters_lora), in both orders of a +// two-adapter set (upstream adds them in its hash map's order, and on a hybrid one ulp at a step moved the next step's +// logits by 0.19 on the CPU); the BASE does the same with no adapter, and the SHAPE batches it, measuring the kernels' +// own difference between one row and four; the BATCH steps all four in one decode, each naming her set on her +// sequence. What this catches: +// - a delta added to another mind's rows, or a mind's rows given another set: each batched mind's logits must match +// her nearer reference within the kernels' own difference (bit-exact on the CPU), and sit ten times closer to it +// than the smallest adapter's effect (her reference against the base); +// - rows reordered with their sequence ids kept (Codex's case), a set rebound under another scale on a warm graph, +// and the base after an adapted owner: each phase below changes one of these and is held to the same bound; +// - interleaved groups (one set on rows 0 and 2): gathered and written back by index, counted, and held to the bound; +// - a token shared by sequences wearing different sets: refused, nothing decoded. +// The adapters are fresh ones with a nonzero B (a fresh B is zero: its delta would be nothing to test). + +#include "arg.h" +#include "common.h" +#include "llama.h" +#include "gguf.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +static constexpr uint32_t N_MINDS = 4; +static constexpr uint32_t PHASE = 6; // steps per phase +static constexpr uint32_t PHASES = 6; + +using set_t = std::vector>; + +// the phases: what each mind wears, and the order of her row in the batch +struct phase_t { + const char * what; + uint32_t order[N_MINDS]; +}; +static const phase_t phases[PHASES] = { + { "each her own set, rows in order", { 0, 1, 2, 3 } }, + { "rows swapped, sequence ids kept", { 1, 0, 3, 2 } }, + { "mind 0 rebound at another scale (warm graph)", { 0, 1, 2, 3 } }, + { "mind 1 on the base after her adapter", { 0, 1, 2, 3 } }, + { "minds 0 and 2 share a set on rows 0 and 2", { 0, 1, 2, 3 } }, + { "the same sets with their rows consecutive", { 0, 2, 1, 3 } }, +}; + +static set_t wears(uint32_t phase, uint32_t m, llama_adapter_lora * a, llama_adapter_lora * b) { + const set_t sets[N_MINDS] = { { { a, 1.0f } }, { { b, 1.0f } }, { { a, 1.0f }, { b, 0.75f } }, {} }; + set_t set = sets[m]; + if (m == 0 && phase >= 2) { set = { { a, 0.5f } }; } + if (m == 1 && phase >= 3) { set = {}; } + if (m == 2 && phase >= 4) { set = { { a, 0.5f } }; } + return set; +} + +static bool ends_with(const std::string & s, const std::string & tail) { + return s.size() >= tail.size() && s.compare(s.size() - tail.size(), tail.size(), tail) == 0; +} + +static void fill(ggml_tensor * t, std::mt19937 & rng, float bound) { + GGML_ASSERT(t->type == GGML_TYPE_F32); + std::uniform_real_distribution u(-bound, bound); + float * v = (float *) t->data; + for (int64_t j = 0; j < ggml_nelements(t); ++j) { + v[j] = u(rng); + } +} + +// a fresh adapter with B drawn as A is, so its delta is nonzero; on a mixture of experts it also adapts every expert +// weight ([n_in, n_out, n_expert]: A [n_in, rank, n_expert], B [rank, n_out, n_expert]), so build_lora_mm_id is tested +static llama_adapter_lora * adapter(llama_model * model, const std::string & model_path, uint32_t seed) { + constexpr int64_t rank = 8; + const std::string path = "test-seq-adapters." + std::to_string(seed) + "." + + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()) + ".gguf"; + GGML_ASSERT(common_lora_write_fresh(model, path, (int32_t) rank, 16, { "attn_q", "attn_v", "ffn_up", "ffn_down" }, seed)); + ggml_context * data = nullptr; + gguf_context * in = gguf_init_from_file(path.c_str(), { /*.no_alloc =*/ false, /*.ctx =*/ &data }); + GGML_ASSERT(in != nullptr && data != nullptr); + gguf_context * out = gguf_init_empty(); + gguf_set_kv(out, in); + std::mt19937 rng(seed); + for (int64_t i = 0; i < gguf_get_n_tensors(in); ++i) { + ggml_tensor * t = ggml_get_tensor(data, gguf_get_tensor_name(in, i)); + if (ends_with(ggml_get_name(t), ".lora_b")) { + fill(t, rng, 0.02f); + } + gguf_add_tensor(out, t); + } + + ggml_context * shapes = nullptr; + gguf_context * base = gguf_init_from_file(model_path.c_str(), { /*.no_alloc =*/ true, /*.ctx =*/ &shapes }); + GGML_ASSERT(base != nullptr && shapes != nullptr); + std::vector> experts; + for (int64_t i = 0; i < gguf_get_n_tensors(base); ++i) { + const std::string name = gguf_get_tensor_name(base, i); + if (ends_with(name, "_exps.weight")) { + experts.emplace_back(ggml_get_tensor(shapes, name.c_str()), name); + } + } + ggml_context * extra = ggml_init({ /*.mem_size =*/ experts.size() * 2 * ggml_tensor_overhead(), /*.mem_buffer =*/ nullptr, /*.no_alloc =*/ true }); + std::vector> owned; + owned.reserve(experts.size() * 2); + for (const auto & [w, name] : experts) { + ggml_tensor * a = ggml_new_tensor_3d(extra, GGML_TYPE_F32, w->ne[0], rank, w->ne[2]); + ggml_tensor * b = ggml_new_tensor_3d(extra, GGML_TYPE_F32, rank, w->ne[1], w->ne[2]); + ggml_set_name(a, (name + ".lora_a").c_str()); + ggml_set_name(b, (name + ".lora_b").c_str()); + for (ggml_tensor * t : { a, b }) { + owned.emplace_back(ggml_nelements(t)); + t->data = owned.back().data(); + fill(t, rng, t == a ? 1.0f / std::sqrt((float) w->ne[0]) : 0.02f); + gguf_add_tensor(out, t); + } + } + GGML_ASSERT(gguf_write_to_file(out, path.c_str(), false)); + printf("seq-adapters: adapter %u adapts %lld expert weights\n", seed, (long long) experts.size()); + gguf_free(base); + ggml_free(shapes); + ggml_free(extra); + gguf_free(out); + gguf_free(in); + ggml_free(data); + llama_adapter_lora * loaded = llama_adapter_lora_init(model, path.c_str()); + GGML_ASSERT(loaded != nullptr); + std::remove(path.c_str()); + return loaded; +} + +// reference_reversed: upstream adds a set's adapters in its map's order, so a two-adapter set's reference is taken in +// both orders; base_batch: the batch with no adapter, the kernels' own difference +enum class arm { reference, reference_reversed, base, batch, base_batch }; + +struct arm_result { + std::vector> logits; // [step * N_MINDS + mind][n_vocab] + uint64_t gathered[PHASES] = {}; + bool refused_shared = false; + int32_t reused[PHASES] = {}; // graphs reused in each phase after its first step +}; + +static arm_result run_arm(const common_params & params, llama_model * model, const std::vector & tokens, + llama_adapter_lora * a, llama_adapter_lora * b, arm kind, bool unified) { + auto cparams = common_context_params_to_llama(params); + cparams.n_seq_max = N_MINDS; + cparams.n_ctx = N_MINDS * 1024; + cparams.n_batch = 1024; + cparams.n_ubatch = 1024; + cparams.kv_unified = unified; + cparams.no_perf = false; // the graphs reused are read back + llama_context * ctx = llama_init_from_model(model, cparams); + GGML_ASSERT(ctx != nullptr); + const int32_t n_vocab = llama_vocab_n_tokens(llama_model_get_vocab(model)); + + auto context_set = [&](const set_t & set) { + std::vector adapters; + std::vector scales; + for (const auto & [ad, sc] : set) { adapters.push_back(ad); scales.push_back(sc); } + if (kind == arm::reference_reversed) { + std::reverse(adapters.begin(), adapters.end()); + std::reverse(scales.begin(), scales.end()); + } + GGML_ASSERT(llama_set_adapters_lora(ctx, adapters.data(), adapters.size(), scales.data()) == 0); + }; + auto seq_set = [&](llama_seq_id seq, const set_t & set) { + std::vector adapters; + std::vector scales; + for (const auto & [ad, sc] : set) { adapters.push_back(ad); scales.push_back(sc); } + GGML_ASSERT(llama_set_seq_adapters_lora(ctx, seq, adapters.data(), adapters.size(), scales.data()) == 0); + }; + + llama_batch_ext * batch = llama_batch_ext_init(ctx); + 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)); + return i; + }; + auto decode = [&]() { + const int32_t ret = llama_process(ctx, LLAMA_PROCESS_TYPE_DECODE, batch); + llama_batch_ext_clear(batch); + return ret; + }; + + // each mind prefilled at her own depth under her first set: the batch arm's named on her sequence first, as a bind + // names it, so her prefill takes the same path as her steps (a whole ubatch in one group) + llama_pos pos[N_MINDS]; + for (uint32_t m = 0; m < N_MINDS; ++m) { + if (kind == arm::batch) { + seq_set((llama_seq_id) m, wears(0, m, a, b)); + } else { + context_set(kind == arm::base || kind == arm::base_batch ? set_t{} : wears(0, m, a, b)); + } + const uint32_t n = 40 + 23 * m; + for (uint32_t i = 0; i < n; ++i) { + put(tokens[(i + 97 * m) % tokens.size()], (llama_pos) i, (llama_seq_id) m, i + 1 == n); + } + GGML_ASSERT(decode() == 0); + pos[m] = (llama_pos) n; + } + // the batch arm's minds name their own sets, and the context wears b: a mind named to the base that fell back to the + // context's set would wear b + context_set(kind == arm::batch ? set_t{ { b, 1.0f } } : set_t{}); + + arm_result r; + r.logits.resize(PHASES * PHASE * N_MINDS); + for (uint32_t ph = 0; ph < PHASES; ++ph) { + if (kind == arm::batch) { + for (uint32_t m = 0; m < N_MINDS; ++m) { + seq_set((llama_seq_id) m, wears(ph, m, a, b)); // named once per phase, as a bind names it + } + } + const uint64_t gathered0 = llama_seq_adapters_gathered(ctx); + int32_t reused0 = 0; + for (uint32_t g = 0; g < PHASE; ++g) { + const uint32_t step = ph * PHASE + g; + auto token = [&](uint32_t m) { return tokens[(size_t) (pos[m] + 31 * m) % tokens.size()]; }; + if (kind == arm::batch || kind == arm::base_batch) { + for (uint32_t row = 0; row < N_MINDS; ++row) { + const uint32_t m = phases[ph].order[row]; + put(token(m), pos[m], (llama_seq_id) m, true); + } + GGML_ASSERT(decode() == 0); + for (uint32_t row = 0; row < N_MINDS; ++row) { + const float * l = llama_get_logits_ith(ctx, (int32_t) row); + r.logits[step * N_MINDS + phases[ph].order[row]].assign(l, l + n_vocab); + } + } else { + for (uint32_t m = 0; m < N_MINDS; ++m) { + context_set(kind == arm::base ? set_t{} : wears(ph, m, a, b)); + put(token(m), pos[m], (llama_seq_id) m, true); + GGML_ASSERT(decode() == 0); + const float * l = llama_get_logits_ith(ctx, -1); + r.logits[step * N_MINDS + m].assign(l, l + n_vocab); + } + } + for (uint32_t m = 0; m < N_MINDS; ++m) { + ++pos[m]; + } + if (g == 0) { + reused0 = llama_perf_context(ctx).n_reused; // the phase's first step builds what its sets need + } + } + r.gathered[ph] = llama_seq_adapters_gathered(ctx) - gathered0; + r.reused[ph] = llama_perf_context(ctx).n_reused - reused0; + } + + if (kind == arm::batch) { + // minds 0 and 1 wear different sets (phase 5: a at 0.5, and the base): one token under both is refused + const int32_t i = put(tokens[0], std::max(pos[0], pos[1]), 0, true); + GGML_ASSERT(llama_batch_ext_add_seq(batch, i, 1)); + r.refused_shared = decode() != 0; + } + llama_batch_ext_free(batch); + llama_free(ctx); + return r; +} + +static float max_diff(const std::vector & x, const std::vector & y) { + float d = 0.0f; + for (size_t i = 0; i < x.size(); ++i) { + d = std::max(d, std::fabs(x[i] - y[i])); + } + return d; +} + +static size_t argmax(const std::vector & x) { + return (size_t) (std::max_element(x.begin(), x.end()) - x.begin()); +} + +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); + llama_adapter_lora * a = adapter(model, params.model.path, 42); + llama_adapter_lora * b = adapter(model, params.model.path, 7); + + std::string text; + for (int i = 0; i < 64; ++i) { + text += "Each mind keeps her own notes about the board, the card, the claim and the review. "; + } + const std::vector tokens = common_tokenize(llama_model_get_vocab(model), text, true, false); + + // the Core's layout (a stream per mind, kv_unified off) and upstream's default (one unified cache). Off, a ubatch + // takes its sequences in consecutive increasing ids (llama_batch_allocr::split_equal, sequential), so a batch whose + // rows are out of that order is split into several ubatches; unified, the swapped and interleaved rows below share + // one ubatch + bool ok = true; + for (const bool unified : { false, true }) { + printf("seq-adapters: kv_unified %s\n", unified ? "on" : "off"); + const arm_result ref = run_arm(params, model, tokens, a, b, arm::reference, unified); + const arm_result rev = run_arm(params, model, tokens, a, b, arm::reference_reversed, unified); + const arm_result base = run_arm(params, model, tokens, a, b, arm::base, unified); + const arm_result batch = run_arm(params, model, tokens, a, b, arm::batch, unified); + const arm_result shape = run_arm(params, model, tokens, a, b, arm::base_batch, unified); + + for (uint32_t ph = 0; ph < PHASES; ++ph) { + float worst = 0.0f, effect = INFINITY, kernels = 0.0f, orders = 0.0f, scale = 0.0f; + uint32_t flips = 0; + for (uint32_t g = 0; g < PHASE; ++g) { + const uint32_t step = ph * PHASE + g; + for (uint32_t m = 0; m < N_MINDS; ++m) { + const size_t k = step * N_MINDS + m; + // her nearer reference: upstream's sum over two adapters takes either order + const float d_ref = max_diff(batch.logits[k], ref.logits[k]); + const float d_rev = max_diff(batch.logits[k], rev.logits[k]); + worst = std::max(worst, std::min(d_ref, d_rev)); + orders = std::max(orders, max_diff(ref.logits[k], rev.logits[k])); + kernels = std::max(kernels, max_diff(shape.logits[k], base.logits[k])); + for (const float v : ref.logits[k]) { scale = std::max(scale, std::fabs(v)); } + flips += argmax(batch.logits[k]) != argmax((d_ref <= d_rev ? ref : rev).logits[k]); + if (!wears(ph, m, a, b).empty()) { + effect = std::min(effect, max_diff(ref.logits[k], base.logits[k])); + } + } + } + // within the kernels' own difference and one ulp at the logits' scale: exact on the CPU; on Metal the + // adapters' matmuls add their own shapes' difference (measured 1.0-1.6x the base's, 2026-11-28: bounded at 2x) + const bool exact = worst <= 2.0f * kernels + FLT_EPSILON * scale; + const bool passed = exact && worst * 10.0f < effect; + const bool counted = batch.gathered[ph] == (ph == 4 ? PHASE : 0); // phase 4 interleaves, in one ubatch either way + // groups never cost a reuse: after its first step, a phase reuses exactly the graphs upstream's batch does + const bool reuses = batch.reused[ph] == shape.reused[ph]; + printf("seq-adapters: phase %u (%s): max |batch - nearer reference| %.3e (kernels' own %.3e, upstream's two orders %.3e), " + "smallest adapter effect %.3e, argmax flips %u of %u, gathered %llu, graphs reused %d (upstream %d)%s\n", + ph, phases[ph].what, worst, kernels, orders, effect, flips, PHASE * N_MINDS, + (unsigned long long) batch.gathered[ph], batch.reused[ph], shape.reused[ph], + passed && counted && reuses ? "" : " <-- FAILED"); + ok = ok && passed && counted && reuses; + } + printf("seq-adapters: a token under two sequences wearing different sets is %s\n", batch.refused_shared ? "refused" : "DECODED <-- FAILED"); + ok = ok && batch.refused_shared; + } + + llama_adapter_lora_free(a); + llama_adapter_lora_free(b); + llama_model_free(model); + llama_backend_free(); + printf("seq-adapters: %s\n", ok ? "OK" : "FAILED"); + return ok ? 0 : 1; +} From 97426c1379dd0279706ecc765983c59eec280224 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sat, 28 Nov 2026 07:58:33 -0600 Subject: [PATCH 2/4] An adapter group adds to its own output rows, and only a free of its own adapter refuses it Codex's two blockers on #172: - Sparse output rows. Past inp_out_ids a tensor holds only the rows whose logits were asked for, so the token-space rows a group knew were the wrong rows there (or out of range: the CPU's get_rows aborted on the new test's phase 6 before this). A group now knows its rows in both spaces, among the ubatch's tokens and among its outputs (the output rank, as inp_out_ids lists them in row order), and each site reads its tensor's row count exactly (the expert ids, the token ids, a projection input's outermost dimension) to pick the space; a count that is neither aborts rather than adding a delta to the wrong rows. - Model-wide free invalidation. Any adapter freed anywhere on the model refused every named set and rebuilt every graph (the new test's unrelated free mid-phase refused the next decode before this). An adapter is now named by its address and a serial unique per load (llama_adapter_lora::serial, one field in upstream's struct): a set is refused only when one of its own adapters is gone or its address holds another load, and the graph's identity compares the serials, so a free of anything else changes nothing. test-seq-adapters gains two phases of two tokens per mind with logits at the end only (outputs a subset; interleaved, then consecutive), an adapter nobody wears loaded and freed mid-phase (reuse must still equal upstream's), and the refusal of a set whose own adapter was freed. Both old failures reproduced against 0d2e3d981's library with this test. ## Measured (the M5, 2026-11-28) - qwen35-0.8b CPU: bit-exact in all 8 phases on both KV layouts (adapter effect 1.4-2.0), both refusals hold. - qwen35-0.8b Metal: <= 3.2e-3, 1.0-1.6x the kernels' own one-row-against-four difference, 0 argmax flips. - random qwen35moe, every expert adapted: OK on CPU and Metal. - graphs reused after each phase's first step equal upstream's batch with no adapter, every phase, including the phase with the unrelated free. test-graph-slots unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- src/llama-adapter-seq.cpp | 185 +++++++++++++++++++++--------------- src/llama-adapter-seq.h | 75 ++++++++++----- src/llama-adapter.h | 5 + src/llama-graph.h | 5 +- tests/test-seq-adapters.cpp | 60 ++++++++---- 5 files changed, 212 insertions(+), 118 deletions(-) diff --git a/src/llama-adapter-seq.cpp b/src/llama-adapter-seq.cpp index bcb9c05342e8..d64b416fb65f 100644 --- a/src/llama-adapter-seq.cpp +++ b/src/llama-adapter-seq.cpp @@ -8,6 +8,7 @@ #include "llama-model.h" #include +#include #include #include @@ -15,63 +16,73 @@ // the sets // +uint64_t llama_adapter_lora_next_serial() { + static std::atomic next{1}; + return next.fetch_add(1, std::memory_order_relaxed); +} + llama_adapter_set llama_adapter_set_of(const llama_adapter_loras & loras, const llama_adapter_lora * shadow) { llama_adapter_set set; set.adapters.reserve(loras.size()); for (const auto & [adapter, scale] : loras) { if (adapter != shadow && scale != 0.0f) { - set.adapters.emplace_back(adapter, scale); + set.adapters.push_back({ adapter, adapter->serial, scale }); } } std::sort(set.adapters.begin(), set.adapters.end()); return set; } +void llama_adapter_seq_rows::add(int32_t row) { + if (n == 0) { + begin = row; + } else if (consecutive() && row != begin + n) { // its rows interleave with another group's: list them + for (int32_t r = begin; r < begin + n; ++r) { + rows.push_back(r); + } + } + if (!consecutive()) { + rows.push_back(row); + } + ++n; +} + bool llama_adapter_seq_groups::gathered() const { - return std::any_of(groups.begin(), groups.end(), [](const llama_adapter_seq_group & group) { return !group.consecutive(); }); + return std::any_of(groups.begin(), groups.end(), [](const llama_adapter_seq_group & group) { + return !group.tokens.consecutive() || !group.outputs.consecutive(); + }); } -llama_adapter_set llama_adapter_seq_sets::wears(llama_seq_id seq, const llama_adapter_set & context_set) const { +const llama_adapter_set & llama_adapter_seq_sets::wears(llama_seq_id seq, const llama_adapter_set & context_set) const { const auto it = by_seq.find(seq); - return it == by_seq.end() ? context_set : it->second.set; + return it == by_seq.end() ? context_set : it->second; } -llama_adapter_seq_groups llama_adapter_seq_sets::group(const llama_ubatch & ubatch, const llama_adapter_set & context_set, uint64_t lora_frees) const { +llama_adapter_seq_groups llama_adapter_seq_sets::group(const llama_ubatch & ubatch, const llama_adapter_set & context_set) const { llama_adapter_seq_groups out; - if (by_seq.empty()) { - return out; - } - bool named = false; - for (uint32_t s = 0; s < ubatch.n_seqs_unq; ++s) { - named = named || by_seq.count(ubatch.seq_id_unq[s]) > 0; + for (uint32_t s = 0; s < ubatch.n_seqs_unq && !by_seq.empty(); ++s) { + out.named = out.named || by_seq.count(ubatch.seq_id_unq[s]) > 0; } - if (!named) { + if (!out.named) { return out; } - out.named = true; - out.lora_frees = lora_frees; - // a row's set is its first sequence's: decode refused a token whose sequences wear different sets (refuses) + // a row's set is its first sequence's: decode refused a token whose sequences wear different sets (refuses). Its + // output rank is its place among the rows whose logits were asked for (inp_out_ids lists them in row order) + int32_t output = 0; for (uint32_t i = 0; i < ubatch.n_tokens; ++i) { - llama_adapter_set set = wears(ubatch.seq_id[i][0], context_set); - if (set.adapters.empty()) { - continue; // the base: no delta, no group - } - auto it = std::find_if(out.groups.begin(), out.groups.end(), [&](const llama_adapter_seq_group & group) { return group.set == set; }); - if (it == out.groups.end()) { - out.groups.push_back({ std::move(set), (int32_t) i, 1, {} }); - continue; - } - if (it->consecutive() && it->begin + it->n == (int32_t) i) { - ++it->n; - continue; - } - if (it->consecutive()) { // its rows interleave with another group's: list them - for (int32_t r = it->begin; r < it->begin + it->n; ++r) { - it->rows.push_back(r); + const bool outputs = ubatch.output == nullptr || ubatch.output[i]; + const llama_adapter_set & set = wears(ubatch.seq_id[i][0], context_set); + if (!set.adapters.empty()) { // the base: no delta, no group + auto it = std::find_if(out.groups.begin(), out.groups.end(), [&](const llama_adapter_seq_group & group) { return group.set == set; }); + if (it == out.groups.end()) { + it = out.groups.insert(out.groups.end(), llama_adapter_seq_group{ set, {}, {} }); + } + it->tokens.add((int32_t) i); + if (outputs) { + it->outputs.add(output); } } - it->rows.push_back((int32_t) i); - ++it->n; + output += outputs; } if (out.gathered()) { ++gathered; @@ -79,20 +90,26 @@ llama_adapter_seq_groups llama_adapter_seq_sets::group(const llama_ubatch & ubat return out; } -const char * llama_adapter_seq_sets::refuses(const llama_batch_ext & batch, const llama_adapter_set & context_set, uint64_t lora_frees) const { +const char * llama_adapter_seq_sets::refuses(const llama_batch_ext & batch, const llama_adapter_set & context_set, const llama_model & model) const { if (by_seq.empty()) { return nullptr; } - for (const auto & [seq, named] : by_seq) { - if (named.lora_frees != lora_frees && !named.set.adapters.empty()) { - return "a sequence's adapter set was named before an adapter was freed; name it again"; + { + std::shared_lock lock(model.loras_mutex); // an adapter may load or free on another thread + for (const auto & [seq, set] : by_seq) { + for (const auto & entry : set.adapters) { + // the address must still be loaded on the model, and be the same load (read only once it is known alive) + if (model.loras.count(entry.adapter) == 0 || entry.adapter->serial != entry.serial) { + return "an adapter a sequence names was freed; name its set again"; + } + } } } for (const auto & token : batch.tokens) { if (token.seq_ids.size() < 2) { continue; } - const llama_adapter_set first = wears(*token.seq_ids.begin(), context_set); + const llama_adapter_set & first = wears(*token.seq_ids.begin(), context_set); for (const llama_seq_id seq : token.seq_ids) { if (wears(seq, context_set) != first) { return "a token is shared by sequences that wear different adapter sets; submit it once per set"; @@ -111,7 +128,7 @@ int32_t llama_context::set_seq_adapters_lora(llama_seq_id seq, llama_adapter_lor LLAMA_LOG_ERROR("%s: sequence %d is outside the context's %u\n", __func__, seq, cparams.n_seq_max); return -1; } - llama_adapter_seq_sets::named named; + llama_adapter_set set; { std::shared_lock lock(model.loras_mutex); // an adapter may load or free on another thread for (size_t i = 0; i < n_adapters; ++i) { @@ -120,13 +137,12 @@ int32_t llama_context::set_seq_adapters_lora(llama_seq_id seq, llama_adapter_lor return -2; } if (scales[i] != 0.0f) { - named.set.adapters.emplace_back(adapters[i], scales[i]); + set.adapters.push_back({ adapters[i], adapters[i]->serial, scales[i] }); } } - named.lora_frees = model.lora_frees.load(std::memory_order_acquire); } - std::sort(named.set.adapters.begin(), named.set.adapters.end()); - seq_adapters.by_seq[seq] = std::move(named); + std::sort(set.adapters.begin(), set.adapters.end()); + seq_adapters.by_seq[seq] = std::move(set); // groups add each set's deltas: the scheduler's node budget is re-reserved only if they could exceed it sched_need_reserve = sched_need_reserve || graph_max_nodes() > sched_max_nodes; return 0; @@ -141,7 +157,7 @@ llama_adapter_set llama_context::seq_adapters_context_set() const { } bool llama_context::seq_adapters_refuse(const llama_batch_ext & batch) const { - const char * why = seq_adapters.refuses(batch, seq_adapters_context_set(), model.lora_frees.load(std::memory_order_acquire)); + const char * why = seq_adapters.refuses(batch, seq_adapters_context_set(), model); if (why != nullptr) { LLAMA_LOG_ERROR("%s: %s\n", __func__, why); } @@ -149,7 +165,7 @@ bool llama_context::seq_adapters_refuse(const llama_batch_ext & batch) const { } void llama_context::seq_adapters_graph_params(llm_graph_params & params, const llama_ubatch & ubatch) const { - params.seq_groups = seq_adapters.group(ubatch, seq_adapters_context_set(), model.lora_frees.load(std::memory_order_acquire)); + params.seq_groups = seq_adapters.group(ubatch, seq_adapters_context_set()); } uint32_t llama_context::seq_adapters_max_nodes() const { @@ -191,10 +207,8 @@ class llm_graph_input_seq_rows : public llm_graph_input_i { ggml_tensor * tensor = nullptr; }; -// t's rows [begin, begin + n), its tokens its outermost dimension -ggml_tensor * rows_view(ggml_context * ctx, ggml_tensor * t, int64_t n_tokens, int32_t begin, int32_t n) { - const int d = ggml_n_dims(t) - 1; - GGML_ASSERT(t->ne[d] == n_tokens && "an adapter group's rows are its tensor's outermost dimension"); +// t's rows [begin, begin + n) along dimension `d`, its rows +ggml_tensor * rows_view(ggml_context * ctx, ggml_tensor * t, int d, int32_t begin, int32_t n) { switch (d) { case 0: return ggml_view_1d(ctx, t, n, begin * t->nb[0]); case 1: return ggml_view_2d(ctx, t, t->ne[0], n, t->nb[1], begin * t->nb[1]); @@ -204,23 +218,38 @@ ggml_tensor * rows_view(ggml_context * ctx, ggml_tensor * t, int64_t n_tokens, i } // namespace -// one delta per adapter of each group that wears one, on that group's rows; `term` builds an adapter's delta on rows -// [begin, begin + n) of its inputs (all of them when n is the ubatch's) +// The rows a tensor holds: the ubatch's tokens, or (after inp_out_ids) its outputs. A count that is neither is a shape +// this path does not know, and building on it would add a delta to the wrong rows. +const llama_adapter_seq_rows & llm_graph_context::seq_rows_of(const llama_adapter_seq_group & group, int64_t rows) const { + if (rows == (int64_t) n_tokens) { + return group.tokens; + } + if (rows == (int64_t) n_outputs) { + return group.outputs; + } + GGML_ABORT("an adapter target holds %lld rows: neither the ubatch's %u tokens nor its %u outputs", (long long) rows, n_tokens, n_outputs); +} + +// one delta per adapter of each group that wears one, on that group's rows of `res`, which holds `rows` rows along +// dimension `d`; `term` builds an adapter's delta on rows [begin, begin + n) of its inputs (all of them when n is `rows`) template -ggml_tensor * llm_graph_context::seq_lora_apply(ggml_tensor * res, ggml_tensor * w, Term term) const { +ggml_tensor * llm_graph_context::seq_lora_apply(ggml_tensor * res, ggml_tensor * w, int d, int64_t rows, Term term) const { for (const auto & group : seq_groups.groups) { - for (const auto & [adapter, scale] : group.set.adapters) { - llama_adapter_lora_weight * lw = adapter->get_weight(w); + const llama_adapter_seq_rows & mine = seq_rows_of(group, rows); + if (mine.n == 0) { + continue; // none of this group's rows are here (none of them asked for logits) + } + for (const auto & entry : group.set.adapters) { + llama_adapter_lora_weight * lw = entry.adapter->get_weight(w); if (lw == nullptr) { continue; } - if (group.n == (int32_t) n_tokens) { - res = ggml_add(ctx0, res, term(adapter, lw, scale, 0, group.n)); - } else if (group.consecutive()) { - const int d = ggml_n_dims(res) - 1; - res = ggml_acc(ctx0, res, term(adapter, lw, scale, group.begin, group.n), res->nb[1], res->nb[2], res->nb[3], group.begin * res->nb[d]); + if (mine.n == rows) { + res = ggml_add(ctx0, res, term(entry.adapter, lw, entry.scale, 0, mine.n)); + } else if (mine.consecutive()) { + res = ggml_acc(ctx0, res, term(entry.adapter, lw, entry.scale, mine.begin, mine.n), res->nb[1], res->nb[2], res->nb[3], mine.begin * res->nb[d]); } else { - res = seq_rows_add(res, term(adapter, lw, scale, 0, (int32_t) n_tokens), group.rows); + res = seq_rows_add(res, term(entry.adapter, lw, entry.scale, 0, (int32_t) rows), mine.rows, rows); } } } @@ -228,7 +257,7 @@ ggml_tensor * llm_graph_context::seq_lora_apply(ggml_tensor * res, ggml_tensor * for (const auto & [adapter, scale] : *loras) { llama_adapter_lora_weight * lw = adapter == shadow && lora_on(adapter) ? adapter->get_weight(w) : nullptr; if (lw != nullptr) { - res = shadow_add(res, term(adapter, lw, scale, 0, (int32_t) n_tokens)); + res = shadow_add(res, term(adapter, lw, scale, 0, (int32_t) rows)); } } return res; @@ -236,35 +265,40 @@ ggml_tensor * llm_graph_context::seq_lora_apply(ggml_tensor * res, ggml_tensor * // base plus term on the listed rows only, as shadow_add: gathered, added, written back into a copy of base, so every // other row is base byte for byte -ggml_tensor * llm_graph_context::seq_rows_add(ggml_tensor * base, ggml_tensor * term, const std::vector & rows) const { - auto inp = std::make_unique(rows); - inp->tensor = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, (int64_t) rows.size()); +ggml_tensor * llm_graph_context::seq_rows_add(ggml_tensor * base, ggml_tensor * term, const std::vector & listed, int64_t rows) const { + auto inp = std::make_unique(listed); + inp->tensor = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, (int64_t) listed.size()); ggml_set_input(inp->tensor); ggml_tensor * idx = inp->tensor; res->add_input(std::move(inp)); GGML_ASSERT(ggml_is_contiguous(base)); - const int64_t n = ggml_nelements(base) / n_tokens; - ggml_tensor * b2 = ggml_n_dims(base) <= 2 ? base : ggml_reshape_2d(ctx0, base, n, n_tokens); - ggml_tensor * t2 = ggml_n_dims(term) <= 2 ? term : ggml_reshape_2d(ctx0, ggml_cont(ctx0, term), n, n_tokens); + const int64_t n = ggml_nelements(base) / rows; + ggml_tensor * b2 = ggml_n_dims(base) <= 2 ? base : ggml_reshape_2d(ctx0, base, n, rows); + ggml_tensor * t2 = ggml_n_dims(term) <= 2 ? term : ggml_reshape_2d(ctx0, ggml_cont(ctx0, term), n, rows); ggml_tensor * sel = ggml_add(ctx0, ggml_get_rows(ctx0, b2, idx), ggml_get_rows(ctx0, t2, idx)); ggml_tensor * updated = ggml_set_rows(ctx0, ggml_dup(ctx0, b2), sel, idx); return ggml_n_dims(base) <= 2 ? updated : ggml_reshape(ctx0, updated, base); } ggml_tensor * llm_graph_context::seq_lora_mm(ggml_tensor * w, ggml_tensor * cur, ggml_tensor * out) const { - return seq_lora_apply(out, w, [&](llama_adapter_lora * adapter, llama_adapter_lora_weight * lw, float scale, int32_t begin, int32_t n) { - ggml_tensor * x = n == (int32_t) n_tokens ? cur : rows_view(ctx0, cur, n_tokens, begin, n); + // a projection's input is [n_in, rows] or [n_in, x, rows]: its rows are its outermost dimension + GGML_ASSERT(cur->ne[3] == 1 && "a LoRA target's input holds its rows in its second or third dimension"); + const int d = cur->ne[2] > 1 ? 2 : 1; + const int64_t rows = cur->ne[d]; + return seq_lora_apply(out, w, d, rows, [&](llama_adapter_lora * adapter, llama_adapter_lora_weight * lw, float scale, int32_t begin, int32_t n) { + ggml_tensor * x = n == rows ? cur : rows_view(ctx0, cur, d, begin, n); ggml_tensor * ab = ggml_mul_mat(ctx0, lw->b, ggml_mul_mat(ctx0, lw->a, x)); return ggml_scale(ctx0, ab, lw->get_scale(adapter->alpha, scale)); }); } ggml_tensor * llm_graph_context::seq_lora_mm_id(ggml_tensor * w, ggml_tensor * cur, ggml_tensor * ids, ggml_tensor * out) const { - return seq_lora_apply(out, w, [&](llama_adapter_lora * adapter, llama_adapter_lora_weight * lw, float scale, int32_t begin, int32_t n) { - const bool all = n == (int32_t) n_tokens; - ggml_tensor * x = all ? cur : rows_view(ctx0, cur, n_tokens, begin, n); - ggml_tensor * id = all ? ids : rows_view(ctx0, ids, n_tokens, begin, n); + const int64_t rows = ids->ne[1]; // ids [n_expert_used, rows]; cur and the result hold their rows in dimension 2 + return seq_lora_apply(out, w, 2, rows, [&](llama_adapter_lora * adapter, llama_adapter_lora_weight * lw, float scale, int32_t begin, int32_t n) { + const bool all = n == rows; + ggml_tensor * x = all ? cur : rows_view(ctx0, cur, 2, begin, n); + ggml_tensor * id = all ? ids : rows_view(ctx0, ids, 1, begin, n); ggml_tensor * ab = ggml_mul_mat_id(ctx0, lw->b, ggml_mul_mat_id(ctx0, lw->a, x, id), id); // as build_lora_mm_id: the rank is B's input width const float rank = (float) lw->b->ne[0]; @@ -273,8 +307,9 @@ ggml_tensor * llm_graph_context::seq_lora_mm_id(ggml_tensor * w, ggml_tensor * c } ggml_tensor * llm_graph_context::seq_lora_embd(ggml_tensor * tok_embd, ggml_tensor * ids, ggml_tensor * cur) const { - return seq_lora_apply(cur, tok_embd, [&](llama_adapter_lora * adapter, llama_adapter_lora_weight * lw, float scale, int32_t begin, int32_t n) { - ggml_tensor * id = n == (int32_t) n_tokens ? ids : rows_view(ctx0, ids, n_tokens, begin, n); + const int64_t rows = ids->ne[0]; // the token ids, one per row + return seq_lora_apply(cur, tok_embd, 1, rows, [&](llama_adapter_lora * adapter, llama_adapter_lora_weight * lw, float scale, int32_t begin, int32_t n) { + ggml_tensor * id = n == rows ? ids : rows_view(ctx0, ids, 0, begin, n); return ggml_scale(ctx0, ggml_mul_mat(ctx0, lw->b, ggml_get_rows(ctx0, lw->a, id)), lw->get_scale(adapter->alpha, scale)); }); } diff --git a/src/llama-adapter-seq.h b/src/llama-adapter-seq.h index d0e4f85aec03..adb1b244f127 100644 --- a/src/llama-adapter-seq.h +++ b/src/llama-adapter-seq.h @@ -11,35 +11,63 @@ // graph upstream builds. At graph build the ubatch's rows are grouped by the set they wear, and each adapter's delta is // computed on its group's rows only: a group of consecutive rows is a view (no copy); rows that interleave with another // group's are gathered and written back by index, correct and slower, and counted (llama_seq_adapters_gathered). -// Rows never move, so the caller's output indices hold. The training shadow stays the context's: it adds to the -// labelled rows whatever set they wear. +// Rows never move, so the caller's output indices hold. A group knows its rows twice: among the ubatch's tokens, and +// among its outputs (after inp_out_ids keeps only the rows whose logits were asked for, a tensor holds those). The +// training shadow stays the context's: it adds to the labelled rows whatever set they wear. +// +// An adapter is named by its address and its serial (llama_adapter_lora::serial, unique per load), so an adapter freed +// and another loaded at its address is another adapter: a set naming a freed one refuses decode until named again, +// and a free of any other adapter changes nothing. #include "llama-adapter.h" #include "llama-batch.h" #include +#include #include -#include #include -// an adapter set by value: each adapter with its scale, ordered by address, no zero scale +// one adapter of a set: who it is, which load of it, at what scale +struct llama_adapter_set_entry { + llama_adapter_lora * adapter = nullptr; + uint64_t serial = 0; + float scale = 0.0f; + + bool operator==(const llama_adapter_set_entry & other) const { + return adapter == other.adapter && serial == other.serial && scale == other.scale; + } + bool operator<(const llama_adapter_set_entry & other) const { + return std::tie(adapter, serial, scale) < std::tie(other.adapter, other.serial, other.scale); + } +}; + +// an adapter set by value, ordered, no zero scale struct llama_adapter_set { - std::vector> adapters; + std::vector adapters; bool operator==(const llama_adapter_set & other) const { return adapters == other.adapters; } bool operator!=(const llama_adapter_set & other) const { return !(*this == other); } }; -// the rows of one ubatch that wear one set: [begin, begin + n) when consecutive, else each row listed -struct llama_adapter_seq_group { - llama_adapter_set set; +// rows of one space (the ubatch's tokens, or its outputs): [begin, begin + n) when consecutive, else each row listed +struct llama_adapter_seq_rows { int32_t begin = 0; int32_t n = 0; std::vector rows; // empty when consecutive bool consecutive() const { return rows.empty(); } + void add(int32_t row); + bool operator==(const llama_adapter_seq_rows & other) const { return begin == other.begin && n == other.n && rows == other.rows; } +}; + +// the rows of one ubatch that wear one set +struct llama_adapter_seq_group { + llama_adapter_set set; + llama_adapter_seq_rows tokens; + llama_adapter_seq_rows outputs; + bool operator==(const llama_adapter_seq_group & other) const { - return set == other.set && begin == other.begin && n == other.n && rows == other.rows; + return set == other.set && tokens == other.tokens && outputs == other.outputs; } }; @@ -48,36 +76,33 @@ struct llama_adapter_seq_group { // in no group (they add nothing, so they never interleave). Empty when no row's sequence names a set of its own: the // graph is upstream's. struct llama_adapter_seq_groups { - bool named = false; // some row's sequence names a set + bool named = false; // some row's sequence names a set std::vector groups; - uint64_t lora_frees = 0; // the model's adapter frees when grouped: an address freed and reused is another adapter bool empty() const { return !named; } bool gathered() const; - bool operator==(const llama_adapter_seq_groups & other) const { - return named == other.named && groups == other.groups && lora_frees == other.lora_frees; - } + bool operator==(const llama_adapter_seq_groups & other) const { return named == other.named && groups == other.groups; } }; // what a context holds: each sequence's own set, as its owner named it struct llama_adapter_seq_sets { - struct named { - llama_adapter_set set; - uint64_t lora_frees = 0; // the model's adapter frees when it was named - }; - std::unordered_map by_seq; - mutable uint64_t gathered = 0; // ubatches whose groups interleaved + std::unordered_map by_seq; + mutable uint64_t gathered = 0; // ubatches whose groups interleaved // the set a row of `seq` wears: her own, or the context's (without the training shadow, which is added apart) - llama_adapter_set wears(llama_seq_id seq, const llama_adapter_set & context_set) const; + const llama_adapter_set & wears(llama_seq_id seq, const llama_adapter_set & context_set) const; // a ubatch's groups; empty when none of its sequences names a set - llama_adapter_seq_groups group(const llama_ubatch & ubatch, const llama_adapter_set & context_set, uint64_t lora_frees) const; + llama_adapter_seq_groups group(const llama_ubatch & ubatch, const llama_adapter_set & context_set) const; - // why a batch cannot be decoded, or nullptr: a token shared by sequences that wear different sets (each set needs - // its own evaluation of the token, so the caller submits it once per set), or a set named before an adapter was freed - const char * refuses(const llama_batch_ext & batch, const llama_adapter_set & context_set, uint64_t lora_frees) const; + // why a batch cannot be decoded, or nullptr: a named set whose adapter is no longer that load on `model`, or a + // token shared by sequences that wear different sets (each set needs its own evaluation of the token, so the + // caller submits it once per set) + const char * refuses(const llama_batch_ext & batch, const llama_adapter_set & context_set, const llama_model & model) const; }; // the context's set as a value, without the training shadow llama_adapter_set llama_adapter_set_of(const llama_adapter_loras & loras, const llama_adapter_lora * shadow); + +// a serial for each adapter loaded (llama_adapter_lora::serial) +uint64_t llama_adapter_lora_next_serial(); diff --git a/src/llama-adapter.h b/src/llama-adapter.h index 9102ff66ab0f..2db3bdd2eeba 100644 --- a/src/llama-adapter.h +++ b/src/llama-adapter.h @@ -60,6 +60,8 @@ struct llama_adapter_lora_weight { llama_adapter_lora_weight(ggml_tensor * a, ggml_tensor * b) : a(a), b(b) {} }; +uint64_t llama_adapter_lora_next_serial(); // Continuum (llama-adapter-seq.cpp) + struct llama_adapter_lora { llama_model * model = nullptr; @@ -76,6 +78,9 @@ struct llama_adapter_lora { // gguf metadata std::unordered_map gguf_kv; + // Continuum: which load of an adapter this is, so an address freed and reused is another adapter (llama-adapter-seq.h) + const uint64_t serial = llama_adapter_lora_next_serial(); + // activated lora (aLoRA) std::vector alora_invocation_tokens; diff --git a/src/llama-graph.h b/src/llama-graph.h index 894c4be689cb..79941207239b 100644 --- a/src/llama-graph.h +++ b/src/llama-graph.h @@ -1612,8 +1612,9 @@ struct llm_graph_context { ggml_tensor * seq_lora_mm_id(ggml_tensor * w, ggml_tensor * cur, ggml_tensor * ids, ggml_tensor * out) const; ggml_tensor * seq_lora_embd(ggml_tensor * tok_embd, ggml_tensor * ids, ggml_tensor * cur) const; template - ggml_tensor * seq_lora_apply(ggml_tensor * res, ggml_tensor * w, Term term) const; - ggml_tensor * seq_rows_add(ggml_tensor * base, ggml_tensor * term, const std::vector & rows) const; + ggml_tensor * seq_lora_apply(ggml_tensor * res, ggml_tensor * w, int d, int64_t rows, Term term) const; + ggml_tensor * seq_rows_add(ggml_tensor * base, ggml_tensor * term, const std::vector & listed, int64_t rows) const; + const llama_adapter_seq_rows & seq_rows_of(const llama_adapter_seq_group & group, int64_t rows) const; // base plus the shadow's term, on the labelled rows only (Cormac, 2026-10-14): those rows of // base and of the term are gathered and added, and written back into a copy of base; every // other row is base, byte for byte. A multiplied 0/1 mask was not: an untrained layer's inf or diff --git a/tests/test-seq-adapters.cpp b/tests/test-seq-adapters.cpp index 5dad755ec9f9..1fc09d2e4d56 100644 --- a/tests/test-seq-adapters.cpp +++ b/tests/test-seq-adapters.cpp @@ -13,7 +13,11 @@ // - rows reordered with their sequence ids kept (Codex's case), a set rebound under another scale on a warm graph, // and the base after an adapted owner: each phase below changes one of these and is held to the same bound; // - interleaved groups (one set on rows 0 and 2): gathered and written back by index, counted, and held to the bound; -// - a token shared by sequences wearing different sets: refused, nothing decoded. +// - steps of two tokens with logits at the end: past inp_out_ids a tensor holds only the output rows, and each +// group adds to its own among them (Codex, #172); +// - an adapter nobody wears loaded and freed mid-phase: nothing named changes, every later step reuses its graph +// (Codex, #172: a free anywhere on the model refused every named set); +// - a token shared by sequences wearing different sets, and a set whose adapter was freed: refused. // The adapters are fresh ones with a nonzero B (a fresh B is zero: its delta would be nothing to test). #include "arg.h" @@ -32,23 +36,28 @@ static constexpr uint32_t N_MINDS = 4; static constexpr uint32_t PHASE = 6; // steps per phase -static constexpr uint32_t PHASES = 6; +static constexpr uint32_t PHASES = 8; using set_t = std::vector>; -// the phases: what each mind wears, and the order of her row in the batch +// the phases: what each mind wears (wears below), the order of her rows in the batch, and how many tokens each mind +// steps (logits only at her last: past inp_out_ids a tensor holds only those rows, a subset of the ubatch's) struct phase_t { const char * what; uint32_t order[N_MINDS]; + uint32_t tokens; }; static const phase_t phases[PHASES] = { - { "each her own set, rows in order", { 0, 1, 2, 3 } }, - { "rows swapped, sequence ids kept", { 1, 0, 3, 2 } }, - { "mind 0 rebound at another scale (warm graph)", { 0, 1, 2, 3 } }, - { "mind 1 on the base after her adapter", { 0, 1, 2, 3 } }, - { "minds 0 and 2 share a set on rows 0 and 2", { 0, 1, 2, 3 } }, - { "the same sets with their rows consecutive", { 0, 2, 1, 3 } }, + { "each her own set, rows in order", { 0, 1, 2, 3 }, 1 }, + { "rows swapped, sequence ids kept", { 1, 0, 3, 2 }, 1 }, + { "mind 0 rebound at another scale (warm graph)", { 0, 1, 2, 3 }, 1 }, + { "mind 1 on the base after her adapter", { 0, 1, 2, 3 }, 1 }, + { "minds 0 and 2 share a set on rows 0 and 2", { 0, 1, 2, 3 }, 1 }, + { "the same sets with their rows consecutive", { 0, 2, 1, 3 }, 1 }, + { "two tokens each, logits at the end, interleaved", { 0, 1, 2, 3 }, 2 }, + { "two tokens each, logits at the end, consecutive", { 0, 2, 1, 3 }, 2 }, }; +static constexpr uint32_t FREES_AN_UNNAMED_ADAPTER = 2; // the phase that loads and frees an adapter nobody wears, mid-phase static set_t wears(uint32_t phase, uint32_t m, llama_adapter_lora * a, llama_adapter_lora * b) { const set_t sets[N_MINDS] = { { { a, 1.0f } }, { { b, 1.0f } }, { { a, 1.0f }, { b, 0.75f } }, {} }; @@ -140,6 +149,7 @@ struct arm_result { std::vector> logits; // [step * N_MINDS + mind][n_vocab] uint64_t gathered[PHASES] = {}; bool refused_shared = false; + bool refused_freed = false; int32_t reused[PHASES] = {}; // graphs reused in each phase after its first step }; @@ -215,34 +225,44 @@ static arm_result run_arm(const common_params & params, llama_model * model, con } const uint64_t gathered0 = llama_seq_adapters_gathered(ctx); int32_t reused0 = 0; + const uint32_t n = phases[ph].tokens; for (uint32_t g = 0; g < PHASE; ++g) { const uint32_t step = ph * PHASE + g; - auto token = [&](uint32_t m) { return tokens[(size_t) (pos[m] + 31 * m) % tokens.size()]; }; + // mind m's tokens, logits at her last only + auto steps = [&](uint32_t m) { + for (uint32_t t = 0; t < n; ++t) { + put(tokens[(size_t) (pos[m] + t + 31 * m) % tokens.size()], pos[m] + (llama_pos) t, (llama_seq_id) m, t + 1 == n); + } + }; if (kind == arm::batch || kind == arm::base_batch) { for (uint32_t row = 0; row < N_MINDS; ++row) { - const uint32_t m = phases[ph].order[row]; - put(token(m), pos[m], (llama_seq_id) m, true); + steps(phases[ph].order[row]); } GGML_ASSERT(decode() == 0); for (uint32_t row = 0; row < N_MINDS; ++row) { - const float * l = llama_get_logits_ith(ctx, (int32_t) row); + const float * l = llama_get_logits_ith(ctx, (int32_t) (row * n + n - 1)); r.logits[step * N_MINDS + phases[ph].order[row]].assign(l, l + n_vocab); } } else { for (uint32_t m = 0; m < N_MINDS; ++m) { context_set(kind == arm::base ? set_t{} : wears(ph, m, a, b)); - put(token(m), pos[m], (llama_seq_id) m, true); + steps(m); GGML_ASSERT(decode() == 0); const float * l = llama_get_logits_ith(ctx, -1); r.logits[step * N_MINDS + m].assign(l, l + n_vocab); } } for (uint32_t m = 0; m < N_MINDS; ++m) { - ++pos[m]; + pos[m] += (llama_pos) n; } if (g == 0) { reused0 = llama_perf_context(ctx).n_reused; // the phase's first step builds what its sets need } + if (ph == FREES_AN_UNNAMED_ADAPTER && g == 2) { + // an adapter nobody wears comes and goes (genes page in and out): nothing named changes, so every later + // step decodes and reuses its graph as before + llama_adapter_lora_free(adapter(model, params.model.path, 99)); + } } r.gathered[ph] = llama_seq_adapters_gathered(ctx) - gathered0; r.reused[ph] = llama_perf_context(ctx).n_reused - reused0; @@ -253,6 +273,12 @@ static arm_result run_arm(const common_params & params, llama_model * model, con const int32_t i = put(tokens[0], std::max(pos[0], pos[1]), 0, true); GGML_ASSERT(llama_batch_ext_add_seq(batch, i, 1)); r.refused_shared = decode() != 0; + // an adapter a sequence names is freed: her decode is refused until her set is named again + llama_adapter_lora * gone = adapter(model, params.model.path, 77); + seq_set(3, { { gone, 1.0f } }); + llama_adapter_lora_free(gone); + put(tokens[0], pos[3], 3, true); + r.refused_freed = decode() != 0; } llama_batch_ext_free(batch); llama_free(ctx); @@ -325,7 +351,7 @@ int main(int argc, char ** argv) { // adapters' matmuls add their own shapes' difference (measured 1.0-1.6x the base's, 2026-11-28: bounded at 2x) const bool exact = worst <= 2.0f * kernels + FLT_EPSILON * scale; const bool passed = exact && worst * 10.0f < effect; - const bool counted = batch.gathered[ph] == (ph == 4 ? PHASE : 0); // phase 4 interleaves, in one ubatch either way + const bool counted = batch.gathered[ph] == (ph == 4 || ph == 6 ? PHASE : 0); // phases 4 and 6 interleave, in one ubatch either way // groups never cost a reuse: after its first step, a phase reuses exactly the graphs upstream's batch does const bool reuses = batch.reused[ph] == shape.reused[ph]; printf("seq-adapters: phase %u (%s): max |batch - nearer reference| %.3e (kernels' own %.3e, upstream's two orders %.3e), " @@ -337,6 +363,8 @@ int main(int argc, char ** argv) { } printf("seq-adapters: a token under two sequences wearing different sets is %s\n", batch.refused_shared ? "refused" : "DECODED <-- FAILED"); ok = ok && batch.refused_shared; + printf("seq-adapters: a decode under a named set whose adapter was freed is %s\n", batch.refused_freed ? "refused" : "DECODED <-- FAILED"); + ok = ok && batch.refused_freed; } llama_adapter_lora_free(a); From 97ead0427b55374b5ebd1d5fb8a1f6b983f6a393 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sat, 28 Nov 2026 08:08:55 -0600 Subject: [PATCH 3/4] A parked mind's freed gene refuses only her own step; the graph budget follows the genes worn, not the genome loaded - refuses() checked every sequence's named set, so a mind parked with a gene unloaded refused every other mind's step (Codex, #172 re-review). It now checks only the sequences the batch decodes. - seq_adapters_max_nodes counted every adapter loaded on the model times n_seq_max. A dynamic genome holds many genes loaded and a few worn per mind, so the budget grew with the genome for nothing. It now counts the distinct named sets' own adapters, each worn set once, skipping an adapter freed since it was named (never read). test-seq-adapters: with a parked mind's gene freed, another mind decodes, she is refused, and she decodes once named again; each arm's compute buffers are read (llama_get_memory_breakdown), and the batch is run again with 16 more genes loaded and worn by no one. ## Measured (the M5, 2026-11-28 14:08Z, qwen35-0.8b, n_ubatch 1024, Metal) - compute buffers: the batch under per-mind genes 1006.09 MiB, upstream's batch with no adapter 1006.09, one mind at a time under the context's set 1006.09 (kv_unified off); 1018.22 for all three with it on. Byte-identical: the groups add no buffer beyond upstream's worst-case reserve. - the genome: 2 genes loaded 992.05 MiB, 18 loaded (2 worn) 992.05 MiB. - every phase as before on 0.8b and the random qwen35moe, CPU and Metal: OK. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- src/llama-adapter-seq.cpp | 42 +++++++++++++++++++++++++++---------- tests/test-seq-adapters.cpp | 35 +++++++++++++++++++++++++++++++ 2 files changed, 66 insertions(+), 11 deletions(-) diff --git a/src/llama-adapter-seq.cpp b/src/llama-adapter-seq.cpp index d64b416fb65f..a3d4864f7294 100644 --- a/src/llama-adapter-seq.cpp +++ b/src/llama-adapter-seq.cpp @@ -95,12 +95,20 @@ const char * llama_adapter_seq_sets::refuses(const llama_batch_ext & batch, cons return nullptr; } { + // only the sequences this batch decodes: a parked mind whose gene was unloaded refuses her own next step, never + // another's (Codex, #172) std::shared_lock lock(model.loras_mutex); // an adapter may load or free on another thread - for (const auto & [seq, set] : by_seq) { - for (const auto & entry : set.adapters) { - // the address must still be loaded on the model, and be the same load (read only once it is known alive) - if (model.loras.count(entry.adapter) == 0 || entry.adapter->serial != entry.serial) { - return "an adapter a sequence names was freed; name its set again"; + for (const auto & token : batch.tokens) { + for (const llama_seq_id seq : token.seq_ids) { + const auto named = by_seq.find(seq); + if (named == by_seq.end()) { + continue; + } + for (const auto & entry : named->second.adapters) { + // the address must still be loaded on the model, and be the same load (read only once known alive) + if (model.loras.count(entry.adapter) == 0 || entry.adapter->serial != entry.serial) { + return "an adapter a sequence of this batch names was freed; name its set again"; + } } } } @@ -172,13 +180,25 @@ uint32_t llama_context::seq_adapters_max_nodes() const { if (seq_adapters.by_seq.empty()) { return 0; } - // every group may wear every adapter, each delta adding the views of its rows and its add into them. Called by - // graph_max_nodes under its shared lock on model.loras_mutex (a second shared lock on one thread is undefined) - uint32_t per_set = 0; - for (const auto & lora : model.loras) { - per_set += lora->get_n_nodes() * 2u; + // what the named sets add, never what the model holds: a genome may hold many genes loaded while each mind wears a + // few, and the graph's budget follows the worn ones. Each worn adapter adds, per group, its delta (get_n_nodes) and + // the views and add into its rows (as many again). A set worn by several sequences is one group: counted once. + // Called by graph_max_nodes under its shared lock on model.loras_mutex (a second shared lock on one thread is + // undefined); an adapter freed since it was named is skipped (decode refuses it), never read. + uint32_t nodes = 0; + std::vector counted; + for (const auto & [seq, set] : seq_adapters.by_seq) { + if (std::any_of(counted.begin(), counted.end(), [&](const llama_adapter_set * other) { return *other == set; })) { + continue; + } + counted.push_back(&set); + for (const auto & entry : set.adapters) { + if (model.loras.count(entry.adapter) > 0 && entry.adapter->serial == entry.serial) { + nodes += entry.adapter->get_n_nodes() * 2u; + } + } } - return per_set * cparams.n_seq_max; + return nodes; } // diff --git a/tests/test-seq-adapters.cpp b/tests/test-seq-adapters.cpp index 1fc09d2e4d56..a7fc72d0ec2c 100644 --- a/tests/test-seq-adapters.cpp +++ b/tests/test-seq-adapters.cpp @@ -24,6 +24,7 @@ #include "common.h" #include "llama.h" #include "gguf.h" +#include "../src/llama-ext.h" // llama_get_memory_breakdown: the compute buffers each arm holds #include #include @@ -150,6 +151,9 @@ struct arm_result { uint64_t gathered[PHASES] = {}; bool refused_shared = false; bool refused_freed = false; + bool others_decode = false; // a parked sequence's freed gene refuses only her + bool renamed_decodes = false; + size_t compute_bytes = 0; // the compute buffers the context holds after its steps int32_t reused[PHASES] = {}; // graphs reused in each phase after its first step }; @@ -277,8 +281,17 @@ static arm_result run_arm(const common_params & params, llama_model * model, con llama_adapter_lora * gone = adapter(model, params.model.path, 77); seq_set(3, { { gone, 1.0f } }); llama_adapter_lora_free(gone); + // mind 3 is parked with it: mind 0 decodes alone (Codex, #172), mind 3 is refused until named again + put(tokens[0], pos[0], 0, true); + r.others_decode = decode() == 0; put(tokens[0], pos[3], 3, true); r.refused_freed = decode() != 0; + seq_set(3, {}); + put(tokens[0], pos[3], 3, true); + r.renamed_decodes = decode() == 0; + } + for (const auto & [type, held] : llama_get_memory_breakdown(ctx)) { + r.compute_bytes += held.compute; } llama_batch_ext_free(batch); llama_free(ctx); @@ -365,6 +378,28 @@ int main(int argc, char ** argv) { ok = ok && batch.refused_shared; printf("seq-adapters: a decode under a named set whose adapter was freed is %s\n", batch.refused_freed ? "refused" : "DECODED <-- FAILED"); ok = ok && batch.refused_freed; + printf("seq-adapters: with a parked mind's gene freed, another mind %s, and she decodes once named again: %s\n", batch.others_decode ? "decodes" : "is REFUSED <-- FAILED", batch.renamed_decodes ? "yes" : "NO <-- FAILED"); + ok = ok && batch.others_decode && batch.renamed_decodes; + printf("seq-adapters: compute buffers: batch %.2f MiB, upstream's batch with no adapter %.2f MiB, one mind at a time under the context's set %.2f MiB\n", + batch.compute_bytes / 1048576.0, shape.compute_bytes / 1048576.0, ref.compute_bytes / 1048576.0); + } + + // the genome: many genes loaded on the model, a few worn. What a context holds follows the worn ones, so the batch + // under the same two worn genes holds the same compute buffers with sixteen more loaded and worn by no one + { + const arm_result few = run_arm(params, model, tokens, a, b, arm::batch, false); + std::vector genome; + for (uint32_t g = 0; g < 16; ++g) { + genome.push_back(adapter(model, params.model.path, 1000 + g)); + } + const arm_result many = run_arm(params, model, tokens, a, b, arm::batch, false); + const bool same = many.compute_bytes == few.compute_bytes; + printf("seq-adapters: the genome: the batch's compute buffers with 2 genes loaded %.2f MiB, with 18 loaded (2 worn) %.2f MiB%s\n", + few.compute_bytes / 1048576.0, many.compute_bytes / 1048576.0, same ? "" : " <-- FAILED"); + ok = ok && same; + for (llama_adapter_lora * gene : genome) { + llama_adapter_lora_free(gene); + } } llama_adapter_lora_free(a); From 897c5bce32b4706195b68cb243f36355fd41ea6c Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sat, 28 Nov 2026 08:44:59 -0600 Subject: [PATCH 4/4] The routing capture grows to the largest graph it serves instead of aborting at its bound The M5 (2026-11-28 14:08Z, 86af36cf71 on 97426c137) restart-looped: 82 aborts at llama-lived-routing.cpp:120, GGML_ASSERT(graph.n_tokens <= buf->ne[1] / lived->n_layer), on decode -> sched_reserve -> graph_reserve, beside a lesson's fresh shadow. The capture was sized once, for the ubatch (rounded to the streams), but a context builds graphs past it: a lesson decodes a whole reply in one graph and raises n_ubatch for it, and a scheduler re-reserved then (a stream naming her genes can raise the node budget, #172) reserves at that size. One owner sizes the capture: routing_capture_alloc(rows) (set_routing_capture's allocation, moved), and routing_capture_fit(n_tokens), called by graph_reserve and process_ubatch before a graph is built (one line each). A graph with more rows than the capture holds grows it to them (rounded to the streams), after the queued reads settle, and drops the kept graphs that view the old buffer. A capture the device has no room to grow turns off by name (logged): serving goes on, and the lessons that need it are refused as when capture is unavailable. test-graph-slots: after the three-stream reserve, a graph of three ubatches is reserved with capture on and the context decodes again. Against the old library: the M5's assert, exactly. Now: "the routing capture grew from 2049 to 6144 rows a graph", exit 0. test-seq-adapters now runs every arm with capture on, as serving does. ## Measured (the M5, 2026-11-28 14:44Z) test-graph-slots and test-seq-adapters OK on qwen35-0.8b and the random qwen35moe, CPU and Metal. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- src/llama-context.cpp | 2 ++ src/llama-context.h | 2 ++ src/llama-lived-routing.cpp | 71 ++++++++++++++++++++++++++----------- tests/test-graph-slots.cpp | 12 ++++++- tests/test-seq-adapters.cpp | 5 +++ 5 files changed, 71 insertions(+), 21 deletions(-) diff --git a/src/llama-context.cpp b/src/llama-context.cpp index 58f46c86f90a..786d549f1f1d 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -1848,6 +1848,7 @@ llm_graph_result * llama_context::process_ubatch(const llama_ubatch & ubatch, ll return nullptr; } + routing_capture_fit(ubatch.n_tokens); // Continuum: the routing capture holds this graph's rows (llama-lived-routing.cpp) 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(); @@ -3062,6 +3063,7 @@ ggml_cgraph * llama_context::graph_reserve( n_tokens = ((n_tokens + (n_seqs - 1)) / n_seqs) * n_seqs; // round to next multiple of n_seqs LLAMA_LOG_DEBUG("%s: making n_tokens a multiple of n_seqs - n_tokens = %u, n_seqs = %u, n_outputs = %u\n", __func__, n_tokens, n_seqs, n_outputs); } + routing_capture_fit(n_tokens); // Continuum: the routing capture holds this graph's rows (llama-lived-routing.cpp) ggml_backend_sched_reset(sched.get()); diff --git a/src/llama-context.h b/src/llama-context.h index 0c7002c05755..cefa430ec882 100644 --- a/src/llama-context.h +++ b/src/llama-context.h @@ -247,6 +247,8 @@ struct llama_context { bool set_pinned_experts(llama_seq_id seq, int32_t n_layer, int32_t n_used, llama_pos pos0, int32_t n_pos, const int32_t * ids); bool pin_lived(llama_seq_id seq, llama_pos pos0, int32_t n_pos); void clear_pin(); + bool routing_capture_alloc(int64_t rows); // the capture buffer for `rows` tokens a graph + void routing_capture_fit(uint32_t n_tokens); // grown before a larger graph is built 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 diff --git a/src/llama-lived-routing.cpp b/src/llama-lived-routing.cpp index be7972588e09..a6fe8bb57802 100644 --- a/src/llama-lived-routing.cpp +++ b/src/llama-lived-routing.cpp @@ -143,28 +143,10 @@ llama_routing_capture llama_context::set_routing_capture(bool on) { if (on && hp.n_expert > (uint32_t) llama_lived_routing::MAX_EXPERTS) { return LLAMA_ROUTING_CAPTURE_TOO_MANY; } - synchronize(); // nothing queued reads the buffer this replaces - lived_routing.capture_dev = nullptr; - lived_routing.capture_buf.reset(); - lived_routing.capture_ctx.reset(); lived_routing.n_layer = (int32_t) hp.n_layer(); lived_routing.n_used = (int32_t) hp.n_expert_used(); - if (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 * 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(); - lived_routing.capture_buf.reset(ggml_backend_alloc_ctx_tensors_from_buft(lived_routing.capture_ctx.get(), buft)); - if (!lived_routing.capture_buf) { - lived_routing.capture_dev = nullptr; - lived_routing.capture_ctx.reset(); - lived_routing.capture = false; - cparams.lived_routing = lived_routing.pin_n > 0 ? &lived_routing : nullptr; - return LLAMA_ROUTING_CAPTURE_NO_ROOM; - } + if (!routing_capture_alloc(on ? capture_rows(cparams) : 0)) { + return LLAMA_ROUTING_CAPTURE_NO_ROOM; } lived_routing.capture = on; cparams.lived_routing = (on || lived_routing.pin_n > 0) ? &lived_routing : nullptr; @@ -172,6 +154,55 @@ llama_routing_capture llama_context::set_routing_capture(bool on) { return on ? LLAMA_ROUTING_CAPTURE_RECORDING : LLAMA_ROUTING_CAPTURE_OFF; } +// The capture buffer for `rows` tokens a graph (none for 0), replacing any it held; false, with capture off and no +// buffer, when the device has no room for it. +bool llama_context::routing_capture_alloc(int64_t rows) { + synchronize(); // nothing queued reads the buffer this replaces + lived_routing.capture_dev = nullptr; + lived_routing.capture_buf.reset(); + lived_routing.capture_ctx.reset(); + if (rows == 0) { + return true; + } + 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 * rows); + 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(); + lived_routing.capture_buf.reset(ggml_backend_alloc_ctx_tensors_from_buft(lived_routing.capture_ctx.get(), buft)); + if (!lived_routing.capture_buf) { + lived_routing.capture_dev = nullptr; + lived_routing.capture_ctx.reset(); + lived_routing.capture = false; + cparams.lived_routing = lived_routing.pin_n > 0 ? &lived_routing : nullptr; + return false; + } + return true; +} + +// Before a graph of `n_tokens` is built: the capture holds its rows. A context builds graphs larger than its ubatch +// (a lesson decodes a whole reply in one graph, raising n_ubatch for it, and a scheduler re-reserved then reserves at +// that size), so the capture grows to the largest graph it serves instead of aborting at its bound (the M5, +// 2026-11-28 14:08Z: 82 aborts, a stream naming her genes re-reserved the scheduler beside a lesson). A capture the +// device has no room to grow turns off by name: serving goes on, and the lessons that need it are refused. +void llama_context::routing_capture_fit(uint32_t n_tokens) { + if (!lived_routing.capture || lived_routing.capture_dev == nullptr) { + return; + } + const int64_t held = lived_routing.capture_dev->ne[1] / lived_routing.n_layer; + if ((int64_t) n_tokens <= held) { + return; + } + const int64_t seqs = std::max(1, cparams.n_seq_max); + const int64_t rows = ((int64_t) n_tokens + seqs - 1) / seqs * seqs; + const bool grown = routing_capture_alloc(rows); + LLAMA_LOG_INFO("%s: the routing capture %s from %lld to %lld rows a graph\n", __func__, grown ? "grew" : "could not grow, so it is off,", + (long long) held, (long long) rows); + drop_reusable_graphs(); // every kept graph views the buffer this replaced +} + bool llama_context::set_pinned_experts(llama_seq_id seq, int32_t n_layer, int32_t n_used, llama_pos pos0, int32_t n_pos, const int32_t * ids) { if (n_pos == 0) { clear_pin(); diff --git a/tests/test-graph-slots.cpp b/tests/test-graph-slots.cpp index 48908968520e..57369982db3b 100644 --- a/tests/test-graph-slots.cpp +++ b/tests/test-graph-slots.cpp @@ -11,6 +11,7 @@ #include "arg.h" #include "common.h" #include "llama.h" +#include "../src/llama-ext.h" // llama_graph_reserve #include #include @@ -191,9 +192,18 @@ int main(int argc, char ** argv) { 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); + // what this catches (the M5, 2026-11-28 14:08Z, 82 aborts): a graph larger than the ubatch the capture was + // sized for (a lesson decodes a whole reply in one graph; a scheduler re-reserved beside it reserves at that + // size) aborted at the capture's bound. The capture grows to hold it, and the context still decodes + llama_batch_ext_clear(batch); + GGML_ASSERT(llama_graph_reserve(ctx, 3 * 2048, 3, 3) != nullptr); + const llama_pos next = 1; + const int32_t j = llama_batch_ext_add_token(batch, 0, tokens[1]); + GGML_ASSERT(j >= 0 && llama_batch_ext_set_pos(batch, j, &next) && llama_batch_ext_set_output_logits(batch, j, 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"); + printf("graph-slots: three streams reserve and decode with routing captured, and a graph past the ubatch grows the capture\n"); } bool ok = true; diff --git a/tests/test-seq-adapters.cpp b/tests/test-seq-adapters.cpp index a7fc72d0ec2c..9c16b492080a 100644 --- a/tests/test-seq-adapters.cpp +++ b/tests/test-seq-adapters.cpp @@ -168,6 +168,11 @@ static arm_result run_arm(const common_params & params, llama_model * model, con cparams.no_perf = false; // the graphs reused are read back llama_context * ctx = llama_init_from_model(model, cparams); GGML_ASSERT(ctx != nullptr); + // as serving runs: each graph also records the routing it served (llama-lived-routing.h), so a graph the groups + // grow is built against the capture buffer too (the M5, 2026-11-28 14:08Z: naming a stream's genes re-reserved the + // scheduler and the capture's bound aborted it) + const auto capture = llama_set_routing_capture(ctx, true); + GGML_ASSERT(capture == LLAMA_ROUTING_CAPTURE_RECORDING || capture == LLAMA_ROUTING_CAPTURE_NO_EXPERTS); const int32_t n_vocab = llama_vocab_n_tokens(llama_model_get_vocab(model)); auto context_set = [&](const set_t & set) {