Skip to content
10 changes: 10 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -395,6 +395,16 @@ if(OpenMP_CXX_FOUND)
endif()
add_dependencies(onebit onebit_npu_forward_syntax)

# What one MTP head step costs on the HOST (tools/mtp_head_bench.cpp). The draft route's per-iteration cost is two
# base passes plus the drafter's logits calls (both on the array) and the head's own arithmetic (this host), so this
# is the only term measurable without the device -- and the term a maths change has to be stated on. It also prints
# a hash of every output hidden, so "no number moves" is checked bit for bit instead of argued.
add_executable(mtp_head_bench tools/mtp_head_bench.cpp npu/mtp/mtp_head.cpp)
target_include_directories(mtp_head_bench PRIVATE npu)
if(OpenMP_CXX_FOUND)
target_link_libraries(mtp_head_bench PRIVATE OpenMP::OpenMP_CXX)
endif()

# ── MoE expert streaming (docs/moe-streaming.md) ─────────────────────────
# The routed-expert cache: pinned RAM slots filled with O_DIRECT reads, and
# `1bit moe-cache`, which replays expert traces through it. Linux only.
Expand Down
43 changes: 30 additions & 13 deletions npu/mtp/mtp_head.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -128,27 +128,44 @@ void rope_partial(float* x, int pos, int rot) {

void Matrix::matvec(const float* a, float* y) const {
const int G = K / kG;
std::vector<double> acc((size_t)N, 0.0);
// Codes are laid out [k][n], so ONE row of a's products walks n with a stride of 1 byte and the columns a
// thread touches are scattered N bytes apart. Doing one n at a time (the first form of this function) is
// therefore a 64-byte cache line per 1-byte code: 424 M codes ~ 27 GB of traffic per head step, measured
// 331 ms for the eight matrices of a step (0.7-4.8 GF/s, TMTPLOOP-STATE 2026-11-04 02:4x).
//
// Blocking n fixes the access pattern without touching the arithmetic: for a block of NB columns the k loop
// reads NB CONTIGUOUS code bytes per row, and each column's accumulation keeps its exact order (g ascending,
// k ascending, then the additive-min pass), so the result is bit-identical to the unblocked form -- asserted
// in tests/mtp_draft_test.cpp [10] against the old code kept there as the reference.
constexpr int NB = 64;
const int nblocks = (N + NB - 1) / NB;
#pragma omp parallel for schedule(static)
for (int n = 0; n < N; n++) {
double acc_n = 0.0;
for (int nb = 0; nb < nblocks; nb++) {
const int n0 = nb * NB, w = std::min(N - n0, NB);
double acc[NB], P[NB], ex[NB];
for (int i = 0; i < w; i++) {
acc[i] = 0.0;
ex[i] = std::ldexp(1.0, (int)eref[(size_t)n0 + i]);
}
for (int g = 0; g < G; g++) {
const int8_t* cg = &codes[(size_t)(g * kG) * N + n];
double P = 0.0;
for (int k = 0; k < kG; k++) P += (double)a[g * kG + k] * (double)cg[(size_t)k * N];
acc_n += P * ((double)ms[(size_t)g * N + n] * std::ldexp(1.0, (int)eref[(size_t)n]));
for (int i = 0; i < w; i++) P[i] = 0.0;
for (int k = 0; k < kG; k++) {
const double av = (double)a[g * kG + k];
const int8_t* ck = &codes[(size_t)(g * kG + k) * N + n0];
for (int i = 0; i < w; i++) P[i] += av * (double)ck[i];
}
const int16_t* mg = &ms[(size_t)g * N + n0];
for (int i = 0; i < w; i++) acc[i] += P[i] * ((double)mg[i] * ex[i]);
}
double ag_sum = 0.0;
// the source's additive min, second pass over g exactly as before
for (int g = 0; g < G; g++) {
double s = 0.0;
for (int k = 0; k < kG; k++) s += a[g * kG + k];
acc_n += s * (double)add[(size_t)g * N + n];
ag_sum += s;
const float* ad = &add[(size_t)g * N + n0];
for (int i = 0; i < w; i++) acc[i] += s * (double)ad[i];
}
(void)ag_sum;
acc[(size_t)n] = acc_n;
for (int i = 0; i < w; i++) y[n0 + i] = (float)acc[i];
}
for (int n = 0; n < N; n++) y[n] = (float)acc[(size_t)n];
}

bool load_weights(const std::string& exact_dir, const std::string& q4k_dir, Weights& w, std::string& err) {
Expand Down
59 changes: 59 additions & 0 deletions tests/mtp_draft_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@

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

using onebit::npu::mtp::BaseModel;
Expand Down Expand Up @@ -469,6 +470,64 @@ int main() {
gs.accepted_at[1], gs.accepted_at[2], gs.accepted_at[3], scored, legacy_scored);
}

// [10] the head's matvec is n-blocked (npu/mtp/mtp_head.cpp): one column at a time walks the [k][n] code image
// with a 64-byte cache line per 1-byte code, which measured 135-331 ms for the eight matrices of one head step
// depending on box load (0.7-7 GF/s; tools/mtp_head_bench.cpp). Blocking n fixes the access pattern and must NOT move a single float: the accumulation order
// per column (g ascending, k ascending, then the additive-min pass) is identical, so this is a bit-identity
// check, not a tolerance check. The unblocked form is kept here as the reference, so a future rewrite has to
// delete the statement of the defect to pass.
{
auto matvec_unblocked = [](const onebit::npu::mtp::Matrix& m, const float* a, float* y) {
const int G = m.K / onebit::npu::mtp::kG;
for (int n = 0; n < m.N; n++) {
double acc_n = 0.0;
for (int g = 0; g < G; g++) {
const int8_t* cg = &m.codes[(size_t)(g * onebit::npu::mtp::kG) * m.N + n];
double P = 0.0;
for (int k = 0; k < onebit::npu::mtp::kG; k++)
P += (double)a[g * onebit::npu::mtp::kG + k] * (double)cg[(size_t)k * m.N];
acc_n += P * ((double)m.ms[(size_t)g * m.N + n] * std::ldexp(1.0, (int)m.eref[(size_t)n]));
}
for (int g = 0; g < G; g++) {
double s = 0.0;
for (int k = 0; k < onebit::npu::mtp::kG; k++) s += a[g * onebit::npu::mtp::kG + k];
acc_n += s * (double)m.add[(size_t)g * m.N + n];
}
y[n] = (float)acc_n;
}
};
// N covers the block tail (200 = 3 x 64 + 8), an exact block (64), one column, and a wide matrix; a
// wrong tail bound or an off-by-one in the block loop shows up as a disagreeing column.
const int shapes[][2] = {{64, 200}, {128, 64}, {32, 1}, {256, 127}, {96, 300}};
int bad_cols = 0, cols = 0;
for (const auto& sh : shapes) {
const int K = sh[0], N = sh[1], G = K / onebit::npu::mtp::kG;
onebit::npu::mtp::Matrix m;
m.K = K;
m.N = N;
m.codes.assign((size_t)K * N, 0);
m.ms.assign((size_t)G * N, 0);
m.eref.resize((size_t)N);
m.add.resize((size_t)G * N);
uint32_t st = 12345u + (uint32_t)(K * 131 + N);
for (auto& c : m.codes) { st = st * 1664525u + 1013904223u; c = (int8_t)((int)((st >> 16) % 16) - 8); }
for (auto& v : m.ms) { st = st * 1664525u + 1013904223u; v = (int16_t)(1000 + (int)((st >> 16) % 30000)); }
for (auto& e : m.eref) { st = st * 1664525u + 1013904223u; e = (int16_t)((int)((st >> 16) % 9) - 4); }
for (auto& v : m.add) { st = st * 1664525u + 1013904223u; v = (float)((int)((st >> 16) % 2001) - 1000) * 0.5f; }
std::vector<float> a((size_t)K), got((size_t)N), want((size_t)N);
for (auto& x : a) { st = st * 1664525u + 1013904223u; x = (float)((int)((st >> 16) % 2001) - 1000) * 0.001f; }
matvec_unblocked(m, a.data(), want.data());
m.matvec(a.data(), got.data());
for (int n = 0; n < N; n++) {
cols++;
if (std::memcmp(&got[(size_t)n], &want[(size_t)n], sizeof(float)) != 0) bad_cols++;
}
}
check(bad_cols == 0, "matvec: the blocked form is BIT-identical to the unblocked form on every column");
std::printf("INFO matvec: %d columns over 5 shapes, %d differ (K x N incl. a 200 = 3x64+8 block tail)\n", cols,
bad_cols);
}

std::printf(fails ? "\n%d CHECK(S) FAILED\n" : "\nall checks passed\n", fails);
return fails ? 1 : 0;
}
55 changes: 55 additions & 0 deletions tools/mtp_acceptance.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
//
// mtp_acceptance --model <dir> --head-exact <pb16i-exact dir> --head-q4k <q4_k dir>
// [--tokens 64] [--k 4] [--tau 0.6] [--prompts 8] [--residual] [--dry-head]
// [--probe-lm N]
// [--offline [--positions-in F]] [--live [--positions-out F] [--match]]
//
// --match is the one that settles "live equals offline": the live loop records where it opened its chains
Expand All @@ -40,6 +41,7 @@
#include "mtp/mtp_head.h"
#include "rt.h"

#include <algorithm>
#include <chrono>
#include <fstream>
#include <cstdio>
Expand Down Expand Up @@ -261,6 +263,7 @@ int main(int argc, char** argv) {
int tokens = 64, k = 4, prompts = 8, prompt_base = 0;
float tau = 0.6f;
bool residual = false, dry = false, selftest = false, offline = false, live = false, batchcheck = false;
int probe_lm = 0;
bool match_mode = false;
std::string gold, positions_out, positions_in;
// prompt index -> the stream positions where the live loop opened its chains
Expand All @@ -283,6 +286,7 @@ int main(int argc, char** argv) {
else if (a == "--offline") offline = true;
else if (a == "--live") live = true;
else if (a == "--batchcheck") batchcheck = true;
else if (a == "--probe-lm") { const std::string v = (i + 1 < argc) ? argv[++i] : "10"; probe_lm = std::atoi(v.c_str()); }
else if (a == "--match") match_mode = true;
else if (a == "--positions-out") positions_out = nexts();
else if (a == "--positions-in") positions_in = nexts();
Expand Down Expand Up @@ -360,6 +364,24 @@ int main(int argc, char** argv) {
std::printf("forward ready: vocab %d, max_batch_rows %d, hidden source %s\n", base.vocab(),
base.max_batch_rows(), residual ? "pre-norm residual" : "post-final-norm");

if (probe_lm > 0) {
// What ONE full-vocab logits call costs on the array, measured rather than fitted. The draft loop makes
// k of them for its k drafts (plus 1 + accepted more that the logits-skip fix drops), so this single number
// decides whether the draft route's cost is the head's maths (host, tools/mtp_head_bench.cpp) or its
// vocabulary projection (array). The hidden is the probe step's own, i.e. exactly what the drafter hands
// the head; a repeat call is the same work every time.
std::vector<float> h = residual ? fwd.last_residual() : fwd.last_hidden(), lg2;
std::vector<double> ms;
for (int r = 0; r < probe_lm; r++) {
const double t0 = now_ms();
if (!base.lm_head(h, lg2)) { std::fprintf(stderr, "lm head probe failed\n"); return 1; }
ms.push_back(now_ms() - t0);
}
std::sort(ms.begin(), ms.end());
std::printf("lm head probe: %d calls over vocab %d, median %.1f ms, min %.1f, max %.1f\n", probe_lm,
(int)lg2.size(), ms[ms.size() / 2], ms.front(), ms.back());
}

if (batchcheck) {
// Does the deferred batch verify give the same answer as plain decode?
//
Expand Down Expand Up @@ -452,6 +474,39 @@ int main(int argc, char** argv) {
pi, differ, checked, first_differ);
std::printf(" batch hidden rows vs sequential hidden: %d rows, min cos %.6f (position %d), max |diff| %.3e\n",
hid_rows, min_cos, worst_pos, max_abs);
// How a verify batch's cost scales with its row count. The loop's own accounting calls an iteration "two
// passes" (one step + one M=nd batch), which is only true if a batch costs a step. The kernels are sealed at
// M=16, so either a 5-row batch is free (pad rows are idle) or it is linear in rows (the GDN/conv work is per
// row) -- and that decides whether the draft route's cost is the base (batch it harder, #805's leaf fill) or
// the head. Measured here, on the same stream, at nd = 1, 2, k+1 and max_batch_rows.
{
const int widths[] = {1, 2, std::min(k + 1, base.max_batch_rows()), base.max_batch_rows()};
std::printf(" verify-batch cost, same stream, --tokens %d:\n", tokens);
std::vector<int> last_width;
for (int w : widths) {
if (w < 1 || w > base.max_batch_rows()) continue;
if (!last_width.empty() && last_width.back() == w) continue;
last_width.push_back(w);
fwd.reset();
std::vector<float> lg3;
for (size_t i = 0; i < ids.size(); i++)
if (!fwd.step(ids[i], (int)i, lg3)) { std::fprintf(stderr, "prefill failed\n"); return 1; }
std::vector<float> all3;
int p3 = (int)ids.size(), batches = 0;
const double t0 = now_ms();
while (p3 + w <= n) {
std::vector<int> rows(stream.begin() + p3, stream.begin() + p3 + w);
if (!base.step_batch_all(rows, p3, all3)) { std::fprintf(stderr, "batch failed\n"); return 1; }
if (!base.commit_verify(w)) { std::fprintf(stderr, "commit refused\n"); return 1; }
p3 += w;
batches++;
}
const double ms = now_ms() - t0;
std::printf(" M %2d rows: %2d batches, %7.2f ms/batch, %5.2f ms/row, %6.1f rows/s\n", w, batches,
batches ? ms / batches : 0.0, batches ? ms / (double)(batches * w) : 0.0,
ms > 0 ? 1000.0 * (double)(batches * w) / ms : 0.0);
}
}
}
return 0;
}
Expand Down
Loading
Loading