Skip to content

npu: the MTP draft loop -- draft k, verify as one batch, keep the longest prefix, roll back - #785

Merged
bong-water-water-bong merged 2 commits into
mainfrom
npu/mtp-draft-loop
Nov 1, 2026
Merged

bong-water-water-bong merged 2 commits into
mainfrom
npu/mtp-draft-loop

Conversation

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator

Plan item 1b (host side, CPU first): the MTP draft loop. Stacked on #784 (item 2's reference); two new files plus a
ctest registration, no device code, no weights.

What it does. DraftHead proposes k tokens from the base model's last hidden state and the token just consumed;
the base verifies all k as one batch; every draft is checked against the model's own choice at that position
(draft 0 against the last step's logits, draft i against row i-1); the longest agreeing prefix is kept, the rest is
dropped, and the loop continues from the logits of the row it stopped at — so a fully accepted iteration also yields
the next token for free. That is the mechanism that turns "one weight pass per emitted token" into "one pass per
accepted+1 tokens" on the M=16 twins.

Rollback is a truncation, not a snapshot. A 400-token state copy per iteration (~100 MB) would cost more than the
drafts save, and every cache here is position-indexed because the caller supplies pos — so "forget everything past
N" is a length bump for attention. A GDN layer's recurrence is the exception (it is not position-indexed), so
BaseModel::truncate() may refuse; the loop then stops with a clear error instead of emitting wrong tokens. Giving
the engine a recurrent-state rollback is the remaining piece, and it is the first thing the device step needs.

The engine change this needs (not in this PR, it touches the hot path): step_batch() returns only the last
row's logits. Verification needs every row, i.e. the final norm + lm head over M rows in one launch — possible
without any new kernel because the head already runs the M=16 twin ("the head is ONE row of activations" is a
property of the current call, not of the design).

Checked on the host, 65 assertions, toy base model with a closed-form truth and three draft heads
(perfect / garbage / prefix-only), k ∈ {0,1,2,4,8}:

emitted tokens identical to plain greedy decode    every case, every head   (a wrong draft costs time, never text)
final state == prompt + emitted                    every case               (no skipped or duplicated positions)
draft rows never exceed max_batch_rows             every case               (k is clamped, never widened)
k = 0                                              bit-identical plain decode, no batch, no truncation
k = 8, perfect head                                24 emitted in 3 steps + 3 batches = **0.25 passes/token**
k = 8, garbage head                                **2.00 passes/token** -- an unhelpful head doubles the work
                                                   and the stats say so instead of hiding it

The two INFO lines are the win/cost condition stated as numbers, which is what tomorrow's real-head measurement has to
beat: with FLM-class acceptance the pass count per token has to land under 1.00 against the current 1.00.

g++-16 -O2 -std=c++20 -I npu tests/mtp_draft_test.cpp -o /tmp/t && /tmp/t     # or: ctest -R mtp_draft

Not merged here. Nothing in it needs an NPU, and nothing in it changes the decode path until a caller opts in.

@bong-water-water-bong bong-water-water-bong left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

VERDICT: READY

Reviewed and run — this is the strongest shape of the three MTP PRs: the loop is a pure state machine with a closed-form
oracle, and the test proves the property that matters (a wrong draft costs time, never text).

Ran at 1c4b7d7c (host-only, no device):

$ cmake -DONEBIT_NPU_HOST=ON … && ninja mtp_draft_test        rc 0
$ ./mtp_draft_test
PASS  k=8 head=perfect: tokens identical to plain decode
PASS  k=8 head=perfect: final state == prompt+emitted (28), no skipped positions
PASS  k=8 head=perfect: draft rows never exceeded max_batch_rows (over=0)
PASS  k=8 head=perfect: acceptance 24/24, mean accept len 8.00, passes/token 0.25
PASS  k=8 head=garbage: tokens identical to plain decode … acceptance 0/192 … passes/token 2.00
PASS  k=0: no batched pass, no rollback, same tokens
INFO  k=8 perfect: iterations=3 steps=3 batches=3 emitted=24 accepted=24 passes/token=0.250
INFO  k=8 garbage: passes/token=2.000 (plain decode = 1.000), rows verified=192
all checks passed                                             rc 0

So all four claims in the body reproduce exactly, including both headline numbers (0.25 passes/token with a perfect
head, 2.00 with a garbage one) and the invariant that every case emits the same tokens as plain greedy decode. That last
one is the whole safety argument for a speculative loop, and it is asserted for every head and every k rather than once.

What I checked in the code, beyond the test: k is clamped to max_batch_rows rather than widening the batch (the
over=0 row is the assertion, and the clamp is where the loop decides rather than where it launches); truncate() is
allowed to refuse and the loop then stops with an error rather than emitting — which is right for a GDN layer whose
recurrence is not position-indexed, and is the honest gap the body names; and the rollback really is a length bump with
no per-iteration state copy.

On the head: this branch is behind — a two-dot diff against current main shows main's newer files as deletions
(docs/hetero-prefill.md, npu/ort/onebit_npu_gemm.cpp, …), which is the behind-branch artifact and not this PR's
content. Its own change is npu/mtp/draft.h, tests/mtp_draft_test.cpp and the CMakeLists.txt registration (+7), and
tools/mtp_head_ref.py is main's copy, not this PR's. I am not adding tprs-ready because the head will move on
update-branch; the verdict will be re-posted at the final head, and per the orchestrator nothing merges before #786 does.

One note for whoever takes the device step: the body's "the head already runs the M=16 twin" is the reason step_batch()
can return all M rows without a new kernel — worth confirming with the real head kernel before the loop is wired to it,
since the loop's correctness assumption is "row i is the model's choice at position i", not merely "M rows came back".

@github-actions

github-actions Bot commented Nov 1, 2026 •

Copy link
Copy Markdown

PR Reviewer Guide 🔍

(Review updated until commit 2a14750)

Here are some key observations to aid the review process:

🎫 Ticket compliance analysis 🔶

784 - Partially compliant

Compliant requirements:

  • Created tools/mtp_head_ref.py with CPU reference of the draft head
  • Defined conversion contract for integer kernels with measured error of 5.4e-4
  • Verified head specification matches shipped container's config.json and FLM's head descriptor
  • Implemented reference implementation checked against naive implementation with agreement to 1e-8
  • Provided kernel mapping for NPU side using existing pb16i M=16 family

Non-compliant requirements:

  • The PR description mentions "Plan item 1b (host side, CPU first): the MTP draft loop" but this PR only implements the draft head reference (item 2) and not the draft loop itself (item 1b)

Requires further human verification:

⏱️ Estimated effort to review: 3 🔵🔵🔵⚪⚪
🧪 PR contains tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Incomplete Implementation

The PR description states that this PR implements "Plan item 1b (host side, CPU first): the MTP draft loop" and is stacked on #784 (item 2's reference). However, the PR only contains the draft head reference implementation (tools/mtp_head_ref.py) and the test for the draft loop (tests/mtp_draft_test.cpp), but does not contain the actual draft loop implementation code. The draft loop implementation is expected to be in a separate PR as per the plan items. This creates confusion as the PR title and description suggest a complete implementation but the code diff only shows the reference and test.

// Copyright 2026 bong-water-water-bong
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// mtp_draft_test.cpp -- the MTP draft loop against a toy base model.  Host only, no NPU, no XRT, no weights.
//
// The toy model has a closed-form "truth": the token at position p is (p*7+3) % V, so a head that knows the
// position can be exactly right and a head that guesses can be exactly wrong.  Everything the loop claims is
// then checkable without a device:
//   [1] emitted tokens are identical to plain greedy decode -- for a perfect head, a garbage head, and k=0;
//   [2] a perfect head accepts every draft and needs ~1 pass per (k+1) tokens;
//   [3] a garbage head accepts nothing, still emits the same tokens, and is honestly reported as a cost;
//   [4] the base state after the loop is the same as plain decoding would leave (rollback is not "close");
//   [5] k is clamped to max_batch_rows(), never silently widened past what one batch can hold.
#include "mtp/draft.h"

#include <cstdio>
#include <cstdlib>
#include <vector>

using onebit::npu::mtp::BaseModel;
using onebit::npu::mtp::DraftHead;
using onebit::npu::mtp::Options;
using onebit::npu::mtp::Result;

namespace {

constexpr int V = 32;          // vocabulary
constexpr int HD = 1;          // hidden: [position] -- enough for a head to be right if it wants to be

int truth(int pos) { return (pos * 7 + 3) % V; }

class ToyBase : public BaseModel {
public:
    explicit ToyBase(int batch_rows = 8) : batch_rows_(batch_rows) {}

    int vocab() const override { return V; }
    int hidden_size() const override { return HD; }
    int max_batch_rows() const override { return batch_rows_; }

    bool step(int token, int pos, std::vector<float>& logits) override {
        if (pos != consumed_) { bad_pos_++; return false; }   // the loop must never skip a position
        consumed_++;
        steps_++;
        logits.assign((size_t)V, 0.0f);
        fill_logits(pos, logits, 0);
        hidden_.assign(HD, (float)consumed_);                 // the head reads the position from here
        return true;
    }

    bool step_batch_all(const std::vector<int>& tokens, int start_pos,
                        std::vector<float>& logits_all) override {
        if (start_pos != consumed_) { bad_pos_++; return false; }
        if ((int)tokens.size() > batch_rows_) { over_batch_++; return false; }
        logits_all.assign(tokens.size() * (size_t)V, 0.0f);
        for (size_t m = 0; m < tokens.size(); m++)
            fill_logits(start_pos + (int)m, logits_all, m * (size_t)V);
        consumed_ += (int)tokens.size();
        batches_++;
        return true;
    }

    // Attention-only toy: truncation is a length bump, exactly like the real position-indexed caches.
    bool truncate(int tokens) override {
        if (tokens < 0 || tokens > consumed_) return false;
        consumed_ = tokens;
        restores_++;
        return true;
    }

    const std::vector<float>& last_hidden() const override { return hidden_; }

    int consumed() const { return consumed_; }
    int steps() const { return steps_; }
    int batches() const { return batches_; }
    int restores() const { return restores_; }
    int bad_pos() const { return bad_pos_; }
    int over_batch() const { return over_batch_; }

private:
    // Writes into a caller-sized buffer (a batch is rows*V; resizing here would wipe the earlier rows).
    // The model consumes the token AT `pos` and then predicts the token at pos+1 -- the same convention as
    // the real forward (logits after a step are the next token's logits).
    static void fill_logits(int pos, std::vector<float>& out, size_t off) {
        out[off + (size_t)truth(pos + 1)] = 1.0f;
    }

    int batch_rows_;
    int consumed_ = 0, steps_ = 0, batches_ = 0, restores_ = 0, bad_pos_ = 0, over_batch_ = 0;
    std::vector<float> hidden_{0.0f};
};

// Knows the truth (reads the position out of the hidden state): every draft should be accepted.
class PerfectHead : public DraftHead {
public:
    int draft(const std::vector<float>& hidden, int, int k, std::vector<int>& out) override {
        const int have = (int)hidden[0];                      // positions consumed so far
        out.clear();
        for (int i = 0; i < k; i++) out.push_back(truth(have + i));
        return (int)out.size();
    }
};

// Proposes the token AFTER the true one at every position: the base must refuse all of it.
class GarbageHead : public DraftHead {
public:
    int draft(const std::vector<float>& hidden, int, int k, std::vector<int>& out) override {
        const int have = (int)hidden[0];
        out.clear();
        for (int i = 0; i < k; i++) out.push_back((truth(have + i) + 1) % V);
        return (int)out.size();
    }
};

// Right for the first draft, wrong afterwards: exercises the longest-prefix accept AND the rollback.
class HalfHead : public DraftHead {
public:
    int draft(const std::vector<float>& hidden, int, int k, std::vector<int>& out) override {
        const int have = (int)hidden[0];
        out.clear();
        if (k > 0) out.push_back(truth(have));                 // accepted
        for (int i = 1; i < k; i++) out.push_back((truth(have + i) + 1) % V);   // refused
        return (int)out.size();
    }
};

bool same(const std::vector<int>& a, const std::vector<int>& b) { return a == b; }

int fails = 0;
void check(bool cond, const char* what) {
    std::printf("%s  %s\n", cond ? "PASS" : "FAIL", what);
    if (!cond) fails++;
}

std::vector<int> prompt() { return {1, 5, 9, 13}; }

}  // namespace

int main() {
    const auto P = prompt();
    const int WANT = 24;
    Options base_opt;
    base_opt.max_tokens = WANT;

    // [1]/[4] the reference: plain greedy decode, and the state it leaves behind.
    ToyBase ref_model;
    const Result ref = onebit::npu::mtp::run_plain(ref_model, P, base_opt);
    check(ref.ok && (int)ref.tokens.size() == WANT, "plain decode produces the requested tokens");

    for (int k : {0, 1, 2, 4, 8}) {
        for (int which = 0; which < 3; which++) {
            ToyBase m(8);
            PerfectHead ph; GarbageHead gh; HalfHead hh;
            DraftHead* h = which == 0 ? (DraftHead*)&ph : which == 1 ? (DraftHead*)&gh : (DraftHead*)&hh;
            Options o = base_opt;
            o.k = k;
            const Result r = onebit::npu::mtp::run(m, h, P, o);
            char msg[160];
            std::snprintf(msg, sizeof msg, "k=%d head=%s: tokens identical to plain decode",
                          k, which == 0 ? "perfect" : which == 1 ? "garbage" : "half");
            check(r.ok && same(r.tokens, ref.tokens), msg);
            std::snprintf(msg, sizeof msg, "k=%d head=%s: final state == prompt+emitted (%d), no skipped positions",
                          k, which == 0 ? "perfect" : which == 1 ? "garbage" : "half", m.consumed());
            check(m.bad_pos() == 0 && m.consumed() == (int)P.size() + (int)r.tokens.size(), msg);
            std::snprintf(msg, sizeof msg, "k=%d head=%s: draft rows never exceeded max_batch_rows (over=%d)",
                          k, which == 0 ? "perfect" : which == 1 ? "garbage" : "half", m.over_batch());
            check(m.over_batch() == 0, msg);
            std::snprintf(msg, sizeof msg,
                          "k=%d head=%s: acceptance %d/%d, mean accept len %.2f, passes/token %.2f",
                          k, which == 0 ? "perfect" : which == 1 ? "garbage" : "half", r.stats.accepted,
                          r.stats.drafted, r.stats.mean_accept_len(), r.stats.passes_per_token());
            if (which == 0 && k > 0)
                check(r.stats.accepted == r.stats.drafted, msg);         // perfect head: nothing refused
            else if (which == 1 && k > 0)
                check(r.stats.accepted == 0, msg);                       // garbage head: nothing accepted
            else if (which == 2 && k > 1)
                check(r.stats.accepted > 0 && r.stats.accepted < r.stats.drafted, msg);  // prefix only
            else
                std::printf("%s\n", msg);                                // informational
        }
        // [1] k=0 must be a bit-for-bit plain decode
        { ToyBase m(8); PerfectHead ph; Options o = base_opt; o.k = 0;
          const Result r = onebit::npu::mtp::run(m, &ph, P, o);
          check(r.ok && same(r.tokens, ref.tokens) && m.batches() == 0 && m.restores() == 0,
                "k=0: no batched pass, no rollback, same tokens"); }
    }

    // [2] the win condition, stated as a number: a perfect head at k=8 amortises the pass
    {
        ToyBase m(8); PerfectHead ph; Options o = base_opt; o.k = 8;
        const Result r = onebit::npu::mtp::run(m, &ph, P, o);
        const double ppt = r.stats.passes_per_token();
        check(ppt < 0.40, "k=8 perfect head: passes per token well under 1 (the whole point)");
        std::printf("INFO k=8 perfect: iterations=%d steps=%d batches=%d emitted=%d accepted=%d passes/token=%.3f\n",
                    r.stats.iterations, r.stats.steps, r.stats.batches, r.stats.emitted, r.stats.accepted, ppt);
    }

    // [3] the cost condition: a bad head must not be free, and must not be silent about it
    {
        ToyBase m(8); GarbageHead gh; Options o = base_opt; o.k = 8;
        const Result r = onebit::npu::mtp::run(m, &gh, P, o);
        check(r.stats.first_reject == r.stats.iterations && r.stats.accepted == 0,
              "garbage head: every iteration is a first-position reject");
        check(r.stats.passes_per_token() > 1.0, "garbage head: more passes per token than plain decode");
        std::printf("INFO k=8 garbage: passes/token=%.3f (plain decode = 1.000), rows verified=%d\n",
                    r.stats.passes_per_token(), r.stats.rows_verified);
    }

    std::printf(fails ? "\n%d CHECK(S) FAILED\n" : "\nall checks passed\n", fails);
    return fails ? 1 : 0;
}
Missing Documentation for Rollback Behavior

The draft loop implementation includes rollback behavior that truncates the base state, but the documentation in the header file does not clearly explain the implications of this behavior for the base model's state management. Specifically, it's unclear how the rollback interacts with models that have recurrent states that are not position-indexed, and what the expected behavior is when truncate() returns false.

// The MTP draft loop: draft k tokens, verify them as ONE batch, keep the longest prefix the base model
// agrees with, roll the base state back, repeat.
//
// Why this shape on this hardware: one weight pass over the 27B container is ~0.44 s of decode, and the
// M=16 twins verify up to 16 rows for the price of one row's weight stream.  So the draft head is worth
// its cost exactly when it turns "one pass per emitted token" into "one pass per (accepted + 1) tokens".
//
// Rollback is a truncation, not a snapshot.  A snapshot of a 400-token context is ~100 MB and one per
// iteration would cost more than the drafts save, while every cache here is position-indexed: the caller
// supplies `pos`, so "forget everything past N" is a length bump for attention.  A GDN layer's recurrence is
// the exception (it is not position-indexed), which is why BaseModel::truncate() may refuse -- the loop then
// falls back to plain decode rather than emitting wrong tokens.

@github-actions

github-actions Bot commented Nov 1, 2026

Copy link
Copy Markdown

Persistent review updated to latest commit 21b436e

bong-water-water-bong added 2 commits November 1, 2026 17:29
…gest prefix, roll back

One weight pass over the 27B container is ~0.44 s of decode and the M=16 twins verify up to 16 rows for
the price of one row's stream, so a draft head is worth its cost exactly when it turns "one pass per
emitted token" into "one pass per accepted+1 tokens".  This is the policy half of that, with no weights
and no device state in it:

  * DraftHead proposes k tokens from the base model's last hidden state and the token just consumed;
  * the base model verifies all k as ONE batch, and every draft is checked against the model's own
    choice AT THAT POSITION (draft 0 against the last step's logits, draft i against row i-1);
  * the longest agreeing prefix is kept, the rest is truncated away, and the loop continues from the
    logits of the row it stopped at -- so a fully accepted iteration also yields the next token free.

Rollback is a truncation, not a snapshot: a 400-token state copy per iteration would cost more than the
drafts save, and every cache here is position-indexed (the caller supplies ).  A GDN layer's
recurrence is the exception, so BaseModel::truncate() may refuse -- the loop then stops with a clear
error rather than emitting wrong tokens; giving the engine a recurrent-state rollback is the remaining
device-side work, and it is named in the header.

tests/mtp_draft_test.cpp pins the invariants on a toy base model (closed-form truth, perfect / garbage /
prefix-only heads, k = 0,1,2,4,8): emitted text is identical to plain greedy decode in every case, the
final state matches prompt+emitted, draft rows never exceed the batch width, and the accounting is honest
-- a perfect head at k=8 costs 0.25 passes per token against 1.00 plain, a garbage head costs 2.00.
…t report it 'Not Run'

ci.yml's build step lists the test targets explicitly, so a target that is not in that list never gets a
binary and its ctest entry fails as 'Not Run' -- which is what the build leg hit. This follows the pattern
the other test-only targets in this file already use (decision_test, systemone_test, systemone_route_test):
the binary is pulled in as a dependency of npu_sampling_test. Adding mtp_draft_test to ci.yml's list is the
cleaner form and needs a workflow-scoped push, which this branch does not have.

@bong-water-water-bong bong-water-water-bong left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

VERDICT: READY

Confirmation at 21b436e3, rebased onto current main (7ba14cde/5a34f624): the tree is identical to the head I
reviewed — git diff --stat 1c4b7d7c 21b436e3 → empty — and build is green.

So the evidence stands: ninja mtp_draft_test rc 0 and all checks passed, including the numbers in the body —
k=8 perfect → acceptance 24/24, passes/token 0.250; k=8 garbage → passes/token 2.000 against plain decode's 1.000;
tokens identical to plain greedy decode in every head/k case; final state == prompt+emitted with no skipped positions;
over=0 on the max_batch_rows bound; and k=0 bit-identical with no batch and no truncation.

tprs-ready applied. If the build fix you mentioned was meant to land here, note that this head's tree is the one I
tested — so if the CI build fails at some later head, that is a different tree and I will re-verdict it rather than
carry this one.

@bong-water-water-bong bong-water-water-bong added the tprs-ready TPRS: review verdict READY posted by the standing reviewer; merge gate satisfied label Nov 1, 2026
@github-actions

github-actions Bot commented Nov 1, 2026

Copy link
Copy Markdown

Persistent review updated to latest commit 2a14750

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Review effort 3/5 tprs-ready TPRS: review verdict READY posted by the standing reviewer; merge gate satisfied

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant