original_prefill_schedule.rs (pure): ring_slots, chunk loop, the expert-stream plan (sequence builder, issue_until/ give_back, streamed and staged walks), PLE read-ahead double buffer, GR write fusion rule, layer-split hand-off, plus a ring/event simulator that rejects unsafe schedules. gen_prefill_ring_trace.py extracts the Original's scheduling code verbatim from prefill.cpp into a host harness; its traces are the committed golden fixture the Rust model must match line for line. backend_original_prompt.rs gains PromptRunner + drive (the contract between generate.cpp and Prefill::run), and executor_original_prompt.rs gets OriginalPromptComposer: one PromptPlan Batched action = one executor.forward + publish transaction. Unselected source owner; verifier windows / final seed / checkpoints go through explicit hooks. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
322 lines
17 KiB
Python
322 lines
17 KiB
Python
#!/usr/bin/env python3
|
|
"""Builds drivers/prefill_ring_trace.cpp by EXTRACTING the expert-stream scheduling code of the Original
|
|
engine/strata/src/prefill/prefill.cpp (the sequence builder + issue_until, wait_issued / give_back, the staged
|
|
stage_one lambda, and the two per-layer expert walks) verbatim between textual markers, wrapped in a host harness whose
|
|
cuda* calls only append to a trace. usage: gen_prefill_ring_trace.py [prefill.cpp] > drivers/prefill_ring_trace.cpp
|
|
The trace line format is the golden-fixture format read by original_prefill_schedule.rs."""
|
|
import hashlib, os, sys
|
|
|
|
here = os.path.dirname(os.path.abspath(__file__))
|
|
path = sys.argv[1] if len(sys.argv) > 1 else os.path.join(here, '../../../engine/strata/src/prefill/prefill.cpp')
|
|
text = open(path).read()
|
|
lines = text.split('\n')
|
|
|
|
def find(marker, start=0):
|
|
for i in range(start, len(lines)):
|
|
if marker in lines[i]:
|
|
return i
|
|
raise SystemExit('marker not found: ' + marker)
|
|
|
|
def cut(first, last_exclusive, start=0):
|
|
a = find(first, start)
|
|
b = find(last_exclusive, a + 1)
|
|
return '\n'.join(lines[a:b]), a + 1, b
|
|
|
|
seq_build, a1, b1 = cut('const strata::kernels::cpu::ExpertLayout& lay0', '// D-5: the stream is issued by its own host thread')
|
|
consumer, a2, b2 = cut("// the consumer's side:", 'host_setup_ms += ms_since(tsetup);')
|
|
staged, a3, b3 = cut('// Stage ahead: the copy stream moves blobs host -> device', "// one expert's products from its blob on the device")
|
|
w_first = find('auto compute = [&](size_t j, const uint8_t* blob_dev, int slot) -> bool {')
|
|
a4 = find('if (!stream_all) {', w_first)
|
|
b4 = find('pt.mark(kPfCombine, cs);', a4)
|
|
walks = '\n'.join(lines[a4:b4])
|
|
ple_a = find('// ---- the PLE rows of the whole chunk')
|
|
ple_first = find('if (ple_on) {', ple_a)
|
|
ple_last = find('for (int64_t t = 0; t < T; ++t) { prev[0] = prev[1];', ple_first)
|
|
ple_block = '\n'.join(lines[ple_first:ple_last])
|
|
assert 'std::async(std::launch::async,' in ple_block
|
|
ple_block = ple_block.replace('std::async(std::launch::async,', 'shim_async(') # the one documented edit: deferred, logged
|
|
fuse_a = find('const int64_t nl = half == 0 ? l : l + 1;')
|
|
fuse_b = find('const core::WeightRef* wnn = nullptr;', fuse_a)
|
|
fuse_block = '\n'.join(lines[fuse_a:fuse_b])
|
|
digest = hashlib.sha256(text.encode()).hexdigest()
|
|
|
|
template = r'''// GENERATED by oracle/gen_prefill_ring_trace.py from engine/strata/src/prefill/prefill.cpp
|
|
// (sha256 __DIGEST__). The code between the VERBATIM markers is copied from that file (lines __R1__, __R2__, __R3__, __R4__);
|
|
// everything else stubs the cuda* calls and records them. Issue is inline (STRATA_PREFILL_ISSUER=0): the threaded issuer
|
|
// makes the same copy-stream calls in the same order, gated by the same consumed + ring rule.
|
|
#include <algorithm>
|
|
#include <atomic>
|
|
#include <cstdint>
|
|
#include <cstdio>
|
|
#include <cstdlib>
|
|
#include <memory>
|
|
#include <thread>
|
|
#include <string>
|
|
#include <vector>
|
|
using cudaStream_t = int;
|
|
using cudaEvent_t = int;
|
|
enum { cudaMemcpyHostToDevice = 1, cudaSuccess = 0 };
|
|
constexpr int STAGE = 8, RING_MAX = 512, DQ = 2;
|
|
static std::vector<std::string> g_ops;
|
|
static void op(const std::string& s) { g_ops.push_back(s); }
|
|
static const char* sname(cudaStream_t s) { return s == 1 ? "C" : "K"; }
|
|
static int slot_of_dev(const void* p) { return (int) (((uintptr_t) p - 0x10000000u) / 0x1000u); }
|
|
static std::string src_of_host(const void* p) {
|
|
const uintptr_t v = (uintptr_t) p;
|
|
if (v >= 0x40000000u) return "stage " + std::to_string((v - 0x40000000u) / 0x1000u);
|
|
return "blob " + std::to_string((v - 0x20000000u) / 0x10000u) + " " + std::to_string(((v - 0x20000000u) % 0x10000u) / 0x10u);
|
|
}
|
|
static int cudaMemcpyAsync(void* dst, const void* src, size_t, int, cudaStream_t s) {
|
|
op(std::string(sname(s)) + " h2d " + std::to_string(slot_of_dev(dst)) + " " + src_of_host(src));
|
|
return 0;
|
|
}
|
|
static std::string ev_name(cudaEvent_t e) {
|
|
if (e >= 4000) return "ple_copied " + std::to_string(e - 4000);
|
|
if (e >= 3000) return "dma " + std::to_string(e - 3000);
|
|
return (e >= 2000 ? "used " + std::to_string(e - 2000) : "copied " + std::to_string(e - 1000));
|
|
}
|
|
static int cudaStreamWaitEvent(cudaStream_t s, cudaEvent_t e, unsigned) { op(std::string(sname(s)) + " wait " + ev_name(e)); return 0; }
|
|
static int cudaEventRecord(cudaEvent_t e, cudaStream_t s) { op(std::string(sname(s)) + " record " + ev_name(e)); return 0; }
|
|
struct Clock { struct time_point {}; static time_point now() { return {}; } };
|
|
static double ms_since(Clock::time_point) { return 0.0; }
|
|
struct ExpertLayoutStub { size_t blob_bytes(int64_t) const { return 4096; } };
|
|
namespace strata { namespace kernels { namespace cpu {
|
|
using ExpertLayout = ExpertLayoutStub;
|
|
inline const ExpertLayout& expert_layout() { static ExpertLayout l; return l; }
|
|
} } }
|
|
struct ModelGeom { int64_t n_expert; int64_t n_layers; };
|
|
struct Scenario {
|
|
const char* name;
|
|
int n_layers, n_expert, lb, le, ring, stager_ring;
|
|
int64_t T; // rows of the chunk (stream_all needs T >= 1024)
|
|
std::vector<std::vector<int32_t>> orders; // per layer in [lb, le): routed experts, ascending
|
|
int resident_mod, resident_rem; // cache-resident when e %% mod == rem (mod 0: none)
|
|
bool cache_present;
|
|
int pinned_mod, transient_mod; // pinned: e %% pinned_mod == 0; transient: (e+l) %% transient_mod == 0
|
|
int chunks;
|
|
};
|
|
static const Scenario* g_sc = nullptr;
|
|
struct Src {
|
|
bool pinned(int64_t, int64_t e) const { return g_sc->pinned_mod != 0 && e %% g_sc->pinned_mod == 0; }
|
|
bool transient(int64_t l, int64_t e) const { return !pinned(l, e) && g_sc->transient_mod != 0 && (e + l) %% g_sc->transient_mod == 0; }
|
|
const uint8_t* blob(int64_t l, int64_t e) const { return (const uint8_t*) (0x20000000u + (uintptr_t) l * 0x10000u + (uintptr_t) e * 0x10u); }
|
|
};
|
|
struct Stager {
|
|
struct Job { const uint8_t* src; size_t bytes; Src* from = nullptr; int32_t l = 0, e = 0; };
|
|
int kRing = 16;
|
|
void start(std::vector<Job>&& js) {
|
|
if (js.empty()) return; // Stager::start
|
|
std::string d = "H stager_start";
|
|
for (auto& j : js) d += j.from ? " T" + std::to_string(j.l) + "." + std::to_string(j.e) : " U";
|
|
op(d + " n=" + std::to_string(js.size()));
|
|
}
|
|
const uint8_t* wait(int j) { op("H stager_wait " + std::to_string(j)); return (const uint8_t*) (0x40000000u + (uintptr_t) (j %% kRing) * 0x1000u); }
|
|
void issued_one(int j, cudaStream_t copy) { cudaEventRecord(3000 + j %% kRing, copy); }
|
|
void finish() { op("H stager_finish"); }
|
|
};
|
|
struct Cache { const uint8_t* device_slot(int s) const { return (const uint8_t*) (0x50000000u + (uintptr_t) s * 0x1000u); } };
|
|
struct Stats { int64_t experts_dma = 0, experts_streamed = 0, experts_resident = 0; double ms_experts_host = 0, ms_ple = 0; };
|
|
constexpr int64_t N = 2560;
|
|
struct PT { void mark(int, cudaStream_t) {} };
|
|
enum { kPfWaitCopy = 0, kPfDequant = 1 };
|
|
inline int64_t stream_all_min() { return 1024; }
|
|
// ---- PLE read-ahead stubs
|
|
#include <future>
|
|
static std::string ple_buf_of(const void* p, uintptr_t base) { return std::to_string(((uintptr_t) p - base) / 0x1000u); }
|
|
static int cudaMemcpyAsync(float* dst, const float* src, size_t, int, cudaStream_t) {
|
|
(void) dst;
|
|
op("K upload ple_emb " + ple_buf_of(src, 0x60000000u));
|
|
return 0;
|
|
}
|
|
static int cudaEventSynchronize(cudaEvent_t e) { op("H sync ple_copied " + std::to_string(e - 4000)); return 0; }
|
|
template <class F> static std::future<bool> shim_async(F f) { op("H ple_async"); return std::async(std::launch::deferred, f); }
|
|
struct PleTable {
|
|
bool gather_batch_device(const uint32_t*, size_t, float*, cudaStream_t, std::string&) { op("K ple_gather_device"); return true; }
|
|
};
|
|
struct PleState { PleTable* table; };
|
|
struct SessionStub { struct { PleTable* table; } ple; };
|
|
struct Impl {
|
|
Src* src = nullptr; const Cache* cache = nullptr; const int32_t* host_res = nullptr; const ModelGeom* g = nullptr;
|
|
int ring = STAGE; cudaStream_t cs = 2, copy = 1;
|
|
std::unique_ptr<Stager> stager;
|
|
uint8_t* stage_dev[RING_MAX] = {};
|
|
cudaEvent_t copied[RING_MAX] = {}, used[RING_MAX] = {};
|
|
bool stage_live[RING_MAX] = {};
|
|
float* ple_emb = nullptr;
|
|
float* ple_emb_host[2] = {};
|
|
cudaEvent_t ple_copied[2] = {};
|
|
std::vector<uint32_t> ple_rows[2];
|
|
int64_t T = 0;
|
|
};
|
|
|
|
static void run_scenario(const Scenario& sc) {
|
|
g_sc = ≻
|
|
g_ops.clear();
|
|
Impl m;
|
|
ModelGeom geom{sc.n_expert, sc.n_layers};
|
|
const ModelGeom& g = geom;
|
|
Src src_obj; Cache cache_obj;
|
|
m.src = &src_obj;
|
|
m.g = &geom;
|
|
m.ring = sc.ring;
|
|
m.stager.reset(new Stager());
|
|
m.stager->kRing = sc.stager_ring;
|
|
for (int i = 0; i < RING_MAX; ++i) {
|
|
m.stage_dev[i] = (uint8_t*) (0x10000000u + (uintptr_t) i * 0x1000u);
|
|
m.copied[i] = 1000 + i; m.used[i] = 2000 + i;
|
|
}
|
|
std::vector<int32_t> host_res_table((size_t) sc.n_layers * sc.n_expert, -1);
|
|
if (sc.cache_present) {
|
|
int next_slot = 0;
|
|
for (int l = 0; l < sc.n_layers; ++l)
|
|
for (int e = 0; e < sc.n_expert; ++e)
|
|
if (sc.resident_mod != 0 && e %% sc.resident_mod == sc.resident_rem) host_res_table[(size_t) l * sc.n_expert + e] = next_slot++;
|
|
m.host_res = host_res_table.data();
|
|
m.cache = &cache_obj;
|
|
}
|
|
Stats stats_;
|
|
PT pt;
|
|
cudaStream_t cs = m.cs;
|
|
const int64_t LB = sc.lb, LE = sc.le, T = sc.T;
|
|
std::string err;
|
|
for (int chunk = 0; chunk < sc.chunks; ++chunk) {
|
|
op("H chunk " + std::to_string(chunk));
|
|
auto chunk_fn = [&]() -> bool {
|
|
// ---- VERBATIM prefill.cpp (sequence, issue_until) ----
|
|
__SEQ_BUILD__
|
|
// ---- end VERBATIM ----
|
|
const bool threaded_issue = false;
|
|
std::atomic<size_t> a_issued{0}, a_consumed{0};
|
|
// ---- VERBATIM prefill.cpp (wait_issued, give_back) ----
|
|
__CONSUMER__
|
|
// ---- end VERBATIM ----
|
|
if (stream_all) issue_until((size_t) m.ring); // prefill.cpp: else if (stream_all) { issue_until((size_t) m.ring); }
|
|
for (int64_t l = LB; l < LE; ++l) {
|
|
const std::vector<int32_t>& order = sc.orders[(size_t) (l - LB)];
|
|
op("H layer " + std::to_string(l));
|
|
const strata::kernels::cpu::ExpertLayout& lay = strata::kernels::cpu::expert_layout();
|
|
// ---- VERBATIM prefill.cpp (staging setup, stage_one) ----
|
|
__STAGED__
|
|
// ---- end VERBATIM ----
|
|
auto compute = [&](size_t j, const uint8_t*, int slot) -> bool {
|
|
op("K compute " + std::to_string(order[j]) + " " + (slot >= 0 ? std::to_string(slot) : std::string("-")));
|
|
if (slot >= 0) cudaEventRecord(m.used[slot], m.cs); // prefill.cpp: after the gather / dequant read of the blob
|
|
return true;
|
|
};
|
|
// ---- VERBATIM prefill.cpp (the walks) ----
|
|
__WALKS__
|
|
// ---- end VERBATIM ----
|
|
op("K combine");
|
|
}
|
|
return true;
|
|
};
|
|
if (!chunk_fn()) { std::fprintf(stderr, "scenario %%s failed: %%s\n", sc.name, err.c_str()); std::exit(2); }
|
|
}
|
|
std::printf("{\"name\":\"%%s\",\"p\":{\"n_layers\":%%d,\"n_expert\":%%d,\"lb\":%%d,\"le\":%%d,\"ring\":%%d,\"stager_ring\":%%d,\"rows\":%%lld,"
|
|
"\"resident_mod\":%%d,\"resident_rem\":%%d,\"cache_present\":%%d,\"pinned_mod\":%%d,\"transient_mod\":%%d,\"chunks\":%%d,\"orders\":[",
|
|
sc.name, sc.n_layers, sc.n_expert, sc.lb, sc.le, sc.ring, sc.stager_ring, (long long) T, sc.resident_mod, sc.resident_rem,
|
|
(int) sc.cache_present, sc.pinned_mod, sc.transient_mod, sc.chunks);
|
|
for (size_t li = 0; li < sc.orders.size(); ++li) {
|
|
std::printf("%%s[", li ? "," : "");
|
|
for (size_t k = 0; k < sc.orders[li].size(); ++k) std::printf("%%s%%d", k ? "," : "", sc.orders[li][k]);
|
|
std::printf("]");
|
|
}
|
|
std::printf("]},\"stats\":[%%lld,%%lld,%%lld],\"ops\":[", (long long) stats_.experts_dma, (long long) stats_.experts_streamed, (long long) stats_.experts_resident);
|
|
for (size_t i = 0; i < g_ops.size(); ++i) std::printf("%%s\"%%s\"", i ? "," : "", g_ops[i].c_str());
|
|
std::printf("]}");
|
|
}
|
|
|
|
struct PleScenario { const char* name; int64_t n, T; bool gpu_cache; };
|
|
static void run_ple_scenario(const PleScenario& sc) {
|
|
g_ops.clear();
|
|
Impl m;
|
|
m.T = sc.T;
|
|
PleTable table;
|
|
SessionStub ss;
|
|
ss.ple.table = &table;
|
|
for (int b = 0; b < 2; ++b) { m.ple_emb_host[b] = (float*) (0x60000000u + (uintptr_t) b * 0x1000u); m.ple_copied[b] = 4000 + b; m.ple_rows[b].assign(4, 0); }
|
|
m.ple_emb = (float*) 0x70000000u;
|
|
Stats stats_;
|
|
std::string err;
|
|
const int64_t n = sc.n;
|
|
const bool ple_on = true, ple_gpu_cache = sc.gpu_cache;
|
|
std::string ple_next_err;
|
|
std::future<bool> ple_next;
|
|
int ple_buf = 0;
|
|
auto ple_gather = [&](int64_t c0, int buf, std::string&) -> bool { op("H ple_gather " + std::to_string(c0) + " " + std::to_string(buf)); return true; };
|
|
for (int64_t c0 = 0; c0 < n; c0 += m.T) {
|
|
const int64_t T = std::min(m.T, n - c0);
|
|
op("H ple_chunk " + std::to_string(c0));
|
|
cudaStream_t cs = 2; (void) cs;
|
|
auto ple_fn = [&]() -> bool {
|
|
// ---- VERBATIM prefill.cpp (the PLE row read-ahead) ----
|
|
__PLE__
|
|
// ---- end VERBATIM ----
|
|
return true;
|
|
};
|
|
if (!ple_fn()) { std::fprintf(stderr, "ple scenario failed\n"); std::exit(2); }
|
|
}
|
|
std::printf("{\"name\":\"%s\",\"ple\":[%lld,%lld,%d],\"ops\":[", sc.name, (long long) sc.n, (long long) sc.T, (int) sc.gpu_cache);
|
|
for (size_t i = 0; i < g_ops.size(); ++i) std::printf("%s\"%s\"", i ? "," : "", g_ops[i].c_str());
|
|
std::printf("]}");
|
|
}
|
|
|
|
// ---- the GR write fusion decision of one half
|
|
namespace strata { namespace kernels { struct CvecStub { bool cover; bool covers(int64_t) const { return cover; } }; inline CvecStub& cvec() { static CvecStub c; return c; } } }
|
|
static bool g_gr_unfused = false;
|
|
static bool gr_unfused() { return g_gr_unfused; }
|
|
static bool fuse_of(int64_t l, int half, int64_t LE, bool ple_on, bool unfused, bool cvec_covers) {
|
|
g_gr_unfused = unfused;
|
|
strata::kernels::cvec().cover = cvec_covers;
|
|
__FUSE__
|
|
return fuse;
|
|
}
|
|
|
|
static std::vector<int32_t> iota_vec(int n, int step = 1, int from = 0) {
|
|
std::vector<int32_t> v;
|
|
for (int i = from; i < n; i += step) v.push_back(i);
|
|
return v;
|
|
}
|
|
int main() {
|
|
std::vector<Scenario> sc;
|
|
// fields: name, n_layers, n_expert, lb, le, ring, stager_ring, T, orders, resident_mod, resident_rem, cache_present, pinned_mod, transient_mod, chunks
|
|
sc.push_back({"stream_basic", 6, 24, 1, 4, 16, 16, 1024,
|
|
{iota_vec(24, 2), iota_vec(24, 3, 1), {0, 1, 2, 5, 23}}, 5, 0, true, 3, 4, 2});
|
|
sc.push_back({"stream_ring_wrap", 4, 40, 0, 3, 16, 16, 2048,
|
|
{iota_vec(40), iota_vec(40), iota_vec(40, 7)}, 0, 0, true, 2, 0, 2});
|
|
sc.push_back({"stream_no_cache_all_pinned", 3, 20, 0, 3, 16, 16, 1024,
|
|
{iota_vec(20), iota_vec(20, 2), {19}}, 0, 0, false, 1, 0, 1});
|
|
sc.push_back({"stream_sparse_release", 5, 40, 1, 4, 16, 4, 4096,
|
|
{{39}, {0}, {5, 6, 7, 30}}, 0, 0, true, 5, 3, 2});
|
|
sc.push_back({"staged_under_threshold", 4, 32, 0, 3, 384, 16, 512,
|
|
{iota_vec(32), iota_vec(32, 3), {2, 4}}, 4, 1, true, 3, 5, 2});
|
|
sc.push_back({"staged_ring8", 3, 12, 0, 2, 8, 16, 4096,
|
|
{iota_vec(12), iota_vec(12, 2)}, 0, 0, false, 2, 3, 1});
|
|
sc.push_back({"staged_few_experts", 3, 10, 0, 2, 16, 16, 100,
|
|
{{1, 3, 4}, {9}}, 3, 0, true, 0, 0, 1});
|
|
std::printf("{\"ring\":[");
|
|
for (size_t i = 0; i < sc.size(); ++i) { if (i) std::printf(",\n"); run_scenario(sc[i]); }
|
|
std::printf("],\n");
|
|
std::vector<PleScenario> ples = {{"ple_two_chunks_gather", 2000, 1024, false}, {"ple_single_chunk", 100, 256, false},
|
|
{"ple_gpu_cache", 3000, 1024, true}, {"ple_four_chunks", 4096, 1024, false},
|
|
{"ple_exact_multiple", 2048, 1024, false}};
|
|
std::printf("\"ple\":[");
|
|
for (size_t i = 0; i < ples.size(); ++i) { if (i) std::printf(",\n"); run_ple_scenario(ples[i]); }
|
|
std::printf("],\n\"fuse\":[");
|
|
bool first = true;
|
|
for (int le : {48, 16}) for (int ple_on = 0; ple_on < 2; ++ple_on) for (int unfused = 0; unfused < 2; ++unfused)
|
|
for (int cv = 0; cv < 2; ++cv) for (int l : {0, 1, 2, 14, 15, 46, 47}) for (int half = 0; half < 2; ++half) {
|
|
if (l >= le) continue;
|
|
std::printf("%s[%d,%d,%d,%d,%d,%d,%d]", first ? "" : ",", le, ple_on, unfused, cv, l, half, (int) fuse_of(l, half, le, ple_on != 0, unfused != 0, cv != 0));
|
|
first = false;
|
|
}
|
|
std::printf("]}\n");
|
|
return 0;
|
|
}
|
|
'''
|
|
out = (template.replace('__DIGEST__', digest)
|
|
.replace('__R1__', f'{a1}-{b1}').replace('__R2__', f'{a2}-{b2}').replace('__R3__', f'{a3}-{b3}').replace('__R4__', f'{a4+1}-{b4}')
|
|
.replace('__SEQ_BUILD__', seq_build).replace('__CONSUMER__', consumer).replace('__STAGED__', staged).replace('__WALKS__', walks).replace('__PLE__', ple_block).replace('__FUSE__', fuse_block))
|
|
out = out.replace('%%', '%')
|
|
sys.stdout.write(out)
|