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; 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-graph.cpp b/src/llama-graph.cpp index 054d9a802486..c84f91b89c6c 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) @@ -1137,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); } @@ -2442,6 +2454,44 @@ 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 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]); + 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 { + 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 +3183,26 @@ 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); + // 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 + // 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; 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/tests/test-walk-exact.cpp b/tests/test-walk-exact.cpp index da714839d382..c487fccd452c 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,8 +1203,9 @@ 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"); + 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; 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();