Files
leleka/tools/decode-sm120/sm120_probe_waitrows.cpp

214 lines
11 KiB
C++

// claude/ffn-wait-m-rows: model-free probe of LELEKA_SM120_WAIT_M_ROWS (D3).
// The folded kernel leleka_verify_wait_copy_rows (crates/cuda-driver/src/sm120_wait_copy_rows.ptx) is run next to the pair it
// replaces, verify_wait_flag_ge_kernel + verify_copy_rows_from_mapped_kernel (original_verify.ptx) and the glue copy
// chain_copy_rows_from_mapped_kernel (chain_window.ptx), on real-size mapped rows (T x 10 rows of 2560 floats, T = 1..8).
// The flag RISES LATE: the kernel is launched while the pinned flag is ring-1 and the pinned rows hold stale bytes; a host thread
// then writes the final rows, fences, and sets the flag to the ring (or above it). A kernel that copied before the flag, or
// that did not wait for the ring value exactly, copies stale bytes and differs. EVERY output byte is compared, to the pair's
// output and to the expected rows (hit rows zero). Prints "RESULT waitrows ..." lines; exits 1 if any comparison differs.
// sm120_probe_waitrows PTXDIR PTXDIR holds original_verify.ptx, chain_window.ptx and sm120_wait_copy_rows.ptx
// A kernel that never sees its flag hangs the probe: run it under `timeout 300`. Never touches the model.
#include <cuda.h>
#include <vector_types.h>
#include <algorithm>
#include <atomic>
#include <chrono>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <functional>
#include <string>
#include <thread>
#include <vector>
#define CU(x) do { CUresult r_ = (x); if (r_ != CUDA_SUCCESS) { const char* s_ = nullptr; cuGetErrorString(r_, &s_); fprintf(stderr, "CUDA error %s at %s:%d: %s\n", #x, __FILE__, __LINE__, s_ ? s_ : "?"); exit(2); } } while (0)
static int g_fail = 0;
static uint64_t g_rng = 0x9e3779b97f4a7c15ull;
static uint32_t rnd() { g_rng ^= g_rng << 13; g_rng ^= g_rng >> 7; g_rng ^= g_rng << 17; return (uint32_t)(g_rng >> 16); }
static const int K = 10; // routed experts per token
static const int64_t ROW4 = 640; // n_embd / 4 float4 per row of parts
static const size_t ROW_BYTES = ROW4 * 16;
static std::string read_file(const std::string& p) {
FILE* f = fopen(p.c_str(), "rb");
if (!f) { fprintf(stderr, "cannot open %s\n", p.c_str()); exit(2); }
std::string s; char buf[1 << 16]; size_t n;
while ((n = fread(buf, 1, sizeof buf, f)) > 0) s.append(buf, n);
fclose(f);
return s;
}
static CUmodule load_module(const std::string& p) {
std::string s = read_file(p);
s.push_back('\0');
CUmodule m; char log[8192] = {};
CUjit_option opt[] = {CU_JIT_ERROR_LOG_BUFFER, CU_JIT_ERROR_LOG_BUFFER_SIZE_BYTES};
void* val[] = {log, (void*)(uintptr_t)sizeof log};
CUresult r = cuModuleLoadDataEx(&m, s.data(), 2, opt, val);
if (r != CUDA_SUCCESS) { fprintf(stderr, "load %s failed: %d %s\n", p.c_str(), (int)r, log); exit(2); }
return m;
}
static CUfunction get_fn(CUmodule m, const char* name) {
CUfunction f; CUresult r = cuModuleGetFunction(&f, m, name);
if (r != CUDA_SUCCESS) { fprintf(stderr, "no entry %s\n", name); exit(2); }
return f;
}
struct Dev {
CUdeviceptr p = 0; size_t n = 0;
void alloc(size_t bytes) { n = bytes; CU(cuMemAlloc(&p, bytes ? bytes : 1)); CU(cuMemsetD8(p, 0, bytes ? bytes : 1)); CU(cuCtxSynchronize()); }
void put(const void* h, size_t bytes) { CU(cuMemcpyHtoD(p, h, bytes)); CU(cuCtxSynchronize()); }
void fill(uint8_t v) { CU(cuMemsetD8(p, v, n)); CU(cuCtxSynchronize()); }
std::vector<uint8_t> get() const { std::vector<uint8_t> v(n); CU(cuMemcpyDtoH(v.data(), p, n)); return v; }
void release() { if (p) cuMemFree(p); p = 0; }
};
static bool same(const char* what, const std::vector<uint8_t>& a, const std::vector<uint8_t>& b) {
if (a.size() != b.size()) { printf("MISMATCH %s: size %zu vs %zu\n", what, a.size(), b.size()); g_fail++; return false; }
size_t bad = 0, first = (size_t)-1;
for (size_t i = 0; i < a.size(); ++i) if (a[i] != b[i]) { if (first == (size_t)-1) first = i; ++bad; }
if (bad) { printf("MISMATCH %s: %zu of %zu bytes differ (first at %zu)\n", what, bad, a.size(), first); g_fail++; return false; }
return true;
}
static CUstream g_s;
static CUmodule mVerify, mChain, mFold;
static CUfunction fWait, fPairCopy, fChainCopy, fFold;
static void launch(CUfunction f, unsigned grid, unsigned block, void** args) {
CU(cuLaunchKernel(f, grid, 1, 1, block, 1, 1, 0, g_s, args, nullptr));
}
// microseconds per body call (best of `iters` graph replays); the flag is already satisfied in the timed bodies
static double time_graph(const std::function<void(int)>& body, int reps, int iters = 8) {
CUgraph g; CUgraphExec ge;
CU(cuStreamBeginCapture(g_s, CU_STREAM_CAPTURE_MODE_GLOBAL));
for (int i = 0; i < reps; ++i) body(i);
CU(cuStreamEndCapture(g_s, &g));
CU(cuGraphInstantiateWithFlags(&ge, g, 0));
for (int i = 0; i < 2; ++i) CU(cuGraphLaunch(ge, g_s));
CU(cuStreamSynchronize(g_s));
CUevent a, b; CU(cuEventCreate(&a, 0)); CU(cuEventCreate(&b, 0));
double best = 1e30;
for (int i = 0; i < iters; ++i) {
CU(cuEventRecord(a, g_s)); CU(cuGraphLaunch(ge, g_s)); CU(cuEventRecord(b, g_s)); CU(cuEventSynchronize(b));
float ms; CU(cuEventElapsedTime(&ms, a, b)); best = std::min(best, ms * 1000.0 / reps);
}
CU(cuGraphExecDestroy(ge)); CU(cuGraphDestroy(g)); CU(cuEventDestroy(a)); CU(cuEventDestroy(b));
return best;
}
// The hit list of a pattern over `blocks` rows: 0 none, 1 block 0 only (the leader), 2 every row but the last, 3 random half, 4 every row.
static std::vector<int32_t> hit_list(int pattern, int blocks) {
std::vector<int32_t> h;
for (int r = 0; r < blocks; ++r) {
bool hit = pattern == 1 ? r == 0 : pattern == 2 ? r != blocks - 1 : pattern == 3 ? (rnd() & 1) : pattern == 4;
if (hit) h.push_back(r);
}
return h;
}
struct Mapped {
uint8_t* host = nullptr; CUdeviceptr dev = 0;
explicit Mapped(size_t bytes) {
CU(cuMemHostAlloc((void**)&host, bytes, CU_MEMHOSTALLOC_DEVICEMAP | CU_MEMHOSTALLOC_PORTABLE));
CU(cuMemHostGetDevicePointer(&dev, host, 0));
}
~Mapped() { cuMemFreeHost(host); }
};
// one case: T tokens, a hit pattern, how long the host waits before it publishes (us), the sleep of the follower blocks (ns)
static bool run_case(int T, int pattern, unsigned delay_us, uint32_t follower_ns) {
const int blocks = T * K;
const size_t bytes = (size_t)blocks * ROW_BYTES;
const uint32_t ring = 1 + (uint32_t)((T * 7 + pattern) % 48);
std::vector<int32_t> hits = hit_list(pattern, blocks);
int32_t count = (int32_t)hits.size();
hits.resize(128, -1);
std::vector<uint8_t> stale(bytes), final_rows(bytes), expected(bytes);
for (auto& b : stale) b = (uint8_t)rnd();
for (auto& b : final_rows) b = (uint8_t)rnd();
expected = final_rows;
for (int i = 0; i < count; ++i) memset(expected.data() + (size_t)hits[i] * ROW_BYTES, 0, ROW_BYTES);
Mapped rows(bytes), flag(64);
volatile uint32_t* flag_h = (volatile uint32_t*)flag.host;
Dev hit, cnt, dFold, dPair, dChain; hit.alloc(512); cnt.alloc(4); dFold.alloc(bytes); dPair.alloc(bytes); dChain.alloc(bytes);
hit.put(hits.data(), 512); cnt.put(&count, 4);
dFold.fill(0xAB); dPair.fill(0xAB); dChain.fill(0xAB);
int64_t row4 = ROW4; uint32_t value = ring;
// the late arm: stale rows, flag one below the ring, the fold launched, THEN the host publishes
memcpy(rows.host, stale.data(), bytes);
*flag_h = ring - 1;
std::atomic_thread_fence(std::memory_order_seq_cst);
void* fold[] = {&dFold.p, &rows.dev, &row4, &hit.p, &cnt.p, &flag.dev, &value, &follower_ns};
launch(fFold, blocks, 128, fold);
std::thread publisher([&] {
std::this_thread::sleep_for(std::chrono::microseconds(delay_us));
memcpy(rows.host, final_rows.data(), bytes);
std::atomic_thread_fence(std::memory_order_seq_cst);
*flag_h = ring + (pattern & 1); // exactly the ring, or above it: the wait is `>=`
});
CU(cuStreamSynchronize(g_s));
publisher.join();
// the pair it replaces, on the now-final rows and the satisfied flag
void* wait[] = {&flag.dev, &value};
void* pair[] = {&dPair.p, &rows.dev, &row4, &hit.p, &cnt.p};
void* chain[] = {&dChain.p, &rows.dev, &row4, &hit.p, &cnt.p};
launch(fWait, 1, 1, wait); launch(fPairCopy, blocks, 128, pair); launch(fChainCopy, blocks, 128, chain);
CU(cuStreamSynchronize(g_s));
std::vector<uint8_t> out = dFold.get();
bool ok = same("fold vs pair", out, dPair.get());
ok &= same("fold vs chain copy", out, dChain.get());
ok &= same("fold vs expected rows", out, expected);
printf("RESULT waitrows T=%d hit_pattern=%d hits=%d delay_us=%u follower_ns=%u ok=%d\n", T, pattern, (int)count, delay_us, follower_ns, ok);
hit.release(); cnt.release(); dFold.release(); dPair.release(); dChain.release();
return ok;
}
// the flag is already satisfied: the pair (wait kernel, rows copy) against the one folded kernel, in a graph of 200 layers' worth of launches
static void time_satisfied(int T) {
const int blocks = T * K;
const size_t bytes = (size_t)blocks * ROW_BYTES;
Mapped rows(bytes), flag(64);
memset(rows.host, 0x11, bytes);
*(volatile uint32_t*)flag.host = 1000;
int32_t count = 1, hit_h[128] = {0};
Dev hit, cnt, d0, d1; hit.alloc(512); cnt.alloc(4); d0.alloc(bytes); d1.alloc(bytes);
hit.put(hit_h, 512); cnt.put(&count, 4);
int64_t row4 = ROW4; uint32_t value = 24, follower_ns = 100;
void* wait[] = {&flag.dev, &value};
void* pair[] = {&d0.p, &rows.dev, &row4, &hit.p, &cnt.p};
void* fold[] = {&d1.p, &rows.dev, &row4, &hit.p, &cnt.p, &flag.dev, &value, &follower_ns};
double tp = time_graph([&](int) { launch(fWait, 1, 1, wait); launch(fPairCopy, blocks, 128, pair); }, 200);
double tc = time_graph([&](int) { launch(fWait, 1, 1, wait); launch(fChainCopy, blocks, 128, pair); }, 200);
double tf = time_graph([&](int) { launch(fFold, blocks, 128, fold); }, 200);
printf("RESULT waitrows_time T=%d flag_satisfied wait+verify_copy_us=%.3f wait+chain_copy_us=%.3f folded_us=%.3f\n", T, tp, tc, tf);
hit.release(); cnt.release(); d0.release(); d1.release();
}
int main(int argc, char** argv) {
if (argc < 2) { fprintf(stderr, "usage: %s PTXDIR\n", argv[0]); return 2; }
std::string dir = argv[1];
CU(cuInit(0));
CUdevice dev; CU(cuDeviceGet(&dev, 0));
CUcontext ctx; CU(cuDevicePrimaryCtxRetain(&ctx, dev)); CU(cuCtxSetCurrent(ctx));
CU(cuStreamCreate(&g_s, CU_STREAM_NON_BLOCKING));
mVerify = load_module(dir + "/original_verify.ptx");
mChain = load_module(dir + "/chain_window.ptx");
mFold = load_module(dir + "/sm120_wait_copy_rows.ptx");
fWait = get_fn(mVerify, "verify_wait_flag_ge_kernel");
fPairCopy = get_fn(mVerify, "verify_copy_rows_from_mapped_kernel");
fChainCopy = get_fn(mChain, "chain_copy_rows_from_mapped_kernel");
fFold = get_fn(mFold, "leleka_verify_wait_copy_rows");
for (int T = 1; T <= 8; ++T)
for (int pattern = 0; pattern <= 4; ++pattern)
for (unsigned delay_us : {0u, 300u, 3000u})
for (uint32_t follower_ns : {100u, 1000u})
run_case(T, pattern, delay_us, follower_ns);
for (int T = 1; T <= 8; ++T) time_satisfied(T);
printf("%s (%d failing comparisons)\n", g_fail ? "FAIL" : "PASS", g_fail);
return g_fail ? 1 : 0;
}