Skip to content
21 changes: 18 additions & 3 deletions ggml/src/ggml-backend.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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;
Expand Down
11 changes: 9 additions & 2 deletions include/llama.h
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand Down
1 change: 1 addition & 0 deletions src/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 6 additions & 2 deletions src/llama-context-learn.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<uint32_t>(cparams.n_batch, m);
cparams.n_ubatch = std::max<uint32_t>(cparams.n_ubatch, m);
cparams.learn_step = &plan;
}
return decode(batch) == 0;
}();
Expand Down
13 changes: 8 additions & 5 deletions src/llama-context-opt-measure.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,13 @@
#include <algorithm>
#include <limits>

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();
Expand All @@ -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);
Expand Down Expand Up @@ -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());
Expand Down
11 changes: 6 additions & 5 deletions src/llama-context-opt.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -174,18 +174,19 @@ 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,
llama_opt_memory_callback callback, void * user_data) {
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) {
Expand Down
6 changes: 4 additions & 2 deletions src/llama-context.h
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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;

Expand Down
3 changes: 3 additions & 0 deletions src/llama-cparams.h
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
76 changes: 73 additions & 3 deletions src/llama-graph.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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);
}

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