feat(sampler): port linear MTP coupling and cooperative verify upstream

Port GitHub PRs #12 and #13 onto Codeberg upstream main, retaining upstream kernel-chain handling. Include the source Clang target-attribute fixes required by the host build; omit the KFD header workaround and unrelated fork work.

Co-Authored-By: Claude Code <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
committed 2026-10-22 22:58:08 +02:00
1 parent 123c439684
commit d912c694f3
37 files changed
+3730 -23

No files matched your search

+76
View File
@@ -0,0 +1,76 @@
/* mtp_couple_bind.h -- the engine's post-commit binding step for a serial drafting row.
*
* Engine::finish_serial_drafter calls this after the step's commit, once the card's proposal states
* have been read back. It answers two questions the position contract turns on:
*
* - WHICH LENGTH the next build will stage the row at. That is the request's committed output
* length AFTER this commit -- the value the next build_step reads -- and nothing else. It is
* deliberately not rebuilt from the draw's pre-commit base plus the slot counter (n_acc): the
* two agree only while the commit emits as many tokens as the card accepted, and a max_tokens
* or context cut emits fewer.
* - WHETHER the row may bind at all. A sequence the plan no longer names, or whose request is no
* longer Running, will not sample again: its rows are terminal work (a carried ahead step, a
* request that finished on this commit). Binding them would put a coupled verify on the card
* for a request that has already left the sampler, which reads as a live coupled round in any
* log and is not one.
*
* The answer comes from Scheduler::committed_seq(), which commit fills under the scheduler lock.
* It is deliberately NOT read off the plan's StepEntry::req: after commit that Request may already
* have been reaped (release_locked destroys it), and a serial bind that dereferenced it would read
* freed memory.
*
* Here rather than in engine_draft.cpp so the rule can be driven against a real scheduler commit
* and the sampler's own build (tests/sched_test.cpp, tests/sample_test.cpp) without an Engine.
*/
#pragma once
#include "advance.h"
#include "rad_spechub.h"
#include <cstring>
#include <string>
namespace rad {
/* Where the next build will sample this sequence, after the current step's commit. */
struct MtpCoupleBindPoint {
bool found = false; /* the committed step carried the sequence */
bool live = false; /* and its request was still Running (not finished/cancelled/failed) */
uint64_t n_out = 0; /* its committed output length: what the next build reads as n_out */
};
/* Bind `done` rounds of this row's draw to the positions the next build samples. `rb` is round 1
* of this row in the engine's readback (stride `rb_stride` states), `tok[rd]` the card's token for
* round rd, `S` the card's slot. Fills `out[0, done)` and sets `*n_bound = done`; a sequence that
* is not live binds nothing (`*n_bound = 0`, RAD_OK) and leaves `out` untouched. RAD_E_STATE with
* `why` for a readback that is not this draw's, or is not a state the proposer could have written.
* `base` is never read here: it is the draft's coordinate, not the verify's. */
inline int mtp_couple_bind_rounds(const MtpCoupleBindPoint& p, const RadMtpCoupleDraw& d,
const RadMtpCoupleState* rb, int rb_stride, int done,
const StepSlot& S, int64_t vocab, RadMtpCoupleState* out,
int* n_bound, std::string* why) {
*n_bound = 0;
if (!p.live) return RAD_OK;
const bool sampled = d.mode == 1;
for (int rd = 1; rd <= done; ++rd) {
const RadMtpCoupleState& st = rb[(size_t)(rd - 1) * (size_t)rb_stride];
if (std::memcmp(&st.draw, &d, sizeof d) || st.round != rd || st.x != S.tok[rd] ||
st.status != (sampled ? 1 : 0) ||
(sampled && !rad_mtp_couple_state_valid(st, vocab))) {
*why = "MTP coupled: sequence " + std::to_string(d.seq) + " round " +
std::to_string(rd) + " returned status " + std::to_string(st.status) +
" round " + std::to_string(st.round) + " x " + std::to_string(st.x) +
" for card token " + std::to_string(S.tok[rd]) + " (draw " +
(std::memcmp(&st.draw, &d, sizeof d) ? "stale" : "current") +
"); refusing the step";
return RAD_E_STATE;
}
RadMtpCoupleState b = st;
b.pos = rad_mtp_couple_verify_pos(p.n_out, rd);
out[rd - 1] = b;
}
*n_bound = done;
return RAD_OK;
}
} // namespace rad
+56
View File
@@ -0,0 +1,56 @@
/* mtp_couple_plan.h -- which draw the engine stages for each serial drafting row.
*
* Engine::stage_couple_draws (core/engine_draft.cpp) reads two things off the step plan: the draw
* of every sequence on its card, and, for each drafting row, the plan entry that names the row's
* sequence on the row's card. Both are pure host bookkeeping over StepPlan/SerialRow, so they live
* here and are checked against a plan without a card.
*
* ONE ENTRY PER CARD SLOT. `by_card` is indexed by StepEntry::card, whose range is [0, max_seqs) --
* the same range as the StepSlots the advance reads. A plane sized for fewer slots makes every
* lookup miss and the first step that drafts refuses with "has no plan entry on its card"; a plane
* sized from cfg_.max_seqs is what lets a coupled run stage its first draw.
*/
#pragma once
#include "batch.h"
#include "scheduler.h" /* Scheduler::SerialRow */
#include "rad_spechub.h"
#include <cstdint>
#include <string>
#include <vector>
namespace rad {
/* Fills `by_card[0, n_card)` from the plan and writes one draw per drafting row to `stage[0, n)`.
* RAD_OK, or RAD_E_STATE with `why` set: the plane is too small for the card slots, or a drafting
* row's card carries no plan entry naming its sequence (a stale row -- the plugin would refuse the
* staged draw, so it is refused here where the row can be named). */
inline int mtp_couple_plan_stage(const StepPlan& plan, int n_card, const Scheduler::SerialRow* rows,
int n, std::vector<RadMtpCoupleDraw>* by_card,
RadMtpCoupleDraw* stage, std::string* why) {
if (!by_card || !stage || !why) return RAD_E_INVAL;
if ((int)by_card->size() < n_card) {
*why = "the draw plane holds " + std::to_string(by_card->size()) +
" card slot(s), the step can use " + std::to_string(n_card);
return RAD_E_STATE;
}
for (int c = 0; c < n_card; ++c) (*by_card)[(size_t)c] = RadMtpCoupleDraw{};
for (const StepEntry& e : plan.e)
if (e.req && e.card >= 0 && e.card < n_card)
(*by_card)[(size_t)e.card] = { e.req->sp.seed, (uint64_t)e.req->output.size(), e.seq,
e.card, e.req->sp.greedy() ? 0u : 1u };
for (int i = 0; i < n; ++i) {
const Scheduler::SerialRow& row = rows[i];
if (row.card < 0 || row.card >= n_card || (*by_card)[(size_t)row.card].seq != row.seq) {
*why = "drafting row " + std::to_string(i) + " (sequence " + std::to_string(row.seq) +
", card " + std::to_string(row.card) + ") has no plan entry on its card";
return RAD_E_STATE;
}
stage[i] = (*by_card)[(size_t)row.card];
}
return RAD_OK;
}
} // namespace rad
+26
View File
@@ -188,6 +188,7 @@ int Scheduler::init(Program& prog, const Config& cfg, IKVManager* kv, IPrefixCac
free_cards_[(size_t)c] = (int32_t)(cfg.max_seqs - 1 - c); /* 0 is taken first */
reqs_.reserve((size_t)cfg.max_seqs);
completed_.reserve((size_t)cfg.max_seqs);
committed_.reserve((size_t)cfg.max_seqs);
by_id_.reserve((size_t)cfg.max_seqs * 2);
hit_blocks_.resize(prog.kv_groups.size());
for (auto& v : hit_blocks_) v.reserve(64);
@@ -307,6 +308,25 @@ Request* Scheduler::find(uint64_t id) {
return it == by_id_.end() ? nullptr : reqs_[(size_t)it->second]->req.get();
}
bool Scheduler::running(uint64_t id) const {
std::lock_guard<std::mutex> lk(mu_);
auto it = by_id_.find(id);
if (it == by_id_.end()) return false;
const SchedReq& s = *reqs_[(size_t)it->second];
return s.req && s.req->state == ReqState::Running;
}
bool Scheduler::committed_seq(uint64_t seq, uint64_t* n_out, bool* live) const {
std::lock_guard<std::mutex> lk(mu_);
for (const CommittedSeq& c : committed_)
if (c.seq == seq) {
if (n_out) *n_out = c.n_out;
if (live) *live = c.live;
return true;
}
return false;
}
int Scheduler::set_draft(uint64_t id, const int32_t* tokens, int n) {
std::lock_guard<std::mutex> lk(mu_);
auto it = by_id_.find(id);
@@ -1804,6 +1824,10 @@ int Scheduler::commit(const StepResult& res) {
}
step_open_ = false;
/* What the serial bind reads after commit, copied here while the Requests are still held:
* reap() may release a finished one before finish_serial_drafter runs. */
committed_.clear();
const int32_t W = conv_window();
/* A mixed step leaves decode rows the same replay factors as a decode step (recurrent path
@@ -1826,6 +1850,7 @@ int Scheduler::commit(const StepResult& res) {
s.pending_free = false;
--n_deferred_;
}
committed_.push_back({e.seq, (uint64_t)r.output.size(), false});
continue;
}
@@ -1982,6 +2007,7 @@ int Scheduler::commit(const StepResult& res) {
} else if (eos) {
close_request(s, ReqState::Finished, "stop", carried);
}
committed_.push_back({e.seq, (uint64_t)r.output.size(), r.state == ReqState::Running});
}
m_.prefill_tokens += step_prefill_tok_;
+18
View File
@@ -133,6 +133,16 @@ public:
const int32_t* first_row = nullptr; /* [n_seq] */
};
/* What commit left a sequence at: the length it was committed at and whether it was still
* Running when its entry was retired. Copied under the lock in commit because reap() may
* destroy the Request before the serial bind reads it; the plan's StepEntry::req must not be
* dereferenced after commit. */
struct CommittedSeq {
uint64_t seq = 0;
uint64_t n_out = 0;
bool live = false;
};
/* `geo` is the already-resolved chunk geometry. The engine resolves it once because
* PrefixCache::configure runs first and needs its checkpoint interval; pass nullptr to
* resolve one here. */
@@ -161,6 +171,12 @@ public:
* under exactly the load that cancels. */
int cancel(uint64_t id);
Request* find(uint64_t id);
/* Whether the request is still admitted and Running, read under the lock. For an evidence
* line written after a step's wait, where the staging that named it is older than the wait. */
bool running(uint64_t id) const;
/* What the step just committed left for `seq`, copied by commit under the lock. False when
* that step carried no such sequence. */
bool committed_seq(uint64_t seq, uint64_t* n_out, bool* live) const;
/* Requests that reached a terminal state since the last call, oldest first, swapped into
* `out` under the lock (old contents discarded). Only the engine consumes it, to drop
@@ -616,6 +632,8 @@ private:
* covered, both decayed with the same time constant, so their ratio is tokens over time. */
double tps_win_prefill_ = 0.0, tps_win_decode_ = 0.0, tps_win_time_ = 0.0;
bool step_open_ = false;
/* The step just committed: its sequences' committed length and liveness, in plan order. */
std::vector<CommittedSeq> committed_;
/* The single-sequence decode floor (rad::DecodeFloor), fed by step_finished. */
DecodeFloor decode_floor_;