From d056280e7f428b89157278d898e516fbc99daed7 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Wed, 18 Nov 2026 08:03:43 -0600 Subject: [PATCH 1/7] A learning step's plan: her rows, the same one for the preflight and the live step llama_learn_step_plan (src/llama-learn-step-plan.{h,cpp}) is one learning step of one sequence: her positions [0, prefix_rows + reply_rows), the last reply_rows the ubatch that carries the gradient. collect_cells finds the cells holding them in a possibly shared (--kv-unified) stream, in position order, skipping every other sequence's cells, and refuses a missing or doubly held position; fill_mask is her causal mask over them. The preflight (llama_opt_measure_shadow_graph, now taking llama_learn_step_geometry) builds its graph under a shaped plan; opt_learn_step decodes each training chunk under a plan bound to its sequence (cparams.learn_step, cleared after). The server preflight measures prefix_rows beside reply_rows; the route renders it from the example, and the residency revalidation passes the request's served prefix. This commit changes no graph: the attention that consumes the plan is the next commit. test-learn-step-plan covers interleaved cells, a too-long reply, a doubly held position, and the mask, with no model. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- include/llama.h | 11 +++- src/CMakeLists.txt | 1 + src/llama-context-learn.cpp | 8 ++- src/llama-context-opt-measure.cpp | 13 +++-- src/llama-context-opt.cpp | 11 ++-- src/llama-context.h | 6 +- src/llama-cparams.h | 3 + src/llama-kv-cache.cpp | 12 ++++ src/llama-kv-cache.h | 5 ++ src/llama-learn-step-plan.cpp | 41 ++++++++++++++ src/llama-learn-step-plan.h | 34 ++++++++++++ tests/CMakeLists.txt | 1 + tests/test-learn-step-plan.cpp | 55 +++++++++++++++++++ .../server/server-context-learn-residency.inc | 2 +- tools/server/server-context-learn.inc | 9 ++- tools/server/server-context.cpp | 15 ++++- 16 files changed, 205 insertions(+), 22 deletions(-) create mode 100644 src/llama-learn-step-plan.cpp create mode 100644 src/llama-learn-step-plan.h create mode 100644 tests/test-learn-step-plan.cpp diff --git a/include/llama.h b/include/llama.h index 6ff7b047fd40..5675b5ec955e 100644 --- a/include/llama.h +++ b/include/llama.h @@ -1892,12 +1892,19 @@ extern "C" { // Select only in disposable metadata: preserve serving scheduler buffers and optimizer state. LLAMA_API bool llama_opt_measure_shadow(struct llama_context * ctx, struct llama_opt_params params, llama_opt_memory_callback callback, void * user_data); + // One learning step's geometry: her positions [0, prefix_rows + reply_rows), the last + // reply_rows of them labelled. The step attends to her rows only, so this, not the cache's + // size or what other sequences hold in it, shapes the step's graph. + struct llama_learn_step_geometry { + uint32_t prefix_rows; + uint32_t reply_rows; + }; // One whole-reply optimizer graph, yielded by graph nodes, never token batches. // Measures the commit graph only: accumulation-only callers use the general - // preflight above. Rows describe the actual example, not a context/window limit. + // preflight above. The geometry is the actual example, not a context/window limit. // Execution remeasures its geometry and re-admits growth before mutation. LLAMA_API bool llama_opt_measure_shadow_graph(struct llama_context * ctx, struct llama_opt_params params, - uint32_t reply_rows, llama_opt_memory_callback callback, void * user_data); + struct llama_learn_step_geometry step, llama_opt_memory_callback callback, void * user_data); LLAMA_API bool llama_opt_measure_memory(struct llama_context * ctx, llama_opt_memory_callback callback, void * user_data); diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 7dcd7a5a3e23..da00f6e4401c 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -27,6 +27,7 @@ add_library(llama llama-impl.cpp llama-io.cpp llama-kv-cache.cpp + llama-learn-step-plan.cpp llama-kv-cache-iswa.cpp llama-kv-cache-dsa.cpp llama-kv-cache-dsa-iswa.cpp diff --git a/src/llama-context-learn.cpp b/src/llama-context-learn.cpp index f9ac912cfa08..4a6f242a630d 100644 --- a/src/llama-context-learn.cpp +++ b/src/llama-context-learn.cpp @@ -216,15 +216,19 @@ llama_opt_learn_status llama_context::opt_learn_step() { opt_learn_labels_done = s.labels_done; // Build one graph for the entire reply. Serving retains its configured batches; // the served context window and label denominator never change. + // A training chunk is one ubatch under its bound plan: attention reads her positions + // [0, prefix + cursor + m) and nothing else of the shared cache (llama_learn_step_plan). + const auto plan = llama_learn_step_plan::for_sequence(s.seq, (uint32_t) (s.prefix + s.cursor), (uint32_t) m); const bool ok = [&] { struct restore_batches { llama_cparams & params; uint32_t batch, ubatch; - ~restore_batches() { params.n_batch = batch; params.n_ubatch = ubatch; } + ~restore_batches() { params.n_batch = batch; params.n_ubatch = ubatch; params.learn_step = nullptr; } } restore{cparams, cparams.n_batch, cparams.n_ubatch}; - if (!s.restoring && s.graph_nodes > 0) { + if (!s.restoring) { cparams.n_batch = std::max(cparams.n_batch, m); cparams.n_ubatch = std::max(cparams.n_ubatch, m); + cparams.learn_step = &plan; } return decode(batch) == 0; }(); diff --git a/src/llama-context-opt-measure.cpp b/src/llama-context-opt-measure.cpp index b2ce0ac10a6a..bbf43bd718fe 100644 --- a/src/llama-context-opt-measure.cpp +++ b/src/llama-context-opt-measure.cpp @@ -6,13 +6,13 @@ #include #include -bool llama_context::opt_measure_memory(llama_opt_memory_callback callback, void * user_data, opt_measure_phase phases, ggml_backend_sched_t held, uint32_t reply_rows) { +bool llama_context::opt_measure_memory(llama_opt_memory_callback callback, void * user_data, opt_measure_phase phases, ggml_backend_sched_t held, const llama_learn_step_plan * step) { if (!callback || !opt_shadow || opt_reply || !memory) { opt_failure = "learning preflight requires a selected shadow and an idle learning boundary"; return false; } - if (reply_rows > cparams.n_ctx_seq) { - opt_failure = "reply geometry exceeds the served window"; + if (step != nullptr && (step->reply_rows == 0 || step->rows() > cparams.n_ctx_seq)) { + opt_failure = "the learning step's rows must be a nonempty reply within the served window"; return false; } synchronize(); @@ -36,8 +36,10 @@ bool llama_context::opt_measure_memory(llama_opt_memory_callback callback, void gf_res_prev->reset(); cparams.training = true; cparams.walk_active = false; - // Shape only: attention still sees the full served memory, without token cuts. - const uint32_t chunk = reply_rows ? reply_rows : cparams.n_ctx_seq; + // A live step's shaped plan builds the graph its decode will run: attention over her rows only. + // Without one (a general caller), shape only over the full served memory, without token cuts. + cparams.learn_step = step; + const uint32_t chunk = step ? step->reply_rows : cparams.n_ctx_seq; size_t max_nodes = graph_max_nodes(chunk); if (cparams.flash_attn && !cparams.fa_back_native) { max_nodes += (size_t) model.hparams.n_layer() * ggml_flash_attn_ext_back_n_nodes(opt_n_ctx_train, 0); @@ -97,6 +99,7 @@ bool llama_context::opt_measure_memory(llama_opt_memory_callback callback, void // A suspended backward graph retains its arena while a neighbour serves. // Price the second arena with the same scheduler planner, never a ratio. cparams.training = false; + cparams.learn_step = nullptr; { llm_graph_result res(max_nodes); llama_batch_allocr serving_batch(model.hparams.n_pos_per_embd()); diff --git a/src/llama-context-opt.cpp b/src/llama-context-opt.cpp index 8107a8ec1825..2e4d0107c576 100644 --- a/src/llama-context-opt.cpp +++ b/src/llama-context-opt.cpp @@ -118,7 +118,7 @@ ggml_opt_params llama_context::opt_params_for(llama_opt_params lopt_params) { return opt_params; } -bool llama_context::opt_measure_shadow(llama_opt_params params, llama_opt_memory_callback callback, void * user_data, opt_measure_phase phase, uint32_t reply_rows) { +bool llama_context::opt_measure_shadow(llama_opt_params params, llama_opt_memory_callback callback, void * user_data, opt_measure_phase phase, const llama_learn_step_plan * step) { if (!callback || !params.adapter || opt_reply) { opt_failure = "shadow preflight requires an idle learning boundary"; return false; @@ -174,7 +174,7 @@ bool llama_context::opt_measure_shadow(llama_opt_params params, llama_opt_memory max_nodes, cparams.pipeline_parallel, cparams.op_offload)); gf_res_prev.reset(new llm_graph_result(max_nodes)); opt_params_base = opt_params_for(params); - return opt_measure_memory(callback, user_data, phase, held_scheduler, reply_rows); + return opt_measure_memory(callback, user_data, phase, held_scheduler, step); } bool llama_opt_measure_shadow(llama_context * ctx, llama_opt_params params, @@ -182,10 +182,11 @@ bool llama_opt_measure_shadow(llama_context * ctx, llama_opt_params params, return ctx && ctx->opt_measure_shadow(params, callback, user_data, llama_context::opt_measure_phase::accumulation_and_commit); } -bool llama_opt_measure_shadow_graph(llama_context * ctx, llama_opt_params params, uint32_t reply_rows, +bool llama_opt_measure_shadow_graph(llama_context * ctx, llama_opt_params params, llama_learn_step_geometry step, llama_opt_memory_callback callback, void * user_data) { - return ctx && reply_rows > 0 && ctx->opt_measure_shadow(params, callback, user_data, - llama_context::opt_measure_phase::whole_reply_commit, reply_rows); + const auto plan = llama_learn_step_plan::shaped(step); + return ctx && step.reply_rows > 0 && ctx->opt_measure_shadow(params, callback, user_data, + llama_context::opt_measure_phase::whole_reply_commit, &plan); } static void opt_bind_admission(ggml_opt_context_t optimizer, const llama_opt_params & params) { diff --git a/src/llama-context.h b/src/llama-context.h index 86bb220f765f..41add2c8b425 100644 --- a/src/llama-context.h +++ b/src/llama-context.h @@ -4,6 +4,7 @@ #include "llama-ext.h" #include "llama-cparams.h" #include "llama-graph.h" +#include "llama-learn-step-plan.h" #include "llama-adapter.h" #include "llama-impl.h" #include "llama-memory.h" @@ -237,8 +238,9 @@ struct llama_context { size_t opt_graph_bytes() const; void opt_visit_memory(llama_opt_memory_callback callback, void * user_data) const; enum class opt_measure_phase { accumulation_and_commit, whole_reply_commit }; - bool opt_measure_memory(llama_opt_memory_callback callback, void * user_data, opt_measure_phase phase, ggml_backend_sched_t held = nullptr, uint32_t reply_rows = 0); - bool opt_measure_shadow(llama_opt_params params, llama_opt_memory_callback callback, void * user_data, opt_measure_phase phase, uint32_t reply_rows = 0); + // step: a live learning step's shaped plan (its graph attends to her rows); null for a general caller + bool opt_measure_memory(llama_opt_memory_callback callback, void * user_data, opt_measure_phase phase, ggml_backend_sched_t held = nullptr, const llama_learn_step_plan * step = nullptr); + bool opt_measure_shadow(llama_opt_params params, llama_opt_memory_callback callback, void * user_data, opt_measure_phase phase, const llama_learn_step_plan * step = nullptr); ggml_opt_params opt_params_for(llama_opt_params params); int64_t opt_shadow_steps(const llama_adapter_lora * shadow) const; diff --git a/src/llama-cparams.h b/src/llama-cparams.h index 9857c99f066d..9010db41e2fd 100644 --- a/src/llama-cparams.h +++ b/src/llama-cparams.h @@ -34,6 +34,9 @@ struct llama_cparams { uint32_t walk_acc_base = 0; // a later chunk's gradient sits on the recurrent state this chunk leaves bool walk_state_surrogate = false; + // a live learning step's plan (llama-learn-step-plan.h): attention reads her rows only. + // Set for the step's own graph (preflight or decode), never for a neighbour's + const struct llama_learn_step_plan * learn_step = nullptr; uint32_t n_ctx_seq; // context for a single sequence uint32_t n_batch; uint32_t n_ubatch; diff --git a/src/llama-kv-cache.cpp b/src/llama-kv-cache.cpp index 76aa5692442e..a6ce37492bed 100644 --- a/src/llama-kv-cache.cpp +++ b/src/llama-kv-cache.cpp @@ -1748,6 +1748,14 @@ static void set_input_kq_mask_impl(const args_set_input_kq_mask & args, T * data } } +void llama_kv_cache::set_input_learn_cells(ggml_tensor * dst, const slot_info & sinfo, const llama_learn_step_plan & plan) const { + GGML_ASSERT(ggml_backend_buffer_is_host(dst->buffer) && dst->type == GGML_TYPE_I32 && ggml_nelements(dst) == plan.rows()); + GGML_ASSERT(sinfo.n_stream() == 1 && "a learning step reads one stream"); + // llama_opt_learn_begin refused a sequence missing any of its served prefix, and this ubatch + // was placed before its inputs are set, so a miss here is a broken invariant, not a refusal + GGML_ASSERT(plan.collect_cells(v_cells[sinfo.strm[0]], (int32_t *) dst->data) && "a learning step's position has no cell"); +} + void llama_kv_cache::set_input_kq_mask(ggml_tensor * dst, const llama_ubatch * ubatch, bool causal_attn) const { const uint32_t n_tokens = ubatch->n_tokens; @@ -2680,6 +2688,10 @@ void llama_kv_cache_context::set_input_kq_mask(ggml_tensor * dst, const llama_ub kv->set_input_kq_mask(dst, ubatch, causal_attn); } +void llama_kv_cache_context::set_input_learn_cells(ggml_tensor * dst, const llama_learn_step_plan & plan) const { + kv->set_input_learn_cells(dst, sinfos[i_cur], plan); +} + void llama_kv_cache_context::set_input_pos_bucket(ggml_tensor * dst, const llama_ubatch * ubatch) const { kv->set_input_pos_bucket(dst, ubatch); } diff --git a/src/llama-kv-cache.h b/src/llama-kv-cache.h index cba1f663b2e4..134cce05dfbe 100644 --- a/src/llama-kv-cache.h +++ b/src/llama-kv-cache.h @@ -3,6 +3,7 @@ #include "llama-batch.h" #include "llama-graph.h" #include "llama-kv-cells.h" +#include "llama-learn-step-plan.h" #include "llama-memory.h" #include @@ -225,6 +226,9 @@ class llama_kv_cache : public llama_memory_i { void set_input_kq_mask (ggml_tensor * dst, const llama_ubatch * ubatch, bool causal_attn) const; void set_input_pos_bucket(ggml_tensor * dst, const llama_ubatch * ubatch) const; + // I32 [plan.rows()]: the cell (within sinfo's one stream) holding each of her positions + void set_input_learn_cells(ggml_tensor * dst, const slot_info & sinfo, const llama_learn_step_plan & plan) const; + void set_input_k_rot(ggml_tensor * dst) const; void set_input_v_rot(ggml_tensor * dst) const; @@ -406,6 +410,7 @@ class llama_kv_cache_context : public llama_memory_context_i { void set_input_k_shift (ggml_tensor * dst) const; void set_input_kq_mask (ggml_tensor * dst, const llama_ubatch * ubatch, bool causal_attn) const; void set_input_pos_bucket(ggml_tensor * dst, const llama_ubatch * ubatch) const; + void set_input_learn_cells(ggml_tensor * dst, const llama_learn_step_plan & plan) const; void set_input_k_rot(ggml_tensor * dst) const; void set_input_v_rot(ggml_tensor * dst) const; diff --git a/src/llama-learn-step-plan.cpp b/src/llama-learn-step-plan.cpp new file mode 100644 index 000000000000..77b1a958151e --- /dev/null +++ b/src/llama-learn-step-plan.cpp @@ -0,0 +1,41 @@ +#include "llama-learn-step-plan.h" + +#include "llama-kv-cells.h" + +#include +#include + +bool llama_learn_step_plan::collect_cells(const llama_kv_cells & cells, int32_t * out) const { + const uint32_t n = rows(); + std::fill(out, out + n, -1); + for (uint32_t i = 0; i < cells.size(); ++i) { + if (cells.is_empty(i) || !cells.seq_has(i, seq)) { + continue; + } + const llama_pos p = cells.pos_get(i); + if (p < 0 || (uint32_t) p >= n) { + continue; + } + if (out[p] >= 0) { + return false; // two cells claim one of her positions: not a sequence this step can read + } + out[p] = (int32_t) i; + } + for (uint32_t p = 0; p < n; ++p) { + if (out[p] < 0) { + return false; + } + } + return true; +} + +void llama_learn_step_plan::fill_mask(const llama_pos * pos, uint32_t n_tokens, ggml_fp16_t * out) const { + const uint32_t n = rows(); + const ggml_fp16_t seen = ggml_fp32_to_fp16(0.0f); + const ggml_fp16_t unseen = ggml_fp32_to_fp16(-INFINITY); + for (uint32_t i = 0; i < n_tokens; ++i) { + for (uint32_t r = 0; r < n; ++r) { + out[(size_t) i*n + r] = (llama_pos) r <= pos[i] ? seen : unseen; + } + } +} diff --git a/src/llama-learn-step-plan.h b/src/llama-learn-step-plan.h new file mode 100644 index 000000000000..c2c4ba00af9a --- /dev/null +++ b/src/llama-learn-step-plan.h @@ -0,0 +1,34 @@ +#pragma once + +#include "llama.h" +#include "ggml.h" + +#include + +class llama_kv_cells; + +// One learning step of one sequence: her positions [0, rows()) in position order, the last +// reply_rows of them the ubatch that carries the gradient. The preflight builds the step's graph +// from a shaped plan and the live step decodes under a bound one, so the two cannot describe +// different attention: both see her rows, never the other cells of a shared cache. +struct llama_learn_step_plan { + llama_seq_id seq = -1; // -1: shape only (the preflight's); set when the step runs + uint32_t prefix_rows = 0; + uint32_t reply_rows = 0; + + uint32_t rows() const { return prefix_rows + reply_rows; } + bool bound() const { return seq >= 0; } + + static llama_learn_step_plan shaped(const llama_learn_step_geometry & step) { + return { -1, step.prefix_rows, step.reply_rows }; + } + static llama_learn_step_plan for_sequence(llama_seq_id seq, uint32_t prefix_rows, uint32_t reply_rows) { + return { seq, prefix_rows, reply_rows }; + } + + // out[p] = the cell holding her position p, for p in [0, rows()); false when one is missing or + // held twice. Cells of other sequences, wherever they sit in a shared stream, are skipped. + bool collect_cells(const llama_kv_cells & cells, int32_t * out) const; + // F16 [rows(), n_tokens]: query i sees her row r when r <= pos[i] + void fill_mask(const llama_pos * pos, uint32_t n_tokens, ggml_fp16_t * out) const; +}; diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index ca0592f3a725..7a4d34a34cf8 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -210,6 +210,7 @@ if (NOT WIN32 OR NOT BUILD_SHARED_LIBS) llama_build_and_test(test-grammar-integration.cpp) llama_build_and_test(test-llama-grammar.cpp) llama_build_and_test(test-batch-alloc.cpp) + llama_build_and_test(test-learn-step-plan.cpp) llama_build_and_test(test-walk-plan.cpp) # the exact walk trains on the window's whole gradient whatever the chunking: run on a pure-attention AND a # hybrid model (-m), on a GPU backend as well as the CPU (a hybrid passed on the CPU while Metal tore its state) diff --git a/tests/test-learn-step-plan.cpp b/tests/test-learn-step-plan.cpp new file mode 100644 index 000000000000..7ead09edefd2 --- /dev/null +++ b/tests/test-learn-step-plan.cpp @@ -0,0 +1,55 @@ +// A learning step's plan reads her rows of a shared (--kv-unified) stream: no model, no backend. +#include "../src/llama-learn-step-plan.h" +#include "../src/llama-kv-cells.h" + +#include +#include +#include + +static int failures = 0; +#define CHECK(c) do { if (!(c)) { std::fprintf(stderr, "FAIL %s:%d %s\n", __FILE__, __LINE__, #c); ++failures; } } while (0) + +static void place(llama_kv_cells & cells, uint32_t cell, llama_seq_id seq, llama_pos pos) { + cells.pos_set(cell, pos); + cells.seq_add(cell, seq); +} + +int main() { + // her positions 0..5 interleaved with a neighbour's 0..3 in one stream, a hole at cell 6 + llama_kv_cells cells; + cells.resize(16); + const llama_seq_id her = 2, neighbour = 0; + const uint32_t her_cells[6] = { 1, 3, 4, 7, 9, 12 }; + for (llama_pos p = 0; p < 6; ++p) { place(cells, her_cells[p], her, p); } + const uint32_t neighbour_cells[4] = { 0, 2, 5, 8 }; + for (llama_pos p = 0; p < 4; ++p) { place(cells, neighbour_cells[p], neighbour, p); } + + // what catches: the step's extent is her rows, in position order, whatever the neighbour holds + const auto plan = llama_learn_step_plan::for_sequence(her, 4, 2); + std::vector got(plan.rows()); + CHECK(plan.collect_cells(cells, got.data())); + for (uint32_t p = 0; p < plan.rows(); ++p) { CHECK(got[p] == (int32_t) her_cells[p]); } + + // what catches: a reply longer than she holds is a refusal, never a read of a neighbour's cell + const auto beyond = llama_learn_step_plan::for_sequence(her, 5, 2); + std::vector none(beyond.rows()); + CHECK(!beyond.collect_cells(cells, none.data())); + + // what catches: a position held twice (a stale placement) is refused, not silently read once + place(cells, 14, her, 3); + CHECK(!plan.collect_cells(cells, got.data())); + + // what catches: the mask is causal over her positions; the frozen prefix is visible to every query + const llama_pos pos[2] = { 4, 5 }; + std::vector mask((size_t) plan.rows() * 2); + plan.fill_mask(pos, 2, mask.data()); + for (uint32_t i = 0; i < 2; ++i) { + for (uint32_t r = 0; r < plan.rows(); ++r) { + const float m = ggml_fp16_to_fp32(mask[(size_t) i*plan.rows() + r]); + CHECK((llama_pos) r <= pos[i] ? m == 0.0f : std::isinf(m) && m < 0); + } + } + + if (failures == 0) { std::printf("test-learn-step-plan: ok\n"); } + return failures == 0 ? 0 : 1; +} diff --git a/tools/server/server-context-learn-residency.inc b/tools/server/server-context-learn-residency.inc index 2271e389d514..ef09340b72b0 100644 --- a/tools/server/server-context-learn-residency.inc +++ b/tools/server/server-context-learn-residency.inc @@ -44,7 +44,7 @@ if (old != learning_residencies.end() && old->second->optimizer != request.optimizer_residency) { return "optimizer residency cannot change while its buffers are retained"; } - const auto measured = learn_preflight({{"engine", learn_engine}, {"lora_id", request.lora_id}, {"reply_rows", request.reply.size()}}); + const auto measured = learn_preflight({{"engine", learn_engine}, {"lora_id", request.lora_id}, {"prefix_rows", request.n_prefix > 0 ? request.n_prefix - 1 : 0}, {"reply_rows", request.reply.size()}}); if (measured.at("refusal") != "none") { return measured.value("detail", std::string("preflight refused")); } server_residency_need optimizer{request.optimizer_residency, residency_subject({{"loaded", {{"lora_id", request.lora_id}, diff --git a/tools/server/server-context-learn.inc b/tools/server/server-context-learn.inc index 100d4056e3da..823f183fa226 100644 --- a/tools/server/server-context-learn.inc +++ b/tools/server/server-context-learn.inc @@ -95,9 +95,11 @@ if (const auto why = train_repack_refusal(model_tgt, params_base); !why.empty()) { return refuse("unsupported", why); } + // the step attends to her served prefix and her reply (llama_learn_step_geometry): both are measured + const int64_t prefix_rows = body.value("prefix_rows", int64_t(-1)); const int64_t reply_rows = body.value("reply_rows", int64_t(0)); - if (reply_rows <= 0 || reply_rows > llama_n_ctx_seq(ctx_tgt)) { - return refuse("invalid", "reply_rows must describe a nonempty example within the served window"); + if (prefix_rows < 0 || reply_rows <= 0 || prefix_rows + reply_rows > llama_n_ctx_seq(ctx_tgt)) { + return refuse("invalid", "prefix_rows and reply_rows must describe a nonempty example within the served window"); } // The loop serializes this with decoding and adapter unload. Restore the active // default composition on exit; update_slots installs each batched slot before decode. @@ -110,13 +112,14 @@ auto set = construct_lora_list({}); set[id].scale = 1.0f; common_set_adapter_lora(ctx_tgt, set); - const bool ok = llama_opt_measure_shadow_graph(ctx_tgt, learning_shadow_params((int32_t) id), (uint32_t) reply_rows, [](const llama_adapter_lora *, const char * device, + const bool ok = llama_opt_measure_shadow_graph(ctx_tgt, learning_shadow_params((int32_t) id), llama_learn_step_geometry{(uint32_t) prefix_rows, (uint32_t) reply_rows}, [](const llama_adapter_lora *, const char * device, const char * buft, const char * kind, size_t bytes, bool host, void * data) { static_cast(data)->push_back({{"device", device}, {"buffer_type", buft}, {"kind", kind}, {"bytes", bytes}, {"host", host}}); }, &out["requirements"]); if (!ok) { return refuse("unsupported", llama_opt_failure(ctx_tgt)); } out["lora_id"] = id; + out["prefix_rows"] = prefix_rows; out["reply_rows"] = reply_rows; out["served_window"] = llama_n_ctx_seq(ctx_tgt); return out; diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index 15831cececbc..7aaa0a05115d 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -6345,16 +6345,27 @@ void server_routes::init_routes() { if (!body.is_object() || body.contains("reply_rows")) { throw std::invalid_argument("preflight requires the example, not caller-computed reply_rows"); } - size_t rows; + if (body.contains("prefix_rows")) { + throw std::invalid_argument("preflight requires the example, not caller-computed prefix_rows"); + } + // the step attends to her prefix and her reply: the prefix is the served prompt but its + // last token, which the step decodes again with the reply (llama_opt_learn_begin) + size_t rows, prefix; if (body.contains("messages")) { - rows = render_learn_example(body).reply.size(); + const auto example = render_learn_example(body); + rows = example.reply.size(); + prefix = example.n_prefix > 0 ? (size_t) example.n_prefix - 1 : 0; } else if (body.contains("learn")) { // Completion-attached corrections share the completion schema, including EOT. rows = server_schema::eval_llama_cmpl_schema(ctx_server.vocab, params, meta->logit_bias_eog, json{{"learn", body.at("learn")}}).learn->reply.size(); + // its prompt is the completion's, not rendered here: price the longest one the slot + // serves; the admission's revalidation measures the actual prompt before mutation + prefix = rows < (size_t) meta->slot_n_ctx ? (size_t) meta->slot_n_ctx - rows : 0; } else { throw std::invalid_argument("preflight requires messages or a completion learn example"); } + body["prefix_rows"] = prefix; body["reply_rows"] = rows; server_http_req measured = req; measured.body = body.dump(); From 0b30083191604148ce1a5a6fe9cd0de014f4779e Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Wed, 18 Nov 2026 08:03:51 -0600 Subject: [PATCH 2/7] The live learning step attends to her rows: no gradient into the whole cache pool The live /learn path (llama_opt_learn on a serving slot) built attention through the serving branch: K/V were the whole stream's cache view with the written reply as its dependency, so the backward made a pool-sized gradient per layer (measured f32 [512, 676864], 1322 MiB each, 40 of them) and the preflight priced it. Under cparams.learn_step, build_attn still writes the reply's K/V into the cache exactly as serving does, then gathers her cells for positions [0, rows) in position order (llm_graph_input_learn_rows: I32 cells + her F16 causal mask, set from the plan), casts them to F16 and attends with flash attention. The reply is the last rows of K/V, so the gradient sinks route dK/dV to this ubatch's own K/V; the gathered prefix is a frozen constant and receives none. Every trainable parameter keeps its gradient through k_cur/v_cur and Q. The preflight's shaped plan builds this same graph, so its measure is the step's. Without flash attention the old path stands, unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- src/llama-graph.cpp | 55 +++++++++++++++++++++++++++++++++++++++++++++ src/llama-graph.h | 25 +++++++++++++++++++++ 2 files changed, 80 insertions(+) diff --git a/src/llama-graph.cpp b/src/llama-graph.cpp index 054d9a802486..05d2b9543c1c 100644 --- a/src/llama-graph.cpp +++ b/src/llama-graph.cpp @@ -504,6 +504,14 @@ void llm_graph_input_attn_no_cache::set_input(const llama_ubatch * ubatch) { } } +void llm_graph_input_learn_rows::set_input(const llama_ubatch * ubatch) { + // the plan was bound to this ubatch's sequence and geometry when its decode began (opt_learn_step) + GGML_ASSERT(plan.bound() && ubatch->n_tokens == plan.reply_rows && ubatch->pos[0] == (llama_pos) plan.prefix_rows); + mctx->set_input_learn_cells(cells, plan); + GGML_ASSERT(ggml_backend_buffer_is_host(mask->buffer)); + plan.fill_mask(ubatch->pos, ubatch->n_tokens, (ggml_fp16_t *) mask->data); +} + void llm_graph_input_attn_kv::set_input(const llama_ubatch * ubatch) { // the store indices are left unallocated when the graph attends without storing K/V // (a training graph reads this ubatch's K/V directly, see build_attn) @@ -2442,6 +2450,34 @@ ggml_tensor * llm_graph_context::build_inp_train_rows() const { return inp_train_rows; } +ggml_tensor * llm_graph_context::build_learn_rows(ggml_tensor * all, const llm_graph_input_learn_rows * rows, ggml_tensor * cur) const { + // all: one layer's K or V over the stream's attended cells, [D, Hkv, n_kv, 1] + GGML_ASSERT(all->ne[3] == 1 && "a learning step reads one stream"); + GGML_ASSERT(all->nb[1] <= all->nb[2] && "a flash-attention cache holds V untransposed"); + const int64_t n_embd = cur->ne[0]*cur->ne[1]; + GGML_ASSERT(ggml_row_size(all->type, n_embd) == all->nb[2]); + ggml_tensor * flat = ggml_view_2d(ctx0, all, n_embd, all->ne[2], all->nb[2], 0); + ggml_tensor * hers = ggml_get_rows(ctx0, flat, rows->cells); // F32 [n_embd, rows] + // a quantized cache trains on the values serving reads (straight-through, as the walk does) + return ggml_cast(ctx0, ggml_reshape_3d(ctx0, hers, cur->ne[0], cur->ne[1], hers->ne[1]), GGML_TYPE_F16); +} + +llm_graph_input_learn_rows * llm_graph_context::build_inp_learn_rows(const llama_kv_cache_context * mctx_cur) const { + if (inp_learn_rows == nullptr) { + const auto & plan = *cparams.learn_step; + GGML_ASSERT(plan.reply_rows == (uint32_t) n_tokens && "a learning step's graph is its reply's ubatch"); + auto inp = std::make_unique(plan, mctx_cur); + inp->cells = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, plan.rows()); + ggml_set_input(inp->cells); + ggml_set_name(inp->cells, "learn_cells"); + inp->mask = ggml_new_tensor_4d(ctx0, GGML_TYPE_F16, plan.rows(), n_tokens, 1, 1); + ggml_set_input(inp->mask); + ggml_set_name(inp->mask, "learn_kq_mask"); + inp_learn_rows = (llm_graph_input_learn_rows *) res->add_input(std::move(inp)); + } + return inp_learn_rows; +} + bool llm_graph_context::lora_on(const llama_adapter_lora * adapter) const { return adapter != shadow || n_shadow_rows > 0; } @@ -3133,6 +3169,25 @@ ggml_tensor * llm_graph_context::build_attn( kq_mask = ggml_cont(ctx0, ggml_view_4d(ctx0, kq_mask, n_past + n_tokens, kq_mask->ne[1], kq_mask->ne[2], kq_mask->ne[3], kq_mask->nb[1], kq_mask->nb[2], kq_mask->nb[3], 0)); } + } else if (cparams.training && cparams.learn_step != nullptr && uses_flash_attn(kq_b, sinks, v_mla)) { + // THE LIVE LEARNING STEP (llama_opt_learn on a serving slot, llama_learn_step_plan). Her + // reply's K/V go into the cache exactly as serving writes them; attention reads HER rows: + // the cells holding her positions [0, rows), gathered in position order, under her causal + // mask. Another sequence's cells in a shared cache are neither attended nor sized, and the + // preflight's shaped plan builds this same graph, so what it measures is what runs. + const auto & k_idxs = inp->get_k_idxs(); + const auto & v_idxs = inp->get_v_idxs(); + ggml_tensor * written_k = mctx_cur->cpy_k(ctx0, k_cur, k_idxs, il); + ggml_tensor * written_v = mctx_cur->cpy_v(ctx0, v_cur, v_idxs, il); + ggml_build_forward_expand(gf, written_k); + ggml_build_forward_expand(gf, written_v); + llm_graph_input_learn_rows * rows = build_inp_learn_rows(mctx_cur); + k = build_learn_rows(mctx_cur->get_k(ctx0, il, written_k), rows, k_cur); + v = build_learn_rows(mctx_cur->get_v(ctx0, il, written_v), rows, v_cur); + // her reply is the last rows of K/V: their gradient goes to this ubatch's own K/V, and the + // frozen prefix (a gather of the cache) receives none, so no pool-sized gradient exists + walk_grad_sinks = { nullptr, k_cur, nullptr, v_cur }; + kq_mask = rows->mask; } else { // store to KV cache const auto & k_idxs = inp->get_k_idxs(); diff --git a/src/llama-graph.h b/src/llama-graph.h index 323dc722d5e1..6e3a05c222b9 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-learn-step-plan.h" #include #include @@ -332,6 +333,24 @@ class llm_graph_input_attn_no_cache : public llm_graph_input_i { const llama_cparams cparams; }; +// The cells holding one learning step's positions, in position order, and her causal mask over +// them (llama_learn_step_plan): the step attends to her rows only, never the shared cache's others. +class llm_graph_input_learn_rows : public llm_graph_input_i { +public: + llm_graph_input_learn_rows(const llama_learn_step_plan & plan, const llama_kv_cache_context * mctx) : plan(plan), mctx(mctx) {} + virtual ~llm_graph_input_learn_rows() = default; + + void set_input(const llama_ubatch * ubatch) override; + + bool can_reuse(const llm_graph_params &) override { return false; } + + ggml_tensor * cells = nullptr; // I32 [rows] + ggml_tensor * mask = nullptr; // F16 [rows, n_tokens, 1, 1] + + const llama_learn_step_plan plan; + const llama_kv_cache_context * mctx; +}; + class llm_graph_input_attn_kv : public llm_graph_input_i { public: llm_graph_input_attn_kv( @@ -1091,6 +1110,7 @@ struct llm_graph_context { llm_graph_result * res; mutable ggml_tensor * inp_train_rows = nullptr; // build_inp_train_rows, once per graph + mutable llm_graph_input_learn_rows * inp_learn_rows = nullptr; // build_inp_learn_rows, once per graph mutable llm_graph_input_training_rows * inp_training_rows = nullptr; ggml_context * ctx0 = nullptr; @@ -1215,6 +1235,11 @@ struct llm_graph_context { // is its cell). One per graph, shared by every attention layer. ggml_tensor * build_inp_train_rows() const; + // A live learning step's rows (cparams.learn_step), shared by every attention layer. + llm_graph_input_learn_rows * build_inp_learn_rows(const llama_kv_cache_context * mctx_cur) const; + // one layer's K or V at her rows, in position order, as F16 [D, Hkv, rows] + ggml_tensor * build_learn_rows(ggml_tensor * all, const llm_graph_input_learn_rows * rows, ggml_tensor * cur) const; + // 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; From 07a6234bef75b15cd040ac15d947b639dc908dad Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Wed, 18 Nov 2026 08:10:26 -0600 Subject: [PATCH 3/7] The learning step reads her prefix as a constant and joins the reply as its own K/V 0b3008319 gathered her rows from the cache AFTER this ubatch's write, so the gather depended on k_cur and the backward refused it on the live q4_0 cache ("no backward through GET_ROWS ... neither F32 nor F16", measured 14:07Z). Her prefix cells are read from the cache as it stood before the write (a constant of the step, no gradient path into the pool), concatenated with this ubatch's F32 K/V, then cast to F16 for flash attention. The grad sinks still route dK/dV to k_cur/v_cur only; the reply is still written to the cache exactly as serving writes it. Measured, real Qwen3.6-35B-A3B Q4_K_M on the M5 with the live engine's flags (-c 676715 --kv-unified q4_0 KV, flash attention), real resident examples, /learn/preflight shared_compute_required on MTL0 (serving's held arena is 4.40 GB of each): speech (prefix 7607, reply 6): 10.94 GB at 5e4163402 -> 10.72 GB at commit 1 -> 4.79 GB code (prefix 63, reply 381): 35.6-81.6 GB live -> 48.1 GB at commit 1 -> 9.09 GB test-learn-step-plan passes. Not yet run: a live /learn step (numerics vs the old path). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- src/llama-graph.cpp | 25 ++++++++++++++++++------- 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/src/llama-graph.cpp b/src/llama-graph.cpp index 05d2b9543c1c..69e9cfedd125 100644 --- a/src/llama-graph.cpp +++ b/src/llama-graph.cpp @@ -2451,15 +2451,24 @@ ggml_tensor * llm_graph_context::build_inp_train_rows() const { } ggml_tensor * llm_graph_context::build_learn_rows(ggml_tensor * all, const llm_graph_input_learn_rows * rows, ggml_tensor * cur) const { - // all: one layer's K or V over the stream's attended cells, [D, Hkv, n_kv, 1] + // all: one layer's K or V over the stream's attended cells, [D, Hkv, n_kv, 1], read BEFORE this + // ubatch's write: her prefix is a constant of the step (no gradient path into the cache, so a + // quantized cache needs no differentiable gather). cur: this ubatch's own K/V (F32, the reply). GGML_ASSERT(all->ne[3] == 1 && "a learning step reads one stream"); GGML_ASSERT(all->nb[1] <= all->nb[2] && "a flash-attention cache holds V untransposed"); + GGML_ASSERT(cur->type == GGML_TYPE_F32); const int64_t n_embd = cur->ne[0]*cur->ne[1]; GGML_ASSERT(ggml_row_size(all->type, n_embd) == all->nb[2]); - ggml_tensor * flat = ggml_view_2d(ctx0, all, n_embd, all->ne[2], all->nb[2], 0); - ggml_tensor * hers = ggml_get_rows(ctx0, flat, rows->cells); // F32 [n_embd, rows] - // a quantized cache trains on the values serving reads (straight-through, as the walk does) - return ggml_cast(ctx0, ggml_reshape_3d(ctx0, hers, cur->ne[0], cur->ne[1], hers->ne[1]), GGML_TYPE_F16); + const int64_t n_prefix = rows->plan.prefix_rows; + ggml_tensor * kv = cur; + if (n_prefix > 0) { + ggml_tensor * flat = ggml_view_2d(ctx0, all, n_embd, all->ne[2], all->nb[2], 0); + ggml_tensor * cells = ggml_view_1d(ctx0, rows->cells, n_prefix, 0); // her prefix, position order + ggml_tensor * prefix = ggml_get_rows(ctx0, flat, cells); // F32 [n_embd, prefix] + // the reply is the last rows: the grad sinks route dK/dV to cur, nothing to the prefix + kv = ggml_concat(ctx0, ggml_reshape_3d(ctx0, prefix, cur->ne[0], cur->ne[1], n_prefix), cur, 2); + } + return ggml_cast(ctx0, kv, GGML_TYPE_F16); } llm_graph_input_learn_rows * llm_graph_context::build_inp_learn_rows(const llama_kv_cache_context * mctx_cur) const { @@ -3182,8 +3191,10 @@ ggml_tensor * llm_graph_context::build_attn( ggml_build_forward_expand(gf, written_k); ggml_build_forward_expand(gf, written_v); llm_graph_input_learn_rows * rows = build_inp_learn_rows(mctx_cur); - k = build_learn_rows(mctx_cur->get_k(ctx0, il, written_k), rows, k_cur); - v = build_learn_rows(mctx_cur->get_v(ctx0, il, written_v), rows, v_cur); + // her prefix is read from the cache as it stood before this ubatch (its cells are not the + // ones written here); the reply joins as this ubatch's own K/V + k = build_learn_rows(mctx_cur->get_k(ctx0, il), rows, k_cur); + v = build_learn_rows(mctx_cur->get_v(ctx0, il), rows, v_cur); // her reply is the last rows of K/V: their gradient goes to this ubatch's own K/V, and the // frozen prefix (a gather of the cache) receives none, so no pool-sized gradient exists walk_grad_sinks = { nullptr, k_cur, nullptr, v_cur }; From 05fd56481139e3418ad3b0b2acf21f25ac5099cb Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Wed, 18 Nov 2026 08:24:46 -0600 Subject: [PATCH 4/7] The hybrid input sets her mask only when the graph allocated it A live learning step attends to her rows under llm_graph_input_learn_rows, so the hybrid input's own KQ mask (and K/V rotation) is never in the graph and has no buffer; set_input wrote it anyway and aborted (GGML_ASSERT(buffer) in ggml_backend_buffer_is_host <- set_input_kq_mask <- llm_graph_input_mem_hybrid::set_input <- opt_learn_step, real 35B, 14:23Z). The same guard as llm_graph_input_attn_kv::set_input, which already skips an unallocated mask, rot and indices. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- src/llama-graph.cpp | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/src/llama-graph.cpp b/src/llama-graph.cpp index 69e9cfedd125..105681d6a16d 100644 --- a/src/llama-graph.cpp +++ b/src/llama-graph.cpp @@ -1145,13 +1145,17 @@ void llm_graph_input_mem_hybrid::set_input(const llama_ubatch * ubatch) { mctx->get_attn()->set_input_v_idxs(inp_attn->self_v_idxs, ubatch); } - mctx->get_attn()->set_input_kq_mask(inp_attn->self_kq_mask, ubatch, cparams.causal_attn); + // the mask is left unallocated when the graph attends under its own mask (a live learning + // step attends to her rows under llm_graph_input_learn_rows): the attn_kv guard, here too + if (inp_attn->self_kq_mask && inp_attn->self_kq_mask->buffer) { + mctx->get_attn()->set_input_kq_mask(inp_attn->self_kq_mask, ubatch, cparams.causal_attn); + } - if (inp_attn->self_k_rot) { + if (inp_attn->self_k_rot && inp_attn->self_k_rot->buffer) { mctx->get_attn()->set_input_k_rot(inp_attn->self_k_rot); } - if (inp_attn->self_v_rot) { + if (inp_attn->self_v_rot && inp_attn->self_v_rot->buffer) { mctx->get_attn()->set_input_v_rot(inp_attn->self_v_rot); } From 49ad6bcea333d9401e3c5ac503310740222e73e6 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Wed, 18 Nov 2026 08:31:41 -0600 Subject: [PATCH 5/7] ggml: a resident expert graph yields between steps; only per-call expert paging refuses, and says why The yielding scheduler step refused every graph holding a MUL_MAT_ID node, silently, so every live /learn step on an MoE base (qwen35moe 35B on the M5) failed with 'the backend failed to compute the training graph' before computing a node. The hazard is per-call expert paging state (container custody, gather tables, the residency cache clock) that a serving call between yields would advance; resident experts carry none. The refusal now names that state and logs. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- ggml/src/ggml-backend.cpp | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/ggml/src/ggml-backend.cpp b/ggml/src/ggml-backend.cpp index 14aaa501134c..aebc60282f51 100644 --- a/ggml/src/ggml-backend.cpp +++ b/ggml/src/ggml-backend.cpp @@ -2722,6 +2722,17 @@ void ggml_backend_sched_graph_discard(ggml_backend_sched_t sched) { ggml_backend_sched_reset(sched); } +// The reason a graph cannot be computed across yields, or nullptr when it can. +static const char * sched_yield_hazard(const struct ggml_cgraph * graph) { + bool expert_op = false; + for (int i = 0; i < graph->n_nodes && !expert_op; ++i) { expert_op = graph->nodes[i]->op == GGML_OP_MUL_MAT_ID; } + if (!expert_op) { return nullptr; } + if (ggml_moe::moe_config().container_dir) { return "its experts page from a container whose custody is per call"; } + if (ggml_moe::moe_config().gather) { return "its experts are gathered through tables recycled per call"; } + if (moe_expert_cache().enabled()) { return "its experts page through a residency cache whose clock advances per call"; } + return nullptr; +} + enum ggml_status ggml_backend_sched_graph_step(ggml_backend_sched_t sched, struct ggml_cgraph * graph, int max_nodes, bool * complete) { GGML_ASSERT(sched && graph && complete); @@ -2732,9 +2743,13 @@ enum ggml_status ggml_backend_sched_graph_step(ggml_backend_sched_t sched, return GGML_STATUS_FAILED; } if (!sched->continuation_graph) { - // Expert paging has a separate generation lifetime; it cannot yield yet. - for (int i = 0; i < graph->n_nodes; ++i) { - if (graph->nodes[i]->op == GGML_OP_MUL_MAT_ID) { return GGML_STATUS_FAILED; } + // A yield lets the serving context run between steps. Expert paging keeps per-call state + // (the residency clock, gather tables, container custody) that a serving call in between + // would advance under this graph, so a paged expert graph cannot yield yet. Resident experts + // (every weight in device memory, as on unified-memory machines) carry no such state. + if (const char * hazard = sched_yield_hazard(graph)) { + GGML_LOG_ERROR("%s: refusing to yield this graph: %s\n", __func__, hazard); + return GGML_STATUS_FAILED; } if (!sched->is_alloc && !ggml_backend_sched_alloc_graph(sched, graph)) { return GGML_STATUS_ALLOC_FAILED; From 76860caa4b38ce554cb291ec7762cdd206923d42 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Wed, 18 Nov 2026 09:11:48 -0600 Subject: [PATCH 6/7] test-walk-exact: the live step at a q4_0 cache against the walk at the same cache The 35B serves q4_0; the f16 live run cannot see a quantized-cache difference between the live learning step and the walk's exact step. A third live configuration (a stream per slot, q4_0, flash attention) compares the in-place step to the walk at the same cache. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- tests/test-walk-exact.cpp | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/tests/test-walk-exact.cpp b/tests/test-walk-exact.cpp index da714839d382..4700156df8bf 100644 --- a/tests/test-walk-exact.cpp +++ b/tests/test-walk-exact.cpp @@ -701,12 +701,17 @@ int main(int argc, char ** argv) { const auto want_f32 = step_delta(params, model, init, tokens, reply, WINDOW, true); g_cache_type = GGML_TYPE_F16; const auto want_f16 = step_delta(params, model, init, tokens, reply, WINDOW, true); + g_cache_type = GGML_TYPE_Q4_0; + const auto want_q4_0 = step_delta(params, model, init, tokens, reply, WINDOW, true); g_cache_type = GGML_TYPE_F32; - for (const bool streams : { false, true }) { + for (const ggml_type live_cache : { GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_Q4_0 }) { + // what the q4_0 run catches: a live step that reads her quantized cache differently from + // the walk at the same cache (the 35B serves q4_0; the f16 run cannot see it) + const bool streams = live_cache != GGML_TYPE_F32; // unified F32 cache with explicit attention, then a stream per slot with an f16 cache and // flash attention: how a serving lane runs (each slot attends over its own stream) - printf(" live sequence, %s:\n", streams ? "a stream per slot, f16 cache, flash attention" : "one unified F32 cache, explicit attention"); + printf(" live sequence, %s:\n", streams ? (live_cache == GGML_TYPE_F16 ? "a stream per slot, f16 cache, flash attention" : "a stream per slot, q4_0 cache, flash attention") : "one unified F32 cache, explicit attention"); size_t graph_segments = 0; auto two_seq_ctx = [&]() { auto cp = common_context_params_to_llama(params); @@ -715,7 +720,7 @@ int main(int argc, char ** argv) { if (getenv("WALK_LIVE_GRAPH_SMALL_UBATCH")) { cp.n_ubatch = WINDOW / 8; } if (getenv("WALK_LIVE_SMALL_RESTORE_BATCH")) { cp.n_batch = cp.n_ubatch = WINDOW / 8; } cp.flash_attn_type = streams ? LLAMA_FLASH_ATTN_TYPE_ENABLED : LLAMA_FLASH_ATTN_TYPE_DISABLED; - cp.type_k = streams ? GGML_TYPE_F16 : GGML_TYPE_F32; cp.type_v = cp.type_k; + cp.type_k = live_cache; cp.type_v = cp.type_k; // Graph segmentation preserves the full token graph and its gradient. // This tests existing scheduler views only, NOT resumable serving yields. if (getenv("WALK_LIVE_GRAPH_SEGMENTS")) { @@ -1198,7 +1203,7 @@ int main(int argc, char ** argv) { got[i] = after[i] - before[i]; } printf(" live sequence: learned=%d \"%s\"\n", (int) learned, learned ? "" : "see the log"); - if (!learned || !same_step(compare("live sequence: her reply learned in place vs the walk's exact step", got, streams ? want_f16 : want_f32))) { + if (!learned || !same_step(compare("live sequence: her reply learned in place vs the walk's exact step", got, live_cache == GGML_TYPE_Q4_0 ? want_q4_0 : live_cache == GGML_TYPE_F16 ? want_f16 : want_f32))) { fprintf(stderr, "FAILED: learning on a live sequence is not the walk's step\n"); ++failures; } From a5bc5652a8dd35ac73733321534bf84648001b02 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Wed, 18 Nov 2026 09:43:17 -0600 Subject: [PATCH 7/7] The learning step gathers all her rows from the cache after her reply is written 07a6234be read her prefix from the cache before this ubatch's write and joined this ubatch's F32 K/V as the reply. At a q4_0 cache that is not what the cache holds: test-walk-exact's live q4_0 case gave cosine 0.6754 / norm ratio 0.7540 against the walk's exact step (worst blk.0.attn_v LoRA B, norm ratio 0.028). Rounding the joined reply through the cache's type did not change it, and neither did disabling the K/V rotation or computing on the CPU, so it is the joined values, not a kernel. Bisect: 5e4163402 and d056280e7 match (1.0000); 0b3008319 aborts; 07a6234be is the first commit that fails. Her rows (prefix and reply) are now gathered from the cache tensor itself, after the write: the write is expanded into the graph first and the graph runs in that order. So she attends exactly what decode reads, and the gather has no edge to k_cur. That keeps 07a6234be's point: no differentiable GET_ROWS from a quantized cache. The grad sinks still give dK/dV of her reply to k_cur/v_cur. The concat and the round-trip are deleted. test-walk-exact prints the worst tensors when the live step strays. Measured, test-walk-exact on qwen2.5-0.5b q4_k_m, M5 Metal, live step vs the walk's exact step: unified F32, explicit attention: cosine 1.0000, norm ratio 0.9997 stream per slot, f16, flash attention: cosine 1.0000, norm ratio 1.0000 stream per slot, q4_0, flash attention: cosine 1.0000, norm ratio 1.0000 (was 0.6754 / 0.7540) Still failing, and failing on the base 5e4163402 too: "a refused chunk graph was not retried cleanly at a smaller horizon". Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- src/llama-graph.cpp | 30 +++++++++++++++--------------- tests/test-walk-exact.cpp | 1 + 2 files changed, 16 insertions(+), 15 deletions(-) diff --git a/src/llama-graph.cpp b/src/llama-graph.cpp index 105681d6a16d..c84f91b89c6c 100644 --- a/src/llama-graph.cpp +++ b/src/llama-graph.cpp @@ -2455,24 +2455,25 @@ ggml_tensor * llm_graph_context::build_inp_train_rows() const { } ggml_tensor * llm_graph_context::build_learn_rows(ggml_tensor * all, const llm_graph_input_learn_rows * rows, ggml_tensor * cur) const { - // all: one layer's K or V over the stream's attended cells, [D, Hkv, n_kv, 1], read BEFORE this - // ubatch's write: her prefix is a constant of the step (no gradient path into the cache, so a - // quantized cache needs no differentiable gather). cur: this ubatch's own K/V (F32, the reply). + // all: one layer's K or V cache over the stream's cells, [D, Hkv, n_kv, 1], the cache tensor itself + // (no edge to this ubatch's write). cur: this ubatch's own K/V (F32), whose shape her rows take. + // Her rows (prefix and reply) are gathered from the cache AFTER this ubatch wrote her reply into it: + // the caller expands the write into the graph first, and the graph runs in that order. So she + // attends exactly the values decode reads (her reply rounded through the cache's type and, for a + // quantized cache, its rotation), and the gather is a constant of the step: no gradient path into + // the cache, so a quantized cache needs no differentiable GET_ROWS. The grad sinks give dK/dV of + // her last rows (the reply) to cur. + // Measured (test-walk-exact, 0.5B, M5): joining cur after a prefix gather instead, even rounded + // through the cache's type, is not what the cache holds at q4_0 (cosine 0.6754 vs the walk's step); + // this gather matches it (cosine 1.0000, norm ratio 1.0000) at F32, f16 and q4_0. GGML_ASSERT(all->ne[3] == 1 && "a learning step reads one stream"); GGML_ASSERT(all->nb[1] <= all->nb[2] && "a flash-attention cache holds V untransposed"); GGML_ASSERT(cur->type == GGML_TYPE_F32); const int64_t n_embd = cur->ne[0]*cur->ne[1]; GGML_ASSERT(ggml_row_size(all->type, n_embd) == all->nb[2]); - const int64_t n_prefix = rows->plan.prefix_rows; - ggml_tensor * kv = cur; - if (n_prefix > 0) { - ggml_tensor * flat = ggml_view_2d(ctx0, all, n_embd, all->ne[2], all->nb[2], 0); - ggml_tensor * cells = ggml_view_1d(ctx0, rows->cells, n_prefix, 0); // her prefix, position order - ggml_tensor * prefix = ggml_get_rows(ctx0, flat, cells); // F32 [n_embd, prefix] - // the reply is the last rows: the grad sinks route dK/dV to cur, nothing to the prefix - kv = ggml_concat(ctx0, ggml_reshape_3d(ctx0, prefix, cur->ne[0], cur->ne[1], n_prefix), cur, 2); - } - return ggml_cast(ctx0, kv, GGML_TYPE_F16); + ggml_tensor * flat = ggml_view_2d(ctx0, all, n_embd, all->ne[2], all->nb[2], 0); + ggml_tensor * hers = ggml_get_rows(ctx0, flat, rows->cells); // F32 [n_embd, rows], position order + return ggml_cast(ctx0, ggml_reshape_3d(ctx0, hers, cur->ne[0], cur->ne[1], hers->ne[1]), GGML_TYPE_F16); } llm_graph_input_learn_rows * llm_graph_context::build_inp_learn_rows(const llama_kv_cache_context * mctx_cur) const { @@ -3195,8 +3196,7 @@ ggml_tensor * llm_graph_context::build_attn( ggml_build_forward_expand(gf, written_k); ggml_build_forward_expand(gf, written_v); llm_graph_input_learn_rows * rows = build_inp_learn_rows(mctx_cur); - // her prefix is read from the cache as it stood before this ubatch (its cells are not the - // ones written here); the reply joins as this ubatch's own K/V + // her rows are read from the cache after the write above (the graph runs in expansion order) k = build_learn_rows(mctx_cur->get_k(ctx0, il), rows, k_cur); v = build_learn_rows(mctx_cur->get_v(ctx0, il), rows, v_cur); // her reply is the last rows of K/V: their gradient goes to this ubatch's own K/V, and the diff --git a/tests/test-walk-exact.cpp b/tests/test-walk-exact.cpp index 4700156df8bf..c487fccd452c 100644 --- a/tests/test-walk-exact.cpp +++ b/tests/test-walk-exact.cpp @@ -1205,6 +1205,7 @@ int main(int argc, char ** argv) { printf(" live sequence: learned=%d \"%s\"\n", (int) learned, learned ? "" : "see the log"); if (!learned || !same_step(compare("live sequence: her reply learned in place vs the walk's exact step", got, live_cache == GGML_TYPE_Q4_0 ? want_q4_0 : live_cache == GGML_TYPE_F16 ? want_f16 : want_f32))) { fprintf(stderr, "FAILED: learning on a live sequence is not the walk's step\n"); + worst_tensors(got, live_cache == GGML_TYPE_Q4_0 ? want_q4_0 : live_cache == GGML_TYPE_F16 ? want_f16 : want_f32, 8); ++failures; } const bool her_ok = her_after == want_her;