diff --git a/include/llama.h b/include/llama.h index 2cc29db52690..e7bd1a1bbabf 100644 --- a/include/llama.h +++ b/include/llama.h @@ -2202,15 +2202,41 @@ extern "C" { // name before anything is decoded (llama_opt_failure). Set before llama_opt_epoch. LLAMA_API void llama_opt_set_walk_host_budget(struct llama_context * lctx, size_t bytes); - // Replay a lesson's routing as it was lived (Continuum): `ids` holds, for each MoE layer and each + // A mind's routing as she lived it (Continuum; llama-lived-routing.h). On a mixture-of-experts base + // with capture on, serving records each row's chosen experts per sequence, position and layer; a + // live lesson (llama_opt_learn_begin) replays its span's, and on a mixture-of-experts base is + // refused while capture is off. Off always succeeds. + enum llama_routing_capture { + LLAMA_ROUTING_CAPTURE_RECORDING = 0, // on: serving records, lessons replay + LLAMA_ROUTING_CAPTURE_NO_EXPERTS = 1, // a dense base: nothing to record, and lessons need none + LLAMA_ROUTING_CAPTURE_TOO_MANY = 2, // more experts than a u8 names (256): refused + LLAMA_ROUTING_CAPTURE_NO_ROOM = 3, // the capture buffer could not be allocated: refused + LLAMA_ROUTING_CAPTURE_OFF = 4, // turned off + }; + LLAMA_API enum llama_routing_capture llama_set_routing_capture(struct llama_context * ctx, bool on); + + // Import a span's routing into the table and pin it: `ids` holds, for each MoE layer and each // position in [pos0, pos0 + n_pos) of sequence `seq`, its n_used chosen experts - // ([n_layer][n_pos][n_used]). Per row: a row of `seq` alone inside the range replays its experts; - // every other row in the same ubatch (a neighbour's, or `seq` outside the range) routes as it - // serves. n_pos 0 clears. Returns false, setting nothing, when the shape is not the model's (its - // layers and experts per token) or an id is not one of its experts. + // ([n_layer][n_pos][n_used]). Per row: a row of `seq` alone inside the span replays its experts; + // every other row in the same ubatch routes as it serves. n_pos 0 clears the pin. Returns false, + // setting nothing, when the shape is not the model's or an id is not one of its experts. LLAMA_API bool llama_set_pinned_experts(struct llama_context * ctx, llama_seq_id seq, int32_t n_layer, int32_t n_used, llama_pos pos0, int32_t n_pos, const int32_t * ids); + // Pin a span from what serving recorded; false, pinning nothing, when a position was never served. + LLAMA_API bool llama_pin_lived_routing(struct llama_context * ctx, llama_seq_id seq, llama_pos pos0, int32_t n_pos); + + // The bytes the lived-routing table holds, for the owner of this context's memory. + LLAMA_API size_t llama_lived_routing_bytes(const struct llama_context * ctx); + + // Read a span's lived routing ([n_layer][n_pos][n_used], -1 where serving never routed that layer at + // that position: the last layer runs only a ubatch's outputs): what a sequence paged out carries + // with it. False when a position was never served. + LLAMA_API bool llama_get_lived_routing(struct llama_context * ctx, llama_seq_id seq, llama_pos pos0, int32_t n_pos, int32_t * ids); + + // The host microseconds capture has spent so far (queueing copies and writing the table): its price. + LLAMA_API int64_t llama_lived_routing_host_us(const struct llama_context * ctx); + // The host bytes the exact walk's largest window so far kept (0 before one ran, or when the // walk is not exact): what a run of this shape needs, from the run's own arithmetic. LLAMA_API size_t llama_opt_walk_host_bytes(struct llama_context * lctx); diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index b17ee5a17869..bc539ac173a0 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -24,7 +24,7 @@ set(LLAMA_CORE_SOURCES llama-context-learn.cpp llama-context-learn-tiles.cpp llama-walk.cpp - llama-pinned-experts.cpp + llama-lived-routing.cpp llama-cparams.cpp llama-grammar.cpp llama-graph.cpp diff --git a/src/llama-context-learn.cpp b/src/llama-context-learn.cpp index 5ece5045cb4a..e5cbb8d58a9d 100644 --- a/src/llama-context-learn.cpp +++ b/src/llama-context-learn.cpp @@ -1,5 +1,6 @@ // Live-sequence learning: one owner for synchronous calls and resumable serving-loop chunks. #include "llama-context.h" +#include "llama-model.h" #include "llama-memory-hybrid.h" #include "llama-memory-recurrent.h" #include @@ -66,6 +67,18 @@ 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; } + // the reply's rows, and the served tail it restores, replay the routing she served them with + // (llama-lived-routing.h); with capture on, a span she never served is refused by name, never routed afresh + if (model.hparams.n_expert > 0 && !lived_routing.capture) { + opt_fail("llama_opt_learn: a lesson on a mixture-of-experts base replays the routing she served, and this context " + "records none: turn on llama_set_routing_capture before she serves"); + return false; + } + if (lived_routing.capture && !pin_lived(seq, n_cached, std::max(n, n_restore))) { + opt_fail("llama_opt_learn: sequence " + std::to_string(seq) + " has positions in [" + std::to_string(n_cached) + ", " + + std::to_string(n_cached + std::max(n, n_restore)) + ") its serving never routed; a lesson replays only what she lived"); + return false; + } // her stable recurrent state at the served prefix, for the restore std::vector snap; if (recr != nullptr) { @@ -73,11 +86,13 @@ bool llama_context::opt_learn_begin(llama_seq_id seq, llama_pos n_cached, const snap.resize(state_seq_get_size(seq, LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY)); 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"); + clear_pin(); 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)); + clear_pin(); return false; } auto state = std::make_unique(); @@ -203,6 +218,7 @@ llama_opt_learn_status llama_context::opt_learn_step() { if (!restored) { opt_fail("live reply could not restore its served prefix: re-prefill it"); opt_reply.reset(); + clear_pin(); // Continuum: the lesson no longer replays her routing return LLAMA_OPT_LEARN_FAILED; } } @@ -212,6 +228,7 @@ llama_opt_learn_status llama_context::opt_learn_step() { cparams.walk_active = false; const auto failure = s.failure; opt_reply.reset(); + clear_pin(); // Continuum: the lesson no longer replays her routing if (!failure.empty()) { opt_fail(failure.c_str()); return LLAMA_OPT_LEARN_FAILED; @@ -263,6 +280,7 @@ llama_opt_learn_status llama_context::opt_learn_step() { if (s.restoring) { opt_fail("live reply restoration failed: re-prefill its sequence"); opt_reply.reset(); + clear_pin(); // Continuum: the lesson no longer replays her routing return LLAMA_OPT_LEARN_FAILED; } s.failure = opt_failure.empty() ? "live reply training chunk failed" : opt_failure; @@ -273,6 +291,7 @@ llama_opt_learn_status llama_context::opt_learn_step() { if (s.restoring && s.cursor == end) { const auto failure = s.failure; opt_reply.reset(); + clear_pin(); // Continuum: the lesson no longer replays her routing if (!failure.empty()) { opt_fail(failure.c_str()); return LLAMA_OPT_LEARN_FAILED; diff --git a/src/llama-context.cpp b/src/llama-context.cpp index 9fa670937a36..554a514a55c2 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -965,6 +965,7 @@ void llama_context::synchronize() { } ggml_backend_sched_synchronize(sched.get()); + routing_settle(); // Continuum: the routing copied after compute lands in her table // FIXME: if multiple single tokens are evaluated without a synchronization, // the stats will be added to the prompt evaluation stats @@ -2440,6 +2441,7 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { if (opt_retains_graph(mctx, res)) { // Continuum: the live owner keeps the prepared graph return 0; } + routing_queue(res, ubatch); // Continuum: what she served, for the lessons that replay it (llama-lived-routing.cpp) // plot the computation graph in dot format (for debugging purposes) //if (n_past%100 == 0) { diff --git a/src/llama-context.h b/src/llama-context.h index 1e0a224cadac..f717345df1a9 100644 --- a/src/llama-context.h +++ b/src/llama-context.h @@ -8,7 +8,7 @@ #include "llama-impl.h" #include "llama-memory.h" #include "llama-moe-cache.h" -#include "llama-pinned-experts.h" +#include "llama-lived-routing.h" #include "ggml-cpp.h" #include "ggml-opt.h" @@ -240,9 +240,26 @@ struct llama_context { llama_context_buffer_bytes buffer_bytes() const; int32_t memory_rows(llama_context_memory_row * out, int32_t n_max) const; // Continuum, llama-context-api.cpp - bool set_pinned_experts(llama_seq_id seq, int32_t n_layer, int32_t n_used, llama_pos pos0, int32_t n_pos, const int32_t * ids); // Continuum, llama-pinned-experts.cpp - void drop_reusable_graphs(); // Continuum: no cached graph is reused across a change it cannot see - llama_pinned_experts pinned_experts; // Continuum: a lesson's lived routing (llama-pinned-experts.h) + // Continuum: her routing as lived (llama-lived-routing.h, .cpp) + llama_routing_capture set_routing_capture(bool on); + bool set_pinned_experts(llama_seq_id seq, int32_t n_layer, int32_t n_used, llama_pos pos0, int32_t n_pos, const int32_t * ids); + bool pin_lived(llama_seq_id seq, llama_pos pos0, int32_t n_pos); + void clear_pin(); + void routing_queue(const llm_graph_result * res, const llama_ubatch & ubatch); // after a serving ubatch computes + void routing_settle(); // at synchronize + void drop_reusable_graphs(); // no cached graph is reused across a change it cannot see + llama_lived_routing lived_routing; + struct routing_pending { + std::vector> seqs; // per ubatch row + std::vector pos; + std::vector out; // per ubatch row: an output row + std::vector pinned; + uint32_t n_tokens = 0; + std::vector> layers; // il, rows it holds at rows [il * n_tokens, ...) + std::vector ids; // the buffer's first n_layer * n_tokens rows + }; + std::vector routing_queued; // reused: [0, routing_used) wait for synchronize + size_t routing_used = 0; llama_memory_breakdown memory_breakdown() const; // diff --git a/src/llama-cparams.h b/src/llama-cparams.h index 330b1e4de406..d6a0c308fe36 100644 --- a/src/llama-cparams.h +++ b/src/llama-cparams.h @@ -34,8 +34,8 @@ 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 lesson's routing as it was lived, replayed by the MoE graphs that train its rows (llama-pinned-experts.h) - const struct llama_pinned_experts * pinned_experts = nullptr; + // her routing as lived: captured by serving graphs, replayed by the MoE graphs that train its rows; set while capture or a pin is on (llama-lived-routing.h) + const struct llama_lived_routing * lived_routing = 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 be6938841486..9f2aa41af816 100644 --- a/src/llama-graph.cpp +++ b/src/llama-graph.cpp @@ -1,5 +1,5 @@ #include "llama-graph.h" -#include "llama-pinned-experts.h" +#include "llama-lived-routing.h" #include "llama-impl.h" #include "llama-model.h" @@ -1570,6 +1570,7 @@ void llm_graph_result::reset() { t_candidates.clear(); t_sampling_all.clear(); t_moe_ids.clear(); + t_routing.clear(); // Continuum params = {}; @@ -2456,7 +2457,7 @@ ggml_tensor * llm_graph_context::build_moe_ffn( selected_experts = ggml_argsort_top_k(ctx0, selection_probs, n_expert_used); // [n_expert_used, n_tokens] cb(selected_experts->src[0], "ffn_moe_argsort", il); } - selected_experts = llama_pin_experts(*this, il, selected_experts); // Continuum: a lesson's rows replay the routing she lived + selected_experts = llama_route_experts(*this, il, selected_experts); // Continuum: replay what she lived, capture what she serves cb(selected_experts, "ffn_moe_topk", il); if (arch == LLM_ARCH_GROVEMOE && n_expert != hparams.n_expert) { diff --git a/src/llama-graph.h b/src/llama-graph.h index f99a8dc9e76b..0deff3325406 100644 --- a/src/llama-graph.h +++ b/src/llama-graph.h @@ -1106,6 +1106,7 @@ class llm_graph_result { // [0] is the LLAMA_MOE_RANDOM_ROUTING input, the rest are views of it std::vector t_moe_ids; + std::vector> t_routing; // Continuum: each MoE layer's selected ids, for capture (llama-lived-routing.h) std::vector inputs; std::vector fused_nodes; diff --git a/src/llama-lived-routing.cpp b/src/llama-lived-routing.cpp new file mode 100644 index 000000000000..bd6a08e3541f --- /dev/null +++ b/src/llama-lived-routing.cpp @@ -0,0 +1,337 @@ +#include "llama-lived-routing.h" + +#include "llama-context.h" +#include "llama-cparams.h" +#include "llama-model.h" + +#include +#include + +// ---- the table ---- + +const uint8_t * llama_lived_routing::at(llama_seq_id seq, llama_pos pos, int32_t il) const { + if (seq < 0 || (size_t) seq >= seqs.size() || pos < 0) { + return nullptr; + } + const auto & rows = seqs[seq]; + const size_t flag = (size_t) pos * (size_t) n_layer + (size_t) il; + if (flag >= rows.lived.size() || !rows.lived[flag]) { + return nullptr; + } + return rows.ids.data() + flag * (size_t) n_used; +} + +void llama_lived_routing::write(llama_seq_id seq, llama_pos pos, int32_t il, const int32_t * ids) { + if ((size_t) seq >= seqs.size()) { + seqs.resize((size_t) seq + 1); + } + auto & rows = seqs[seq]; + const size_t n_flags = ((size_t) pos + 1) * (size_t) n_layer; + if (rows.lived.size() < n_flags) { + rows.lived.resize(n_flags, 0); + rows.ids.resize(n_flags * (size_t) n_used, 0); + } + const size_t flag = (size_t) pos * (size_t) n_layer + (size_t) il; + uint8_t * dst = rows.ids.data() + flag * (size_t) n_used; + for (int32_t k = 0; k < n_used; ++k) { + dst[k] = (uint8_t) ids[k]; + } + rows.lived[flag] = 1; +} + +bool llama_lived_routing::lived(llama_seq_id seq, llama_pos pos0, int32_t n) const { + for (int32_t p = 0; p < n; ++p) { + if (at(seq, pos0 + p, 0) == nullptr) { + return false; + } + } + return true; +} + +bool llama_lived_routing::pinned(const llama_ubatch & ubatch, uint32_t i) const { + return pin_n > 0 && ubatch.n_seq_id[i] == 1 && ubatch.seq_id[i][0] == pin_seq && + ubatch.pos[i] >= pin0 && ubatch.pos[i] < pin0 + pin_n; +} + +size_t llama_lived_routing::bytes() const { + size_t total = 0; + for (const auto & rows : seqs) { + total += rows.ids.capacity() + rows.lived.capacity(); + } + return total; +} + +// ---- the graph ---- + +void llm_graph_input_pinned_experts::set_input(const llama_ubatch * ubatch) { + GGML_ASSERT(ggml_backend_buffer_is_host(ids->buffer) && ggml_backend_buffer_is_host(mask->buffer)); + int32_t * id = (int32_t *) ids->data; + float * m = (float *) mask->data; + const int32_t n_used = lived.n_used; + const bool every_row = ids->ne[1] == (int64_t) ubatch->n_tokens; + GGML_ASSERT(every_row || ubatch->output); + int64_t row = 0; + for (uint32_t i = 0; i < ubatch->n_tokens; ++i) { + if (!every_row && !ubatch->output[i]) { + continue; + } + const uint8_t * lived_ids = lived.pinned(*ubatch, i) ? lived.at(ubatch->seq_id[i][0], ubatch->pos[i], il) : nullptr; + m[row] = lived_ids ? 1.0f : 0.0f; + for (int32_t k = 0; k < n_used; ++k) { + id[(size_t) row * n_used + k] = lived_ids ? (int32_t) lived_ids[k] : 0; + } + ++row; + } + GGML_ASSERT(row == ids->ne[1]); +} + +bool llm_graph_input_pinned_experts::can_reuse(const llm_graph_params & params) { + // the same pin is still set (setting or clearing one also drops the cached graphs) + return params.cparams.lived_routing == &lived && lived.pin_n > 0; +} + +ggml_tensor * llama_route_experts(const llm_graph_context & graph, int32_t il, ggml_tensor * routed) { + const llama_lived_routing * lived = graph.cparams.lived_routing; + if (lived == nullptr || lived->n_used != routed->ne[0] || il >= lived->n_layer) { + return routed; + } + ggml_context * ctx = graph.ctx0; + ggml_tensor * selected = routed; + if (lived->pin_n > 0) { + const int64_t n_used = routed->ne[0], n_rows = routed->ne[1]; + auto inp = std::make_unique(*lived, il); + inp->ids = ggml_new_tensor_2d(ctx, GGML_TYPE_I32, n_used, n_rows); + inp->mask = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, 1, n_rows); + ggml_set_input(inp->ids); + ggml_set_input(inp->mask); + ggml_tensor * ids = inp->ids; + ggml_tensor * mask = inp->mask; + graph.res->add_input(std::move(inp)); + // per row: routed + mask * (lived - routed), in F32 (expert ids are exact far below 2^24) + ggml_tensor * r = ggml_cast(ctx, routed, GGML_TYPE_F32); + ggml_tensor * p = ggml_cast(ctx, ids, GGML_TYPE_F32); + selected = ggml_cast(ctx, ggml_add(ctx, r, ggml_mul(ctx, ggml_sub(ctx, p, r), mask)), GGML_TYPE_I32); + } + if (lived->capture && lived->capture_dev != nullptr && !graph.cparams.training) { + // this layer's choice into its slice of the capture buffer, a copy kernel in the step's own + // command stream (as the K/V cache is written); one read per ubatch then carries every layer + ggml_tensor * buf = lived->capture_dev; + const int64_t rows = selected->ne[1]; + GGML_ASSERT(graph.n_tokens <= buf->ne[1] / lived->n_layer); + ggml_tensor * dst = ggml_view_2d(ctx, buf, lived->n_used, rows, buf->nb[1], (size_t) il * graph.n_tokens * buf->nb[1]); + ggml_build_forward_expand(graph.gf, ggml_cpy(ctx, selected, dst)); + graph.res->t_routing.emplace_back(il, dst); + } + return selected; +} + +// ---- the context ---- + +llama_routing_capture llama_context::set_routing_capture(bool on) { + const auto & hp = model.hparams; + if (on && hp.n_expert == 0) { + return LLAMA_ROUTING_CAPTURE_NO_EXPERTS; + } + if (on && hp.n_expert > (uint32_t) llama_lived_routing::MAX_EXPERTS) { + return LLAMA_ROUTING_CAPTURE_TOO_MANY; + } + synchronize(); // nothing queued reads the buffer this replaces + lived_routing.capture_dev = nullptr; + lived_routing.capture_buf.reset(); + lived_routing.capture_ctx.reset(); + lived_routing.n_layer = (int32_t) hp.n_layer(); + lived_routing.n_used = (int32_t) hp.n_expert_used(); + if (on) { + ggml_init_params params = { /*.mem_size =*/ ggml_tensor_overhead(), /*.mem_buffer =*/ nullptr, /*.no_alloc =*/ true }; + lived_routing.capture_ctx.reset(ggml_init(params)); + lived_routing.capture_dev = ggml_new_tensor_2d(lived_routing.capture_ctx.get(), GGML_TYPE_I32, lived_routing.n_used, + (int64_t) lived_routing.n_layer * cparams.n_ubatch); + ggml_set_name(lived_routing.capture_dev, "lived_routing_capture"); + ggml_backend_dev_t dev = model.dev_output(); + auto * buft = dev ? ggml_backend_dev_buffer_type(dev) : ggml_backend_cpu_buffer_type(); + lived_routing.capture_buf.reset(ggml_backend_alloc_ctx_tensors_from_buft(lived_routing.capture_ctx.get(), buft)); + if (!lived_routing.capture_buf) { + lived_routing.capture_dev = nullptr; + lived_routing.capture_ctx.reset(); + lived_routing.capture = false; + cparams.lived_routing = lived_routing.pin_n > 0 ? &lived_routing : nullptr; + return LLAMA_ROUTING_CAPTURE_NO_ROOM; + } + } + lived_routing.capture = on; + cparams.lived_routing = (on || lived_routing.pin_n > 0) ? &lived_routing : nullptr; + drop_reusable_graphs(); // a graph built the other way registers (or not) what this one needs + return on ? LLAMA_ROUTING_CAPTURE_RECORDING : LLAMA_ROUTING_CAPTURE_OFF; +} + +bool llama_context::set_pinned_experts(llama_seq_id seq, int32_t n_layer, int32_t n_used, llama_pos pos0, int32_t n_pos, const int32_t * ids) { + if (n_pos == 0) { + clear_pin(); + return true; + } + const auto & hp = model.hparams; + if (ids == nullptr || seq < 0 || pos0 < 0 || n_pos < 0 || n_layer != (int32_t) hp.n_layer() || + n_used != (int32_t) hp.n_expert_used() || hp.n_expert > (uint32_t) llama_lived_routing::MAX_EXPERTS) { + return false; + } + const size_t n = (size_t) n_layer * (size_t) n_pos * (size_t) n_used; + // -1 (as llama_get_lived_routing reads it): serving never routed that layer there, and the row routes + for (size_t k = 0; k < n; ++k) { + if (ids[k] < -1 || ids[k] >= (int32_t) hp.n_expert) { + return false; // not an expert of this model + } + } + routing_settle(); // nothing queued may land over what is imported + lived_routing.n_layer = n_layer; + lived_routing.n_used = n_used; + for (int32_t il = 0; il < n_layer; ++il) { + for (int32_t p = 0; p < n_pos; ++p) { + const int32_t * row = ids + ((size_t) il * n_pos + p) * n_used; + if (row[0] >= 0) { + lived_routing.write(seq, pos0 + p, il, row); + } + } + } + return pin_lived(seq, pos0, n_pos); +} + +bool llama_context::pin_lived(llama_seq_id seq, llama_pos pos0, int32_t n_pos) { + synchronize(); // every serving ubatch so far has reached the table + if (n_pos <= 0 || !lived_routing.lived(seq, pos0, n_pos)) { + return false; + } + lived_routing.pin_seq = seq; + lived_routing.pin0 = pos0; + lived_routing.pin_n = n_pos; + cparams.lived_routing = &lived_routing; + drop_reusable_graphs(); // a graph built without this pin has no input to carry it + return true; +} + +void llama_context::clear_pin() { + if (lived_routing.pin_n == 0) { + return; + } + lived_routing.pin_seq = -1; + lived_routing.pin0 = 0; + lived_routing.pin_n = 0; + cparams.lived_routing = lived_routing.capture ? &lived_routing : nullptr; + drop_reusable_graphs(); +} + +void llama_context::routing_queue(const llm_graph_result * res, const llama_ubatch & ubatch) { + if (res->t_routing.empty() || lived_routing.capture_dev == nullptr) { + return; + } + const int64_t t0 = ggml_time_us(); + // entries and their buffers are reused across steps: a step allocates nothing once warm + if (routing_used == routing_queued.size()) { + routing_queued.emplace_back(); + } + routing_pending & pending = routing_queued[routing_used++]; + pending.n_tokens = ubatch.n_tokens; + pending.seqs.resize(ubatch.n_tokens); + pending.pos.resize(ubatch.n_tokens); + pending.out.resize(ubatch.n_tokens); + pending.pinned.resize(ubatch.n_tokens); + for (uint32_t i = 0; i < ubatch.n_tokens; ++i) { + pending.seqs[i].assign(ubatch.seq_id[i], ubatch.seq_id[i] + ubatch.n_seq_id[i]); + pending.pos[i] = ubatch.pos[i]; + pending.out[i] = ubatch.output ? ubatch.output[i] : 1; + pending.pinned[i] = lived_routing.pinned(ubatch, i); + } + pending.layers.clear(); + int32_t top = 0; + for (const auto & [il, dst] : res->t_routing) { + pending.layers.emplace_back(il, dst->ne[1]); + top = std::max(top, il + 1); + } + // one read: the first `top * n_tokens` rows hold every captured layer of this ubatch + ggml_tensor * buf = lived_routing.capture_dev; + const size_t bytes = (size_t) top * ubatch.n_tokens * buf->nb[1]; + pending.ids.resize(bytes / sizeof(int32_t)); + ggml_backend_t backend = ggml_backend_sched_get_tensor_backend(sched.get(), res->t_routing.front().second); + GGML_ASSERT(backend != nullptr); + ggml_backend_tensor_get_async(backend, buf, pending.ids.data(), 0, bytes); + lived_routing.host_us += ggml_time_us() - t0; +} + +void llama_context::routing_settle() { + if (routing_used == 0) { + return; + } + const int64_t t0 = ggml_time_us(); + const int32_t n_used = lived_routing.n_used; + for (size_t q = 0; q < routing_used; ++q) { + const auto & pending = routing_queued[q]; + const uint32_t n_tokens = pending.n_tokens; + for (const auto & [il, rows] : pending.layers) { + const int32_t * layer = pending.ids.data() + (size_t) il * n_tokens * n_used; + const bool every_row = rows == (int64_t) n_tokens; + size_t row = 0; + for (uint32_t i = 0; i < n_tokens; ++i) { + if (!every_row && !pending.out[i]) { + continue; // the last layer ran only the outputs: the others were never routed there + } + if (!pending.pinned[i]) { // a pinned row replayed what the table already holds + for (const llama_seq_id seq : pending.seqs[i]) { + lived_routing.write(seq, pending.pos[i], il, layer + row * (size_t) n_used); + } + } + ++row; + } + } + } + routing_used = 0; + lived_routing.host_us += ggml_time_us() - t0; +} +void llama_context::drop_reusable_graphs() { + for (auto & res : gf_res_prev) { + res->reset(); + } + gf_res_prev_active = nullptr; +} + +// ---- the API ---- + +llama_routing_capture llama_set_routing_capture(llama_context * ctx, bool on) { + GGML_ASSERT(ctx != nullptr); + return ctx->set_routing_capture(on); +} + +bool llama_set_pinned_experts(llama_context * ctx, llama_seq_id seq, int32_t n_layer, int32_t n_used, llama_pos pos0, int32_t n_pos, const int32_t * ids) { + return ctx && ctx->set_pinned_experts(seq, n_layer, n_used, pos0, n_pos, ids); +} + +bool llama_pin_lived_routing(llama_context * ctx, llama_seq_id seq, llama_pos pos0, int32_t n_pos) { + return ctx && ctx->pin_lived(seq, pos0, n_pos); +} + +size_t llama_lived_routing_bytes(const llama_context * ctx) { + return ctx ? ctx->lived_routing.bytes() : 0; +} + +bool llama_get_lived_routing(llama_context * ctx, llama_seq_id seq, llama_pos pos0, int32_t n_pos, int32_t * ids) { + if (ctx == nullptr || ids == nullptr || n_pos <= 0) { + return false; + } + ctx->synchronize(); // every serving ubatch so far has reached the table + const llama_lived_routing & lived = ctx->lived_routing; + if (!lived.lived(seq, pos0, n_pos)) { + return false; + } + for (int32_t il = 0; il < lived.n_layer; ++il) { + for (int32_t p = 0; p < n_pos; ++p) { + int32_t * dst = ids + ((size_t) il * n_pos + p) * lived.n_used; + const uint8_t * src = lived.at(seq, pos0 + p, il); + for (int32_t k = 0; k < lived.n_used; ++k) { + dst[k] = src ? (int32_t) src[k] : -1; // -1: serving never routed this layer here + } + } + } + return true; +} + +int64_t llama_lived_routing_host_us(const llama_context * ctx) { + return ctx ? ctx->lived_routing.host_us : 0; +} diff --git a/src/llama-lived-routing.h b/src/llama-lived-routing.h new file mode 100644 index 000000000000..c5a0b793ea9a --- /dev/null +++ b/src/llama-lived-routing.h @@ -0,0 +1,89 @@ +#pragma once + +// A mind's routing as she lived it (Continuum; IN-PROCESS-LEARNING.md, "Routing is part of what was +// lived"). On a mixture-of-experts base a near-tie in a row's top-k picks a different expert when the +// arithmetic differs slightly (a tile of 64 rows against one of 512, CPU against CUDA), and that discrete +// choice turns a 1e-4 difference into a different function. So serving records each row's chosen +// experts, per sequence, position and layer, and a lesson replays them: it trains the function she +// served. +// +// One owner per context: +// - the table: per sequence, [position][layer][n_used] expert ids as u8 (a model with more than 256 +// experts is refused) beside a flag per position and layer that serving routed it (the last +// layer runs only a ubatch's output rows). A later serving decode at a position overwrites it; a +// rewind keeps it, since a lesson rewinds to the served prefix and must still find what she lived. +// - capture: serving graphs (never training ones) hand their selected ids to the table, copied +// asynchronously after compute and written at the context's synchronize, so the GPU never waits. +// - the pin: rows of one sequence inside a span replay the table, per row and per layer; every other +// row in the same ubatch routes as it serves. While a pin is set every MoE layer carries it, so a +// graph's shape never depends on which rows a ubatch covers, and setting or clearing a pin drops the +// cached graphs. + +#include "llama.h" +#include "llama-graph.h" + +#include "ggml-cpp.h" + +#include +#include + +struct llama_lived_routing { + static constexpr int32_t MAX_EXPERTS = 256; // ids are u8 + + int32_t n_layer = 0; + int32_t n_used = 0; + bool capture = false; + + // the pin: rows of `pin_seq` in [pin0, pin0 + pin_n) replay the table (pin_n 0: none) + llama_seq_id pin_seq = -1; + llama_pos pin0 = 0; + int32_t pin_n = 0; + + // the capture buffer: I32 [n_used, n_layer * n_ubatch] on the output device. A serving graph copies + // layer il's choice into rows [il * n_tokens, il * n_tokens + rows), so one read per ubatch carries + // every layer (a read per layer cost a command buffer each on Metal: 405 us per decode, 2026-11-27) + ggml_context_ptr capture_ctx; + ggml_backend_buffer_ptr capture_buf; + ggml_tensor * capture_dev = nullptr; + + // host time spent capturing (queue and settle), for the probe that prices it + int64_t host_us = 0; + + // per sequence id: ids [position][layer][n_used], and whether serving routed that layer [position][layer] + struct seq_rows { + std::vector ids; + std::vector lived; + }; + std::vector seqs; + + // the layer's lived ids at (seq, pos), or nullptr where serving never routed it + const uint8_t * at(llama_seq_id seq, llama_pos pos, int32_t il) const; + void write(llama_seq_id seq, llama_pos pos, int32_t il, const int32_t * ids); + // every position of [pos0, pos0 + n) of `seq` was routed by serving (its first layer recorded) + bool lived(llama_seq_id seq, llama_pos pos0, int32_t n) const; + // row i of `ubatch` lies in the pin + bool pinned(const llama_ubatch & ubatch, uint32_t i) const; + size_t bytes() const; +}; + +// The graph input that carries, for the rows a layer sees, each pinned and lived row's experts and a +// mask (1 replayed, 0 routed). Rows are the ubatch's, or after the last layer's cut only its outputs, +// in ubatch order (as out_ids keeps them). +class llm_graph_input_pinned_experts : public llm_graph_input_i { +public: + llm_graph_input_pinned_experts(const llama_lived_routing & lived, int32_t il) : lived(lived), il(il) {} + virtual ~llm_graph_input_pinned_experts() = default; + + void set_input(const llama_ubatch * ubatch) override; + bool can_reuse(const llm_graph_params & params) override; + + ggml_tensor * ids = nullptr; // I32 [n_used, n_rows], 0 on a routed row + ggml_tensor * mask = nullptr; // F32 [1, n_rows] + + const llama_lived_routing & lived; + const int32_t il; +}; + +// The one hook in build_moe_ffn, after the router: `routed` with pinned rows replaced by what she lived, +// and in a serving graph the selection registered for capture. +ggml_tensor * llama_route_experts(const llm_graph_context & graph, int32_t il, ggml_tensor * routed); diff --git a/src/llama-pinned-experts.cpp b/src/llama-pinned-experts.cpp deleted file mode 100644 index 30d6136b9530..000000000000 --- a/src/llama-pinned-experts.cpp +++ /dev/null @@ -1,108 +0,0 @@ -#include "llama-pinned-experts.h" - -#include "llama-context.h" -#include "llama-cparams.h" -#include "llama-model.h" - -#include - -bool llama_pinned_experts::pinned(const llama_ubatch & ubatch, uint32_t i) const { - return n_pos > 0 && ubatch.n_seq_id[i] == 1 && ubatch.seq_id[i][0] == seq && - ubatch.pos[i] >= pos0 && ubatch.pos[i] < pos0 + n_pos; -} - -const int32_t * llama_pinned_experts::at(int32_t il, llama_pos pos) const { - return ids.data() + ((size_t) il * (size_t) n_pos + (size_t) (pos - pos0)) * (size_t) n_used; -} - -void llm_graph_input_pinned_experts::set_input(const llama_ubatch * ubatch) { - GGML_ASSERT(ggml_backend_buffer_is_host(ids->buffer) && ggml_backend_buffer_is_host(mask->buffer)); - int32_t * id = (int32_t *) ids->data; - float * m = (float *) mask->data; - const bool every_row = ids->ne[1] == (int64_t) ubatch->n_tokens; - GGML_ASSERT(every_row || ubatch->output); - int64_t row = 0; - for (uint32_t i = 0; i < ubatch->n_tokens; ++i) { - if (!every_row && !ubatch->output[i]) { - continue; - } - const bool p = pinned.pinned(*ubatch, i); - m[row] = p ? 1.0f : 0.0f; - if (p) { - std::memcpy(id + (size_t) row * pinned.n_used, pinned.at(il, ubatch->pos[i]), sizeof(int32_t) * pinned.n_used); - } else { - std::memset(id + (size_t) row * pinned.n_used, 0, sizeof(int32_t) * pinned.n_used); - } - ++row; - } - GGML_ASSERT(row == ids->ne[1]); -} - -bool llm_graph_input_pinned_experts::can_reuse(const llm_graph_params & params) { - // the same pin is still set (setting or clearing one also drops the cached graphs) - return params.cparams.pinned_experts == &pinned; -} - -ggml_tensor * llama_pin_experts(const llm_graph_context & graph, int32_t il, ggml_tensor * routed) { - const llama_pinned_experts * pinned = graph.cparams.pinned_experts; - // While a pin is set, every MoE layer carries it, covered rows or not: the graph's shape does not - // depend on which rows a ubatch covers, so a reused graph never skips a pin (Codex on #167); its - // input sets each row's mask per ubatch. - if (pinned == nullptr || pinned->n_used != routed->ne[0] || il >= pinned->n_layer) { - return routed; - } - const int64_t n_used = routed->ne[0], n_rows = routed->ne[1]; - auto inp = std::make_unique(*pinned, il); - inp->ids = ggml_new_tensor_2d(graph.ctx0, GGML_TYPE_I32, n_used, n_rows); - inp->mask = ggml_new_tensor_2d(graph.ctx0, GGML_TYPE_F32, 1, n_rows); - ggml_set_input(inp->ids); - ggml_set_input(inp->mask); - ggml_tensor * ids = inp->ids; - ggml_tensor * mask = inp->mask; - graph.res->add_input(std::move(inp)); - // per row: routed + mask * (pinned - routed), in F32 (expert ids are exact far below 2^24) - ggml_context * ctx = graph.ctx0; - ggml_tensor * r = ggml_cast(ctx, routed, GGML_TYPE_F32); - ggml_tensor * p = ggml_cast(ctx, ids, GGML_TYPE_F32); - ggml_tensor * mixed = ggml_add(ctx, r, ggml_mul(ctx, ggml_sub(ctx, p, r), mask)); - return ggml_cast(ctx, mixed, GGML_TYPE_I32); -} - -bool llama_context::set_pinned_experts(llama_seq_id seq, int32_t n_layer, int32_t n_used, llama_pos pos0, int32_t n_pos, const int32_t * ids) { - if (n_pos == 0) { - pinned_experts = {}; - cparams.pinned_experts = nullptr; - drop_reusable_graphs(); - return true; - } - const auto & hp = model.hparams; - if (ids == nullptr || seq < 0 || n_pos < 0 || n_layer != (int32_t) hp.n_layer() || n_used != (int32_t) hp.n_expert_used()) { - return false; - } - const size_t n = (size_t) n_layer * (size_t) n_pos * (size_t) n_used; - for (size_t k = 0; k < n; ++k) { - if (ids[k] < 0 || ids[k] >= (int32_t) hp.n_expert) { - return false; // not an expert of this model - } - } - pinned_experts.seq = seq; - pinned_experts.n_layer = n_layer; - pinned_experts.n_used = n_used; - pinned_experts.pos0 = pos0; - pinned_experts.n_pos = n_pos; - pinned_experts.ids.assign(ids, ids + n); - cparams.pinned_experts = &pinned_experts; - drop_reusable_graphs(); // a graph built without this pin has no input to carry it - return true; -} - -void llama_context::drop_reusable_graphs() { - for (auto & res : gf_res_prev) { - res->reset(); - } - gf_res_prev_active = nullptr; -} - -bool llama_set_pinned_experts(llama_context * ctx, llama_seq_id seq, int32_t n_layer, int32_t n_used, llama_pos pos0, int32_t n_pos, const int32_t * ids) { - return ctx && ctx->set_pinned_experts(seq, n_layer, n_used, pos0, n_pos, ids); -} diff --git a/src/llama-pinned-experts.h b/src/llama-pinned-experts.h deleted file mode 100644 index 9bd05b3bf753..000000000000 --- a/src/llama-pinned-experts.h +++ /dev/null @@ -1,51 +0,0 @@ -#pragma once - -// A lesson's routing as it was lived (Continuum): each position's chosen experts, per layer, for ONE -// sequence, so a mixture-of-experts graph that trains those rows replays them instead of routing -// again. A near-tie in a row's top-k picks a different expert when the arithmetic differs slightly (a -// tile of 64 rows against one of 512, CPU against CUDA), and that discrete choice turns a 1e-4 -// difference into a different function; replaying the lived choice trains the function that was -// served. The pin is per row: a row of the pinned sequence inside its range replays, every other row -// (a neighbour's, or the lesson's own outside the range) routes as it serves, in the same ubatch. - -#include "llama.h" -#include "llama-graph.h" - -#include -#include - -struct llama_pinned_experts { - llama_seq_id seq = -1; - int32_t n_layer = 0; - int32_t n_used = 0; - llama_pos pos0 = 0; - int32_t n_pos = 0; - // [layer][position - pos0][n_used] - std::vector ids; - - // row i of `ubatch` replays: it belongs to the pinned sequence alone and its position is covered - bool pinned(const llama_ubatch & ubatch, uint32_t i) const; - const int32_t * at(int32_t il, llama_pos pos) const; -}; - -// The graph input that carries, for the rows a layer sees, each pinned row's experts and a mask (1 -// pinned, 0 routed). Rows are the ubatch's, or after the last layer's cut only its outputs, in ubatch -// order (as out_ids keeps them). -class llm_graph_input_pinned_experts : public llm_graph_input_i { -public: - llm_graph_input_pinned_experts(const llama_pinned_experts & pinned, int32_t il) : pinned(pinned), il(il) {} - virtual ~llm_graph_input_pinned_experts() = default; - - void set_input(const llama_ubatch * ubatch) override; - bool can_reuse(const llm_graph_params & params) override; - - ggml_tensor * ids = nullptr; // I32 [n_used, n_rows], 0 on a routed row - ggml_tensor * mask = nullptr; // F32 [1, n_rows] - - const llama_pinned_experts & pinned; - const int32_t il; -}; - -// `routed` ([n_used, n_rows], the router's choice) with every pinned row of this graph replaced by its -// lived choice; `routed` itself when no row of the ubatch is pinned. -ggml_tensor * llama_pin_experts(const llm_graph_context & graph, int32_t il, ggml_tensor * routed); diff --git a/tests/test-walk-exact.cpp b/tests/test-walk-exact.cpp index e31b299ede0f..eb0fd05324c0 100644 --- a/tests/test-walk-exact.cpp +++ b/tests/test-walk-exact.cpp @@ -284,6 +284,13 @@ static int32_t model_n_expert(const llama_model * model) { GGML_ASSERT(llama_model_meta_val_str(model, (std::string(arch) + ".expert_count").c_str(), val, sizeof(val)) > 0); return (int32_t) std::atoi(val); } +// the model's experts per token, from its own metadata (.expert_used_count) +static int32_t model_n_expert_used(const llama_model * model) { + char arch[64], val[32]; + GGML_ASSERT(llama_model_meta_val_str(model, "general.architecture", arch, sizeof(arch)) > 0); + GGML_ASSERT(llama_model_meta_val_str(model, (std::string(arch) + ".expert_used_count").c_str(), val, sizeof(val)) > 0); + return (int32_t) std::atoi(val); +} // what this catches (Codex on fork #167): a context-wide pin that hands a neighbour the lesson's experts // at the same positions, or drops the whole ubatch to the router when one row is uncovered. static int pinned_rows_are_per_sequence(const common_params & params, llama_model * model, const std::vector & tokens) { @@ -391,6 +398,113 @@ static int pinned_rows_survive_graph_reuse(const common_params & params, llama_m } return failed; } + +// what this catches: serving's capture recording something other than what the graph selected, or a +// last-layer row serving never routed (the cut keeps only outputs) recorded as lived. One serving +// decode of n rows, only the last an output (a prompt's prefill), with capture on and the graph's own +// ffn_moe_topk recorded beside it: every layer but the last matches row by row, and the last holds +// only the output row. +static int capture_records_what_serving_routed(const common_params & params_in, llama_model * model, const std::vector & tokens) { + const uint32_t n = 32; + common_params params = params_in; + lived_routing r; + r.n_layer = llama_model_n_layer(model); + r.n_pos = (int32_t) n; + params.cb_eval = routing_eval; + params.cb_eval_user_data = &r; + auto cparams = common_context_params_to_llama(params); + cparams.n_ctx = 2 * n; + cparams.n_batch = n; + cparams.n_ubatch = n; + cparams.kv_unified = true; + llama_context * ctx = llama_init_from_model(model, cparams); + GGML_ASSERT(ctx != nullptr); + GGML_ASSERT(llama_set_routing_capture(ctx, true) == LLAMA_ROUTING_CAPTURE_RECORDING); + llama_batch batch = llama_batch_init((int32_t) n, 0, 1); + for (uint32_t i = 0; i < n; ++i) { + batch.token[i] = tokens[i]; + batch.pos[i] = (llama_pos) i; + batch.n_seq_id[i] = 1; + batch.seq_id[i][0] = 0; + batch.logits[i] = i + 1 == n; + } + batch.n_tokens = (int32_t) n; + GGML_ASSERT(llama_decode(ctx, batch) == 0); + llama_batch_free(batch); + std::vector table((size_t) r.n_layer * n * r.n_used); + GGML_ASSERT(llama_get_lived_routing(ctx, 0, 0, (int32_t) n, table.data())); + const size_t bytes = llama_lived_routing_bytes(ctx); + llama_free(ctx); + int wrong = 0; + const int32_t last = r.n_layer - 1; + for (int32_t il = 0; il < r.n_layer; ++il) { + for (uint32_t p = 0; p < n; ++p) { + const int32_t * got = &table[((size_t) il * n + p) * r.n_used]; + if (il == last && p + 1 < n) { + wrong += got[0] != -1; // never routed by serving + continue; + } + // the recorder keeps the last layer's single output row at its row 0 + const size_t row = il == last ? 0 : p; + wrong += std::memcmp(got, &r.ids[((size_t) il * r.n_pos + row) * r.n_used], sizeof(int32_t) * r.n_used) != 0; + } + } + printf(" capture: %d of %u rows x %d layers differ from what the graph selected (the last layer: its output only); table %zu bytes\n", + wrong, n, r.n_layer, bytes); + return wrong == 0 ? 0 : 1; +} + +// WALK_ROUTING_BENCH: what capture costs serving. One context, a prefill, then single-token decodes +// (the generation shape) with capture off and on, alternated so the node's other load falls on both +// arms alike; each arm reports tokens per second over its decodes. +static void routing_capture_bench(const common_params & params, llama_model * model, const std::vector & tokens) { + const uint32_t n_prompt = 64, n_gen = 64, rounds = 8; + auto cparams = common_context_params_to_llama(params); + cparams.n_ctx = n_prompt + rounds * 2 * n_gen + 8; + cparams.n_batch = n_prompt; + cparams.n_ubatch = n_prompt; + cparams.kv_unified = true; + llama_context * ctx = llama_init_from_model(model, cparams); + GGML_ASSERT(ctx != nullptr); + llama_batch batch = llama_batch_init((int32_t) n_prompt, 0, 1); + auto put = [&](uint32_t k, llama_token t, llama_pos p, bool out) { + batch.token[k] = t; batch.pos[k] = p; batch.n_seq_id[k] = 1; batch.seq_id[k][0] = 0; batch.logits[k] = out; + }; + for (uint32_t i = 0; i < n_prompt; ++i) { + put(i, tokens[i], (llama_pos) i, i + 1 == n_prompt); + } + batch.n_tokens = (int32_t) n_prompt; + GGML_ASSERT(llama_decode(ctx, batch) == 0); + llama_synchronize(ctx); + llama_pos pos = (llama_pos) n_prompt; + double tps[2][8] = {}; + for (uint32_t r = 0; r < rounds; ++r) { + for (int on = 0; on < 2; ++on) { + GGML_ASSERT(llama_set_routing_capture(ctx, on != 0) == (on ? LLAMA_ROUTING_CAPTURE_RECORDING : LLAMA_ROUTING_CAPTURE_OFF)); + const int64_t t0 = ggml_time_us(); + for (uint32_t g = 0; g < n_gen; ++g) { + put(0, tokens[(size_t) pos % tokens.size()], pos, true); + batch.n_tokens = 1; + GGML_ASSERT(llama_decode(ctx, batch) == 0); + (void) llama_get_logits_ith(ctx, -1); // the sampler's read: the step's synchronize + ++pos; + } + tps[on][r] = n_gen * 1e6 / (double) (ggml_time_us() - t0); + } + } + llama_batch_free(batch); + auto median = [&](int on) { + std::vector v(tps[on], tps[on] + rounds); + std::sort(v.begin(), v.end()); + return (v[rounds / 2 - 1] + v[rounds / 2]) / 2.0; + }; + printf(" capture bench (%u rounds of %u decodes, alternated): median off %.2f tok/s, on %.2f tok/s (on/off %.3f); table %zu bytes; capture host time %.1f us per captured decode\n", + rounds, n_gen, median(0), median(1), median(1) / median(0), llama_lived_routing_bytes(ctx), (double) llama_lived_routing_host_us(ctx) / (rounds * n_gen)); + for (uint32_t r = 0; r < rounds; ++r) { + printf(" round %u: off %.2f on %.2f\n", r, tps[0][r], tps[1][r]); + } + llama_free(ctx); +} // one SGD step from the fresh adapter: the step itself, -lr * the gradient it took static std::vector step_delta(const common_params & params, llama_model * model, const std::string & init, const std::vector & tokens, const std::vector & labelled, @@ -860,11 +974,25 @@ int main(int argc, char ** argv) { // walk, or routing flips between row shapes? Both are measured: each graph routing for itself, then // both replaying the routing the window was served with. If pinning restores agreement, routing // was the cause, and the walk replays the lived routing by design. + if (getenv("WALK_ROUTING_BENCH")) { + routing_capture_bench(params, model, tokens); + std::remove(init.c_str()); + llama_model_free(model); + llama_backend_free(); + return 0; + } if (getenv("WALK_PINNED")) { - if (pinned_rows_are_per_sequence(params, model, tokens) != 0 || pinned_rows_survive_graph_reuse(params, model, tokens) != 0) { + if (capture_records_what_serving_routed(params, model, tokens) != 0 || pinned_rows_are_per_sequence(params, model, tokens) != 0 || + pinned_rows_survive_graph_reuse(params, model, tokens) != 0) { fprintf(stderr, "FAILED: a pinned row is not its own sequence's (Codex on fork #167)\n"); return 1; } + if (getenv("WALK_PINNED_CHECKS_ONLY")) { // the routing checks alone, without the learning comparison + std::remove(init.c_str()); + llama_model_free(model); + llama_backend_free(); + return 0; + } std::vector all(WINDOW + 1, 1); all[0] = 0; const uint32_t tile = getenv("WALK_PINNED_TILE") ? (uint32_t) atoi(getenv("WALK_PINNED_TILE")) : 64; @@ -1012,7 +1140,11 @@ int main(int argc, char ** argv) { }; cp.cb_eval_user_data = &graph_segments; } - return llama_init_from_model(model, cp); + llama_context * c = llama_init_from_model(model, cp); + if (getenv("WALK_LIVE_PINNED")) { // serving records her routing; her lesson replays it + GGML_ASSERT(llama_set_routing_capture(c, true) == LLAMA_ROUTING_CAPTURE_RECORDING); + } + return c; }; auto decode_span = [&](llama_context * c, llama_seq_id sq, const llama_token * t, llama_pos p0, int32_t n) { llama_batch b = llama_opt_batch_init(WINDOW); @@ -1063,6 +1195,22 @@ int main(int argc, char ** argv) { if (getenv("WALK_LIVE_BRACKET_NEIGHBOURS")) { want_second_neighbour = seq_state(ctl, 2); } + // WALK_LIVE_PINNED: her routing as served, and the reference step that replays it + lived_routing served_routing; + std::vector want_pinned; + if (getenv("WALK_LIVE_PINNED")) { + served_routing.n_layer = llama_model_n_layer(model); + served_routing.n_used = model_n_expert_used(model); + served_routing.n_pos = (int32_t) WINDOW; + served_routing.ids.resize((size_t) served_routing.n_layer * WINDOW * served_routing.n_used); + GGML_ASSERT(llama_get_lived_routing(ctl, 0, 0, (int32_t) WINDOW, served_routing.ids.data())); + const ggml_type kept = g_cache_type; + g_cache_type = streams ? GGML_TYPE_F16 : GGML_TYPE_F32; // the cache the live context keeps + g_pinned = &served_routing; + want_pinned = step_delta(params, model, init, tokens, reply, WINDOW, true); + g_pinned = nullptr; + g_cache_type = kept; + } llama_free(ctl); llama_adapter_lora * adapter = llama_adapter_lora_init(model, init.c_str()); @@ -1072,6 +1220,19 @@ int main(int argc, char ** argv) { GGML_ASSERT(llama_set_adapters_lora(ctx, &adapter, 1, &scale) == 0); decode_span(ctx, 1, neighbour, 0, 200); decode_span(ctx, 0, tokens.data(), 0, r0); // her context, as served + if (getenv("WALK_LIVE_PINNED")) { + // her reply was served in the control: carry its routing here, as a sequence paged in carries + // it, then lift the pin so only her lesson replays it (the table keeps it) + const int32_t span = (int32_t) WINDOW - r0; + std::vector reply_routing((size_t) served_routing.n_layer * span * served_routing.n_used); + for (int32_t il = 0; il < served_routing.n_layer; ++il) { + std::memcpy(&reply_routing[(size_t) il * span * served_routing.n_used], + &served_routing.ids[((size_t) il * WINDOW + r0) * served_routing.n_used], + sizeof(int32_t) * span * served_routing.n_used); + } + GGML_ASSERT(llama_set_pinned_experts(ctx, 0, served_routing.n_layer, served_routing.n_used, r0, span, reply_routing.data())); + GGML_ASSERT(llama_set_pinned_experts(ctx, 0, served_routing.n_layer, served_routing.n_used, 0, 0, nullptr)); + } if (getenv("WALK_LIVE_BRACKET_NEIGHBOURS")) { decode_span(ctx, 2, neighbour, 0, 200); } const std::vector neighbour_before = seq_state(ctx, 1); struct admission_counts { size_t statics = 0, workspace = 0; bool allow_workspace = true; std::map limits; } stale_admission, current_admission; @@ -1540,7 +1701,8 @@ 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))) { + const auto & want_live = getenv("WALK_LIVE_PINNED") ? want_pinned : (streams ? want_f16 : want_f32); + if (!learned || !same_step(compare("live sequence: her reply learned in place vs the walk's exact step", got, want_live))) { fprintf(stderr, "FAILED: learning on a live sequence is not the walk's step\n"); ++failures; }