mirror of
https://github.com/Helldez/BigMoeOnEdge.git
synced 2026-10-03 03:25:42 +00:00
* feat(engine): MTP self-speculative decoding for Qwen3.5/3.6 (proposal)
Qwen3.5/3.6 ship a trained multi-token-prediction block inside the gguf. With
--mtp that head drafts --mtp-draft continuation tokens and the target verifies
all of them in one wider decode, confirming the longest prefix whose argmax
equals what the target itself would have produced. Nothing is approximated and
no weight is skipped, so the quality is the full model's — but it is NOT
byte-identical the way --overlap and --prefetch are, and must not be used in a
byte-identity gate: a verify pass evaluates 1+N positions in one batch, and a
batched matmul is not bit-identical to N single-token ones, so a near-tie can
flip. Off by default.
The prize is that a decode's dominant cost, moving the dense weights and the
routed expert slices, is paid once per group instead of once per token. The
counterweight is that the verify positions route independently, so a layer's
read set widens toward N*k wherever adjacent tokens disagree, and the draft
pass routes through the MTP block's own expert layer on top. Measured on the
desktop host (DRAM-bandwidth-bound, model streamed at ~1.4x RAM): +15.1% at
draft 3 with the host's best recipe (7.12 -> 8.19 tok/s), +29% without the
lossy drop knob, acceptance falling from 71% at draft 2 to 52% at draft 4, and
flash bytes per token rising 19.7 -> 33.7 MiB as the widening predicts. Draft 3
is the optimum here; 4 is worse than 2. On a flash-I/O-bound phone that balance
can invert, so the flag ships off pending the device A/B.
The orchestration is llama.cpp's own (common/speculative.h, public headers
only): no fork, no patch, no submodule bump. Self-speculation is one model with
two contexts over it — the target, created with n_rs_seq so a rejected tail is
rewound from a bounded snapshot rather than replayed, and a draft context
created with ctx_type = LLAMA_CONTEXT_TYPE_MTP. The engine builds the draft
context itself rather than through common_speculative_init_from_params because
the eval callback is per-context: the streamer only sees the MTP block's expert
layer if the draft context carries the same cb_eval.
The MTP block is streamed like any other layer. It sits at layer index n_layer,
contiguous with the trunk and using the same tensor naming, so the hook and the
expert source are sized n_layer + n_layer_nextn; left at n_layer its experts
stay silently mmap-resident. Two consequences that are easy to get wrong: the
capture warm-up has to run on the draft context too (the MTP graph is built
nowhere else), and prefill is fed through the driver so the draft context's KV
reaches the last prompt position.
The loop accepts BEFORE catching the draft context up, so the catch-up runs on
the accepted prefix instead of the whole verify batch. Acceptance depends only
on the target's logits, which are already in hand once the decode returns, and
the rejected tail was being computed only to be deleted a few statements later.
The resulting state is identical — the driver seeds from row
min(n_accepted, n_rows-1), the same row under either batch, and the surviving
KV is exactly the range the rollback used to carve out — while skipping
n_draft - n_accepted positions through the MTP block per group. Since that
block carries its own MoE FFN, on a streamed device those are expert reads that
no longer happen. It also removes the draft context's rollback entirely: it is
never given a tail to drop.
Requires an MTP-converted gguf (most quantisations strip the nextn tensors) and
greedy decoding; both are rejected at load with a message rather than silently
ignored, as is a n_ubatch narrower than the verify batch, which would split the
graph back into single-token passes and spend the draft for nothing.
Telemetry: an "mtp:" summary line, an mtp_batch per-token CSV column (a verify
decode's whole cost is charged to its group's first row, the rest carry zeros),
mtp_drafted / mtp_accepted / mtp_decodes in the CSV trailer and in BMOE_DONE,
and mtp / mtp_draft_max in the CSV preamble. The Android app exposes the flag
and the draft width, off by default.
Host gates pass. Validated on Qwen3.6-35B-A3B-MXFP4 with the streamed recipe:
draft 1 and draft 3 produce identical text, which is the invariant a broken
accept/rollback path would violate. Device A/B still owed.
* perf(mtp): shrink the draft context, make its cost measurable, record the device verdict
The first on-device A/B says MTP loses at every draft width, and the counters
say why. Same gguf with the flag on and off, shipping recipe (overlap, 3000 MiB
cache, pinned dense, drop 0.75), Qwen3.6-35B-A3B-Q4_K_M streamed:
off 5.82 / 6.14 tok/s 69.3 MiB/tok 69-109 majflt/tok
--mtp-draft 2 5.59 93.8 230
--mtp-draft 3 4.38 106.6 633
Speculation is working - 2.35-2.52 tokens per verify decode, 52-69% acceptance
- and still losing, because the prize does not exist in this regime.
stall_s/tok is 0.025-0.027 in every one of those runs, MTP on or off: 11-16% of
the token. This configuration is compute-bound, and what MTP amortises is weight
movement. The costs meanwhile are real and monotonic in the draft width: the read
set widens (+35%, +54% flash bytes per token), CPU per token rises (+28%, +67%),
and the draft context's memory tips the device into a fault storm.
Two things follow, and both are engine bugs rather than facts of nature.
The draft context's graph width drops from 256 to 32. Compute buffers are
reserved for the widest ubatch and the dominant term scales with
ubatch x vocabulary; on device that reservation measured 493 MiB - for a context
that evaluates ONE token per draft step and is handed at most 1 + draft_max
positions by the catch-up, with no logits asked for. Only prefill ever feeds it a
wide batch, and that is one layer, so splitting it costs very little. On this
engine memory is never free: it is the expert cache's, and the cache is what
decides whether the widened verify read set is a hit or a flash read.
And the cost of speculation is now measured instead of inferred. Drafting happens
between decodes, so it never entered wall_ms and tok/s never included it - a
speculated run could report a rate the user was not experiencing. New
mtp_draft_ms per-token column (a slice of loop_overhead_ms, not an addition),
mtp_draft_s/tok in the CSV trailer, mtp_draft_s_tok and loop_overhead_s_tok in
BMOE_DONE, and a second "mtp:" summary line printing the effective rate next to
the reported one.
Adds --mtp-p-min F, which stops drafting once the head's confidence in what it is
proposing falls below F. The draft loop already had this floor and the engine was
passing 0, so it always drafted the full width however unsure the head was - with
roughly half the drafts rejected at draft 3, that is the cheapest waste available
to cut. On a streamed device it pays twice: a draft not made is a pass through the
MTP block (which carries its own MoE FFN, so its own expert reads) that never
happens, AND one fewer independently routed position in the verify batch. Default
0, the setting the host numbers were measured at; the useful value is a property
of a device's balance between drafting cost and acceptance, so it is a knob to
measure rather than a constant to guess.
The Android app now reads the mtp_* keys it was already being sent: acceptance,
tokens per pass, and the effective rate. Before this the UI could not tell whether
speculation had run at all - only the session CSV could - which made the A/B this
commit reports impossible to run from the phone.
Neither mitigation changes the regime. The honest expectation is nearer
break-even, not a win, and the flag stays off by default.
Host gates pass. Note the noise floor: the two off runs did byte-identical work
and still differ by 5.6% in tok/s, and the runs were back-to-back without thermal
gating - the mechanism counters are the trustworthy part, not the exact deltas.
* perf(mtp): split the drafting flash cost from the widened verify batch
A speculated run streams more bytes per token for two unrelated reasons: the
MTP block carries its own MoE FFN, so every draft pass routes experts of its
own, and the verify batch widens the trunk's read set wherever adjacent
positions disagree. They need opposite fixes -- a narrower draft attacks the
first, only better agreement attacks the second -- and the route trace can
separate neither, since its framing brackets the target decode while the head
only ever runs in the draft context.
Measure the head's share directly by bracketing both drafting passes with the
expert source's byte counter, and report it as a third mtp: summary line.
Also record the branch-deletion rule in AGENTS.md: a branch list should only
show work in flight, and a rejected PR loses nothing.
* feat(engine): n-gram prompt-lookup draft source, and the measurement that closes it
The flash split added last commit said where MTP's cost actually is: at draft 3 on
the host, the head's own routing was 2.9% of the extra bytes a speculated run
streams and the widened verify batch was the other 97.1%. So a cheaper draft
producer is worth almost nothing, and the only property that could matter is one
the head does not have -- the ability to decline to draft at zero cost.
--ngram is that source. It takes the last few tokens, finds where that run occurred
before in the prompt or in what has been generated, and proposes whatever followed.
No head, no draft context, no decode, no expert read, and it works on any gguf
including the ones --mtp refuses for want of a nextn block. Below --ngram-min-match
it proposes nothing and the step falls through to a plain single-token decode.
Measured on the host, Qwen3.6-35B-A3B-MXFP4 streamed, 256 greedy tokens, cells
back-to-back with off run twice:
prose off 5.80 / 6.59 mtp3 7.32 eff ngram3 6.51 (cov 7.4%)
copy-heavy off 5.45 / 5.65 mtp3 6.43 eff ngram3 5.24 (cov 15%)
The zero-cost claim holds exactly -- mtp_draft_s/tok reads 0.0000 in every n-gram
cell, against 0.020-0.023 for the head plus the ~500 MiB of expert cache its draft
context takes. But the floor turns out to be per STEP, not per run: the 15% of steps
that did draft widened the read set to 67.2 MiB/token against 48-58 at baseline and,
at 44% acceptance, bought 1.20 tokens per decode. That is not enough to earn the
widening back, and a modest fraction of such steps sinks the run.
A --ngram-min-match sweep settles it rather than leaving it open. Raising the gate
3 -> 5 -> 8 lifts acceptance 44% -> 75% while coverage collapses 15% -> 3.4%, and
narrowing to --draft 1 reaches 82.6% -- the head's own figure on this prompt. Every
cell climbs toward baseline from BELOW and none crosses it; the best configuration
found lands on the floor. A knob whose optimum is its own disablement is not a
tuning problem. Acceptance, not drafting cost, is what pays for a widened batch, and
what a trained head buys is being right often enough to justify a batch that has
already been widened.
--ngram ships off. It is kept because it is the only speculation available on a
model with no head, because the per-step floor is real, and because the counters it
adds make the next speculation claim falsifiable.
Wiring. MtpConfig became SpecConfig with DraftSource {none, mtp, ngram}, and
--mtp-draft became --draft: the width belongs to the verify batch, not to whoever
filled it. --mtp and --ngram are rejected together rather than resolved by flag
order. In the session the gate split in two -- spec_on (wide batch, acceptance,
rollback: both sources) against mtp_on (draft context, common/speculative.h, the
catch-up: the head only) -- which is what lets the n-gram source reuse the whole
verify half while allocating nothing.
A step that drafts nothing now takes the plain path: llama_batch_get_one with a
logits row of -1, byte for byte the unspeculated decode. It used to build the wide
batch anyway. Required for --ngram, and it tightens --mtp-p-min's zero-draft steps
for free.
The matcher is pure policy over token ids with no llama.cpp at all -- not even
llama.h, since llama_token is int32_t -- so it sits on the clean side of the seam,
adds no dependency on the common layer, and is unit-tested with no model
(tests/ngram_test.cpp covers tie-breaks, clipping, self-match exclusion and the gate
boundary). Telemetry: spec= / spec_draft_max= / ngram_min_match= in the CSV
preamble, a new drafted_steps key in the trailer and BMOE_DONE, and an ngram: line
reporting coverage -- without which a delta cannot be divided by the fraction of the
run it applies to. The per-token and trailer counters keep their mtp_ names: they
always described the loop rather than a source, spec_* already means the temporal
prefetch in that trailer, and renaming would break every CSV already holding a
measurement. The Android setting became a three-way picker, migrating the old
boolean preference.
The device A/B agrees and adds a cost the host could not show. Thermally gated cells
(a 120 s settle, then a battery-temperature gate, so all six start between 35.3 and
36.4 C): prose 4.90 inside a 4.59-5.17 band, copy-heavy 3.14 against 4.43 -- a 29%
loss, worse than MTP's 18%. Major faults per token go 126 -> 1427 for a source that
allocates no draft context at all, and that is the rollback snapshots: n_rs_seq =
draft_max is asked for by ANY speculation, since rejecting a draft means rewinding the
KV, and on a hybrid attention/SSM model that snapshot is a real allocation scaling with
the context. The n-gram source escapes MTP's draft context but not the loop's own
memory, and on device that memory is the expert cache's.
The same run re-measured MTP with the thermal confound removed -- 3.64 effective
against 4.43, so the earlier device verdict was not an artefact of benching without a
cooldown gate -- and reproduced the flash split at 3.7% head against 96.3% widened
verify batch, matching the host's 2.9-3.0%.
Byte-identity gates pass; speculation stays out of them for the reason docs/mtp.md
gives.
The app's CSV configuration surface follows: the three new preamble keys get their own
glossary entries rather than falling through to the unexplained-key renderer, and the
draft source joins the short run label. A speculated run is not the same KIND of run --
under speculation a decode confirms a whole group, so its per-token rows are not even
accounted the same way -- and two compare legends differing by it must not read alike.
113 lines
6.1 KiB
C++
113 lines
6.1 KiB
C++
// Unit tests for ngram_draft() (core/src/engine/ngram_draft.cpp) — the prompt-lookup draft source.
|
|
//
|
|
// The matcher is pure policy over token ids: no model, no llama.cpp, fully deterministic, so it runs
|
|
// unconditionally in ctest. That is the point of keeping it on this side of the seam — the drafting
|
|
// decision is testable exhaustively, while what it costs is a bench question.
|
|
//
|
|
// Nothing here can be a byte-identity gate: what the loop does with a draft is verified by a batched
|
|
// decode, which is not bit-identical to single-token decodes (see docs/mtp.md). These tests cover the
|
|
// decision, not the arithmetic.
|
|
//
|
|
// Checks are explicit (not <cassert>): the Release build defines NDEBUG, which compiles assert out.
|
|
|
|
#include "bmoe/ngram_draft.h"
|
|
|
|
#include <cstdio>
|
|
#include <string>
|
|
#include <vector>
|
|
|
|
using namespace bmoe;
|
|
|
|
static int failures = 0;
|
|
|
|
static std::string show(const std::vector<int32_t> & v) {
|
|
std::string s = "[";
|
|
for (size_t i = 0; i < v.size(); ++i) {
|
|
if (i) s += ", ";
|
|
s += std::to_string(v[i]);
|
|
}
|
|
return s + "]";
|
|
}
|
|
|
|
// Draft against `corpus` where the last element plays the part of the just-confirmed token, which is
|
|
// how the session calls it: ctx holds everything already emitted, `last` is not yet appended.
|
|
static void expect_draft(const char * name,
|
|
const std::vector<int32_t> & corpus,
|
|
int n_max,
|
|
int min_match,
|
|
int max_match,
|
|
const std::vector<int32_t> & want) {
|
|
std::vector<int32_t> ctx(corpus.begin(), corpus.end() - 1);
|
|
const int32_t last = corpus.back();
|
|
|
|
std::vector<int32_t> got;
|
|
const int n = ngram_draft(ctx, last, n_max, min_match, max_match, got);
|
|
|
|
if (n == (int) got.size() && got == want) {
|
|
std::printf("[PASS] %s -> %s\n", name, show(got).c_str());
|
|
} else {
|
|
std::printf("[FAIL] %s\n want %s, got %s (returned %d)\n", name, show(want).c_str(), show(got).c_str(), n);
|
|
++failures;
|
|
}
|
|
}
|
|
|
|
int main() {
|
|
// A corpus with nothing to go on cannot draft. These are the steps that must cost exactly a
|
|
// plain decode — the floor the whole source rests on.
|
|
expect_draft("an empty corpus drafts nothing", {7}, 3, 3, 12, {});
|
|
expect_draft("a corpus shorter than the minimum match drafts nothing", {1, 2}, 3, 3, 12, {});
|
|
expect_draft("a corpus with no repetition drafts nothing", {1, 2, 3, 4, 5, 6}, 3, 3, 12, {});
|
|
// A repetition shorter than the gate is not evidence: 2 tokens match, the floor is 3.
|
|
expect_draft("a match shorter than the minimum drafts nothing", {1, 2, 3, 9, 9, 2, 3}, 3, 3, 12, {});
|
|
|
|
// The base case: the trigram (1,2,3) occurred before and was followed by 4,5,6.
|
|
expect_draft("a repeated trigram drafts its continuation", {1, 2, 3, 4, 5, 6, 0, 1, 2, 3}, 3, 3, 12, {4, 5, 6});
|
|
// The draft width caps what is proposed, not what is matched.
|
|
expect_draft("the draft width caps the proposal", {1, 2, 3, 4, 5, 6, 0, 1, 2, 3}, 2, 3, 12, {4, 5});
|
|
// Only what actually followed exists. Here the best match ends two tokens from the corpus end,
|
|
// so a width of 3 is clipped to the 2 tokens that are actually evidence.
|
|
expect_draft("the continuation is clipped at the corpus end", {1, 2, 1, 2, 1, 2}, 3, 3, 12, {1, 2});
|
|
|
|
// Selection is by match length first. The pattern (8,1,2,3) matches 4 tokens at the earlier
|
|
// occurrence and only 3 at the later one, so the longer — and older — match must win.
|
|
expect_draft("the longest match wins over a more recent shorter one", {8, 1, 2, 3, 40, 9, 1, 2, 3, 50, 8, 1, 2, 3},
|
|
1, 3, 12, {40});
|
|
// With the lengths genuinely equal — each occurrence of (1,2,3) is preceded by a different
|
|
// token, so both match exactly 3 — recency breaks the tie and the later continuation wins.
|
|
expect_draft("the most recent wins among equal-length matches", {7, 1, 2, 3, 40, 8, 1, 2, 3, 50, 9, 1, 2, 3}, 1, 3,
|
|
12, {50});
|
|
|
|
// max_match is a scan bound. Capping it at 3 makes the two candidates below tie at 3 instead of
|
|
// ranking 5 against 3, which hands the pick to recency — the observable effect of the cap.
|
|
expect_draft("capping the match length lets recency decide", {7, 7, 1, 2, 3, 40, 0, 0, 1, 2, 3, 50, 7, 7, 1, 2, 3},
|
|
1, 3, 3, {50});
|
|
|
|
// The just-confirmed token is part of the pattern, not a spectator: without it, the suffix
|
|
// (1,2) matches in two places and the trigram gate would reject. With it the match is (1,2,3).
|
|
expect_draft("the confirmed token participates in the pattern", {1, 2, 3, 77, 5, 1, 2, 3}, 1, 3, 12, {77});
|
|
|
|
// A match may overlap the pattern, which is how a run of one token predicts itself: the corpus
|
|
// is four 9s, the pattern the last three, the match the three before it. Only one token of
|
|
// evidence follows that match, so a width of 2 still drafts one.
|
|
expect_draft("a repeated token predicts itself", {9, 9, 9, 9}, 2, 3, 12, {9});
|
|
|
|
// The pattern itself is never its own match — otherwise every step would "match" at the end and
|
|
// draft nothing meaningful. Here the only occurrence of (1,2,3) is the pattern.
|
|
expect_draft("the pattern is not matched against itself", {0, 0, 0, 1, 2, 3}, 3, 3, 12, {});
|
|
|
|
// Boundary of the gate: the same corpus drafts at min_match 2 and not at 3.
|
|
expect_draft("a two-token match is rejected at a floor of three", {5, 6, 42, 0, 5, 6}, 2, 3, 12, {});
|
|
expect_draft("the same two-token match is accepted at a floor of two", {5, 6, 42, 0, 5, 6}, 2, 2, 12, {42, 0});
|
|
|
|
// Degenerate arguments are answered, not asserted on: the caller's validation already rejects
|
|
// them, and a draft source that throws would be a decode-loop crash.
|
|
expect_draft("a draft width of zero drafts nothing", {1, 2, 3, 4, 1, 2, 3}, 0, 3, 12, {});
|
|
expect_draft("a maximum match below the minimum drafts nothing", {1, 2, 3, 4, 1, 2, 3}, 3, 3, 2, {});
|
|
|
|
if (failures == 0) {
|
|
std::printf("all n-gram draft checks passed\n");
|
|
return 0;
|
|
}
|
|
std::printf("%d n-gram draft check(s) failed\n", failures);
|
|
return 1;
|
|
}
|