From 17b42eafb87793be3064d4b34530daf147bdd606 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sun, 8 Nov 2026 15:58:03 -0600 Subject: [PATCH 1/3] server: yield live-sequence learning through the existing serving loop --- include/llama.h | 15 ++ src/CMakeLists.txt | 1 + src/llama-context-learn.cpp | 186 +++++++++++++++++++ src/llama-context-opt.cpp | 142 +-------------- src/llama-context.h | 20 ++ tests/test-walk-exact.cpp | 35 +++- tools/server/server-context-learn.inc | 221 +++++++++++++++++++++++ tools/server/server-context.cpp | 215 +++++----------------- tools/server/tests/learn-chunk-yields.py | 84 +++++++++ 9 files changed, 606 insertions(+), 313 deletions(-) create mode 100644 src/llama-context-learn.cpp create mode 100644 tools/server/server-context-learn.inc create mode 100644 tools/server/tests/learn-chunk-yields.py diff --git a/include/llama.h b/include/llama.h index 447c147c2187..54633f3da841 100644 --- a/include/llama.h +++ b/include/llama.h @@ -1852,6 +1852,21 @@ extern "C" { // A reply within one batch is one exact step; a longer one steps per batch, its gradient // stopped at each batch boundary. false: refused or failed by name (llama_opt_failure), // with the sequence restored. + // Resumable form of the same live-sequence owner. The caller retains exclusive custody + // of the learning sequence and optimizer until DONE/FAILED; other sequences may decode + // between steps. Each step executes at most one chunk (training OR stable restoration). + // The chunk is a compute quantum, not a context/window limit. result must outlive the reply. + enum llama_opt_learn_status { + LLAMA_OPT_LEARN_MORE, + LLAMA_OPT_LEARN_DONE, + LLAMA_OPT_LEARN_FAILED, + }; + LLAMA_API bool llama_opt_learn_begin( + struct llama_context * ctx, llama_seq_id seq, llama_pos n_cached, + const llama_token * tokens, const llama_token * labels, int32_t n, + ggml_opt_result_t result); + LLAMA_API enum llama_opt_learn_status llama_opt_learn_step(struct llama_context * ctx); + LLAMA_API bool llama_opt_learn( struct llama_context * lctx, llama_seq_id seq, diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index cd429130227d..f53d420b7c51 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -17,6 +17,7 @@ add_library(llama llama-chat.cpp llama-context.cpp llama-context-opt.cpp + llama-context-learn.cpp llama-walk.cpp llama-cparams.cpp llama-grammar.cpp diff --git a/src/llama-context-learn.cpp b/src/llama-context-learn.cpp new file mode 100644 index 000000000000..671f7063269b --- /dev/null +++ b/src/llama-context-learn.cpp @@ -0,0 +1,186 @@ +// Live-sequence learning: one owner for synchronous calls and resumable serving-loop chunks. +#include "llama-context.h" +#include "llama-memory-hybrid.h" +#include "llama-memory-recurrent.h" +#include + +bool llama_context::opt_learn_begin(llama_seq_id seq, llama_pos n_cached, const llama_token * tokens, const llama_token * labels, + int32_t n, ggml_opt_result_t result) { + if (opt_reply) { + opt_fail("a live reply already owns this context's optimizer; finish its restoration first"); + return false; + } + if (opt_ctx == nullptr) { + opt_fail("llama_opt_learn needs llama_opt_init on this context first"); + return false; + } + if (opt_shadow && opt_shadow->restore_quarantined) { + opt_fail("shadow generation restore is uncertain; restore a known-good generation before learning"); + return false; + } + // each call answers for itself: a refusal before it does not refuse this one + opt_alloc_failed.store(false); + opt_stop_requested.store(false); + opt_failure.clear(); + if (n <= 0 || n_cached < 0 || tokens == nullptr || labels == nullptr) { + opt_fail("llama_opt_learn: an empty reply, a negative served prefix, or no tokens / labels"); + return false; + } + if ((int64_t) n_cached + n > (int64_t) cparams.n_ctx_seq) { + opt_fail("llama_opt_learn: the reply ends at " + std::to_string((int64_t) n_cached + n) + ", past the sequence's context of " + + std::to_string(cparams.n_ctx_seq) + " positions"); + return false; + } + // the parts of the memory: a recurrent state cannot be cut back, attention cells can + llama_memory_recurrent * recr = nullptr; + llama_memory_i * attn = memory.get(); + if (auto * hybrid = dynamic_cast(memory.get())) { + recr = hybrid->get_mem_recr(); + attn = hybrid->get_mem_attn(); + } else if (auto * r = dynamic_cast(memory.get())) { + recr = r; + attn = nullptr; + } + // refusals before anything is touched + const llama_pos held = memory->seq_pos_max(seq) + 1; + if (held < n_cached) { + opt_fail("llama_opt_learn: sequence " + std::to_string(seq) + " holds " + std::to_string(held) + + " positions, fewer than the " + std::to_string(n_cached) + " served before the reply"); + return false; + } + if (recr != nullptr && recr->seq_pos_max(seq) + 1 != n_cached) { + opt_fail("llama_opt_learn: the recurrent state of sequence " + std::to_string(seq) + " ends at " + + std::to_string(recr->seq_pos_max(seq) + 1) + ", not at the served prefix " + std::to_string(n_cached) + + ": restore the served-prefix checkpoint first"); + return false; + } + if (recr != nullptr && recr->rollback_pending(seq)) { + opt_fail("llama_opt_learn: sequence " + std::to_string(seq) + " has a pending recurrent rollback: finish or drop the draft first"); + return false; + } + if (attn != nullptr && !attn->seq_rm(seq, n_cached, -1)) { + opt_fail("llama_opt_learn: could not drop sequence " + std::to_string(seq) + "'s cells past " + std::to_string(n_cached)); + return false; + } + // her stable recurrent state at the served prefix, for the restore + std::vector snap; + if (recr != nullptr) { + synchronize(); + snap.resize(state_seq_get_size(seq, LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY)); + GGML_ASSERT(state_seq_get_data(seq, snap.data(), snap.size(), LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY) == snap.size()); + } + auto state = std::make_unique(); + state->seq = seq; + state->prefix = n_cached; + state->tokens.assign(tokens, tokens + n); + state->labels.assign(labels, labels + n); + state->snapshot = std::move(snap); + state->recurrent = recr; + state->attention = attn; + state->chunk_tokens = n_batch(); + state->batch = llama_batch_init(n_batch(), 0, 1); + state->result = result; + state->n_train = n; + while (state->n_train > 0 && labels[state->n_train - 1] < 0) { --state->n_train; } + for (int32_t i = 0; i < state->n_train; ++i) { state->n_labels += labels[i] >= 0; } + opt_reply = std::move(state); + return true; +} + +// One existing decode chunk, then return to the caller. The served window and the +// gradient's label denominator remain whole; chunking changes scheduling, not examples. +llama_opt_learn_status llama_context::opt_learn_step() { + if (!opt_reply) { + opt_fail("no live reply is active"); + return LLAMA_OPT_LEARN_FAILED; + } + auto & s = *opt_reply; + if (!s.restoring && s.cursor >= s.n_train) { + s.restoring = true; + s.cursor = 0; + bool restored = s.attention == nullptr || s.attention->seq_rm(s.seq, s.prefix, -1); + if (s.recurrent != nullptr) { + synchronize(); + restored = restored && state_seq_set_data(s.seq, s.snapshot.data(), s.snapshot.size(), + LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY) == s.snapshot.size(); + } + if (!restored) { + opt_fail("live reply could not restore its served prefix: re-prefill it"); + opt_reply.reset(); + return LLAMA_OPT_LEARN_FAILED; + } + } + const int32_t end = s.restoring ? (int32_t) s.tokens.size() : s.n_train; + const int32_t m = std::min(s.chunk_tokens, end - s.cursor); + auto & batch = s.batch; + batch.n_tokens = m; + for (int32_t i = 0; i < m; ++i) { + batch.token[i] = s.tokens[s.cursor + i]; + batch.pos[i] = s.prefix + s.cursor + i; + batch.n_seq_id[i] = 1; + batch.seq_id[i][0] = s.seq; + batch.label[i] = s.restoring ? -1 : s.labels[s.cursor + i]; + batch.logits[i] = !s.restoring && batch.label[i] >= 0; + } + if (s.restoring) { batch.logits[m - 1] = true; } + opt_result_active = s.restoring ? nullptr : s.result; + opt_outputs_internal = !s.restoring; + opt_learn_labels = s.restoring ? 0 : s.n_labels; + opt_learn_labels_done = s.labels_done; + const bool ok = decode(batch) == 0; + s.labels_done = opt_learn_labels_done; + // No training flags leak into a neighbour's decode between calls. + opt_result_active = nullptr; + opt_outputs_internal = false; + opt_learn_labels = 0; + opt_learn_labels_done = 0; + synchronize(); // completion and its duration belong to this chunk, not the next turn + if (!ok) { + if (s.restoring) { + opt_fail("live reply restoration failed: re-prefill its sequence"); + opt_reply.reset(); + return LLAMA_OPT_LEARN_FAILED; + } + s.failure = opt_failure.empty() ? "live reply training chunk failed" : opt_failure; + s.cursor = s.n_train; // the next call restores, even after a refused chunk + return LLAMA_OPT_LEARN_MORE; + } + s.cursor += m; + if (s.restoring && s.cursor == end) { + const auto failure = s.failure; + opt_reply.reset(); + if (!failure.empty()) { + opt_fail(failure.c_str()); + return LLAMA_OPT_LEARN_FAILED; + } + return LLAMA_OPT_LEARN_DONE; + } + return LLAMA_OPT_LEARN_MORE; +} + +bool llama_context::opt_learn(llama_seq_id seq, llama_pos n_cached, const llama_token * tokens, + const llama_token * labels, int32_t n, ggml_opt_result_t result) { + if (!opt_learn_begin(seq, n_cached, tokens, labels, n, result)) { return false; } + llama_opt_learn_status status; + do { status = opt_learn_step(); } while (status == LLAMA_OPT_LEARN_MORE); + return status == LLAMA_OPT_LEARN_DONE; +} + +bool llama_opt_learn_begin(llama_context * ctx, llama_seq_id seq, llama_pos prefix, + const llama_token * tokens, const llama_token * labels, int32_t n, + ggml_opt_result_t result) { + return ctx->opt_learn_begin(seq, prefix, tokens, labels, n, result); +} + +llama_opt_learn_status llama_opt_learn_step(llama_context * ctx) { return ctx->opt_learn_step(); } + +bool llama_opt_learn( + struct llama_context * ctx, + llama_seq_id seq, + llama_pos n_cached, + const llama_token * tokens, + const llama_token * labels, + int32_t n, + ggml_opt_result_t result) { + return ctx->opt_learn(seq, n_cached, tokens, labels, n, result); +} diff --git a/src/llama-context-opt.cpp b/src/llama-context-opt.cpp index ddc31f35f58d..23d9a911fcf0 100644 --- a/src/llama-context-opt.cpp +++ b/src/llama-context-opt.cpp @@ -809,140 +809,6 @@ const char * llama_opt_failure(struct llama_context * ctx) { return ctx->opt_failure.c_str(); } -bool llama_context::opt_learn(llama_seq_id seq, llama_pos n_cached, const llama_token * tokens, const llama_token * labels, - int32_t n, ggml_opt_result_t result) { - if (opt_ctx == nullptr) { - opt_fail("llama_opt_learn needs llama_opt_init on this context first"); - return false; - } - if (opt_shadow && opt_shadow->restore_quarantined) { - opt_fail("shadow generation restore is uncertain; restore a known-good generation before learning"); - return false; - } - // each call answers for itself: a refusal before it does not refuse this one - opt_alloc_failed.store(false); - opt_stop_requested.store(false); - opt_failure.clear(); - if (n <= 0 || n_cached < 0 || tokens == nullptr || labels == nullptr) { - opt_fail("llama_opt_learn: an empty reply, a negative served prefix, or no tokens / labels"); - return false; - } - if ((int64_t) n_cached + n > (int64_t) cparams.n_ctx_seq) { - opt_fail("llama_opt_learn: the reply ends at " + std::to_string((int64_t) n_cached + n) + ", past the sequence's context of " - + std::to_string(cparams.n_ctx_seq) + " positions"); - return false; - } - // the parts of the memory: a recurrent state cannot be cut back, attention cells can - llama_memory_recurrent * recr = nullptr; - llama_memory_i * attn = memory.get(); - if (auto * hybrid = dynamic_cast(memory.get())) { - recr = hybrid->get_mem_recr(); - attn = hybrid->get_mem_attn(); - } else if (auto * r = dynamic_cast(memory.get())) { - recr = r; - attn = nullptr; - } - // refusals before anything is touched - const llama_pos held = memory->seq_pos_max(seq) + 1; - if (held < n_cached) { - opt_fail("llama_opt_learn: sequence " + std::to_string(seq) + " holds " + std::to_string(held) - + " positions, fewer than the " + std::to_string(n_cached) + " served before the reply"); - return false; - } - if (recr != nullptr && recr->seq_pos_max(seq) + 1 != n_cached) { - opt_fail("llama_opt_learn: the recurrent state of sequence " + std::to_string(seq) + " ends at " - + std::to_string(recr->seq_pos_max(seq) + 1) + ", not at the served prefix " + std::to_string(n_cached) - + ": restore the served-prefix checkpoint first"); - return false; - } - if (recr != nullptr && recr->rollback_pending(seq)) { - opt_fail("llama_opt_learn: sequence " + std::to_string(seq) + " has a pending recurrent rollback: finish or drop the draft first"); - return false; - } - if (attn != nullptr && !attn->seq_rm(seq, n_cached, -1)) { - opt_fail("llama_opt_learn: could not drop sequence " + std::to_string(seq) + "'s cells past " + std::to_string(n_cached)); - return false; - } - // her stable recurrent state at the served prefix, for the restore - std::vector snap; - if (recr != nullptr) { - synchronize(); - snap.resize(state_seq_get_size(seq, LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY)); - GGML_ASSERT(state_seq_get_data(seq, snap.data(), snap.size(), LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY) == snap.size()); - } - const uint32_t nb = n_batch(); - llama_batch batch = llama_batch_init(nb, 0, 1); - // [c0, c0 + m) of the reply into the batch; with labels, the trainable layer sees those rows - auto fill = [&](int32_t c0, int32_t m, bool labelled) { - batch.n_tokens = m; - for (int32_t i = 0; i < m; ++i) { - batch.token [i] = tokens[c0 + i]; - batch.pos [i] = n_cached + c0 + i; - batch.n_seq_id[i] = 1; - batch.seq_id [i][0] = seq; - batch.label [i] = labelled ? labels[c0 + i] : -1; - batch.logits [i] = labelled && labels[c0 + i] >= 0; - } - if (!labelled) { - batch.logits[m - 1] = true; - } - }; - // train up to the last labelled row: rows after it cannot change the loss, and in one batch an - // unlabelled row after the run is refused (a run ends its sequence's rows); the restore below - // still decodes all n - int32_t n_train = n; - while (n_train > 0 && labels[n_train - 1] < 0) { - --n_train; - } - bool ok = true; - opt_result_active = result; - opt_outputs_internal = true; - opt_learn_labels = 0; - opt_learn_labels_done = 0; - for (int32_t i = 0; i < n_train; ++i) { - opt_learn_labels += labels[i] >= 0; - } - for (int32_t c0 = 0; c0 < n_train && ok; c0 += (int32_t) nb) { - const int32_t m = std::min((int32_t) nb, n_train - c0); - fill(c0, m, true); - ok = decode(batch) == 0; - if (!ok && !opt_alloc_failed.load()) { - opt_fail("llama_opt_learn: the reply's training batch at " + std::to_string(n_cached + c0) + " failed to decode"); - } - } - opt_result_active = nullptr; - opt_outputs_internal = false; - opt_learn_labels = 0; - opt_learn_labels_done = 0; - // RESTORE: the reply's cells and the recurrent state decoded again under her stable set - bool restored = attn == nullptr || attn->seq_rm(seq, n_cached, -1); - if (recr != nullptr) { - synchronize(); - restored = restored && state_seq_set_data(seq, snap.data(), snap.size(), LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY) == snap.size(); - } - for (int32_t c0 = 0; c0 < n && restored; c0 += (int32_t) nb) { - const int32_t m = std::min((int32_t) nb, n - c0); - fill(c0, m, false); - restored = decode(batch) == 0; - } - llama_batch_free(batch); - if (!restored) { - opt_fail("llama_opt_learn: sequence " + std::to_string(seq) + " could not be restored after training: re-prefill it"); - return false; - } - return ok; -} - -bool llama_opt_learn( - struct llama_context * ctx, - llama_seq_id seq, - llama_pos n_cached, - const llama_token * tokens, - const llama_token * labels, - int32_t n, - ggml_opt_result_t result) { - return ctx->opt_learn(seq, n_cached, tokens, labels, n, result); -} void llama_opt_epoch( struct llama_context * ctx, @@ -964,7 +830,7 @@ void llama_opt_epoch( bool llama_context::opt_prepare_restore(const llama_batch & retained) { opt_alloc_failed.store(false); opt_failure.clear(); - if (!ggml_opt_can_prepare_restore(opt_ctx)) { + if (opt_reply || !ggml_opt_can_prepare_restore(opt_ctx)) { opt_fail("restore preparation requires a fresh optimizer; existing graph ownership was preserved"); return false; } @@ -1043,7 +909,7 @@ bool llama_opt_prepare_restore(llama_context * ctx, llama_batch retained) { bool llama_context::opt_state_restore(llama_adapter_lora * shadow, FILE * weights, FILE * optimizer, const char * binding) { - if (!shadow || opt_shadow != shadow || !opt_ctx) { return false; } + if (opt_reply || !shadow || opt_shadow != shadow || !opt_ctx) { return false; } // The serving set must exclude the shadow throughout restore, including its preparation. if (loras->count(shadow)) { return false; } std::unique_ptr adapter_state( @@ -1067,7 +933,7 @@ bool llama_opt_state_restore(llama_context * ctx, llama_adapter_lora * shadow, } bool llama_context::opt_state_write(FILE * optimizer, const char * binding) { - return opt_ctx && opt_shadow && !opt_shadow->restore_quarantined && + return !opt_reply && opt_ctx && opt_shadow && !opt_shadow->restore_quarantined && ggml_opt_state_write(opt_ctx, optimizer, binding); } @@ -1076,7 +942,7 @@ bool llama_opt_state_write(llama_context * ctx, FILE * optimizer, const char * b } bool llama_context::opt_state_write_initial(FILE * optimizer, const char * binding) { - return opt_ctx && opt_shadow && !opt_shadow->restore_quarantined && !loras->count(const_cast(opt_shadow)) && + return !opt_reply && opt_ctx && opt_shadow && !opt_shadow->restore_quarantined && !loras->count(const_cast(opt_shadow)) && ggml_opt_state_write_initial(opt_ctx, optimizer, binding); } diff --git a/src/llama-context.h b/src/llama-context.h index 441076c49746..eef7eb07f629 100644 --- a/src/llama-context.h +++ b/src/llama-context.h @@ -223,6 +223,26 @@ struct llama_context { // the largest training graph the allocation preflight measured on a GPU device (bytes) size_t opt_graph_bytes() const; + struct opt_live_reply { + llama_seq_id seq; + llama_pos prefix; + std::vector tokens, labels; + std::vector snapshot; + llama_memory_i * attention = nullptr; + llama_memory_i * recurrent = nullptr; + llama_batch batch{}; + ggml_opt_result_t result = nullptr; + int32_t chunk_tokens = 0, cursor = 0, n_train = 0; + int64_t n_labels = 0, labels_done = 0; + bool restoring = false; + std::string failure; + ~opt_live_reply() { if (batch.token) { llama_batch_free(batch); } } + }; + std::unique_ptr opt_reply; + bool opt_learn_begin(llama_seq_id seq, llama_pos n_cached, const llama_token * tokens, + const llama_token * labels, int32_t n, ggml_opt_result_t result); + llama_opt_learn_status opt_learn_step(); + bool opt_learn(llama_seq_id seq, llama_pos n_cached, const llama_token * tokens, const llama_token * labels, int32_t n, ggml_opt_result_t result); diff --git a/tests/test-walk-exact.cpp b/tests/test-walk-exact.cpp index a1ebbb7140b6..9924dc28fd03 100644 --- a/tests/test-walk-exact.cpp +++ b/tests/test-walk-exact.cpp @@ -504,6 +504,14 @@ int main(int argc, char ** argv) { const std::string init = "test-walk-exact." + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()) + ".init.gguf"; GGML_ASSERT(common_lora_write_fresh(model, init, 8, 16, { "attn_q", "attn_v" }, 42)); + // Fixture provisioning for the real server protocol tests, using the same adapter owner. + if (const char * shadow = getenv("WALK_WRITE_SHADOW")) { + GGML_ASSERT(std::rename(init.c_str(), shadow) == 0); + llama_model_free(model); + llama_backend_free(); + return 0; + } + // words in a fixed pseudo-random order: a window the model cannot already predict, so its // loss, and the gradient under test, is well above the kernels' batch-size noise static const char * words[] = { "room", "card", "claim", "review", "patch", "lease", "board", "turn", @@ -727,6 +735,8 @@ int main(int argc, char ** argv) { decode_span(ctl, 0, tokens.data(), 0, r0); decode_span(ctl, 0, tokens.data() + r0, r0, WINDOW - r0); const std::vector want_her = seq_state(ctl, 0); + decode_span(ctl, 1, neighbour + 200, 200, 1); + const auto want_neighbour_turn = seq_state(ctl, 1); llama_free(ctl); llama_adapter_lora * adapter = llama_adapter_lora_init(model, init.c_str()); @@ -763,7 +773,30 @@ int main(int argc, char ** argv) { } } const auto generation_prefix = seq_state(ctx, 0); - const bool learned = llama_opt_learn(ctx, 0, r0, tokens.data() + r0, labels.data(), WINDOW - r0, nullptr); + // What this catches: yielding with training flags still installed, losing accumulated + // labels between chunks, or restoring the neighbour instead of the learning sequence. + // Real neighbour inference runs at every yield; learning still covers the entire reply. + GGML_ASSERT(llama_opt_learn_begin(ctx, 0, r0, tokens.data() + r0, labels.data(), WINDOW - r0, nullptr)); + // A checkpoint may not publish an optimizer/cursor pair from half a live reply. + FILE * partial_state = tmpfile(); + GGML_ASSERT(partial_state != nullptr); + GGML_ASSERT(!llama_opt_state_write(ctx, partial_state, "active-live-reply")); + fclose(partial_state); + llama_opt_learn_status progress; + int yielded = 0; + do { + progress = llama_opt_learn_step(ctx); + if (progress == LLAMA_OPT_LEARN_MORE) { + GGML_ASSERT(llama_state_seq_set_data(ctx, neighbour_before.data(), neighbour_before.size(), 1) == neighbour_before.size()); + decode_span(ctx, 1, neighbour + 200, 200, 1); + GGML_ASSERT(seq_state(ctx, 1) == want_neighbour_turn); + ++yielded; + } + } while (progress == LLAMA_OPT_LEARN_MORE); + GGML_ASSERT(yielded >= 1); + // Restore the fixture's original neighbour for its unchanged-custody assertions below. + GGML_ASSERT(llama_state_seq_set_data(ctx, neighbour_before.data(), neighbour_before.size(), 1) == neighbour_before.size()); + const bool learned = progress == LLAMA_OPT_LEARN_DONE; const std::vector her_after = seq_state(ctx, 0); const std::vector neighbour_after = seq_state(ctx, 1); if (learned && !streams) { diff --git a/tools/server/server-context-learn.inc b/tools/server/server-context-learn.inc new file mode 100644 index 000000000000..9512871c91f7 --- /dev/null +++ b/tools/server/server-context-learn.inc @@ -0,0 +1,221 @@ +// Methods of server_context_impl; one owner for completion and /learn custody. + // One reply learned on `slot`, which holds the served prompt (POST /learn between its turns, or a + // completion's own learn before its slot is released): the slot's stable set plus the shadow on + // the reply's labelled rows, then the slot back to its whole served prompt. + learn_outcome learn_on_slot(server_slot & slot, const learn_request & L, int64_t t0) { + if (learning) { + learn_outcome out; + out.deferred = true; + out.failure = "the lane optimizer is restoring an admitted reply; retain this experience for retry"; + return out; + } + for (const auto & other : slots) { + if (other.id != slot.id && other.is_processing() && t0 < learn_next_us) { + learn_outcome out; + out.deferred = true; + out.retry_after_ms = (learn_next_us - t0 + 999) / 1000; + out.failure = "learning deferred while another slot is busy; retain replayable input context and learning inputs for retry"; + return out; + } + } + return learn_on_slot_admitted(slot, L, t0); + } + + learn_outcome learn_on_slot_admitted(server_slot & slot, const learn_request & L, int64_t t0) { + auto refused = [&](const std::string & why) { + learn_outcome out; + out.failure = why; + SRV_WRN("learn refused: %s\n", why.c_str()); + return out; + }; + // the same refusal /train gives: repacked CPU weights fail the backward (x86) or crash + // the copy to Metal (an M5 at -ngl 0), card 5b497852 + if (const std::string why = train_repack_refusal(model_tgt, params_base); !why.empty()) { + return refused(why); + } + auto & loras = params_base.lora_adapters; + if (L.lora_id < 0 || (size_t) L.lora_id >= loras.size() || loras[L.lora_id].ptr == nullptr) { + return refused("no loaded adapter " + std::to_string(L.lora_id) + " to train (POST /lora-adapters/load it first)"); + } + if (learn_lora_id >= 0 && learn_lora_id != L.lora_id) { + return refused("this server trains adapter " + std::to_string(learn_lora_id) + "; one shadow per server run"); + } + const int32_t n0 = L.n_prefix - 1; // the last prompt token is re-decoded with the reply's first token as its label + if (n0 < 0 || L.n_prefix > slot.prompt.n_tokens() || L.reply.empty()) { + return refused("slot " + std::to_string(slot.id) + " holds " + std::to_string(slot.prompt.n_tokens()) + + " prompt tokens; the served prefix is " + std::to_string(L.n_prefix) + " and the reply must not be empty"); + } + // the served prompt, when the request carries it: her slot must still hold exactly it (a + // slot that has served other turns since, or compacted, would teach the wrong context) + if (!L.prompt.empty()) { + int32_t i = 0; + while (i < L.n_prefix && slot.prompt.tokens[i] == L.prompt[i]) { + ++i; + } + if (i < L.n_prefix) { + return refused("slot " + std::to_string(slot.id) + " no longer holds this turn's prompt (it differs at token " + + std::to_string(i) + " of " + std::to_string(L.n_prefix) + "): serve the prompt again, then learn"); + } + } + // the recurrent part cannot be cut back: her state one token before the prompt's end + const common_prompt_checkpoint * cp = nullptr; + const bool needs_cp = ctx_tgt_seq_rm_type == COMMON_CONTEXT_SEQ_RM_TYPE_FULL || ctx_tgt_seq_rm_type == COMMON_CONTEXT_SEQ_RM_TYPE_RS; + if (needs_cp) { + for (const auto & c : slot.prompt.checkpoints) { + if (c.n_tokens == n0) { + cp = &c; + } + } + if (cp == nullptr) { + return refused("slot " + std::to_string(slot.id) + " has no checkpoint one token before its prompt's end (" + + std::to_string(n0) + "): the lane learns only with --train-dir, which keeps one"); + } + } + // the tokens from the last prompt token on, each labelled with the next + std::vector toks; + toks.push_back(slot.prompt.tokens[n0]); + toks.insert(toks.end(), L.reply.begin(), L.reply.end()); + std::vector labels(toks.size(), -1); + for (size_t i = 0; i + 1 < toks.size(); ++i) { + labels[i] = toks[i + 1]; + } + // her stable set plus the shadow: the shadow applies to labelled rows only + std::vector set = slot.lora.empty() ? construct_lora_list({}) : slot.lora; + if ((size_t) L.lora_id >= set.size()) { + set = construct_lora_list({}); + } + set[L.lora_id].scale = 1.0f; + common_set_adapter_lora(ctx_tgt, set); + learn_lr = L.lr; + if (learn_lora_id < 0) { + llama_opt_params lopt{}; + lopt.param_filter = llama_opt_param_filter_all; + lopt.get_opt_pars = learn_opt_pars; + lopt.get_opt_pars_ud = &learn_lr; + lopt.optimizer_type = GGML_OPT_OPTIMIZER_TYPE_ADAMW; + lopt.adapter = loras[L.lora_id].ptr; + llama_opt_init(ctx_tgt, model_tgt, lopt); + learn_lora_id = L.lora_id; + } + // drop what follows n0 (attention) and put her recurrent state back at n0 + if (cp != nullptr) { + cp->load_tgt(ctx_tgt, slot.id, LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY); + } + ggml_opt_result_t result = ggml_opt_result_init(); + const bool begun = llama_opt_learn_begin(ctx_tgt, slot.id, n0, toks.data(), labels.data(), (int32_t) toks.size(), result); + common_set_adapter_lora(ctx_tgt, slot.lora); + learning = std::unique_ptr(new pending_learn{ &slot, cp, std::move(set), result, + toks[0], L.n_prefix, (int32_t) toks.size() - 1, t0 }); + if (!begun) { + learning->finished = false; + learning->failure = llama_opt_failure(ctx_tgt); + } + slot.state = SLOT_STATE_LEARNING; + slot.learn_release_requested = false; + return {}; // no outcome is published until advance_learning restores the slot + } + + void advance_learning() { + if (!learning) { return; } + auto & pending = *learning; + auto & slot = *pending.slot; + if (!pending.finished) { + const auto chunk_started = ggml_time_us(); + common_set_adapter_lora(ctx_tgt, pending.adapters); + const auto status = llama_opt_learn_step(ctx_tgt); + common_set_adapter_lora(ctx_tgt, slot.lora); + pending.compute_us += ggml_time_us() - chunk_started; + if (status != LLAMA_OPT_LEARN_MORE) { + pending.finished = status == LLAMA_OPT_LEARN_DONE; + pending.failure = status == LLAMA_OPT_LEARN_DONE ? "" : llama_opt_failure(ctx_tgt); + } + // Even the final chunk yields before the last prompt token is restored below. + return; + } + const auto restore_started = ggml_time_us(); + const auto * cp = pending.checkpoint; + const int32_t n0 = pending.prefix - 1; + const bool ok = *pending.finished; + double loss = 0.0, unc = 0.0; + if (ok) { ggml_opt_result_loss(pending.result, &loss, &unc); } + // her own adapter set again before anything else is decoded for her (the shadow is + // already off for a batch without labels: llama-graph.cpp lora_on, n_shadow_rows = + // the ubatch's label count; this does not rely on it) + common_set_adapter_lora(ctx_tgt, slot.lora); + // her slot goes back to her whole served prompt (attention cells, recurrent state, + // tokens and checkpoints agree; her next turn reuses all of it): back to n0 from the + // checkpoint, then the last prompt token decoded again under her stable set. A draft + // model's cache is cut to n0 with its own checkpoint, and the slot's tokens with it. + llama_memory_seq_rm(llama_get_memory(ctx_tgt), slot.id, n0, -1); + if (cp != nullptr) { + cp->load_tgt(ctx_tgt, slot.id, LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY); + } + int32_t n_keep = n0; + if (ctx_dft != nullptr) { + llama_memory_seq_rm(llama_get_memory(ctx_dft), slot.id, n0, -1); + if (cp != nullptr) { + cp->load_dft(ctx_dft, slot.id, LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY); + } + } else { + llama_batch one = llama_batch_get_one(&pending.last_prompt, 1); + llama_pos pos = n0; + one.pos = &pos; + llama_seq_id sid = slot.id; + int32_t nsid = 1; + llama_seq_id * sids = &sid; + one.n_seq_id = &nsid; + one.seq_id = &sids; + if (llama_decode(ctx_tgt, one) == 0) { + n_keep = pending.prefix; + } else { + llama_memory_seq_rm(llama_get_memory(ctx_tgt), slot.id, n0, -1); + if (cp != nullptr) { + cp->load_tgt(ctx_tgt, slot.id, LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY); + } + } + } + slot.prompt.tokens.keep_first(n_keep); + slot.prompt.checkpoints.remove_if([&](const common_prompt_checkpoint & c) { return c.n_tokens > n_keep; }); + learn_outcome out; + out.ok = ok; + out.failure = pending.failure; + out.loss = loss; + out.n_labels = pending.n_labels; + pending.compute_us += ggml_time_us() - restore_started; + out.t_ms = pending.compute_us / 1000.0; + SRV_INF("learned on slot %d: %d labels from position %d, loss %.4f, %.1f ms%s\n", slot.id, out.n_labels, n0, loss, + out.t_ms, ok ? "" : (" (failed: " + out.failure + ")").c_str()); + const bool separate = pending.separate_request; + const bool cancelled = slot.learn_release_requested; + const auto finished = ggml_time_us(); + learn_next_us = finished + (int64_t) (pending.compute_us * (1.0/LEARN_DUTY - 1.0)); + learning.reset(); + slot.state = SLOT_STATE_DONE_PROMPT; // release now owns fully restored KV + if (!cancelled) { + if (separate) { + auto res = std::make_unique(); + res->id = slot.task->id; + res->outcome = std::move(out); + queue_results.send(std::move(res)); + } else { + slot.learned = std::move(out); + send_final_response(slot); + } + } + slot.release(); + } + + // A completion that carries a learn learns its reply on its own slot as it finishes, before the + // slot is released: no other request can take the slot between the turn and its learning (on + // a one-slot lane that is busy almost always, a separate POST /learn lost that race 12 times in + // 12 on the M5's 27B, 2026-10-15). + void learn_if_asked(server_slot & slot) { + if (!slot.task->params.learn) { + return; + } + learn_request L = *slot.task->params.learn; + L.id_slot = slot.id; + L.n_prefix = slot.task->n_tokens(); + slot.learned = learn_on_slot(slot, L, ggml_time_us()); + } + diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index 9adc928c8d8c..2a3f0a8bba15 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -83,6 +83,7 @@ enum slot_state { SLOT_STATE_PROCESSING_PROMPT, SLOT_STATE_DONE_PROMPT, SLOT_STATE_GENERATING, + SLOT_STATE_LEARNING, // admitted optimizer transaction owns the sequence until restoration }; struct server_slot; // forward declaration @@ -555,8 +556,15 @@ struct server_slot { // the outcome of the finishing task's learn (task_params::learn), for its final response std::optional learned; + bool learn_release_requested = false; void release() { + if (state == SLOT_STATE_LEARNING) { + // Cancellation cannot hand partially restored KV to the next request. + // Finish the admitted transaction, then release without a final response. + learn_release_requested = true; + return; + } if (is_processing()) { GGML_ASSERT(task); @@ -706,6 +714,7 @@ struct server_slot { {"n_ctx", n_ctx}, {"speculative", can_speculate()}, {"is_processing", is_processing()}, + {"is_learning", state == SLOT_STATE_LEARNING}, }; // The engine's own positions for this slot's sequence (Continuum fork): what its cache holds @@ -959,6 +968,21 @@ struct server_context_impl { p.adamw.wd = 0.0f; return p; } + struct pending_learn { + server_slot * slot; + const common_prompt_checkpoint * checkpoint; + std::vector adapters; + ggml_opt_result_t result; + llama_token last_prompt; + int32_t prefix, n_labels; + int64_t started; + int64_t compute_us = 0; + bool separate_request = false; + std::optional finished; + std::string failure; + ~pending_learn() { ggml_opt_result_free(result); } + }; + std::unique_ptr learning; common_context_seq_rm_type ctx_dft_seq_rm_type = COMMON_CONTEXT_SEQ_RM_TYPE_NO; common_speculative_ptr spec; @@ -2163,174 +2187,7 @@ struct server_context_impl { queue_results.send(std::move(res)); } - // One reply learned on `slot`, which holds the served prompt (POST /learn between its turns, or a - // completion's own learn before its slot is released): the slot's stable set plus the shadow on - // the reply's labelled rows, then the slot back to its whole served prompt. - learn_outcome learn_on_slot(server_slot & slot, const learn_request & L, int64_t t0) { - for (const auto & other : slots) { - if (other.id != slot.id && other.is_processing() && t0 < learn_next_us) { - learn_outcome out; - out.deferred = true; - out.retry_after_ms = (learn_next_us - t0 + 999) / 1000; - out.failure = "learning deferred while another slot is busy; retain replayable input context and learning inputs for retry"; - return out; - } - } - auto out = learn_on_slot_admitted(slot, L, t0); - const int64_t finished = ggml_time_us(); - learn_next_us = finished + (int64_t) ((finished - t0) * (1.0/LEARN_DUTY - 1.0)); - return out; - } - - learn_outcome learn_on_slot_admitted(server_slot & slot, const learn_request & L, int64_t t0) { - auto refused = [&](const std::string & why) { - learn_outcome out; - out.failure = why; - SRV_WRN("learn refused: %s\n", why.c_str()); - return out; - }; - // the same refusal /train gives: repacked CPU weights fail the backward (x86) or crash - // the copy to Metal (an M5 at -ngl 0), card 5b497852 - if (const std::string why = train_repack_refusal(model_tgt, params_base); !why.empty()) { - return refused(why); - } - auto & loras = params_base.lora_adapters; - if (L.lora_id < 0 || (size_t) L.lora_id >= loras.size() || loras[L.lora_id].ptr == nullptr) { - return refused("no loaded adapter " + std::to_string(L.lora_id) + " to train (POST /lora-adapters/load it first)"); - } - if (learn_lora_id >= 0 && learn_lora_id != L.lora_id) { - return refused("this server trains adapter " + std::to_string(learn_lora_id) + "; one shadow per server run"); - } - const int32_t n0 = L.n_prefix - 1; // the last prompt token is re-decoded with the reply's first token as its label - if (n0 < 0 || L.n_prefix > slot.prompt.n_tokens() || L.reply.empty()) { - return refused("slot " + std::to_string(slot.id) + " holds " + std::to_string(slot.prompt.n_tokens()) - + " prompt tokens; the served prefix is " + std::to_string(L.n_prefix) + " and the reply must not be empty"); - } - // the served prompt, when the request carries it: her slot must still hold exactly it (a - // slot that has served other turns since, or compacted, would teach the wrong context) - if (!L.prompt.empty()) { - int32_t i = 0; - while (i < L.n_prefix && slot.prompt.tokens[i] == L.prompt[i]) { - ++i; - } - if (i < L.n_prefix) { - return refused("slot " + std::to_string(slot.id) + " no longer holds this turn's prompt (it differs at token " - + std::to_string(i) + " of " + std::to_string(L.n_prefix) + "): serve the prompt again, then learn"); - } - } - // the recurrent part cannot be cut back: her state one token before the prompt's end - const common_prompt_checkpoint * cp = nullptr; - const bool needs_cp = ctx_tgt_seq_rm_type == COMMON_CONTEXT_SEQ_RM_TYPE_FULL || ctx_tgt_seq_rm_type == COMMON_CONTEXT_SEQ_RM_TYPE_RS; - if (needs_cp) { - for (const auto & c : slot.prompt.checkpoints) { - if (c.n_tokens == n0) { - cp = &c; - } - } - if (cp == nullptr) { - return refused("slot " + std::to_string(slot.id) + " has no checkpoint one token before its prompt's end (" - + std::to_string(n0) + "): the lane learns only with --train-dir, which keeps one"); - } - } - // the tokens from the last prompt token on, each labelled with the next - std::vector toks; - toks.push_back(slot.prompt.tokens[n0]); - toks.insert(toks.end(), L.reply.begin(), L.reply.end()); - std::vector labels(toks.size(), -1); - for (size_t i = 0; i + 1 < toks.size(); ++i) { - labels[i] = toks[i + 1]; - } - // her stable set plus the shadow: the shadow applies to labelled rows only - std::vector set = slot.lora.empty() ? construct_lora_list({}) : slot.lora; - if ((size_t) L.lora_id >= set.size()) { - set = construct_lora_list({}); - } - set[L.lora_id].scale = 1.0f; - common_set_adapter_lora(ctx_tgt, set); - learn_lr = L.lr; - if (learn_lora_id < 0) { - llama_opt_params lopt{}; - lopt.param_filter = llama_opt_param_filter_all; - lopt.get_opt_pars = learn_opt_pars; - lopt.get_opt_pars_ud = &learn_lr; - lopt.optimizer_type = GGML_OPT_OPTIMIZER_TYPE_ADAMW; - lopt.adapter = loras[L.lora_id].ptr; - llama_opt_init(ctx_tgt, model_tgt, lopt); - learn_lora_id = L.lora_id; - } - // drop what follows n0 (attention) and put her recurrent state back at n0 - if (cp != nullptr) { - cp->load_tgt(ctx_tgt, slot.id, LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY); - } - ggml_opt_result_t result = ggml_opt_result_init(); - const bool ok = llama_opt_learn(ctx_tgt, slot.id, n0, toks.data(), labels.data(), (int32_t) toks.size(), result); - double loss = 0.0, unc = 0.0; - if (ok) { - ggml_opt_result_loss(result, &loss, &unc); - } - ggml_opt_result_free(result); - // her own adapter set again before anything else is decoded for her (the shadow is - // already off for a batch without labels: llama-graph.cpp lora_on, n_shadow_rows = - // the ubatch's label count; this does not rely on it) - common_set_adapter_lora(ctx_tgt, slot.lora); - // her slot goes back to her whole served prompt (attention cells, recurrent state, - // tokens and checkpoints agree; her next turn reuses all of it): back to n0 from the - // checkpoint, then the last prompt token decoded again under her stable set. A draft - // model's cache is cut to n0 with its own checkpoint, and the slot's tokens with it. - llama_memory_seq_rm(llama_get_memory(ctx_tgt), slot.id, n0, -1); - if (cp != nullptr) { - cp->load_tgt(ctx_tgt, slot.id, LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY); - } - int32_t n_keep = n0; - if (ctx_dft != nullptr) { - llama_memory_seq_rm(llama_get_memory(ctx_dft), slot.id, n0, -1); - if (cp != nullptr) { - cp->load_dft(ctx_dft, slot.id, LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY); - } - } else { - llama_batch one = llama_batch_get_one(&toks[0], 1); - llama_pos pos = n0; - one.pos = &pos; - llama_seq_id sid = slot.id; - int32_t nsid = 1; - llama_seq_id * sids = &sid; - one.n_seq_id = &nsid; - one.seq_id = &sids; - if (llama_decode(ctx_tgt, one) == 0) { - n_keep = L.n_prefix; - } else { - llama_memory_seq_rm(llama_get_memory(ctx_tgt), slot.id, n0, -1); - if (cp != nullptr) { - cp->load_tgt(ctx_tgt, slot.id, LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY); - } - } - } - slot.prompt.tokens.keep_first(n_keep); - slot.prompt.checkpoints.remove_if([&](const common_prompt_checkpoint & c) { return c.n_tokens > n_keep; }); - learn_outcome out; - out.ok = ok; - out.failure = ok ? "" : llama_opt_failure(ctx_tgt); - out.loss = loss; - out.n_labels = (int32_t) toks.size() - 1; - out.t_ms = (ggml_time_us() - t0) / 1000.0; - SRV_INF("learned on slot %d: %d labels from position %d, loss %.4f, %.1f ms%s\n", slot.id, out.n_labels, n0, loss, - out.t_ms, ok ? "" : (" (failed: " + out.failure + ")").c_str()); - return out; - } - - // A completion that carries a learn learns its reply on its own slot as it finishes, before the - // slot is released: no other request can take the slot between the turn and its learning (on - // a one-slot lane that is busy almost always, a separate POST /learn lost that race 12 times in - // 12 on the M5's 27B, 2026-10-15). - void learn_if_asked(server_slot & slot) { - if (!slot.task->params.learn) { - return; - } - learn_request L = *slot.task->params.learn; - L.id_slot = slot.id; - L.n_prefix = slot.task->n_tokens(); - slot.learned = learn_on_slot(slot, L, ggml_time_us()); - } +#include "server-context-learn.inc" void send_final_response(server_slot & slot) { auto res = std::make_unique(); @@ -3343,7 +3200,12 @@ struct server_context_impl { break; } res->outcome = learn_on_slot(*slot, L, t0); - queue_results.send(std::move(res)); + if (slot->state == SLOT_STATE_LEARNING) { + learning->separate_request = true; + slot->task = std::make_unique(std::move(task)); + } else { + queue_results.send(std::move(res)); + } } break; case SERVER_TASK_TYPE_UNLOAD_LORA: { @@ -3607,6 +3469,7 @@ struct server_context_impl { // a prefill step adds its duration to the decode time owed; a decode-only step pays it back const int64_t t_step = ggml_time_us() - t_step_start; t_decode_owed_us = has_prompt ? t_decode_owed_us + t_step : std::max(0, t_decode_owed_us - t_step); + advance_learning(); } void pre_decode() { @@ -3824,7 +3687,7 @@ struct server_context_impl { return; // batch is full, skip remaining slots } - if (!slot.is_processing()) { + if (!slot.is_processing() || slot.state == SLOT_STATE_LEARNING) { return; } @@ -4671,8 +4534,10 @@ struct server_context_impl { // release slot because of stop condition slot.print_timings(); learn_if_asked(slot); - send_final_response(slot); - slot.release(); + if (slot.state != SLOT_STATE_LEARNING) { + send_final_response(slot); + slot.release(); + } return; } @@ -4793,8 +4658,10 @@ struct server_context_impl { if (!process_token(result, slot)) { slot.print_timings(); learn_if_asked(slot); - send_final_response(slot); - slot.release(); + if (slot.state != SLOT_STATE_LEARNING) { + send_final_response(slot); + slot.release(); + } return; } diff --git a/tools/server/tests/learn-chunk-yields.py b/tools/server/tests/learn-chunk-yields.py new file mode 100644 index 000000000000..633887b15580 --- /dev/null +++ b/tools/server/tests/learn-chunk-yields.py @@ -0,0 +1,84 @@ +#!/usr/bin/env python3 +"""Real two-slot server test; requires an isolated server and shadow-05.gguf. + +What this catches: a reply loop that blocks the event loop until learning ends, +or releases its slot before stable restoration. A neighbour must emit tokens +while /slots reports the first slot learning, not merely before/after the request. +Run with -np 2 -b 128 -ub 128 -c 4096 --slots --train-dir FIXTURE. +""" +import json +import os +import threading +import time +import urllib.request + +URL = os.environ["LLAMA_SERVER_URL"] + + +def request(path, body=None): + data = None if body is None else json.dumps(body).encode() + req = urllib.request.Request(URL + path, data=data, + headers={"Content-Type": "application/json"}) + with urllib.request.urlopen(req, timeout=120) as response: + return json.load(response) + + +shadow = request("/lora-adapters/load", {"name": "shadow-05.gguf"})["id"] +frames, errors, result = [], [], [] +started, stop = threading.Event(), threading.Event() + + +def neighbour(): + req = urllib.request.Request(URL + "/completion", data=json.dumps({ + "prompt": "Count positive integers:", "id_slot": 1, "n_predict": -1, + "ignore_eos": True, "stream": True, "temperature": 0, + }).encode(), headers={"Content-Type": "application/json"}) + try: + with urllib.request.urlopen(req, timeout=120) as response: + for line in response: + if stop.is_set(): + break + if line.startswith(b"data:"): + frames.append(time.monotonic()) + started.set() + except Exception as error: + errors.append(str(error)) + started.set() + + +def learn(): + try: + result.append(request("/completion", { + "prompt": "Remember these observed facts:", "id_slot": 0, + "n_predict": 1, "temperature": 0, + "learn": {"lora_id": shadow, "lr": 0.001, + "reply": "A room contains a card and a window. " * 55}, + })["learn"]) + except Exception as error: + errors.append(str(error)) + + +worker = threading.Thread(target=neighbour, daemon=True) +worker.start() +assert started.wait(120) and not errors, errors +training = threading.Thread(target=learn, daemon=True) +training.start() +observed = [] +deadline = time.monotonic() + 120 +try: + while training.is_alive() and time.monotonic() < deadline: + slots = request("/slots") + if slots[0]["is_learning"]: + assert slots[0]["is_processing"], slots + observed.append(len(frames)) + time.sleep(0.01) + training.join(timeout=1) + assert not training.is_alive() and not errors, errors + assert result and result[0]["success"] and result[0]["n_labels"] > 256, result + assert len(observed) >= 2 and max(observed) > min(observed), observed + slots = request("/slots") + assert not slots[0]["is_learning"] and not slots[0]["is_processing"], slots + print(json.dumps({"learn": result[0], "learning_observations": len(observed), + "neighbour_frames_during_learning": max(observed) - min(observed)})) +finally: + stop.set() From c6959788481c4109dd34048feaf1c2bf438ba702 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sun, 8 Nov 2026 16:06:51 -0600 Subject: [PATCH 2/3] learn: restore the actual served tail once and refuse invalid snapshots --- include/llama.h | 3 +- src/llama-context-learn.cpp | 30 +++++++++------ src/llama-context.h | 4 +- tests/test-walk-exact.cpp | 2 +- tools/server/server-context-learn.inc | 48 ++++++++---------------- tools/server/server-context.cpp | 1 + tools/server/tests/learn-chunk-yields.py | 12 ++++-- 7 files changed, 48 insertions(+), 52 deletions(-) diff --git a/include/llama.h b/include/llama.h index 54633f3da841..dc0f5fcc5f57 100644 --- a/include/llama.h +++ b/include/llama.h @@ -1855,6 +1855,7 @@ extern "C" { // Resumable form of the same live-sequence owner. The caller retains exclusive custody // of the learning sequence and optimizer until DONE/FAILED; other sequences may decode // between steps. Each step executes at most one chunk (training OR stable restoration). + // restore_tokens are the exact original served tail, which may differ from a correction. // The chunk is a compute quantum, not a context/window limit. result must outlive the reply. enum llama_opt_learn_status { LLAMA_OPT_LEARN_MORE, @@ -1864,7 +1865,7 @@ extern "C" { LLAMA_API bool llama_opt_learn_begin( struct llama_context * ctx, llama_seq_id seq, llama_pos n_cached, const llama_token * tokens, const llama_token * labels, int32_t n, - ggml_opt_result_t result); + const llama_token * restore_tokens, int32_t n_restore, ggml_opt_result_t result); LLAMA_API enum llama_opt_learn_status llama_opt_learn_step(struct llama_context * ctx); LLAMA_API bool llama_opt_learn( diff --git a/src/llama-context-learn.cpp b/src/llama-context-learn.cpp index 671f7063269b..028cf8597e4b 100644 --- a/src/llama-context-learn.cpp +++ b/src/llama-context-learn.cpp @@ -5,7 +5,7 @@ #include bool llama_context::opt_learn_begin(llama_seq_id seq, llama_pos n_cached, const llama_token * tokens, const llama_token * labels, - int32_t n, ggml_opt_result_t result) { + int32_t n, const llama_token * restore_tokens, int32_t n_restore, ggml_opt_result_t result) { if (opt_reply) { opt_fail("a live reply already owns this context's optimizer; finish its restoration first"); return false; @@ -22,6 +22,10 @@ bool llama_context::opt_learn_begin(llama_seq_id seq, llama_pos n_cached, const opt_alloc_failed.store(false); opt_stop_requested.store(false); opt_failure.clear(); + if (n_restore <= 0 || restore_tokens == nullptr || (int64_t) n_cached + n_restore > (int64_t) cparams.n_ctx_seq) { + opt_fail("live learn needs the exact served tail to restore within the existing window"); + return false; + } if (n <= 0 || n_cached < 0 || tokens == nullptr || labels == nullptr) { opt_fail("llama_opt_learn: an empty reply, a negative served prefix, or no tokens / labels"); return false; @@ -58,21 +62,25 @@ bool llama_context::opt_learn_begin(llama_seq_id seq, llama_pos n_cached, const opt_fail("llama_opt_learn: sequence " + std::to_string(seq) + " has a pending recurrent rollback: finish or drop the draft first"); return false; } - if (attn != nullptr && !attn->seq_rm(seq, n_cached, -1)) { - opt_fail("llama_opt_learn: could not drop sequence " + std::to_string(seq) + "'s cells past " + std::to_string(n_cached)); - return false; - } // her stable recurrent state at the served prefix, for the restore std::vector snap; if (recr != nullptr) { synchronize(); snap.resize(state_seq_get_size(seq, LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY)); - GGML_ASSERT(state_seq_get_data(seq, snap.data(), snap.size(), LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY) == snap.size()); + if (state_seq_get_data(seq, snap.data(), snap.size(), LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY) != snap.size()) { + opt_fail("could not capture the recurrent prefix; live learning was not started"); + return false; + } + } + if (attn != nullptr && !attn->seq_rm(seq, n_cached, -1)) { + opt_fail("llama_opt_learn: could not drop sequence " + std::to_string(seq) + "'s cells past " + std::to_string(n_cached)); + return false; } auto state = std::make_unique(); state->seq = seq; state->prefix = n_cached; state->tokens.assign(tokens, tokens + n); + state->restore_tokens.assign(restore_tokens, restore_tokens + n_restore); state->labels.assign(labels, labels + n); state->snapshot = std::move(snap); state->recurrent = recr; @@ -110,12 +118,12 @@ llama_opt_learn_status llama_context::opt_learn_step() { return LLAMA_OPT_LEARN_FAILED; } } - const int32_t end = s.restoring ? (int32_t) s.tokens.size() : s.n_train; + const int32_t end = s.restoring ? (int32_t) s.restore_tokens.size() : s.n_train; const int32_t m = std::min(s.chunk_tokens, end - s.cursor); auto & batch = s.batch; batch.n_tokens = m; for (int32_t i = 0; i < m; ++i) { - batch.token[i] = s.tokens[s.cursor + i]; + batch.token[i] = s.restoring ? s.restore_tokens[s.cursor + i] : s.tokens[s.cursor + i]; batch.pos[i] = s.prefix + s.cursor + i; batch.n_seq_id[i] = 1; batch.seq_id[i][0] = s.seq; @@ -160,7 +168,7 @@ llama_opt_learn_status llama_context::opt_learn_step() { bool llama_context::opt_learn(llama_seq_id seq, llama_pos n_cached, const llama_token * tokens, const llama_token * labels, int32_t n, ggml_opt_result_t result) { - if (!opt_learn_begin(seq, n_cached, tokens, labels, n, result)) { return false; } + if (!opt_learn_begin(seq, n_cached, tokens, labels, n, tokens, n, result)) { return false; } llama_opt_learn_status status; do { status = opt_learn_step(); } while (status == LLAMA_OPT_LEARN_MORE); return status == LLAMA_OPT_LEARN_DONE; @@ -168,8 +176,8 @@ bool llama_context::opt_learn(llama_seq_id seq, llama_pos n_cached, const llama_ bool llama_opt_learn_begin(llama_context * ctx, llama_seq_id seq, llama_pos prefix, const llama_token * tokens, const llama_token * labels, int32_t n, - ggml_opt_result_t result) { - return ctx->opt_learn_begin(seq, prefix, tokens, labels, n, result); + const llama_token * restore_tokens, int32_t n_restore, ggml_opt_result_t result) { + return ctx->opt_learn_begin(seq, prefix, tokens, labels, n, restore_tokens, n_restore, result); } llama_opt_learn_status llama_opt_learn_step(llama_context * ctx) { return ctx->opt_learn_step(); } diff --git a/src/llama-context.h b/src/llama-context.h index eef7eb07f629..3bfa384c86b4 100644 --- a/src/llama-context.h +++ b/src/llama-context.h @@ -226,7 +226,7 @@ struct llama_context { struct opt_live_reply { llama_seq_id seq; llama_pos prefix; - std::vector tokens, labels; + std::vector tokens, labels, restore_tokens; std::vector snapshot; llama_memory_i * attention = nullptr; llama_memory_i * recurrent = nullptr; @@ -240,7 +240,7 @@ struct llama_context { }; std::unique_ptr opt_reply; bool opt_learn_begin(llama_seq_id seq, llama_pos n_cached, const llama_token * tokens, - const llama_token * labels, int32_t n, ggml_opt_result_t result); + const llama_token * labels, int32_t n, const llama_token * restore_tokens, int32_t n_restore, ggml_opt_result_t result); llama_opt_learn_status opt_learn_step(); bool opt_learn(llama_seq_id seq, llama_pos n_cached, const llama_token * tokens, const llama_token * labels, int32_t n, diff --git a/tests/test-walk-exact.cpp b/tests/test-walk-exact.cpp index 9924dc28fd03..6dfe69e25c21 100644 --- a/tests/test-walk-exact.cpp +++ b/tests/test-walk-exact.cpp @@ -776,7 +776,7 @@ int main(int argc, char ** argv) { // What this catches: yielding with training flags still installed, losing accumulated // labels between chunks, or restoring the neighbour instead of the learning sequence. // Real neighbour inference runs at every yield; learning still covers the entire reply. - GGML_ASSERT(llama_opt_learn_begin(ctx, 0, r0, tokens.data() + r0, labels.data(), WINDOW - r0, nullptr)); + GGML_ASSERT(llama_opt_learn_begin(ctx, 0, r0, tokens.data() + r0, labels.data(), WINDOW - r0, tokens.data() + r0, WINDOW - r0, nullptr)); // A checkpoint may not publish an optimizer/cursor pair from half a live reply. FILE * partial_state = tmpfile(); GGML_ASSERT(partial_state != nullptr); diff --git a/tools/server/server-context-learn.inc b/tools/server/server-context-learn.inc index 9512871c91f7..a18204a17f00 100644 --- a/tools/server/server-context-learn.inc +++ b/tools/server/server-context-learn.inc @@ -101,11 +101,14 @@ if (cp != nullptr) { cp->load_tgt(ctx_tgt, slot.id, LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY); } + const auto & served_tokens = slot.prompt.tokens.get_tokens(); ggml_opt_result_t result = ggml_opt_result_init(); - const bool begun = llama_opt_learn_begin(ctx_tgt, slot.id, n0, toks.data(), labels.data(), (int32_t) toks.size(), result); + const bool begun = llama_opt_learn_begin(ctx_tgt, slot.id, n0, toks.data(), labels.data(), (int32_t) toks.size(), + served_tokens.data() + n0, (int32_t) served_tokens.size() - n0, result); common_set_adapter_lora(ctx_tgt, slot.lora); learning = std::unique_ptr(new pending_learn{ &slot, cp, std::move(set), result, toks[0], L.n_prefix, (int32_t) toks.size() - 1, t0 }); + learning->began = begun; if (!begun) { learning->finished = false; learning->failure = llama_opt_failure(ctx_tgt); @@ -142,40 +145,19 @@ // already off for a batch without labels: llama-graph.cpp lora_on, n_shadow_rows = // the ubatch's label count; this does not rely on it) common_set_adapter_lora(ctx_tgt, slot.lora); - // her slot goes back to her whole served prompt (attention cells, recurrent state, - // tokens and checkpoints agree; her next turn reuses all of it): back to n0 from the - // checkpoint, then the last prompt token decoded again under her stable set. A draft - // model's cache is cut to n0 with its own checkpoint, and the slot's tokens with it. - llama_memory_seq_rm(llama_get_memory(ctx_tgt), slot.id, n0, -1); - if (cp != nullptr) { - cp->load_tgt(ctx_tgt, slot.id, LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY); - } - int32_t n_keep = n0; - if (ctx_dft != nullptr) { - llama_memory_seq_rm(llama_get_memory(ctx_dft), slot.id, n0, -1); - if (cp != nullptr) { - cp->load_dft(ctx_dft, slot.id, LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY); - } - } else { - llama_batch one = llama_batch_get_one(&pending.last_prompt, 1); - llama_pos pos = n0; - one.pos = &pos; - llama_seq_id sid = slot.id; - int32_t nsid = 1; - llama_seq_id * sids = &sid; - one.n_seq_id = &nsid; - one.seq_id = &sids; - if (llama_decode(ctx_tgt, one) == 0) { - n_keep = pending.prefix; - } else { - llama_memory_seq_rm(llama_get_memory(ctx_tgt), slot.id, n0, -1); - if (cp != nullptr) { - cp->load_tgt(ctx_tgt, slot.id, LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY); - } + // The native owner restored the exact served tail once (not the supplied correction). + // Target KV, token metadata and the untouched draft therefore still name the same tail. + // If begin refused after loading the recurrent prefix, retain only that proven prefix. + if (!pending.began || !ok) { + llama_memory_seq_rm(llama_get_memory(ctx_tgt), slot.id, n0, -1); + if (cp) { cp->load_tgt(ctx_tgt, slot.id, LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY); } + if (ctx_dft) { + llama_memory_seq_rm(llama_get_memory(ctx_dft), slot.id, n0, -1); + if (cp) { cp->load_dft(ctx_dft, slot.id, LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY); } } + slot.prompt.tokens.keep_first(n0); + slot.prompt.checkpoints.remove_if([&](const common_prompt_checkpoint & c) { return c.n_tokens > n0; }); } - slot.prompt.tokens.keep_first(n_keep); - slot.prompt.checkpoints.remove_if([&](const common_prompt_checkpoint & c) { return c.n_tokens > n_keep; }); learn_outcome out; out.ok = ok; out.failure = pending.failure; diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index 2a3f0a8bba15..4e94c5eecb06 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -978,6 +978,7 @@ struct server_context_impl { int64_t started; int64_t compute_us = 0; bool separate_request = false; + bool began = false; std::optional finished; std::string failure; ~pending_learn() { ggml_opt_result_free(result); } diff --git a/tools/server/tests/learn-chunk-yields.py b/tools/server/tests/learn-chunk-yields.py index 633887b15580..ab60067dd336 100644 --- a/tools/server/tests/learn-chunk-yields.py +++ b/tools/server/tests/learn-chunk-yields.py @@ -50,10 +50,10 @@ def learn(): try: result.append(request("/completion", { "prompt": "Remember these observed facts:", "id_slot": 0, - "n_predict": 1, "temperature": 0, + "n_predict": 8, "temperature": 0, "learn": {"lora_id": shadow, "lr": 0.001, "reply": "A room contains a card and a window. " * 55}, - })["learn"]) + })) except Exception as error: errors.append(str(error)) @@ -74,11 +74,15 @@ def learn(): time.sleep(0.01) training.join(timeout=1) assert not training.is_alive() and not errors, errors - assert result and result[0]["success"] and result[0]["n_labels"] > 256, result + assert result and result[0]["learn"]["success"] and result[0]["learn"]["n_labels"] > 256, result assert len(observed) >= 2 and max(observed) > min(observed), observed slots = request("/slots") assert not slots[0]["is_learning"] and not slots[0]["is_processing"], slots - print(json.dumps({"learn": result[0], "learning_observations": len(observed), + # The supplied correction is different from the generated reply. Retain the actual + # served reply's cache, never advertise correction tokens under generated metadata. + assert result[0]["tokens_predicted"] >= 3, result + assert slots[0]["kv_pos_max"] > result[0]["tokens_evaluated"] - 1, (slots, result) + print(json.dumps({"learn": result[0]["learn"], "retained_kv_end": slots[0]["kv_pos_max"], "learning_observations": len(observed), "neighbour_frames_during_learning": max(observed) - min(observed)})) finally: stop.set() From 9b309d71e4dc10e444cef5336d70e41cc859ded1 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sun, 8 Nov 2026 16:16:03 -0600 Subject: [PATCH 3/3] test: exercise learning cancellation and subsequent slot reuse --- tools/server/tests/learn-cancel-custody.py | 58 ++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 tools/server/tests/learn-cancel-custody.py diff --git a/tools/server/tests/learn-cancel-custody.py b/tools/server/tests/learn-cancel-custody.py new file mode 100644 index 000000000000..f2dfa510525e --- /dev/null +++ b/tools/server/tests/learn-cancel-custody.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Disconnect during learning, then reuse the slot through the real server queue. + +What this catches: HTTP cancellation releasing a sequence while its training or +stable restoration still owns KV. Run on an isolated two-slot server with +--slots, batch 128, and a fresh shadow-05.gguf under --train-dir. +""" +import json +import os +import socket +import time +import urllib.parse +import urllib.request + +url = os.environ["LLAMA_SERVER_URL"] + + +def request(path, body=None): + data = None if body is None else json.dumps(body).encode() + req = urllib.request.Request(url + path, data=data, + headers={"Content-Type": "application/json"}) + with urllib.request.urlopen(req, timeout=120) as response: + return json.load(response) + + +sid = request("/lora-adapters/load", {"name": "shadow-05.gguf"})["id"] +target = urllib.parse.urlsplit(url) +body = json.dumps({"prompt": "Remember these observed facts:", "id_slot": 0, + "n_predict": 8, "temperature": 0, + "learn": {"lora_id": sid, "lr": 0.001, + "reply": "A room contains a card and a window. " * 55}}).encode() +conn = socket.create_connection((target.hostname, target.port), timeout=120) +try: + conn.sendall(("POST /completion HTTP/1.1\r\nHost: " + target.netloc + + "\r\nContent-Type: application/json\r\nContent-Length: " + + str(len(body)) + "\r\nConnection: close\r\n\r\n").encode() + body) + deadline = time.monotonic() + 120 + while time.monotonic() < deadline: + held = request("/slots")[0] + if held["is_learning"]: + break + time.sleep(0.01) + else: + raise AssertionError("learning never became observable") + assert held["is_processing"], held + conn.shutdown(socket.SHUT_RDWR) +finally: + conn.close() + +# This competes for the same slot while cancellation is being delivered. It must +# wait for stable restoration, not run against the half-trained sequence. +following = request("/completion", {"prompt": "Which city is the capital of Kansas?", + "id_slot": 0, "n_predict": 4, "temperature": 0}) +assert following["tokens_predicted"] > 0, following +after = request("/slots")[0] +assert not after["is_learning"] and not after["is_processing"], after +print(json.dumps({"cancelled_task": held["id_task"], "next_task": after["id_task"], + "next_tokens": following["tokens_predicted"], "slot_restored": True}))