Merge upstream main (v1.17.0 -> v2.1.0) into the SYCL port

102 upstream commits. Nine conflicts resolved. Fork side of the merge:
- libxe2: declare the givens_dense_quant schema (upstream 2.0 dropped it
  from libavx and libref; the device libraries now each carry it).
- plain_norm becomes an ABI 42 append to RadBuildCtx; abi layout table
  regenerated, kTableAbi = 42.

Known before the PR: arch_test (MTP lint and pinned graph hashes for
qwen35_fp8, qwen35moe_fp8, qwen4exp with MTP).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
aneinanderandClaude Opus 5.5 committed 2026-11-18 15:06:17 +01:00
commit 4b70a96378
850 files changed
+157819 -58519

No files matched your search

+44 -4
View File
@@ -24,6 +24,7 @@ int Ctx::init(const CtxDesc& d) {
if (!d.program) return RAD_E_INVAL;
program_ = d.program;
rank_ = d.rank;
slot_ = d.slot >= 0 ? d.slot : d.rank;
world_size_= d.world_size < 1 ? 1 : d.world_size;
device_ = d.device;
record_passes_ = d.record_passes;
@@ -80,7 +81,8 @@ void Ctx::shutdown() {
route_.clear();
if (route_pool_) { rad_dev_free(route_pool_, RAD_MEM_HOST_PINNED); route_pool_ = nullptr; }
if (route_dev_) { rad_dev_free(route_dev_, RAD_MEM_DEVICE); route_dev_ = nullptr; }
if (route_dev_ && !route_dev_arena_) rad_dev_free(route_dev_, RAD_MEM_DEVICE);
route_dev_ = nullptr;
/* After the syncs: the device half is a grouped GEMM operand, the host half a copy source. */
free_weight_tables();
@@ -197,11 +199,19 @@ int Ctx::bind_arena() {
return RAD_OK;
}
void Ctx::refresh_buf_numel() {
buf_numel_.assign(buf_tmpl_.size(), 0);
for (size_t i = 1; i < buf_tmpl_.size(); ++i)
buf_numel_[i] = rad_tensor_numel(&buf_tmpl_[i]);
}
int Ctx::bind_buffers() {
Program& P = *program_;
buf_tmpl_.assign(P.buffers.size(), RadTensor{});
buf_bits_.assign(P.buffers.size(), 0);
buf_host_.assign(P.buffers.size(), 0);
buf_live0_.assign(P.buffers.size(), -1);
buf_live1_.assign(P.buffers.size(), -1);
for (size_t i = 1; i < P.buffers.size(); ++i) {
BufferInfo& bi = P.buffers[i];
@@ -231,9 +241,12 @@ int Ctx::bind_buffers() {
bi.ptr = t.data;
buf_bits_[i] = rad_dtype_bits(bi.decl.dtype);
buf_host_[i] = bi.decl.domain == RAD_DOMAIN_HOST ? 1 : 0;
buf_live0_[i] = bi.first_def;
buf_live1_[i] = bi.last_use;
}
level_tmpl_.assign(1, buf_tmpl_);
level_ = 0;
refresh_buf_numel();
return RAD_OK;
}
@@ -275,6 +288,7 @@ int Ctx::set_level(int level) {
if (level == level_) return RAD_OK;
buf_tmpl_ = level_tmpl_[(size_t)level];
level_ = level;
refresh_buf_numel(); /* a level's transient extents differ from level 0's */
return RAD_OK;
}
@@ -284,6 +298,7 @@ int Ctx::bind_weights() {
Program& P = *program_;
w_tmpl_.assign(P.weights.size(), RadTensor{});
w_bits_.assign(P.weights.size(), 0);
w_numel_.assign(P.weights.size(), 0);
for (auto& g : waited_gen_) g.assign(P.weights.size(), UINT32_MAX);
w_direct_.assign(P.weights.size(), 0);
@@ -304,6 +319,7 @@ int Ctx::bind_weights() {
rad_tensor_pack(&t);
t.data = wi.ptr;
w_bits_[i] = rad_dtype_bits(t.dtype);
w_numel_[i] = rad_tensor_numel(&t);
}
return RAD_OK;
}
@@ -566,19 +582,34 @@ int Ctx::bind_routing() {
*
* The card rows are not banked: reports and the end-of-pass flush are both on the compute
* stream, so the next pass's reports queue behind the flush. A report's copy then targets the
* same address every step, so recorded passes replay unchanged. */
* same address every step, so recorded passes replay unchanged.
*
* The rows are the plugin's own buffer where it declared one (rad_route_table): its routers
* write them as declared operands and no report copies. */
const int64_t elems = n_layer * kRouteBanks * n_expert;
const int64_t bytes = elems * (int64_t)sizeof(int32_t);
const int64_t dbytes = n_layer * n_expert * (int64_t)sizeof(int32_t);
void* tab = nullptr;
if (P.route_table != RAD_NULL_HANDLE) {
const BufferInfo& bi = P.buffers[P.route_table];
if (bi.bytes < dbytes) {
RAD_ERR("routing: the routing table '%s' holds %s, and %lld reporting layers of %lld "
"experts need %s (rad_route_table)", bi.name.c_str(), humanb(bi.bytes).c_str(),
(long long)n_layer, (long long)n_expert, humanb(dbytes).c_str());
return RAD_E_SHAPE;
}
tab = buf_tmpl_[P.route_table].data; /* this context's, not the program's last */
}
void* p = rad_dev_alloc(bytes, RAD_MEM_HOST_PINNED);
void* d = rad_dev_alloc(dbytes, RAD_MEM_DEVICE);
void* d = tab ? tab : rad_dev_alloc(dbytes, RAD_MEM_DEVICE);
if (!p || !d) {
RAD_ERR("routing: %s of %s staging failed: %s", humanb(p ? dbytes : bytes).c_str(),
p ? "device" : "pinned", rad_dev_last_error());
if (p) rad_dev_free(p, RAD_MEM_HOST_PINNED);
if (d) rad_dev_free(d, RAD_MEM_DEVICE);
if (d && !tab) rad_dev_free(d, RAD_MEM_DEVICE);
return RAD_E_NOMEM;
}
route_dev_arena_ = tab != nullptr;
route_pool_ = static_cast<int32_t*>(p);
route_dev_ = static_cast<int32_t*>(d);
std::memset(route_pool_, 0, (size_t)elems * sizeof(int32_t));
@@ -1216,6 +1247,7 @@ bool Ctx::tapes_agree(const PassTape& a, const PassTape& b, std::string* why) {
const TapeHost& x = a.host[i];
const TapeHost& y = b.host[i];
bool same = x.h == y.h && x.launch == y.launch && x.n == y.n && x.drain == y.drain &&
x.touch[0] == y.touch[0] && x.touch[1] == y.touch[1] &&
x.args.n_t == y.args.n_t && x.args.scratch == y.args.scratch;
for (int k = 0; same && k < x.args.n_t; ++k)
same = std::memcmp(&x.t[k], &y.t[k], sizeof(RadTensor)) == 0;
@@ -1270,6 +1302,14 @@ int Ctx::play_pass(PassTape& t) {
case kTapeHost: {
TapeHost& th = t.host[(size_t)st.a];
lane_ = st.lane;
/* The join as the recording made it. The stretches played so far submitted the
* pass's device ops, their host-arena touches' event records among them, without
* passing issue(), which is where a touch is marked pending; the mark the pass was
* entered with says nothing about them. Without this a pass entered with no touch
* pending ran its host op at once, on what the previous step left in the host arena
* (a host gather on the previous step's row ids). */
host_touch_pending_[0] = host_touch_pending_[0] || th.touch[0];
host_touch_pending_[1] = host_touch_pending_[1] || th.touch[1];
rc = host_join_wait(th.drain);
if (rc >= 0) {
th.args.t = th.t;
+33 -2
View File
@@ -137,7 +137,8 @@ struct RouteSlot {
* operand that is not rank 4 (paged) or rank 3 (conv), so it never arrives as a flat span.
* Layouts, as libref/ref_ops.h defines them:
*
* FULL / WINDOW [n_blocks, n_head_kv, block_size, 2 * head_dim] K then V inside a slot
* FULL / WINDOW [n_blocks, n_head_kv, block_size, 2 * head_dim] K then V inside a slot;
* the int8 cache's last extent is 2 * head_dim + 4 (rad_kv_row_elems)
* LINEAR [n_states, n_head_kv, state_dim[0], state_dim[1]]
* CONV [n_states, n_head_kv * head_dim, conv_slots] channel-major, then time
*/
@@ -187,6 +188,7 @@ int kvstage_run(Ctx* c, int group, int layer, bool after);
struct CtxDesc {
Program* program = nullptr;
int rank = 0;
int slot = -1; /* RadBuildCtx::slot_base + rank: rad_slot(); -1 is the rank */
int world_size = 1;
int device = 0; /* the one device this rank owns */
RadStream stream = nullptr; /* null: the Ctx creates its own compute stream */
@@ -242,6 +244,7 @@ public:
/* ---------------------------------------------------------- run-phase queries */
const RadBatch* batch() const { return batch_; }
int rank() const { return rank_; }
int slot() const { return slot_; }
/* Whether repeated passes are recorded and played back (prepare() says when they are not). */
bool records_passes() const { return tape_on_; }
/* Whether the pass being issued is being recorded. */
@@ -391,6 +394,7 @@ public:
return c;
}
void* arena_base() const { return arena_.base(); }
int64_t arena_bytes() const { return arena_.bytes(); }
void* scratch() const { return arena_.scratch(); }
/* ---- the arena's levels ------------------------------------------------------------------
@@ -451,6 +455,7 @@ private:
int64_t n = 0;
void** host = nullptr;
void* dev = nullptr;
bool carved = false; /* host and dev lie in wtab_host_ and wtab_dev_ */
/* Entries' dtype, rank, shape and stride are checked against entry 0 once, at the first
* issue; they are declaration facts and cannot change. */
bool checked = false;
@@ -458,6 +463,12 @@ private:
std::vector<int32_t> pend; /* entries a residency change named since the last issue */
bool full = false; /* every entry: the templates were rebound */
};
/* The block every table declared at prepare is carved from, at the same offset in both; a
* table resolved later has arrays of its own. */
static constexpr int64_t kWtabAlign = 64;
void* wtab_host_ = nullptr;
void* wtab_dev_ = nullptr;
int64_t wtab_bytes_ = 0, wtab_used_ = 0;
/* Which tables hold a weight, as a linked list per weight: `wmemb_head_[w]` indexes `wmemb_`,
* -1 means none. Two ops may share a run, so a weight can be in several tables. */
struct WMemb { int32_t slot, entry, next; };
@@ -517,6 +528,9 @@ private:
RadTensor t[MAX_OPERANDS] = {};
int64_t n = 0;
bool drain = false; /* an operand the arena does not track: drain instead */
/* The lanes with a host-arena touch pending when the op joined: the device ops this
* pass issued before it among them, which a play submits again without passing issue(). */
bool touch[2] = { false, false };
};
struct PassTape {
uint64_t key = 0;
@@ -554,7 +568,7 @@ private:
int rec1);
int haz_mark(PassTape& t);
static constexpr size_t kTapes = 24; /* recorded passes kept, least recently used out */
static constexpr size_t kTapes = 48; /* recorded passes kept, least recently used out */
static constexpr int64_t kAuditPlays = 1024;
std::vector<PassTape> tapes_;
@@ -594,6 +608,12 @@ private:
std::vector<WeightTable> wtabs_;
std::unordered_map<uint64_t, size_t> wtab_of_;
/* A direct-mapped slot cache in front of wtab_of_: a WTAB operand's (op, operand) key
* repeats every step, and the map lookup was paid per issue. An entry counts only on a full
* key match (key 0 is empty: op handles start at 1, so a real key is >= 2^32); a miss falls
* back to the map and refills the entry. Slots are wtabs_ indices, stable as it grows. */
struct WtabSlotCache { uint64_t key = 0; size_t slot = 0; };
WtabSlotCache wtab_cache_[256] = {};
/* Resolves the run, refreshes the table if it moved, and fills `out` with the tensor the
* kernel sees: entry 0's dtype and trailing extents, `shape[0]` = n, `stride[0]` = 0.
@@ -670,6 +690,7 @@ private:
int xp_step_run(int layer);
int rank_ = 0;
int slot_ = 0;
int world_size_ = 1;
int device_ = 0;
RadStream stream_ = nullptr;
@@ -755,6 +776,14 @@ private:
std::vector<RadTensor> buf_tmpl_;
std::vector<int32_t> buf_bits_;
std::vector<uint8_t> buf_host_; /* per handle: a RAD_DOMAIN_HOST buffer */
/* Per-handle element counts and planned lifetimes, snapshotted at bind (the builder writes
* first_def/last_use during planning only) so an issue's fit and lifetime checks read two
* compact arrays instead of recomputing the template's numel and chasing BufferInfo. A
* buffer's numel follows the active level's template; set_level refreshes it. */
std::vector<int64_t> buf_numel_;
std::vector<int64_t> w_numel_;
std::vector<int32_t> buf_live0_, buf_live1_; /* BufferInfo::first_def / last_use */
void refresh_buf_numel();
/* Every level's templates; `buf_tmpl_` is a copy of the active one. */
std::vector<std::vector<RadTensor>> level_tmpl_;
int level_ = 0;
@@ -788,6 +817,8 @@ private:
* route_report. */
int32_t* route_pool_ = nullptr; /* host */
int32_t* route_dev_ = nullptr; /* card */
/* The card rows are the plugin's buffer (rad_route_table), which the arena owns. */
bool route_dev_arena_ = false;
RadEvent route_done_[kRouteBanks] = {};
/* The layers this pass reported into `route_bank_`, as [lo, hi]; lo > hi when none. */
int route_bank_ = -1, route_lo_ = 1, route_hi_ = 0;
+136 -50
View File
@@ -21,6 +21,7 @@
#include "ctx.h"
#include "device/device.h"
#include "kvstream/bind.h"
#include "util/simd.h"
#include "wtab.h"
#include <cstring>
@@ -42,15 +43,17 @@ static inline void narrow_cols(const RadOperand& o, RadTensor* t) {
* `offset` + sum((extent - 1) * stride). Comparing shape[0] instead would be wrong: a [T, 2560]
* buffer read at 160 columns is legitimately T*16 rows of 160 (the PLE gather does this).
*
* An empty extent reaches nothing; the kernel's own bounds decide. */
static inline bool operand_fits(const RadTensor& t, int64_t offset, const RadTensor& decl) {
* An empty extent reaches nothing; the kernel's own bounds decide. `decl_numel` is the declared
* tensor's element count, snapshotted at bind (Ctx::buf_numel_ / w_numel_) where this used to
* recompute rad_tensor_numel(&decl) per operand per issue. */
static inline bool operand_fits(const RadTensor& t, int64_t offset, int64_t decl_numel) {
if (offset < 0) return false;
int64_t span = offset;
for (uint32_t d = 0; d < t.rank; ++d) {
if (t.shape[d] <= 0) return true;
span += (t.shape[d] - 1) * t.stride[d];
}
return span < rad_tensor_numel(&decl);
return span < decl_numel;
}
std::string tensor_shape_str(const RadTensor& t) {
@@ -84,9 +87,7 @@ static bool issue_host_span_max(const RadTensor& t, const int32_t* device, const
const std::uint64_t first = delta / sizeof(int32_t);
const std::uint64_t count = (std::uint64_t)t.shape[0];
if (first > (std::uint64_t)total || count > (std::uint64_t)total - first) return false;
int32_t maximum = host[first];
for (std::uint64_t i = 1; i < count; ++i) maximum = std::max(maximum, host[first + i]);
*out = maximum;
*out = simd::max_i32(host + first, (size_t)count);
return true;
}
@@ -99,18 +100,37 @@ static int32_t issue_kv_used_max_h(const RadBatch* b, const RadTensor* t, int n)
else if (found != value) return false;
return true;
};
/* Every candidate contributes through add(), which is order-independent (a disagreement is
* -1 either way), so the candidates are gathered cheapest first: exact seqused operands by
* pointer equality (the attention ops' shape, and the batch's precomputed maximum), then
* seqused slices, which only reach the span walk when the operand pointer falls inside a
* group's array at all. Most ops name neither and pay the pointer comparisons only. */
if (b->kv && b->kv_used_max_h) {
for (int i = 0; i < n; ++i) {
if (!t[i].data || t[i].shape[0] != b->n_seq || !issue_vector_operand(t[i])) continue;
for (int g = 0; g < b->n_kv_groups; ++g)
if (t[i].data == b->kv[g].seqused && !add(b->kv_used_max_h[g])) return -1;
}
}
if (b->kv) {
for (int i = 0; i < n; ++i) {
if (!t[i].data || !issue_vector_operand(t[i]) || t[i].shape[0] <= 0) continue;
for (int g = 0; g < b->n_kv_groups; ++g) {
const int32_t* dev = b->kv[g].seqused;
if (!dev) continue;
/* The exact case above already contributed this group's maximum, which the span
* walk over the whole array would recompute to the same value. */
if (b->kv_used_max_h && t[i].data == dev && t[i].shape[0] == b->n_seq) continue;
const std::uintptr_t p = (std::uintptr_t)t[i].data, base = (std::uintptr_t)dev;
if (p < base || p >= base + (std::uintptr_t)b->n_seq * sizeof(int32_t)) continue;
int32_t used = -1;
if (issue_host_span_max(t[i], dev, b->kv[g].seqused_h, b->n_seq, &used) &&
!add(used)) return -1;
}
}
}
for (int i = 0; i < n; ++i) {
if (!t[i].data || !issue_vector_operand(t[i]) || t[i].shape[0] <= 0) continue;
if (b->kv) for (int g = 0; g < b->n_kv_groups; ++g) {
if (b->kv_used_max_h && t[i].data == b->kv[g].seqused &&
t[i].shape[0] == b->n_seq) {
if (!add(b->kv_used_max_h[g])) return -1;
continue;
}
int32_t used = -1;
if (issue_host_span_max(t[i], b->kv[g].seqused, b->kv[g].seqused_h,
b->n_seq, &used) && !add(used)) return -1;
}
/* ArPieces' first attention uses positions[R] as its exact KV end: it is the position after
* the first query piece. This special operand is one length for one ordinary prefill seq. */
if (b->phase == RAD_PHASE_PREFILL && b->n_seq == 1 && b->n_spec == 0 &&
@@ -180,12 +200,21 @@ int Ctx::ensure_weight_table(uint64_t key, rad_weight first, int64_t n, size_t*
t.key = key;
t.first = first;
t.n = n;
t.host = (void**)rad_dev_alloc(n * (int64_t)sizeof(void*), RAD_MEM_HOST_PINNED);
t.dev = rad_dev_alloc(n * (int64_t)sizeof(void*), RAD_MEM_DEVICE);
if (!t.host || !t.dev) {
if (t.host) rad_dev_free(t.host, RAD_MEM_HOST_PINNED);
if (t.dev) rad_dev_free(t.dev, RAD_MEM_DEVICE);
return RAD_E_NOMEM;
const int64_t arr = n * (int64_t)sizeof(void*);
const int64_t take = align_up(arr, kWtabAlign);
if (wtab_used_ + take <= wtab_bytes_) {
t.host = reinterpret_cast<void**>(static_cast<char*>(wtab_host_) + wtab_used_);
t.dev = static_cast<char*>(wtab_dev_) + wtab_used_;
t.carved = true;
wtab_used_ += take;
} else {
t.host = (void**)rad_dev_alloc(arr, RAD_MEM_HOST_PINNED);
t.dev = rad_dev_alloc(arr, RAD_MEM_DEVICE);
if (!t.host || !t.dev) {
if (t.host) rad_dev_free(t.host, RAD_MEM_HOST_PINNED);
if (t.dev) rad_dev_free(t.dev, RAD_MEM_DEVICE);
return RAD_E_NOMEM;
}
}
std::memset(t.host, 0, (size_t)n * sizeof(void*));
t.pend.reserve((size_t)n);
@@ -209,6 +238,32 @@ int Ctx::ensure_weight_table(uint64_t key, rad_weight first, int64_t n, size_t*
int Ctx::bind_weight_tables() {
const Program& P = *program_;
int64_t tables = 0, bytes = 0;
/* One pinned block and one device block for all of them: a model can declare hundreds of
* small tables, and an allocation each would map hundreds of buffers, every pin taking the
* process's memory map lock. Filled by ensure_weight_table below. */
if (!wtab_host_) {
int64_t total = 0;
for (size_t oi = 1; oi < P.ops.size(); ++oi) {
const OpInfo& op = P.ops[oi];
if (!op.schema || op.weights.size() != op.weight_opd.size()) continue;
for (int p = 0; p < op.schema->n_operands; ++p) {
if (op.schema->operands[p].role != RAD_OPD_WTAB) continue;
int64_t cnt = 0;
for (int opd : op.weight_opd) cnt += opd == p;
total += align_up(cnt * (int64_t)sizeof(void*), kWtabAlign);
}
}
if (total > 0) {
wtab_host_ = rad_dev_alloc(total, RAD_MEM_HOST_PINNED);
wtab_dev_ = rad_dev_alloc(total, RAD_MEM_DEVICE);
if (!wtab_host_ || !wtab_dev_) {
RAD_ERR("weight tables: %s of pointer arrays could not be allocated",
humanb(total * 2).c_str());
return RAD_E_NOMEM;
}
wtab_bytes_ = total;
}
}
for (size_t oi = 1; oi < P.ops.size(); ++oi) {
const OpInfo& op = P.ops[oi];
if (!op.schema || op.weights.size() != op.weight_opd.size()) continue;
@@ -260,8 +315,19 @@ int Ctx::resolve_weight_table(rad_op h, int operand, rad_weight first, int64_t n
RadTensor* out) {
const uint64_t key = ((uint64_t)h << 32) | (uint32_t)operand;
size_t slot;
auto it = wtab_of_.find(key);
if (it == wtab_of_.end()) {
/* The (op, operand) pair repeats every step: the direct-mapped cache (ctx.h) answers it
* without the map. A hit still takes the first/n agreement check below. */
WtabSlotCache& ce = wtab_cache_[((key >> 32) * 131u + (uint32_t)key) & 255u];
auto it = ce.key == key ? wtab_of_.end() : wtab_of_.find(key);
if (ce.key == key) {
slot = ce.slot;
if (wtabs_[slot].first != first || wtabs_[slot].n != n)
return abort_step_msg(h, RAD_E_INVAL,
fmt("operand %d named weights [%u, +%lld) and now names "
"[%u, +%lld). A table's run is fixed by the declaration",
operand, wtabs_[slot].first, (long long)wtabs_[slot].n,
first, (long long)n));
} else if (it == wtab_of_.end()) {
/* A plugin issued a table at an operand position its declaration did not name. Legal, but
* it allocates on the step path. */
RAD_DEBUG("op %u operand %d issued a weight table of %lld entries that the declaration did "
@@ -281,6 +347,8 @@ int Ctx::resolve_weight_table(rad_op h, int operand, rad_weight first, int64_t n
operand, wtabs_[slot].first, (long long)wtabs_[slot].n,
first, (long long)n));
}
ce.key = key;
ce.slot = slot;
WeightTable& t = wtabs_[slot];
/* While recording, the refresh is host work: cut the tape and name the table, so a play
* refreshes it on this lane with whatever the mover has changed by then. */
@@ -433,11 +501,16 @@ int Ctx::weight_table_tensor(rad_op h, int operand, const WeightTable& t, const
void Ctx::free_weight_tables() {
for (WeightTable& t : wtabs_) {
if (t.carved) continue;
if (t.host) rad_dev_free(t.host, RAD_MEM_HOST_PINNED);
if (t.dev) rad_dev_free(t.dev, RAD_MEM_DEVICE);
}
wtabs_.clear();
wtab_of_.clear();
if (wtab_host_) rad_dev_free(wtab_host_, RAD_MEM_HOST_PINNED);
if (wtab_dev_) rad_dev_free(wtab_dev_, RAD_MEM_DEVICE);
wtab_host_ = wtab_dev_ = nullptr;
wtab_bytes_ = wtab_used_ = 0;
}
/* RADIANCE_DEBUG_ISSUE: host cost of the issue path, split from the launch it wraps. Kernel
@@ -706,6 +779,10 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
* stale ones, since args.n_t covers every schema slot (rad_plugin.h). */
for (int i = n_opd; i < p.n_opd_schema; ++i) t[i] = RadTensor{};
bool touches_host = false; /* a host-domain buffer among the operands; see host_touch_ev_ */
/* Where the lifetime check below judges this op. A core-appended op (runtime LoRA) is judged
* at the op it rides on: it touches that op's activation and output inside that op's issue,
* never after it. Loop-invariant, so computed once here rather than per buffer operand. */
const int32_t at_op = p.info && p.info->anchor >= 0 ? p.info->anchor : (int32_t)h;
for (int i = 0; i < n_opd; ++i) {
const RadOperand& o = opd[i];
@@ -740,8 +817,13 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
/* An operand may name fewer rows than the declaration, never more. A write past the
* end lands on whatever buffer the liveness packing placed there, which changes with
* the graph, so the corruption is silent and config-dependent (e.g. a MoE expert plane
* declared at max_tok rows but written at rows*top_k). */
if (!operand_fits(tt, o.offset, buf_tmpl_[bh]))
* declared at max_tok rows but written at rows*top_k). Only a sliced operand can
* overrun -- unsliced, tt is the template itself, whose packed span is numel-1 -- so
* whole-buffer issues skip it, as whole-weight ones do below. The numel guard keeps
* the rank-0 and empty-extent corners on the checked path, where operand_fits
* decides them as it always has. */
if ((o.offset || o.rows > 0 || o.cols > 0 || buf_numel_[bh] <= 0) &&
!operand_fits(tt, o.offset, buf_numel_[bh]))
return abort_step_msg(h, RAD_E_SHAPE,
fmt("operand %d reaches past buffer '%s': %s at offset "
"%lld, declared %s", i,
@@ -753,22 +835,18 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
* program. An op touching a declared buffer outside [first_def, last_use] may see
* bytes the arena reused for another buffer, typically because the op gained a read
* its declaration never mentioned. Refused, not warned: the failure is silent and
* depends on the plan's packing. */
{
const BufferInfo& bi = program_->buffers[bh];
/* A core-appended op (runtime LoRA) is judged at the op it rides on: it touches
* that op's activation and output inside that op's issue, never after it. */
const int32_t at = p.info && p.info->anchor >= 0 ? p.info->anchor : (int32_t)h;
if (bi.first_def >= 0 && (at < bi.first_def || at > bi.last_use))
return abort_step_msg(h, RAD_E_STATE,
fmt("operand %d names buffer '%s', which this op never "
"declared: the plan gives it ops %d..%d and this is "
"op %u, so the arena may have reused those bytes. "
"Call rad_op_reads/rad_op_writes for it at declare",
i,
bi.name.c_str(), (int)bi.first_def,
(int)bi.last_use, (unsigned)h));
}
* depends on the plan's packing. The bounds are the bind-time snapshot
* (buf_live0_/buf_live1_); the name for the refusal still comes from BufferInfo. */
if (buf_live0_[bh] >= 0 && (at_op < buf_live0_[bh] || at_op > buf_live1_[bh]))
return abort_step_msg(h, RAD_E_STATE,
fmt("operand %d names buffer '%s', which this op never "
"declared: the plan gives it ops %d..%d and this is "
"op %u, so the arena may have reused those bytes. "
"Call rad_op_reads/rad_op_writes for it at declare",
i,
program_->buffers[bh].name.c_str(),
(int)buf_live0_[bh], (int)buf_live1_[bh],
(unsigned)h));
break;
}
@@ -802,7 +880,7 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
* and yields plausible numbers. Only a sliced operand can overrun, so whole-weight
* issues skip it. */
if ((o.offset || o.rows > 0 || o.cols > 0) &&
!operand_fits(tt, o.offset, w_tmpl_[wh]))
!operand_fits(tt, o.offset, w_numel_[wh]))
return abort_step_msg(h, RAD_E_SHAPE,
fmt("operand %d reaches past weight '%s': %s at offset "
"%lld, declared %s", i,
@@ -916,13 +994,13 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
* entry per schema operand, the trailing optional ones the issue left out null. */
ip.args.n_t = std::max(n_opd, (int)p.n_opd_schema);
ip.args.kv_used_max_h = issue_kv_used_max_h(batch_, t, ip.args.n_t);
/* A plugin with no pass-key callback has its decode, verify and draft passes recorded
* (pass_key), and a played pass keeps the arguments it was recorded with, so a launch there
* must not read a bound the key does not: it gets the step's context bound plus its longest
* query, both keyed, which crosses a bucket every 1024 tokens or more (batch.cpp) instead of
* moving with every token. Its prefill and mixed passes are never recorded and keep the
* exact maximum. */
if (ip.args.kv_used_max_h > 0 && !arch_pass_key_ && batch_ &&
/* Decode, verify and draft passes are recorded (pass_key), and a played pass keeps the
* arguments it was recorded with, so a launch there must not read a bound the key does not:
* it gets the step's context bound plus its longest query, both keyed, which crosses a bucket
* every 1024 tokens or more (batch.cpp) instead of moving with every token. Prefill and mixed
* passes keep the exact maximum; they are recorded only under an architecture key that holds
* the split it gives. */
if (ip.args.kv_used_max_h > 0 && batch_ &&
batch_->phase != RAD_PHASE_PREFILL && batch_->phase != RAD_PHASE_MIXED)
ip.args.kv_used_max_h = (int32_t)std::min<int64_t>(
INT32_MAX, (int64_t)batch_->max_ctx_len + batch_->max_q_len);
@@ -957,6 +1035,7 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
*
* The device caches host-arena memory, so rad_dev_host_wrote after the launch makes the
* host's writes visible to later kernels. */
const bool touch0[2] = { host_touch_pending_[0], host_touch_pending_[1] };
if (dom == RAD_DOMAIN_HOST) {
/* Timed apart from the op: it is the cost of stopping the pipeline. */
if (profiling_) {
@@ -1027,6 +1106,8 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
th.args = ip.args;
th.n = n;
th.drain = host_join_drains(opd, n_opd);
th.touch[0] = touch0[0];
th.touch[1] = touch0[1];
for (int i = 0; i < n_opd; ++i) th.t[i] = t[i];
TapeStep st;
st.kind = kTapeHost;
@@ -1056,6 +1137,9 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
}
}
/* The backend needs to know which launches wait for another card (rad_dev_peer_launch). */
const bool peer = p.collective && dom == RAD_DOMAIN_DEVICE;
if (peer) rad_dev_peer_launch(1);
int s;
if (profiling_ && dom == RAD_DOMAIN_HOST) {
@@ -1134,6 +1218,7 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
} else {
s = ip.launch(la, cur_stream());
}
if (peer) rad_dev_peer_launch(0);
if (hold) {
/* Always released, by a barrier unless the launch ended the hold itself
* (RAD_LINK_ENDED); otherwise a list waiting on the hold never ends. */
@@ -1351,6 +1436,7 @@ int rad_kv_layer_index(RadCtx* c, rad_kvgroup group, int layer) {
return c ? (int)static_cast<rad::Ctx*>(c)->kv_layer_index(group, layer) : -1;
}
int rad_rank(RadCtx* c) { return c ? static_cast<rad::Ctx*>(c)->rank() : 0; }
int rad_slot(RadCtx* c) { return c ? static_cast<rad::Ctx*>(c)->slot() : 0; }
int rad_world_size(RadCtx* c) { return c ? static_cast<rad::Ctx*>(c)->world_size() : 1; }
int rad_ctx_wgp_count(RadCtx* c) {
return c ? static_cast<rad::Ctx*>(c)->wgp_count() : 32;
+1 -1
View File
@@ -40,7 +40,7 @@ void bind_kv_pools(const Program& p, const std::function<const KVGroupPlan*(int3
b.shape[0] = gp->pool_blocks();
b.shape[1] = d.n_head_kv;
b.shape[2] = gp->block_size;
b.shape[3] = 2 * d.head_dim;
b.shape[3] = rad_kv_row_elems(d.dtype, d.head_dim);
kv_bind_views(*gp, &b);
break;
case RAD_KV_LINEAR:
+69 -19
View File
@@ -5,8 +5,10 @@
#include <algorithm>
#include <chrono>
#include <cpuid.h>
#include <cstring>
#include <immintrin.h>
#include <pthread.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. */
@@ -37,15 +39,69 @@ constexpr int64_t kXpBehind = 3;
/* Dispatches after a dropped request's mark before its signal may be reused; far more than the
* pass that completes it. */
constexpr int64_t kXpMarkHold = 4096;
/* Payoff. A used copy saves link time under the GEMM; an unused one costs link time the GEMMs
* wanted, and the prediction always costs a little. On Qwen3.8-Flash-Next break-even is near a
* quarter of copies used (--tp 1 used half and decode was 3.6% faster; --tp 2, where the pool holds
* rarely routed experts, used a sixth and was 4-6% slower). Every kXpWindow predictions the share
* used over the last window is judged; below kXpMinUse the prefetch rests for kXpRest passes. */
/* Payoff, on one rank (the engine opens no prefetch over several: engine_bringup.cpp). A used copy
* saves link time under the GEMM; an unused one costs link time the GEMMs wanted, and the
* prediction always costs a little. On Qwen3.8-Flash-Next at --tp 1 break-even is near a quarter
* of copies used (half were, and decode was 3.6% faster). Every kXpWindow predictions the share
* used over the last window is judged; below kXpMinUse the prefetch rests for kXpRest passes. A
* window with fewer than kXpMinJudged copies is not judged, which one sequence with few misses
* never reaches. */
constexpr int64_t kXpWindow = 2048;
constexpr double kXpMinUse = 0.30;
constexpr uint32_t kXpMinJudged = 512;
constexpr int64_t kXpRest = 8192;
/* The serving thread's waits read the clock once every this many pauses (plus one, a mask): a
* clock read is a system call on a host whose clocksource is not the TSC (HPET, ~1-2 us), which
* read on every pause kept two cores in the kernel through every wait, while a timeout of 100 ms
* or 5 s needs no finer look than ~1024 pauses (tens of microseconds). */
constexpr uint32_t kXpSpinsPerLook = 1023;
/* With MONITORX the thread sleeps until a store reaches the watched line (the plan kernel's write
* over the link invalidates it) or this many TSC cycles pass (~25 us), and reads the clock once
* every kXpNapsPerLook + 1 naps (a few ms). */
constexpr uint32_t kXpNapCycles = 100000;
constexpr uint32_t kXpNapsPerLook = 63;
/* AMD's MONITORX/MWAITX run at user level (CPUID 0x80000001 ECX bit 29). */
bool xp_have_mwaitx() {
static const bool have = [] {
unsigned a, b, c, d;
return __get_cpuid(0x80000001u, &a, &b, &c, &d) && ((c >> 29) & 1u);
}();
return have;
}
__attribute__((target("mwaitx"))) void xp_arm(const volatile void* line) {
_mm_monitorx(const_cast<void*>(line), 0, 0);
}
__attribute__((target("mwaitx"))) void xp_nap() {
_mm_mwaitx(2 /* timer on */, 0, kXpNapCycles);
}
/* Waits until done() holds, `line` being where the awaited store lands. False once `limit` passed
* or *stop was set first. A mailbox is waited on for as long as the host runs ahead of the GPU, a
* pass or more: spinning on pause kept a core busy through all of it. */
template <class Done>
bool xp_wait(const volatile void* line, Done done, std::chrono::steady_clock::duration limit,
const std::atomic<bool>* stop) {
if (done()) return true;
const auto t0 = std::chrono::steady_clock::now();
const bool nap = xp_have_mwaitx();
const uint32_t mask = nap ? kXpNapsPerLook : kXpSpinsPerLook;
for (uint32_t k = 1;; ++k) {
if (nap) {
xp_arm(line);
if (done()) return true;
xp_nap();
} else {
_mm_pause();
}
if (done()) return true;
if ((k & mask) == 0 && ((stop && stop->load(std::memory_order_relaxed)) ||
std::chrono::steady_clock::now() - t0 > limit))
return false;
}
}
} // namespace
@@ -151,6 +207,7 @@ void Ctx::xp_close() {
/* Host thread: hands each request's mailbox to the DMA queue once the plan has written it. */
void Ctx::xp_serve(XpState& x) {
pthread_setname_np(pthread_self(), "rad-xp");
for (;;) {
XpReq r;
{
@@ -169,15 +226,8 @@ void Ctx::xp_serve(XpState& x) {
/* The mailbox reaches the request number once the plan has run; a higher number means a
* later request overwrote it 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;
}
}
bool got = xp_wait(&b->seq, [&] { return (int32_t)(b->seq - r.seq) >= 0; }, std::chrono::seconds(5),
&x.stop);
if (got && b->seq != r.seq) got = false;
std::atomic_thread_fence(std::memory_order_acquire);
uint64_t src[kXpSlots], dst[kXpSlots], bytes[kXpSlots];
@@ -186,11 +236,11 @@ void Ctx::xp_serve(XpState& x) {
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; }
if (!xp_wait(&b->jobs[i].tag, [&] { return b->jobs[i].tag == r.seq; },
std::chrono::milliseconds(100), nullptr)) {
got = false;
break;
}
std::atomic_thread_fence(std::memory_order_acquire);
src[i] = b->jobs[i].src;
dst[i] = b->jobs[i].dst;