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..a3d4864f7294 --- /dev/null +++ b/src/llama-adapter-seq.cpp @@ -0,0 +1,355 @@ +// 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 +#include + +// +// 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.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.tokens.consecutive() || !group.outputs.consecutive(); + }); +} + +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; +} + +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; + 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 (!out.named) { + return out; + } + // 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) { + 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); + } + } + output += outputs; + } + if (out.gathered()) { + ++gathered; + } + return out; +} + +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; + } + { + // 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 & 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"; + } + } + } + } + } + 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_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) { + 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) { + set.adapters.push_back({ adapters[i], adapters[i]->serial, scales[i] }); + } + } + } + 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; +} + +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); + 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()); +} + +uint32_t llama_context::seq_adapters_max_nodes() const { + if (seq_adapters.by_seq.empty()) { + return 0; + } + // 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 nodes; +} + +// +// 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) 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]); + 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 + +// 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, int d, int64_t rows, Term term) const { + for (const auto & group : seq_groups.groups) { + 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 (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(entry.adapter, lw, entry.scale, 0, (int32_t) rows), mine.rows, 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) rows)); + } + } + 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 & 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) / 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 { + // 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 { + 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]; + 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 { + 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)); + }); +} + +// +// 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..adb1b244f127 --- /dev/null +++ b/src/llama-adapter-seq.h @@ -0,0 +1,108 @@ +#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. 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 + +// 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; + + bool operator==(const llama_adapter_set & other) const { return adapters == other.adapters; } + bool operator!=(const llama_adapter_set & other) const { return !(*this == other); } +}; + +// 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 && tokens == other.tokens && outputs == other.outputs; + } +}; + +// 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; + + bool empty() const { return !named; } + bool gathered() const; + 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 { + 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) + 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) 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-context.cpp b/src/llama-context.cpp index 4624b7e571f4..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(); @@ -2183,6 +2184,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 +2965,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 @@ -3058,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()); @@ -3139,6 +3145,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..cefa430ec882 100644 --- a/src/llama-context.h +++ b/src/llama-context.h @@ -247,12 +247,22 @@ 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 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..79941207239b 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,17 @@ 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, 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/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/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-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 new file mode 100644 index 000000000000..9c16b492080a --- /dev/null +++ b/tests/test-seq-adapters.cpp @@ -0,0 +1,416 @@ +// 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; +// - 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" +#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 +#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 = 8; + +using set_t = std::vector>; + +// 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 }, 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 } }, {} }; + 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; + 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 +}; + +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); + // 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) { + 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; + const uint32_t n = phases[ph].tokens; + for (uint32_t g = 0; g < PHASE; ++g) { + const uint32_t step = ph * PHASE + g; + // 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) { + 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 * 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)); + 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] += (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; + } + + 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; + // 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); + // 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); + 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 || 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), " + "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; + 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); + llama_adapter_lora_free(b); + llama_model_free(model); + llama_backend_free(); + printf("seq-adapters: %s\n", ok ? "OK" : "FAILED"); + return ok ? 0 : 1; +}