radiance 1.4.0

- Qwen3.8-Flash-Next on one card: the heat engine moves 64 experts a step (was 8), its copies and
  the prefill's expert staging run on the card's DMA engines instead of as copy kernels, and at
  decode the next layer's likeliest experts are copied onto the card ahead of its GEMMs. Against
  1.3.0 at --tp 1: prefill +17-20% from 8K tokens up, throughput under load +16-20%
- deploy/compose/flashnext-tp1.yaml: Qwen3.8-Flash-Next on one card and 64 GB of host RAM
  (4096-token prefill steps, 4 sequences, a 301K-token cache)
- #61: --busy-prefill-chunk (default auto): a long prefill leaves the rest of the step to the
  requests decoding beside it and to new arrivals, instead of taking all of it (baKon)
- LiquidAI's LFM2 and LFM2-VL, and d1's /v1/systemone (after zivius's PR #50)
- a startup report: every option with its value and where it came from, the hardware, and what
  on it costs speed with the fix; /diagnostics serves it (behind the API key; without one, only
  to the same machine)
- #69: a GPU memory fault names the buffer and kernel argument behind it and ends the server at
  once (exit status 70), instead of hanging or writing a core of tens of gigabytes
- #64: a card without Resizable BAR is refused at startup, naming what to turn on, instead of
  crashing at the first launch
- the image is built with ROCm 10.1 (the host's amdgpu driver must support it), with ROCm's
  libLLVM rebuilt so the same source compiles to the same kernels every time; a source build
  takes ROCm 10.1 or 7.2
- #71: the image ships curl, jq and a CA bundle, so --model <HF repo id> works in the container,
  and hfget.sh runs under its busybox (baKon)
- --profile-ops shows how long each op's lane sat idle before it; cardclock.py skips an
  integrated GPU instead of stopping
This commit is contained in:
Deadcode committed 2026-10-12 11:46:14 +02:00
1 parent d5b65cddc6
commit dc339b4cd2
153 files changed
+12956 -1067

No files matched your search

+80 -11
View File
@@ -4,6 +4,7 @@
*/
#include <vector>
#include "ctx.h"
#include "xp_state.h"
#include "../device/device.h"
#include <algorithm>
@@ -15,6 +16,7 @@ namespace rad {
/* ================================================================== lifecycle */
Ctx::Ctx() = default;
Ctx::~Ctx() { shutdown(); }
int Ctx::init(const CtxDesc& d) {
@@ -53,6 +55,7 @@ int Ctx::init(const CtxDesc& d) {
void Ctx::shutdown() {
oracle_close();
xp_close();
/* The one host synchronisation in the whole component, and it is at teardown rather than on
* the step path. Everything below frees memory the stream may still be reading or writing --
* the routing staging is the destination of a copy nobody waited on by design (spec §5.5), and
@@ -342,6 +345,7 @@ int Ctx::bind_ops() {
op_domain_ = std::vector<std::atomic<uint8_t>>(P.ops.size());
band_table_.clear();
issue_table_.clear();
gate_params_.clear();
int64_t n_bands_total = 0, n_plans = 0;
for (auto& o : P.ops) { n_bands_total += (int64_t)o.bands.size(); }
@@ -357,9 +361,9 @@ int Ctx::bind_ops() {
p.n_bands = (int32_t)oi.bands.size();
p.plan_off = (int32_t)issue_table_.size();
p.n_opd_schema = oi.schema ? (int32_t)oi.schema->n_operands : -1;
/* The one op whose issue costs interconnect bytes. Matched by name once, here, rather
* than on the issue path -- see OpPlan::collective. */
p.collective = (oi.op == "all_reduce");
/* Matched by name once, here, rather than on the issue path -- see OpPlan::billed. */
p.billed = (oi.op == "all_reduce");
p.collective = p.billed;
for (const Band& b : oi.bands) band_table_.push_back(b.hi);
@@ -370,6 +374,7 @@ int Ctx::bind_ops() {
if (r && r.row && r.row->info && r.row->info->launch) {
ip.row = r.row;
ip.launch = r.row->info->launch;
if (r.row->collective) p.collective = true;
/* Bound once. args.p views the frozen geometry inside Program::ops, which is
* why declare must not touch a Resolved after this point: the vector would
@@ -383,6 +388,20 @@ int Ctx::bind_ops() {
ip.args.instance = r.instance;
ip.args.rank = rank_;
ip.args.world_size = world_size_;
/* A launch that ends its own hold on the link is handed the word the hold is
* kept in, as one parameter more after the geometry's -- when it holds one. */
if (r.row->releases_link)
if (void* g = rad_link_gate(stream_)) {
std::vector<RadParam>& v =
gate_params_.emplace_back(ip.args.p, ip.args.p + ip.args.n_p);
RadParam q{};
q.key = "link_gate";
q.kind = RAD_P_INT;
q.ival = (long long)(uintptr_t)g;
v.push_back(q);
ip.gate_p = v.data();
ip.gate_n_p = (int)v.size();
}
if (r.scratch_bytes > arena_.scratch_bytes()) {
RAD_ERR("op '%s' band %lld kernel %s wants %s of scratch but the plan "
@@ -847,6 +866,7 @@ int Ctx::bind_profiling() {
prof_calls_.assign(program_->ops.size(), 0);
prof_host_.assign(program_->ops.size(), 0);
prof_join_ms_.assign(program_->ops.size(), 0.0);
prof_wait_ms_.assign(program_->ops.size(), 0.0);
if (!profiling_) return RAD_OK;
/* Printed, not buried in a doc. Anyone reading a profiled run's numbers has to see this on the
@@ -888,12 +908,21 @@ void Ctx::profile_collect() {
++n_host_syncs_; /* counted, so the caveat is a number and not a claim */
if (rad_stream_sync(stream_) < 0) prof_n_ = 0;
}
/* The idle time before each op, per lane: the first op a lane runs in the step has nothing
* before it on that lane, and the gap from the last step is mostly this collection's own
* synchronisation, so it is not charged. */
const ProfSlot* prev[2] = { nullptr, nullptr };
for (size_t i = 0; i < prof_n_; ++i) {
ProfSlot& s = prof_ring_[i];
float ms = 0.0f;
if (rad_event_elapsed_ms(s.a, s.b, &ms) < 0) continue;
prof_ms_[(size_t)s.op] += (double)ms;
prof_calls_[(size_t)s.op] += 1;
const ProfSlot*& p = prev[s.lane & 1];
float gap = 0.0f;
if (p && rad_event_elapsed_ms(p->b, s.a, &gap) >= 0 && gap > 0.0f)
prof_wait_ms_[(size_t)s.op] += (double)gap;
p = &s;
}
if (prof_overflowed_) {
RAD_WARN("per-op timing: the step issued more than %zu ops; the tail was not timed",
@@ -912,9 +941,10 @@ void Ctx::dump_profile() const {
"enabling this restores synchronisations that change the mover's slot supply.\n"
"A row marked `host` was timed on the HOST CLOCK around a host-site launch and\n"
"includes everything that call waited on -- page faults, link reads. The rest are\n"
"device event pairs around a kernel.\n\n"
" %10s %12s %10s %5s %10s %s\n", rank_, "calls", "total ms", "us/call", "site",
"join us", "op / geometry");
"device event pairs around a kernel. `wait us` is how long, a call, the op's lane\n"
"sat idle before it started -- stream waits and issue delays, in no op's time.\n\n"
" %10s %12s %10s %5s %10s %10s %s\n", rank_, "calls", "total ms", "us/call", "site",
"join us", "wait us", "op / geometry");
/* Slowest first: the only ordering anybody reads this table in. */
std::vector<size_t> order;
@@ -922,7 +952,7 @@ void Ctx::dump_profile() const {
std::sort(order.begin(), order.end(),
[&](size_t a, size_t b) { return prof_ms_[a] > prof_ms_[b]; });
double total = 0.0;
double total = 0.0, waited = 0.0;
for (size_t i : order) {
const OpInfo& o = program_->ops[i];
const bool ho = i < prof_host_.size() && prof_host_[i];
@@ -936,13 +966,16 @@ void Ctx::dump_profile() const {
* tied to anything. */
const char* wname = !o.weights.empty() && o.weights[0] < program_->weights.size()
? program_->weights[o.weights[0]].name.c_str() : "-";
fprintf(stderr, " %10lld %12.3f %10.2f %5s %s %s %s #%d %s\n",
const double wait = i < prof_wait_ms_.size() ? prof_wait_ms_[i] : 0.0;
fprintf(stderr, " %10lld %12.3f %10.2f %5s %s %10.2f %s %s #%d %s\n",
(long long)prof_calls_[i], prof_ms_[i],
prof_ms_[i] * 1000.0 / (double)prof_calls_[i], ho ? "host" : "dev", jbuf,
wait * 1000.0 / (double)prof_calls_[i],
o.op.c_str(), o.base.str().c_str(), (int)o.index, wname);
total += prof_ms_[i];
waited += wait;
}
fprintf(stderr, " %10s %12.3f\n\n", "total", total);
fprintf(stderr, " %10s %12.3f (waited %.3f ms besides)\n\n", "total", total, waited);
}
/* ================================================================== the step driver */
@@ -1200,6 +1233,22 @@ bool Ctx::tapes_agree(const PassTape& a, const PassTape& b, std::string* why) {
same = std::memcmp(&x.t[k], &y.t[k], sizeof(RadTensor)) == 0;
if (!same) { *why = fmt("host op %zu (op %u) differs", i, (unsigned)x.h); return false; }
}
if (a.xp.size() != b.xp.size()) {
*why = fmt("%zu prefetch calls against %zu", a.xp.size(), b.xp.size());
return false;
}
for (size_t i = 0; i < a.xp.size(); ++i) {
const TapeXp& x = a.xp[i];
const TapeXp& y = b.xp[i];
const RadPrefetchNext& u = x.next;
const RadPrefetchNext& v = y.next;
if (u.layer != v.layer || u.router != v.router || u.n_expert != v.n_expert || u.top_k != v.top_k ||
u.n_parts != v.n_parts || u.parts != v.parts || u.count_at != v.count_at || x.h != y.h ||
x.r0 != y.r0 || x.rows != y.rows || x.n_embd != y.n_embd) {
*why = fmt("prefetch call %zu (for layer %d) differs", i, x.next.layer);
return false;
}
}
for (size_t i = 0; i < a.route.size(); ++i)
if (a.route[i].first != b.route[i].first ||
std::memcmp(&a.route[i].second, &b.route[i].second, sizeof(RadRouting)) != 0) {
@@ -1248,6 +1297,23 @@ int Ctx::play_pass(PassTape& t) {
rc = route_report_impl(t.route[(size_t)st.a].first, &t.route[(size_t)st.a].second,
false);
break;
case kTapeXp: {
const TapeXp& p = t.xp[(size_t)st.a];
lane_ = st.lane;
rc = xp_ ? xp_predict_run(p.next, p.h, p.r0, p.rows, p.n_embd) : RAD_OK;
lane_ = l0;
break;
}
case kTapeXpMark:
lane_ = st.lane;
rc = xp_ ? xp_mark_run() : RAD_OK;
lane_ = l0;
break;
case kTapeXpStep:
lane_ = st.lane;
rc = xp_ ? xp_step_run(st.a) : RAD_OK;
lane_ = l0;
break;
}
if (rc < 0) {
if (step_status_ >= 0) step_status_ = rc;
@@ -1350,6 +1416,11 @@ int Ctx::run_step(const RadBatch* b) {
return RAD_E_STATE;
}
/* BEFORE THE RESIDENCY SYNC: a stager may give back weights it published for this pass when
* it turns the pass down (runtime/stager.h), and the sync is what carries that into the
* tables the pass resolves. */
staging_ = stager_ != nullptr && stager_->begin_pass(b);
/* The mover relocates between steps, never during one. Honouring WeightInfo::generation here
* costs one relaxed atomic load per step instead of one per weight per issue. */
if (weights_dirty_.exchange(false, std::memory_order_acq_rel))
@@ -1361,8 +1432,6 @@ int Ctx::run_step(const RadBatch* b) {
step_fail_.clear();
prof_n_ = 0;
in_step_ = true;
staging_ = stager_ != nullptr && stager_->begin_pass(b);
{
const int rc = run_pass(b);
if (rc < 0 && step_status_ >= 0) step_status_ = rc;
+57 -6
View File
@@ -33,7 +33,9 @@
#include "device/device.h"
#include <atomic>
#include <memory>
#include <string>
#include <deque>
#include <vector>
#include <unordered_map>
@@ -45,6 +47,9 @@ struct RadCtx { };
namespace rad {
struct XpState;
struct XpLayer;
/* The widest op in the conventional vocabulary is gdn_conv_prep at sixteen operands, with
* gdn_recurrent_update behind it at fourteen -- both grew when the two kernel plugins' schemas
* were reconciled (docs/OPS.md, "How a schema is written"). Thirty-two leaves room for an
@@ -64,6 +69,11 @@ struct IssuePlan {
RadArgs args{};
RadLaunchFn launch = nullptr;
const KernelRow* row = nullptr;
/* The parameters a launch that holds the link is handed: the geometry's and `link_gate`, for a
* row that ends the hold itself; null for every other. Only such a launch takes them, so a
* step that holds nothing -- every decode step -- never pays the kernel's read of the word. */
const RadParam* gate_p = nullptr;
int gate_n_p = 0;
};
/* Per declared op. Trivially copyable on purpose: the bucket table and the issue plans live in two
@@ -79,10 +89,14 @@ struct OpPlan {
int32_t n_opd_schema = -1;
bool issued = false; /* did the run phase ever issue it (spec §16's graph dump) */
/* IS THIS OP A COLLECTIVE -- i.e. does issuing it put bytes on the interconnect? Set once at
* bind, so the accounting on the issue path is a predicted branch and not a string compare.
* The link is shared with the expert mover, so separating "how much of it is the all-reduce"
* needs the collective's own traffic counted. */
* bind, from the rows it resolved to (rad_kernel_collective) and the conventional all_reduce,
* so the issue path tests a predicted branch and not a string. The weight stager's copies
* share the link, and give way to it while it runs (Ctx::issue_body). */
bool collective = false;
/* The conventional all_reduce, whose `n` IS the message's element count -- the one collective
* the link bill can be charged for without guessing its wire format. The link is shared with
* the expert mover, so separating "how much of it is the all-reduce" needs this counted. */
bool billed = false;
};
/* ------------------------------------------------------------------ routing handoff */
@@ -203,7 +217,7 @@ struct CtxDesc {
/* ------------------------------------------------------------------ Ctx */
class Ctx : public RadCtx {
public:
Ctx() = default;
Ctx(); /* out of line, beside ~Ctx: xp_ points to a type this header only names */
~Ctx();
Ctx(const Ctx&) = delete;
Ctx& operator=(const Ctx&) = delete;
@@ -266,6 +280,16 @@ public:
* dense model, where nothing routes and bind_routing allocated nothing. */
int n_route_layers() const { return (int)route_.size(); }
int64_t route_n_expert() const { return route_n_expert_; }
/* ---------------------------------------------------- the next-layer expert prefetch
* (xprefetch.h). xp_open at bringup, once the placement has made its pinned pools: their device
* ranges and unit strides; it stays off -- and the three calls no-ops -- where the backend or the
* placement gives it nothing to do. */
void xp_open(const uint64_t* lo, const uint64_t* hi, const uint64_t* stride, int n);
void xp_close();
int xp_predict(const RadPrefetchNext* next, rad_buf h, int64_t r0, int64_t rows, int64_t n_embd);
int xp_mark();
int xp_step(int layer);
/* DRAIN, DO NOT SAMPLE. `next_histogram` returns the oldest staging bank holding a LANDED
* histogram for a step past `after_step` and before `before_step`, or -1; a caller loops on it
* with the step of the last one it credited and so sees every histogram the device produced,
@@ -489,7 +513,14 @@ private:
* fresh issue again every kAuditPlays plays. A difference means the pass depends on something
* the key does not carry, and it fails the step naming the first dispatch that differs -- a
* silent difference would be wrong output. */
enum TapeKind : uint8_t { kTapePlay = 0, kTapeTable = 1, kTapeHost = 2, kTapeRoute = 3 };
enum TapeKind : uint8_t { kTapePlay = 0, kTapeTable = 1, kTapeHost = 2, kTapeRoute = 3,
kTapeXp = 4, kTapeXpMark = 5, kTapeXpStep = 6 };
/* A prefetch call (Ctx::xp_predict), run again where the pass made it. */
struct TapeXp {
RadPrefetchNext next{};
rad_buf h = 0;
int64_t r0 = 0, rows = 0, n_embd = 0;
};
struct TapeStep {
uint8_t kind = kTapePlay;
uint8_t lane = 0; /* the lane the host work ran on */
@@ -510,6 +541,7 @@ private:
std::vector<TapeStep> steps;
std::vector<TapeHost> host;
std::vector<std::pair<int, RadRouting>> route;
std::vector<TapeXp> xp;
/* What the recording added to the Ctx's counters, and the bookkeeping it ended on. */
int64_t issues = 0, ar_calls = 0, ar_bytes = 0, stream_waits = 0, host_syncs = 0;
bool touch_pending[2] = {};
@@ -633,6 +665,16 @@ private:
int issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n);
ArchStepFn arch_step_ = nullptr;
/* The expert prefetch's state (xp_state.h), null while it is off. */
std::unique_ptr<XpState> xp_;
void xp_free(XpState& x);
void xp_serve(XpState& x);
void xp_judge(XpState& x);
bool xp_bind(XpLayer& L, int layer);
int xp_predict_run(const RadPrefetchNext& next, rad_buf h, int64_t r0, int64_t rows, int64_t n_embd);
int xp_mark_run();
int xp_step_run(int layer);
int rank_ = 0;
int world_size_ = 1;
int device_ = 0;
@@ -752,6 +794,9 @@ private:
std::vector<uint32_t> unflushed_;
std::vector<int64_t> band_table_;
std::vector<IssuePlan> issue_table_;
/* The parameter lists of the launches handed `link_gate`: the geometry's and that one. A deque,
* so a plan's pointer into one stays good as the next is added. */
std::deque<std::vector<RadParam>> gate_params_;
std::vector<std::atomic<uint8_t>> op_domain_; /* sized once, never resized */
std::vector<RouteSlot> route_;
@@ -771,7 +816,7 @@ private:
/* Profiling. Off by default; when on it restores synchronisations that change the mover's slot
* supply, so a profiled run is not comparable against an unprofiled one (spec §16). */
bool profiling_ = false;
struct ProfSlot { RadEvent a = nullptr, b = nullptr; int32_t op = 0; };
struct ProfSlot { RadEvent a = nullptr, b = nullptr; int32_t op = 0; uint8_t lane = 0; };
std::vector<ProfSlot> prof_ring_;
size_t prof_n_ = 0;
bool prof_overflowed_ = false;
@@ -785,6 +830,12 @@ private:
* the pipeline the op STOPS, not of the arithmetic it does, and the two differ by two orders
* of magnitude on the PLE gather. */
std::vector<double> prof_join_ms_;
/* How long each op's lane sat idle before the op started: from the end of the op before it on
* that lane to this one's start. A stream wait (a staged layer's copies, the other lane, a
* host op's output) and a host that has not issued the op yet both land here, and neither is
* in any op's own time -- so a step whose ops sum to less than its wall time says where the
* rest went. */
std::vector<double> prof_wait_ms_;
std::atomic<bool> weights_dirty_{false};
/* Bumped whenever bind_weights rewrites the templates: any weight pointer resolved from one
+42 -6
View File
@@ -873,7 +873,7 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
* operand 0 carries the dtype it is sent in, which is the ACTIVATION's dtype and not the op's
* `dtype` key -- that key is the architecture's operand-combination spelling ("w4a8"), which
* is not an element width. Two relaxed adds on seventeen issues a step. */
if (p.collective && n_opd > 0) {
if (p.billed && n_opd > 0) {
const int bits = rad_dtype_bits(t[0].dtype);
ar_calls_.fetch_add(1, std::memory_order_relaxed);
if (bits > 0) ar_bytes_.fetch_add(n * bits / 8, std::memory_order_relaxed);
@@ -991,6 +991,24 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
if (host_paused) tape_pause(true);
const int rec0 = rec_ && !host_paused ? tape_mark() : 0;
/* A COLLECTIVE HAS THE CARD'S LINK TO ITSELF in a pass the stager copies weights through: the
* stager's lists yield while the hold is in force (rad_link_hold says why). Taken here, after
* every wait this op's operands put on the stream, so the stream waits on nothing between the
* hold and its release -- a weight it waited on could be behind a yielding list. */
const bool hold = staging_ && p.collective && dom == RAD_DOMAIN_DEVICE;
const RadArgs* la = &ip.args;
RadArgs gate_args;
if (hold) {
const int hs = rad_link_hold(cur_stream(), 1);
if (hs < 0) return abort_step(h, b, dom, ip, n, hs);
if (ip.gate_p) {
gate_args = ip.args;
gate_args.p = ip.gate_p;
gate_args.n_p = ip.gate_n_p;
la = &gate_args;
}
}
int s;
if (profiling_ && dom == RAD_DOMAIN_HOST) {
@@ -1007,7 +1025,7 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
* Wall clock and not a device event, so it includes whatever the host call waits on:
* page faults, the link read of its input, everything. That is the number that matters. */
const auto t0 = std::chrono::steady_clock::now();
s = ip.launch(&ip.args, cur_stream());
s = ip.launch(la, cur_stream());
const auto t1 = std::chrono::steady_clock::now();
prof_ms_[(size_t)h] +=
std::chrono::duration<double, std::milli>(t1 - t0).count();
@@ -1020,12 +1038,13 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
if (prof_n_ < prof_ring_.size()) {
ProfSlot& ps = prof_ring_[prof_n_++];
ps.op = (int32_t)h;
ps.lane = (uint8_t)lane_;
rad_event_record(ps.a, cur_stream());
s = ip.launch(&ip.args, cur_stream());
s = ip.launch(la, cur_stream());
rad_event_record(ps.b, cur_stream());
} else {
prof_overflowed_ = true;
s = ip.launch(&ip.args, cur_stream());
s = ip.launch(la, cur_stream());
}
/* RANK 0 ONLY, FOR THE SECOND TIME IN THIS FILE. `Ctx::issue` runs on every rank thread, so a
* file-scope accumulator is written by both. Unguarded, the digest above gives wrong NUMBERS
@@ -1034,7 +1053,7 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
* race at all. Anything this instrument accumulates belongs to one thread. */
} else if (g_dbg_issue && rank() == 0) {
const auto ta = std::chrono::steady_clock::now();
s = ip.launch(&ip.args, cur_stream());
s = ip.launch(la, cur_stream());
const auto tb = std::chrono::steady_clock::now();
using us = std::chrono::duration<double, std::micro>;
g_iss_own += us(ta - t_iss0).count();
@@ -1081,7 +1100,13 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
g_iss_lau_p = g_iss_lau;
}
} else {
s = ip.launch(&ip.args, cur_stream());
s = ip.launch(la, cur_stream());
}
if (hold) {
/* Released whatever the launch said, by a barrier unless the launch said it ended the hold
* itself (RAD_LINK_ENDED): a list waiting on the hold would otherwise never end. */
const int hr = rad_link_hold(cur_stream(), la != &ip.args && s == RAD_LINK_ENDED ? 2 : 0);
if (hr < 0 && s >= 0) s = hr;
}
if (host_paused) tape_pause(false);
@@ -1315,6 +1340,17 @@ int32_t* rad_route_counts(RadCtx* c, int layer, int64_t n_expert) {
return c ? static_cast<rad::Ctx*>(c)->route_counts(layer, n_expert) : nullptr;
}
int rad_expert_prefetch(RadCtx* c, const RadPrefetchNext* next, rad_buf h, int64_t r0, int64_t rows,
int64_t n_embd) {
return c ? static_cast<rad::Ctx*>(c)->xp_predict(next, h, r0, rows, n_embd) : RAD_E_INVAL;
}
int rad_expert_prefetch_mark(RadCtx* c) {
return c ? static_cast<rad::Ctx*>(c)->xp_mark() : RAD_E_INVAL;
}
int rad_expert_prefetch_step(RadCtx* c, int layer) {
return c ? static_cast<rad::Ctx*>(c)->xp_step(layer) : RAD_E_INVAL;
}
void* rad_weight_ptr(RadCtx* c, rad_weight w) {
return c ? static_cast<rad::Ctx*>(c)->weight_ptr(w) : nullptr;
}
+6 -2
View File
@@ -21,7 +21,9 @@ class OpStager {
public:
virtual ~OpStager() = default;
/* The pass is about to be issued: whether the stager takes part in it. */
/* The pass is about to be issued: whether the stager takes part in it. Called before the
* run phase brings the weight tables up to date, so a stager turning down a pass may give back
* weights it published ahead for it (see end_pass). */
virtual bool begin_pass(const RadBatch* b) = 0;
/* Before op `h` is issued on stream `s`. `*resync` is set when the residency table changed,
@@ -31,7 +33,9 @@ public:
/* After op `h` was issued on stream `s`: the point a staged weight's last reader is behind. */
virtual int after_op(rad_op h, RadStream s) = 0;
/* The pass has been issued, on `s`: nothing the stager published may outlive it. */
/* The pass has been issued, on `s`: nothing the stager published for it may outlive it. It
* may publish weights for a later pass it expects to arm for, which that pass's begin_pass
* keeps or gives back. */
virtual int end_pass(RadStream s) = 0;
};
+82
View File
@@ -0,0 +1,82 @@
/* xp_state.h -- the expert prefetch's host state, held by the Ctx (Ctx::xp_). See xprefetch.h. */
#pragma once
#include "xprefetch.h"
#include "rad_runtime.h"
#include "../device/device.h"
#include <atomic>
#include <condition_variable>
#include <cstdint>
#include <deque>
#include <mutex>
#include <string>
#include <thread>
#include <utility>
#include <vector>
namespace rad {
/* A routed layer as the prefetch knows it: the next-layer description a plugin hands over, and the
* device map from expert to its table entries, built at the first call after the layer's tables are
* bound. `want` is the request made for it this pass, which its step patches in. */
struct XpLayer {
RadPrefetchNext next{};
void** map = nullptr; /* device [kXpMaxNe][kXpParts]: entry addresses, null for none */
int32_t* place = nullptr; /* device [kXpMaxNe]: the expert's place in the routing counts */
bool bound = false;
bool want = false;
int g = 0;
uint32_t seq = 0;
};
/* A request: the group's mailbox the plan writes, and the mark the DMA list waits for. */
struct XpReq {
int g = 0;
uint32_t seq = 0;
void* mark = nullptr;
RadStream ms = nullptr; /* the stream the mark rides */
bool valid = false;
};
struct XpState {
int device = 0;
RadStream stream = nullptr; /* logits and plan, behind rides on the compute stream */
RadEvent tail = nullptr; /* the pass start waits for the stream's work of the last */
RadEvent sync = nullptr; /* the router input's readiness, where a ride is refused */
bool tail_live = false;
char* ring = nullptr; /* uncached: kXpGroups x kXpSlots slots of `slot` bytes */
uint64_t slot = 0;
XpPools pools{};
XpRec* rec = nullptr; /* [kXpGroups][kXpSlots] */
int32_t* nrec = nullptr; /* [kXpGroups] */
XpBox* box = nullptr; /* [kXpGroups], pinned host */
uint32_t* done = nullptr; /* [kXpGroups], pinned host: the last request whose copies landed */
XpStats* stats = nullptr; /* device */
XpStats* stats_h = nullptr; /* pinned host, read at the end */
float* logits = nullptr; /* [kXpGroups][kXpMaxRows][kXpMaxNe] */
void** maps = nullptr; /* [layers][kXpMaxNe][kXpParts] */
int32_t* places = nullptr; /* [layers][kXpMaxNe] */
std::vector<XpLayer> layers;
uint32_t seq[kXpGroups] = {};
int last_layer = -1; /* the last layer predicted for: a lower one starts a pass */
/* WHETHER IT PAYS: the share of its copies the steps use, judged every kXpWindow predictions from
* the counters (stats_h, one window on their way to the host); under kXpMinUse it rests. */
int64_t passes = 0, rest_until = 0, rests = 0;
int64_t calls = 0;
uint32_t snap_copied = 0, snap_routed = 0;
bool have_snap = false, judge = false;
int restore_g = -1; /* the group the next step puts back */
XpReq pend; /* made at a router, waiting for its mark */
/* The host thread: each mailbox, once the plan has written it, to the DMA queue. */
std::thread thr;
std::mutex mu;
std::condition_variable cv;
std::deque<XpReq> q;
std::atomic<bool> stop{false};
std::deque<std::pair<void*, int64_t>> marks; /* thread only: a mark and the list that polls it */
int64_t lists = 0; /* thread only: lists handed over */
std::atomic<int64_t> dropped{0}; /* requests the queue was too far behind for */
};
} /* namespace rad */
+439
View File
@@ -0,0 +1,439 @@
/* xprefetch.cpp -- the expert prefetch's host half: Ctx::xp_*. See xprefetch.h for what it does. */
#include "ctx.h"
#include "xp_state.h"
#include "rad_internal.h"
#include <algorithm>
#include <chrono>
#include <cstring>
#include <immintrin.h>
#if !(defined(RAD_HAVE_HIP) && RAD_HAVE_HIP)
/* A build without HIP has no kernels to launch: rad_xp_supported is 0 there, so nothing calls these. */
extern "C" int rad_xp_logits_launch(const uint16_t*, const uint16_t*, float*, uint32_t, uint32_t, uint32_t, void*) {
return -1;
}
extern "C" int rad_xp_plan_launch(const float*, uint32_t, uint32_t, uint32_t, void** const*, const int32_t*,
const int32_t*, rad::XpPools, uint64_t, uint64_t, rad::XpRec*, int32_t*,
rad::XpBox*, uint32_t, rad::XpStats*, void*) {
return -1;
}
extern "C" int rad_xp_step_launch(const rad::XpRec*, const int32_t*, const rad::XpRec*, const int32_t*,
const uint32_t*, uint32_t, void*) {
return -1;
}
#endif
namespace rad {
namespace {
/* A pool class wider than this holds whole tables (the token embedding read in place), not experts. */
constexpr uint64_t kXpMaxUnit = (uint64_t)64 << 20;
/* Lists the queue may be behind before a request is dropped. Nothing waits for these lists, so
* nothing slows a queue that falls behind but this: its copies could not land in time anyway, and a
* queue that only grows would end up polling marks that have long gone back to the pool. */
constexpr int64_t kXpBehind = 3;
/* Dispatches past a dropped request's mark before the signal can be made again: far more than the
* pass that completes it. */
constexpr int64_t kXpMarkHold = 4096;
/* WHETHER IT PAYS. A copy the step uses saves the link time of reading that expert under the GEMM;
* one it does not use costs link time the GEMMs wanted, and the prediction costs a little whatever
* comes of it. Measured on Qwen3.8-Flash-Next, the two balance near a quarter of the copies used: at
* --tp 1 the steps used half of them and the decode step was 3.6% faster, at --tp 2 -- where each card
* keeps most experts and its pool holds the ones the steps rarely route -- a sixth, and it was 4-6%
* slower. So every kXpWindow predictions the prefetch looks at the share of its copies used over the
* last window, and under kXpMinUse it rests for kXpRest passes -- no prediction, no copy -- and then
* measures again. */
constexpr int64_t kXpWindow = 2048;
constexpr double kXpMinUse = 0.30;
constexpr uint32_t kXpMinJudged = 512;
constexpr int64_t kXpRest = 8192;
} // namespace
void Ctx::xp_free(XpState& x) {
if (x.stream) rad_stream_sync(x.stream);
if (x.ring) rad_dev_free_uncached(x.ring);
for (void* p : {(void*)x.rec, (void*)x.nrec, (void*)x.stats, (void*)x.logits, (void*)x.maps,
(void*)x.places})
if (p) rad_dev_free(p, RAD_MEM_DEVICE);
for (void* p : {(void*)x.box, (void*)x.done, (void*)x.stats_h})
if (p) rad_dev_free(p, RAD_MEM_HOST_PINNED);
if (x.tail) rad_event_destroy(x.tail);
if (x.sync) rad_event_destroy(x.sync);
if (x.stream) rad_stream_destroy(x.stream);
}
/* At bringup, once the placement has made its pinned pools: everything the prefetch needs, or nothing
* and a line saying why it is off. */
void Ctx::xp_open(const uint64_t* lo, const uint64_t* hi, const uint64_t* stride, int n) {
if (xp_ || device_is_host() || route_.empty()) return;
if (!rad_xp_supported(device_)) {
RAD_INFO("rank %d: expert prefetch off: the device backend has no DMA engine to spare for it",
rank_);
return;
}
auto x = std::make_unique<XpState>();
x->device = device_;
for (int i = 0; i < n && x->pools.n < kXpMaxPools; ++i) {
if (stride[i] == 0 || stride[i] > kXpMaxUnit || hi[i] <= lo[i]) continue;
x->pools.lo[x->pools.n] = lo[i];
x->pools.hi[x->pools.n] = hi[i];
x->pools.stride[x->pools.n] = stride[i];
x->slot = std::max(x->slot, stride[i]);
++x->pools.n;
}
if (x->pools.n == 0) return;
const int64_t nl = (int64_t)route_.size();
const int64_t ring = (int64_t)(kXpGroups * kXpSlots * x->slot);
if (rad_dev_set(device_) < 0) return;
x->ring = (char*)rad_dev_alloc_uncached(ring);
x->rec = (XpRec*)rad_dev_alloc((int64_t)sizeof(XpRec) * kXpGroups * kXpSlots, RAD_MEM_DEVICE);
x->nrec = (int32_t*)rad_dev_alloc(4 * kXpGroups, RAD_MEM_DEVICE);
x->stats = (XpStats*)rad_dev_alloc((int64_t)sizeof(XpStats), RAD_MEM_DEVICE);
x->logits = (float*)rad_dev_alloc(4 * (int64_t)kXpGroups * kXpMaxRows * kXpMaxNe, RAD_MEM_DEVICE);
x->maps = (void**)rad_dev_alloc(nl * kXpMaxNe * kXpParts * (int64_t)sizeof(void*), RAD_MEM_DEVICE);
x->places = (int32_t*)rad_dev_alloc(nl * kXpMaxNe * 4, RAD_MEM_DEVICE);
x->box = (XpBox*)rad_dev_alloc((int64_t)sizeof(XpBox) * kXpGroups, RAD_MEM_HOST_PINNED);
x->done = (uint32_t*)rad_dev_alloc(4 * kXpGroups, RAD_MEM_HOST_PINNED);
x->stats_h = (XpStats*)rad_dev_alloc((int64_t)sizeof(XpStats), RAD_MEM_HOST_PINNED);
const bool ok = x->ring && x->rec && x->nrec && x->stats && x->logits && x->maps && x->places && x->box &&
x->done && x->stats_h && rad_xp_stream_create(&x->stream) >= 0 &&
rad_event_create_local(&x->tail) >= 0 && rad_event_create_local(&x->sync) >= 0 &&
rad_memset_async(x->nrec, 0, 4 * kXpGroups, stream_) >= 0 &&
rad_memset_async(x->stats, 0, sizeof(XpStats), stream_) >= 0 && rad_stream_sync(stream_) >= 0;
if (!ok) {
const char* why = rad_dev_last_error();
RAD_WARN("rank %d: expert prefetch off: %s", rank_, why && *why ? why : "no memory for it");
xp_free(*x);
return;
}
std::memset((void*)x->box, 0, sizeof(XpBox) * kXpGroups);
std::memset(x->done, 0, 4 * kXpGroups);
x->layers.resize((size_t)nl);
XpState* xs = x.get();
x->thr = std::thread([this, xs] { xp_serve(*xs); });
RAD_INFO("rank %d: expert prefetch on: %d copies a routed layer by DMA, ring %s", rank_, kXpSlots,
humanb(ring).c_str());
xp_ = std::move(x);
}
void Ctx::xp_close() {
if (!xp_) return;
XpState& x = *xp_;
/* NOTHING MAY READ OR WRITE THE RING WHEN IT GOES: the compute work issued so far can read it
* through entries still pointed at it, and the queue's lists write it until they finish. */
if (stream_) rad_stream_sync(stream_);
if (lane1_) rad_stream_sync(lane1_);
{
std::lock_guard<std::mutex> lk(x.mu);
x.stop = true;
}
x.cv.notify_all();
if (x.thr.joinable()) x.thr.join();
const auto t0 = std::chrono::steady_clock::now();
while (rad_xp_behind(x.device) > 0) {
if (std::chrono::steady_clock::now() - t0 > std::chrono::seconds(5)) {
RAD_WARN("rank %d: the prefetch DMA queue still has %lld lists after 5 s; its ring is freed anyway",
rank_, (long long)rad_xp_behind(x.device));
break;
}
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
/* What it came to: copies planned, and of the restored ones how many the step routed. */
if (x.stream && rad_memcpy_async(x.stats_h, x.stats, sizeof(XpStats), x.stream) >= 0 &&
rad_stream_sync(x.stream) >= 0 && x.stats_h->planned)
RAD_INFO("rank %d: expert prefetch: %u copies planned, %u of %u looked back on routed (%.1f%%), %lld "
"requests dropped behind a slow queue, %lld rests", rank_, x.stats_h->planned, x.stats_h->routed,
x.stats_h->copied, x.stats_h->copied ? 100.0 * x.stats_h->routed / x.stats_h->copied : 0.0,
(long long)x.dropped.load(), (long long)x.rests);
xp_free(x);
xp_.reset();
}
/* The host thread: each request's mailbox, once the plan has written it, to the DMA queue. */
void Ctx::xp_serve(XpState& x) {
for (;;) {
XpReq r;
{
std::unique_lock<std::mutex> lk(x.mu);
x.cv.wait(lk, [&] { return x.stop.load() || !x.q.empty(); });
if (x.stop) return;
r = x.q.front();
x.q.pop_front();
}
/* The marks of finished lists go back to the pool. */
const int64_t behind = rad_xp_behind(x.device);
while (!x.marks.empty() && x.marks.front().second <= x.lists - behind) {
rad_ride_release(x.marks.front().first, nullptr, 0);
x.marks.pop_front();
}
/* The mailbox reaches the request's number once the plan has run; a number past it means it
* was written over by a later request and this one is stale. */
volatile XpBox* b = x.box + r.g;
const auto t0 = std::chrono::steady_clock::now();
bool got = true;
while ((int32_t)(b->seq - r.seq) < 0) {
_mm_pause();
if (x.stop || std::chrono::steady_clock::now() - t0 > std::chrono::seconds(5)) {
got = false;
break;
}
}
if (got && b->seq != r.seq) got = false;
std::atomic_thread_fence(std::memory_order_acquire);
uint64_t src[kXpSlots], dst[kXpSlots], bytes[kXpSlots];
int n = 0;
if (got) {
n = std::min<int>((int)b->n, kXpSlots);
for (int i = 0; i < n && got; ++i) {
/* A job seen before its own stores landed carries an older tag. */
const auto t1 = std::chrono::steady_clock::now();
while (b->jobs[i].tag != r.seq &&
std::chrono::steady_clock::now() - t1 < std::chrono::milliseconds(100))
_mm_pause();
if (b->jobs[i].tag != r.seq) { got = false; break; }
std::atomic_thread_fence(std::memory_order_acquire);
src[i] = b->jobs[i].src;
dst[i] = b->jobs[i].dst;
bytes[i] = b->jobs[i].bytes;
}
}
if (!got || n == 0 || behind > kXpBehind) {
if (got && n > 0) ++x.dropped;
if (r.mark) rad_ride_release(r.mark, r.ms, kXpMarkHold);
continue;
}
if (rad_xp_list(x.device, r.mark, n, src, dst, bytes, x.done + r.g, r.seq) == RAD_OK) {
++x.lists;
if (r.mark) x.marks.emplace_back(r.mark, x.lists);
} else {
if (r.mark) rad_ride_release(r.mark, r.ms, kXpMarkHold);
RAD_WARN("rank %d: the prefetch DMA queue refused a list", rank_);
}
}
}
/* The layer's map from expert to table entries, once all its tables are bound; false until then. An
* expert whose weights are not each in exactly one table stays out of the map. */
bool Ctx::xp_bind(XpLayer& L, int layer) {
const RadPrefetchNext& nx = L.next;
std::vector<void**> hm((size_t)kXpMaxNe * kXpParts, nullptr);
std::vector<int32_t> hp((size_t)kXpMaxNe, -1);
for (int64_t e = 0; e < nx.n_expert; ++e) {
void** ent[kXpParts] = {};
bool usable = true;
for (int64_t k = 0; k < nx.n_parts && usable; ++k) {
const rad_weight w = nx.parts[e * nx.n_parts + k];
if (!w) continue;
if ((size_t)w >= wmemb_head_.size() || wmemb_head_[w] < 0) { usable = false; break; }
const WMemb& m = wmemb_[(size_t)wmemb_head_[w]];
if (m.next >= 0) { usable = false; break; }
const WeightTable& t = wtabs_[(size_t)m.slot];
if (!t.dev) return false;
ent[k] = (void**)t.dev + m.entry;
}
if (usable)
for (int k = 0; k < kXpParts; ++k) hm[(size_t)(e * kXpParts + k)] = ent[k];
hp[(size_t)e] = nx.count_at ? nx.count_at[e] : (int32_t)e;
}
XpState& x = *xp_;
void** map = x.maps + (size_t)layer * kXpMaxNe * kXpParts;
int32_t* place = x.places + (size_t)layer * kXpMaxNe;
/* Once a layer, at its first issue: the one host wait here is not on the step path. */
if (rad_memcpy_async(map, hm.data(), (int64_t)hm.size() * (int64_t)sizeof(void*), stream_) < 0 ||
rad_memcpy_async(place, hp.data(), (int64_t)hp.size() * 4, stream_) < 0 || rad_stream_sync(stream_) < 0)
return false;
L.map = map;
L.place = place;
L.bound = true;
return true;
}
/* The counters the last judgement sent to the host are a window old: the share of copies used is
* judged from them, then the next window's are sent. A window that follows a rest is not judged --
* its counters left before the rest -- so a rest is followed by one full window measured afresh. */
void Ctx::xp_judge(XpState& x) {
if (x.have_snap) {
const volatile XpStats* h = x.stats_h;
const uint32_t copied = h->copied, routed = h->routed;
const uint32_t dc = copied - x.snap_copied, dr = routed - x.snap_routed;
x.snap_copied = copied;
x.snap_routed = routed;
if (x.judge && dc >= kXpMinJudged && (double)dr < kXpMinUse * (double)dc) {
x.rest_until = x.passes + kXpRest;
x.judge = false;
if (x.rests++ == 0)
RAD_INFO("rank %d: expert prefetch resting: the steps used %.0f%% of its last %u copies, under the "
"%.0f%% that pays for them; it measures again every %lld passes", rank_,
100.0 * dr / dc, dc, 100.0 * kXpMinUse, (long long)kXpRest);
} else {
x.judge = true;
}
}
if (rad_memcpy_async(x.stats_h, x.stats, sizeof(XpStats), x.stream) >= 0) x.have_snap = true;
}
/* A pass being recorded keeps each of the three calls as a step of its own, run again where the tape
* plays it: what a call issues -- on its own stream, or a ride on the next played dispatch -- is
* issued again at every play rather than recorded. */
int Ctx::xp_predict(const RadPrefetchNext* nx, rad_buf h, int64_t r0, int64_t rows, int64_t n_embd) {
/* A pass this wide predicts nothing, and its tape is better without a step that does nothing. */
if (!xp_ || !nx || rows <= 0 || rows > kXpMaxRows) return RAD_OK;
if (!rec_) return xp_predict_run(*nx, h, r0, rows, n_embd);
tape_cut();
TapeXp p;
p.next = *nx;
p.h = h;
p.r0 = r0;
p.rows = rows;
p.n_embd = n_embd;
TapeStep st;
st.kind = kTapeXp;
st.lane = (uint8_t)lane_;
st.a = (int32_t)rec_->xp.size();
rec_->xp.push_back(p);
rec_->steps.push_back(st);
tape_pause(true);
const int rc = xp_predict_run(*nx, h, r0, rows, n_embd);
tape_pause(false);
return rc;
}
int Ctx::xp_mark() {
if (!xp_) return RAD_OK;
if (!rec_) return xp_mark_run();
tape_cut();
TapeStep st;
st.kind = kTapeXpMark;
st.lane = (uint8_t)lane_;
rec_->steps.push_back(st);
tape_pause(true);
const int rc = xp_mark_run();
tape_pause(false);
return rc;
}
int Ctx::xp_step(int layer) {
if (!xp_) return RAD_OK;
if (!rec_) return xp_step_run(layer);
tape_cut();
TapeStep st;
st.kind = kTapeXpStep;
st.lane = (uint8_t)lane_;
st.a = layer;
rec_->steps.push_back(st);
tape_pause(true);
const int rc = xp_step_run(layer);
tape_pause(false);
return rc;
}
int Ctx::xp_predict_run(const RadPrefetchNext& nx, rad_buf h, int64_t r0, int64_t rows, int64_t n_embd) {
XpState& x = *xp_;
const int layer = nx.layer;
if (rows <= 0 || rows > kXpMaxRows || nx.top_k <= 0 || nx.top_k > kXpMaxK || nx.n_expert <= 0 ||
nx.n_expert > kXpMaxNe || nx.n_parts <= 0 || nx.n_parts > kXpParts || !nx.parts || n_embd % 256 ||
n_embd > 4096 || layer < 0 || layer >= (int)x.layers.size())
return RAD_OK;
XpLayer& L = x.layers[(size_t)layer];
if (!L.bound) {
L.next = nx;
if (!xp_bind(L, layer)) return RAD_OK;
}
const void* w = weight_ptr(nx.router);
const char* hb = (const char*)buf_ptr(h);
if (!w || !hb) return RAD_OK;
const RadStream cs = cur_stream();
/* A NEW PASS waits for the prefetch stream's work of the last one, so that stream is never a pass
* behind the compute stream: the records and mailboxes a request reuses are three layers old. */
if (layer <= x.last_layer) {
if (x.tail_live) {
RAD_TRY(rad_event_record(x.tail, x.stream));
RAD_TRY(rad_event_wait(cs, x.tail));
x.tail_live = false;
}
++x.passes;
}
x.last_layer = layer;
if (x.passes < x.rest_until) return RAD_OK;
/* THE ROUTER INPUT IS READ IN PLACE, behind the next dispatch on the compute stream -- the router,
* which reads it -- by a ride rather than a barrier packet between two kernels. */
void* rt = nullptr;
if (rad_ride(cs, &rt) == RAD_OK) {
RAD_TRY(rad_ride_wait(x.stream, rt));
} else {
RAD_TRY(rad_event_record(x.sync, cs));
RAD_TRY(rad_event_wait(x.stream, x.sync));
}
/* An earlier request still waiting for its mark goes now, unmarked. */
if (x.pend.valid) {
{
std::lock_guard<std::mutex> lk(x.mu);
x.q.push_back(x.pend);
}
x.cv.notify_one();
x.pend.valid = false;
}
const int g = layer % kXpGroups;
const uint32_t seq = ++x.seq[g];
const uint16_t* hg = (const uint16_t*)(hb + r0 * n_embd * 2);
float* lg = x.logits + (size_t)g * kXpMaxRows * kXpMaxNe;
const int32_t* cnt = route_n_expert_ > 0 && nx.n_expert <= route_n_expert_
? route_dev_ + (int64_t)layer * route_n_expert_ : nullptr;
const uint64_t ring = (uint64_t)(uintptr_t)(x.ring + (size_t)g * kXpSlots * x.slot);
if (rad_xp_logits_launch(hg, (const uint16_t*)w, lg, (uint32_t)rows, (uint32_t)n_embd, (uint32_t)nx.n_expert,
(void*)x.stream) ||
rad_xp_plan_launch(lg, (uint32_t)rows, (uint32_t)nx.n_expert, (uint32_t)nx.top_k, (void** const*)L.map,
L.place, cnt, x.pools, ring, x.slot, x.rec + (size_t)g * kXpSlots, x.nrec + g,
(XpBox*)rad_dev_device_ptr(x.box + g), seq, x.stats, (void*)x.stream))
return RAD_E_DEVICE;
x.tail_live = true;
if (++x.calls % kXpWindow == 0) xp_judge(x);
x.pend.g = g;
x.pend.seq = seq;
x.pend.mark = nullptr;
x.pend.ms = nullptr;
x.pend.valid = true;
L.want = true;
L.g = g;
L.seq = seq;
return RAD_OK;
}
int Ctx::xp_mark_run() {
XpState& x = *xp_;
if (!x.pend.valid) return RAD_OK;
/* Refused only while another ride waits on the stream: the list then starts without one. */
void* mark = nullptr;
if (rad_ride(cur_stream(), &mark) == RAD_OK) {
x.pend.mark = mark;
x.pend.ms = cur_stream();
}
{
std::lock_guard<std::mutex> lk(x.mu);
x.q.push_back(x.pend);
}
x.cv.notify_one();
x.pend.valid = false;
return RAD_OK;
}
int Ctx::xp_step_run(int layer) {
XpState& x = *xp_;
XpLayer* L = layer >= 0 && (size_t)layer < x.layers.size() ? &x.layers[(size_t)layer] : nullptr;
const bool patch = L && L->want;
if (!patch && x.restore_g < 0) return RAD_OK;
const XpRec* rrec = x.restore_g >= 0 ? x.rec + (size_t)x.restore_g * kXpSlots : nullptr;
const int32_t* rn = x.restore_g >= 0 ? x.nrec + x.restore_g : nullptr;
const XpRec* prec = patch ? x.rec + (size_t)L->g * kXpSlots : nullptr;
const int32_t* pn = patch ? x.nrec + L->g : nullptr;
const uint32_t* done = patch ? (const uint32_t*)rad_dev_device_ptr(x.done + L->g) : nullptr;
if (rad_xp_step_launch(rrec, rn, prec, pn, done, patch ? L->seq : 0, (void*)cur_stream())) return RAD_E_DEVICE;
x.restore_g = patch ? L->g : -1;
if (L) L->want = false;
return RAD_OK;
}
} /* namespace rad */
+93
View File
@@ -0,0 +1,93 @@
/* xprefetch.h -- the next-layer expert prefetch at decode: what the host half (xprefetch.cpp) and the
* kernels (xprefetch.hip) share.
*
* WHAT IT DOES. Under expert-tiered placement a routed layer's GEMMs read the experts that are not on
* the card from the pinned host pool, across the link, while they run. A layer's router input predicts
* the NEXT routed layer's choice well: that layer's router applied to it ranks the experts the next
* layer will route. So at each routed layer the prefetch applies the next layer's router to this
* layer's router input, takes the likeliest experts that sit in the pinned pool, copies them onto the
* card with the DMA engine while the rest of this layer runs, and points the next layer's weight tables
* at the copies just before its GEMMs. The GEMMs then read those experts from the card.
*
* NOTHING IT DOES CHANGES A RESULT. A copy holds the bytes of the pool slot it was made from, and an
* entry is pointed at it only where it still names that slot (a compare-and-swap: a heat-engine move
* since then wins) and only once the copy has landed. Late copies are not used; nothing waits for them.
*
* THE PIECES, per routed layer l predicting layer l+1:
* - at l's router input (Ctx::xp_predict): on a stream of its own, behind the compute stream's
* dispatch that reads the input (a ride), xp_logits applies l+1's router to the input rows and
* xp_plan picks the copies and writes them to a mailbox in pinned host memory;
* - after l's routed down GEMM (Ctx::xp_mark): a ride on the compute stream that the DMA list polls,
* so the copies cross the link under l+1's attention rather than under l's own streamed experts;
* - a host thread hands each mailbox to the card's prefetch DMA queue: wait for the mark, copy, then
* write the request's number to the group's done word;
* - ahead of l+1's routed GEMMs (Ctx::xp_step, on the compute stream): xp_step puts the previous
* layer's entries back (its GEMMs are behind it in the stream) and points l+1's at the copies if
* the done word says they have landed.
* The ring holds kXpGroups layers' copies, kXpSlots each; a group is copied into again three layers
* later, after the step that put its entries back. */
#pragma once
#include <cstdint>
namespace rad {
constexpr int kXpSlots = 2; /* copies a layer: the link fits about two units between the marks */
constexpr int kXpGroups = 3;
constexpr int kXpMaxRows = 16; /* decode passes; a wider pass makes no prediction */
constexpr int kXpMaxK = 16;
constexpr int kXpMaxNe = 512;
constexpr int kXpMaxPools = 4;
constexpr int kXpParts = 4; /* the weights one expert's unit is made of */
/* One copied unit: its table entries, what they held and what they hold while patched, and where the
* layer's routing counts say whether the step used it. */
struct XpRec {
void** ent[kXpParts];
void* oldv[kXpParts];
void* newv[kXpParts];
const int32_t* cnt;
int32_t place;
int32_t pad;
};
struct XpJob {
uint64_t src, dst, bytes, tag; /* tag: the request's number, written after the rest */
};
/* A group's mailbox, in pinned host memory: xp_plan writes the jobs, then `seq`. */
struct XpBox {
XpJob jobs[kXpSlots];
int32_t n;
volatile uint32_t seq;
};
struct XpPools {
uint64_t lo[kXpMaxPools], hi[kXpMaxPools], stride[kXpMaxPools];
int32_t n;
};
/* Restored records: [0] units copied, [1] of them the step routed; [2] units planned. */
struct XpStats {
unsigned int copied, routed, planned, pad;
};
/* What the prefetch takes on the card for a model of `layers` routed layers whose largest expert unit
* is `unit` bytes: the ring and the buffers beside it (Ctx::xp_open allocates exactly these), in the
* 2 MiB grains the card's allocations come in -- the ring its own, the small buffers sharing theirs. */
inline int64_t xp_device_bytes(int64_t unit, int64_t layers) {
constexpr int64_t kGrain = (int64_t)2 << 20;
auto grains = [](int64_t b) { return (b + kGrain - 1) / kGrain * kGrain; };
const int64_t ring = (int64_t)kXpGroups * kXpSlots * unit;
const int64_t small = (int64_t)sizeof(XpRec) * kXpGroups * kXpSlots + 4 * kXpGroups + (int64_t)sizeof(XpStats) +
4 * (int64_t)kXpGroups * kXpMaxRows * kXpMaxNe + layers * kXpMaxNe * kXpParts * 8 +
layers * kXpMaxNe * 4;
return grains(ring) + grains(small);
}
} /* namespace rad */
extern "C" int rad_xp_logits_launch(const uint16_t* h, const uint16_t* w, float* logits, uint32_t rows,
uint32_t n_embd, uint32_t ne, void* stream);
extern "C" int rad_xp_plan_launch(const float* logits, uint32_t rows, uint32_t ne, uint32_t k,
void** const* map, const int32_t* place, const int32_t* cnt,
rad::XpPools pools, uint64_t ring, uint64_t ring_stride, rad::XpRec* rec,
int32_t* nrec, rad::XpBox* box, uint32_t seq, rad::XpStats* stats,
void* stream);
extern "C" int rad_xp_step_launch(const rad::XpRec* rrec, const int32_t* rn, const rad::XpRec* prec,
const int32_t* pn, const uint32_t* done, uint32_t seq, void* stream);
+314
View File
@@ -0,0 +1,314 @@
/* xprefetch.hip -- the expert prefetch's kernels. See xprefetch.h. */
#include <hip/hip_runtime.h>
#include <math.h>
#include "xprefetch.h"
namespace {
__device__ __forceinline__ float xp_bf(uint32_t x) { return __uint_as_float(x << 16); }
/* logits[r, e] = h[r, :] . w[e, :], h and w bf16. A block takes 16 experts, two a 32-lane group. Every
* lane issues all of its weight loads first -- n_embd / 256 sixteen-byte loads an expert, kept in
* registers -- so the kernel waits on memory once rather than once a K chunk; the rows are staged in
* LDS in as few chunks as 40 KiB allows (one at sixteen rows of 2560 needs two). fp32 accumulation.
* Requires n_embd % 256 == 0 and n_embd <= 4096 (rad_xp_logits_launch checks). WIDE ON PURPOSE: the
* router input is read in place and the block overwrites it once its GEMMs are done, so a narrower
* grid that waits longer for CUs beside the compute stream reads it too late and predicts badly. */
constexpr uint32_t kLgE = 16, kLgJ = 16, kLgLds = 40u << 10;
/* For gfx9-4-generic, one of rad_core's portable targets, LLVM leaves the row loop inside the
* unrolled K loop a loop and warns once a copy; every other target unrolls it. The warning is
* silenced for this kernel only, which changes no code. */
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wpass-failed"
__global__ __launch_bounds__(256) void xp_logits(const uint16_t* __restrict__ h,
const uint16_t* __restrict__ w, float* __restrict__ lg,
uint32_t rows, uint32_t n_embd, uint32_t ne) {
__shared__ uint4 s_h[kLgLds / 16];
const uint32_t lane = threadIdx.x % 32u, grp = threadIdx.x / 32u;
const uint32_t e0 = blockIdx.x * kLgE + grp * 2u;
const uint32_t J = n_embd / 256u;
uint4 wv[2][kLgJ];
#pragma unroll
for (int a = 0; a < 2; ++a)
#pragma unroll
for (uint32_t j = 0; j < kLgJ; ++j)
if (j < J && e0 + a < ne) wv[a][j] = ((const uint4*)(w + (size_t)(e0 + a) * n_embd))[j * 32u + lane];
float acc[2][rad::kXpMaxRows];
#pragma unroll
for (int a = 0; a < 2; ++a)
#pragma unroll
for (int r = 0; r < rad::kXpMaxRows; ++r) acc[a][r] = 0.f;
/* A chunk is a whole number of 32-unit columns (one j) for every row. */
const uint32_t jc = max(1u, min(J, (kLgLds / 16u) / (rows * 32u)));
for (uint32_t j0 = 0; j0 < J; j0 += jc) {
const uint32_t j1 = min(J, j0 + jc), w32 = (j1 - j0) * 32u;
__syncthreads();
for (uint32_t i = threadIdx.x; i < rows * w32; i += blockDim.x) {
const uint32_t r = i / w32, c = i % w32;
s_h[r * w32 + c] = ((const uint4*)(h + (size_t)r * n_embd))[j0 * 32u + c];
}
__syncthreads();
#pragma unroll
for (uint32_t j = 0; j < kLgJ; ++j) {
if (j < j0 || j >= j1) continue;
float wf[2][8];
#pragma unroll
for (int a = 0; a < 2; ++a) {
const uint32_t x[4] = { wv[a][j].x, wv[a][j].y, wv[a][j].z, wv[a][j].w };
#pragma unroll
for (int t = 0; t < 4; ++t) { wf[a][2 * t] = xp_bf(x[t] & 0xffffu); wf[a][2 * t + 1] = xp_bf(x[t] >> 16); }
}
#pragma unroll
for (int r = 0; r < rad::kXpMaxRows; ++r) {
if ((uint32_t)r >= rows) break;
const uint4 hv = s_h[r * w32 + (j - j0) * 32u + lane];
const uint32_t y[4] = { hv.x, hv.y, hv.z, hv.w };
float hf[8];
#pragma unroll
for (int t = 0; t < 4; ++t) { hf[2 * t] = xp_bf(y[t] & 0xffffu); hf[2 * t + 1] = xp_bf(y[t] >> 16); }
#pragma unroll
for (int a = 0; a < 2; ++a) {
float d = 0.f;
#pragma unroll
for (int t = 0; t < 8; ++t) d += wf[a][t] * hf[t];
acc[a][r] += d;
}
}
}
}
#pragma unroll
for (int a = 0; a < 2; ++a) {
const uint32_t e = e0 + (uint32_t)a;
/* No unroll pragma: the exit at `rows` keeps this a loop, and the compiler refuses one. */
for (int r = 0; r < rad::kXpMaxRows; ++r) {
if ((uint32_t)r >= rows) break;
float v = acc[a][r];
for (int o = 16; o > 0; o >>= 1) v += __shfl_xor(v, o, 32);
if (lane == 0 && e < ne) lg[(size_t)r * ne + e] = v;
}
}
}
#pragma clang diagnostic pop
/* One block. Count what the group's previous records came to (whether the step routed them), take each
* row's top-k with its softmax probability, keep the distinct experts whose entries all sit in one
* pinned pool slot, score each by its highest probability -- half as much again where the previous
* pass routed it at this layer -- and write the kXpSlots best into the ring's group as jobs, then the
* mailbox's number. The previous records' entries are back already: xp_step puts them back. */
constexpr float kXpPrevBoost = 0.5f;
__global__ __launch_bounds__(256) void xp_plan(const float* __restrict__ lg, uint32_t rows, uint32_t ne,
uint32_t k, void** const* __restrict__ map,
const int32_t* __restrict__ place,
const int32_t* __restrict__ cnt, rad::XpPools pools,
uint64_t ring, uint64_t rs, rad::XpRec* rec, int32_t* nrec,
rad::XpBox* box, uint32_t seq, rad::XpStats* stats) {
constexpr int NC = rad::kXpMaxRows * rad::kXpMaxK;
__shared__ int s_e[NC];
__shared__ float s_pr[NC];
__shared__ int s_pool[NC];
__shared__ uint64_t s_p[NC];
__shared__ float s_sc[NC]; /* the candidate's score, or -1 */
__shared__ int s_sel[rad::kXpSlots];
__shared__ int s_n;
const uint32_t tid = threadIdx.x, lane = tid % warpSize, wave = tid / warpSize;
const uint32_t nw = blockDim.x / warpSize;
if (tid == 0) {
const int nr = *nrec;
for (int t = 0; t < nr; ++t) {
const rad::XpRec& rc = rec[t];
atomicAdd(&stats->copied, 1u);
if (rc.cnt && rc.place >= 0 && rc.cnt[rc.place] > 0) atomicAdd(&stats->routed, 1u);
}
}
/* Rank-major order: o = j * rows + r, every row's first choice before any second one. */
for (uint32_t r = wave; r < rows; r += nw) {
float v[16];
float m = -INFINITY;
#pragma unroll
for (uint32_t i = 0; i < 16; ++i) {
const uint32_t e = lane + i * warpSize;
v[i] = e < ne ? lg[(size_t)r * ne + e] : -INFINITY;
m = fmaxf(m, v[i]);
}
for (int o = warpSize / 2; o > 0; o >>= 1) m = fmaxf(m, __shfl_xor(m, o));
float sum = 0.f;
#pragma unroll
for (uint32_t i = 0; i < 16; ++i) sum += v[i] > -INFINITY ? __expf(v[i] - m) : 0.f;
for (int o = warpSize / 2; o > 0; o >>= 1) sum += __shfl_xor(sum, o);
for (uint32_t j = 0; j < k; ++j) {
float bv = -INFINITY;
int bi = -1;
#pragma unroll
for (int i = 0; i < 16; ++i)
if (v[i] > bv) { bv = v[i]; bi = i; }
const int be = bi >= 0 ? (int)(lane + (uint32_t)bi * warpSize) : 0x7fffffff;
float rv = bv;
int re = be;
for (int o = warpSize / 2; o > 0; o >>= 1) {
const float ov = __shfl_xor(rv, o);
const int oe = __shfl_xor(re, o);
if (ov > rv || (ov == rv && oe < re)) { rv = ov; re = oe; }
}
if (lane == 0) {
s_e[j * rows + r] = re;
s_pr[j * rows + r] = __expf(rv - m) / sum;
}
#pragma unroll
for (int i = 0; i < 16; ++i)
if (i == bi && re == be) v[i] = -INFINITY;
}
}
__syncthreads();
const uint32_t nc = rows * k;
for (uint32_t o = tid; o < nc; o += blockDim.x) {
const int e = s_e[o];
s_pool[o] = -1;
s_p[o] = 0;
if (e >= 0 && (uint32_t)e < ne) {
void** ent = map[(size_t)e * rad::kXpParts];
if (ent) {
const uint64_t p = (uint64_t)*(void* volatile*)ent;
s_p[o] = p;
int pi = -1;
for (int i = 0; i < pools.n; ++i)
if (p >= pools.lo[i] && p < pools.hi[i]) { pi = i; break; }
/* Every entry of the unit in the same pool slot: the mover patches a layer's tables
* one at a time, and a unit caught between two of its patches is left alone. */
if (pi >= 0) {
const uint64_t lo = pools.lo[pi], st = pools.stride[pi];
const uint64_t base = lo + ((p - lo) / st) * st;
for (int q = 1; q < rad::kXpParts && pi >= 0; ++q) {
void** eq = map[(size_t)e * rad::kXpParts + q];
if (!eq) continue;
const uint64_t v = (uint64_t)*(void* volatile*)eq;
if (v < base || v >= base + st) pi = -1;
}
}
s_pool[o] = pi;
}
}
}
__syncthreads();
/* The first occurrence of an expert carries its highest probability; the rest drop out. */
for (uint32_t o = tid; o < nc; o += blockDim.x) {
const int e = s_e[o];
float best = s_pr[o];
bool first = true;
for (uint32_t u = 0; u < nc; ++u)
if (s_e[u] == e) {
if (u < o) first = false;
best = fmaxf(best, s_pr[u]);
}
/* The previous pass routed it here: the counts row still holds that pass until this layer's
* router runs. */
if (first && cnt && place && e >= 0 && (uint32_t)e < ne) {
const int pl = place[e];
if (pl >= 0 && cnt[pl] > 0) best *= 1.f + kXpPrevBoost;
}
s_sc[o] = (first && s_pool[o] >= 0) ? best : -1.f;
}
if (tid == 0) s_n = 0;
__syncthreads();
for (uint32_t o = tid; o < nc; o += blockDim.x) {
const float sc = s_sc[o];
if (sc < 0.f) continue;
uint32_t rank = 0;
for (uint32_t u = 0; u < nc; ++u) {
const float su = s_sc[u];
if (su > sc || (su == sc && u < o)) ++rank;
}
if (rank < (uint32_t)rad::kXpSlots) { s_sel[rank] = (int)o; atomicAdd(&s_n, 1); }
}
__syncthreads();
const int n = s_n;
for (int t = (int)tid; t < n * rad::kXpParts; t += (int)blockDim.x) {
const int j = t / rad::kXpParts, q = t % rad::kXpParts, o = s_sel[j], e = s_e[o], pi = s_pool[o];
const uint64_t lo = pools.lo[pi], st = pools.stride[pi];
const uint64_t base = lo + ((s_p[o] - lo) / st) * st;
const uint64_t dst = ring + (uint64_t)j * rs;
if (q == 0) {
/* System-scope stores write through to host memory themselves, so the tag needs only their
* completion, not a writeback of the whole L2 -- which would take the compute stream's dirty
* lines with it, every layer. */
__hip_atomic_store(&box->jobs[j].src, base, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM);
__hip_atomic_store(&box->jobs[j].dst, dst, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM);
__hip_atomic_store(&box->jobs[j].bytes, st, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM);
rec[j].cnt = cnt;
rec[j].place = place ? place[e] : -1;
}
void** ent = map[(size_t)e * rad::kXpParts + q];
rec[j].ent[q] = ent;
if (ent) {
const uint64_t old = (uint64_t)*(void* volatile*)ent;
rec[j].oldv[q] = (void*)old;
rec[j].newv[q] = (void*)(dst + (old - base));
}
/* The tag after the job's own stores have completed: a tag the host sees vouches for them. */
if (q == 0) {
__builtin_amdgcn_fence(__ATOMIC_RELEASE, "agent");
__hip_atomic_store(&box->jobs[j].tag, (uint64_t)seq, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM);
}
}
__syncthreads();
if (tid == 0) {
*nrec = n;
__hip_atomic_store(&box->n, n, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM);
atomicAdd(&stats->planned, (unsigned)n);
__builtin_amdgcn_fence(__ATOMIC_RELEASE, "agent");
__hip_atomic_store((uint32_t*)&box->seq, seq, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM);
}
}
/* On the compute stream ahead of a layer's routed GEMMs. The previous layer's patches go back -- its
* GEMMs are behind this in the stream -- then this layer's units point at the ring, only where an entry
* still holds what the plan read (a heat-engine move since wins) and only if the copies have landed:
* the list's last write before its number puts the request's number in `done`. */
__global__ __launch_bounds__(128) void xp_step(const rad::XpRec* __restrict__ rrec, const int32_t* __restrict__ rn,
const rad::XpRec* __restrict__ prec, const int32_t* __restrict__ pn,
const uint32_t* done, uint32_t seq) {
const int t = (int)threadIdx.x;
if (rrec && t < *rn * rad::kXpParts) {
const rad::XpRec& r = rrec[t / rad::kXpParts];
const int q = t % rad::kXpParts;
if (r.ent[q])
atomicCAS((unsigned long long*)r.ent[q], (unsigned long long)r.newv[q], (unsigned long long)r.oldv[q]);
}
if (!prec) return;
if (__hip_atomic_load((uint32_t*)done, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM) != seq) return;
if (t >= *pn * rad::kXpParts) return;
const rad::XpRec& r = prec[t / rad::kXpParts];
const int q = t % rad::kXpParts;
if (r.ent[q])
atomicCAS((unsigned long long*)r.ent[q], (unsigned long long)r.oldv[q], (unsigned long long)r.newv[q]);
}
} // namespace
extern "C" int rad_xp_logits_launch(const uint16_t* h, const uint16_t* w, float* logits, uint32_t rows,
uint32_t n_embd, uint32_t ne, void* stream) {
if (rows == 0 || rows > (uint32_t)rad::kXpMaxRows || n_embd % 256u || n_embd > 256u * kLgJ) return -1;
hipLaunchKernelGGL(xp_logits, dim3((ne + kLgE - 1) / kLgE), dim3(256), 0, (hipStream_t)stream, h, w,
logits, rows, n_embd, ne);
return hipGetLastError() == hipSuccess ? 0 : -1;
}
extern "C" int rad_xp_plan_launch(const float* logits, uint32_t rows, uint32_t ne, uint32_t k,
void** const* map, const int32_t* place, const int32_t* cnt,
rad::XpPools pools, uint64_t ring, uint64_t ring_stride, rad::XpRec* rec,
int32_t* nrec, rad::XpBox* box, uint32_t seq, rad::XpStats* stats,
void* stream) {
if (k == 0 || k > (uint32_t)rad::kXpMaxK || ne > (uint32_t)rad::kXpMaxNe) return -1;
hipLaunchKernelGGL(xp_plan, dim3(1), dim3(256), 0, (hipStream_t)stream, logits, rows, ne, k, map, place,
cnt, pools, ring, ring_stride, rec, nrec, box, seq, stats);
return hipGetLastError() == hipSuccess ? 0 : -1;
}
extern "C" int rad_xp_step_launch(const rad::XpRec* rrec, const int32_t* rn, const rad::XpRec* prec,
const int32_t* pn, const uint32_t* done, uint32_t seq, void* stream) {
hipLaunchKernelGGL(xp_step, dim3(1), dim3(128), 0, (hipStream_t)stream, rrec, rn, prec, pn, done, seq);
return hipGetLastError() == hipSuccess ? 0 : -1;
}