Merge upstream main (v1.12 -> v1.15.1, 408 commits) into the SYCL port

Conflicts from the old m2xfp branch take upstream's version. Two libxe2 fixes the merge needs:
- rad_plugin_abi_layout: the plugin now exports the ABI layout hash the loader checks.
- gemm_nt_q_w4a16: upstream 492d33c sends bf16 activations to the w4a16 GEMM (the separate cast
  is gone); the fast kernel took only f16, so every call fell back to the exact path (decode
  ~2.5 tok/s). A bf16 activation is narrowed to f16 (round to nearest even) into a workspace first,
  the dropped cast bit for bit; decode back to ~57 tok/s on one request.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
claudeandClaude Opus 5.5 committed 2026-11-02 00:25:57 +01:00
commit 7580ec3d17
937 files changed
+285776 -8914

No files matched your search

+12 -5
View File
@@ -5,15 +5,18 @@
namespace rad {
int Arena::init(int64_t plan_bytes, int64_t scratch_bytes, int kind, int regions) {
int Arena::init(int64_t plan_bytes, int64_t scratch_bytes, int kind, int regions,
int64_t scratch_bytes1) {
release();
if (plan_bytes < 0 || scratch_bytes < 0 || regions < 1) return RAD_E_INVAL;
if (scratch_bytes1 < 0 || scratch_bytes1 > scratch_bytes) scratch_bytes1 = scratch_bytes;
/* Scratch starts on a page boundary, so a workspace gets 4 KiB alignment for at most one
* page of padding. */
const int64_t off = align_up(plan_bytes, RAD_ALIGN_UNIT);
const int64_t pitch = align_up(scratch_bytes, RAD_ALIGN_UNIT);
const int64_t tail = pitch * regions;
const int64_t pitch = align_up(scratch_bytes, RAD_ALIGN_UNIT);
const int64_t pitch1 = align_up(scratch_bytes1, RAD_ALIGN_UNIT);
const int64_t tail = pitch + pitch1 * (regions - 1);
int64_t total = off + tail;
/* Never zero bytes: a null base would turn a plan bug into an anonymous segfault. */
@@ -33,6 +36,8 @@ int Arena::init(int64_t plan_bytes, int64_t scratch_bytes, int kind, int regions
scratch_off_ = off;
scratch_bytes_ = scratch_bytes;
scratch_pitch_ = pitch;
scratch_bytes1_ = regions > 1 ? scratch_bytes1 : 0;
scratch_pitch1_ = regions > 1 ? pitch1 : 0;
scratch_regions_ = regions;
return RAD_OK;
}
@@ -87,8 +92,10 @@ int64_t arena_plan_bytes(const Program& P, int64_t* dev_out, int64_t* total_out)
/* The staging region sits above every buffer, so it is a separate term. */
if (P.arena_stage_bytes > 0 && P.arena_stage_off >= 0)
dev_bytes = std::max(dev_bytes, P.arena_stage_off + P.arena_stage_bytes);
int64_t total = align_up(dev_bytes, RAD_ALIGN_UNIT) +
align_up(P.scratch_bytes, RAD_ALIGN_UNIT) * std::max<int64_t>(P.scratch_regions, 1);
const int64_t s1 = P.scratch_bytes_lane1 < 0 || P.scratch_bytes_lane1 > P.scratch_bytes
? P.scratch_bytes : P.scratch_bytes_lane1;
int64_t total = align_up(dev_bytes, RAD_ALIGN_UNIT) + align_up(P.scratch_bytes, RAD_ALIGN_UNIT) +
align_up(s1, RAD_ALIGN_UNIT) * (std::max<int64_t>(P.scratch_regions, 1) - 1);
if (total == 0) total = RAD_ALIGN_UNIT; /* Arena::init's floor, for the same reason */
if (dev_out) *dev_out = dev_bytes;
if (total_out) *total_out = total;
+13 -4
View File
@@ -25,18 +25,25 @@ public:
Arena& operator=(const Arena&) = delete;
/* `kind` is a RAD_MEM_* class: RAD_MEM_DEVICE for the device arena, RAD_MEM_HOST for the
* second arena a program with RAD_DOMAIN_HOST buffers gets. `regions` scratch regions of
* `scratch_bytes` each sit at the tail, one per lane. */
int init(int64_t plan_bytes, int64_t scratch_bytes, int kind, int regions = 1);
* second arena a program with RAD_DOMAIN_HOST buffers gets. `regions` scratch regions sit at the
* tail, one per lane: region 0 of `scratch_bytes`, the others of `scratch_bytes1` (-1: the same;
* Program::scratch_bytes_lane1). */
int init(int64_t plan_bytes, int64_t scratch_bytes, int kind, int regions = 1,
int64_t scratch_bytes1 = -1);
void release();
char* base() const { return base_; }
/* Region `r`, or region 0 when the arena holds fewer. */
void* scratch(int r = 0) const {
if (!base_) return nullptr;
return base_ + scratch_off_ + (r > 0 && r < scratch_regions_ ? r * scratch_pitch_ : 0);
return base_ + scratch_off_ +
(r > 0 && r < scratch_regions_ ? scratch_pitch_ + (r - 1) * scratch_pitch1_ : 0);
}
/* Region 0's size (the program's largest kernel), or region `r`'s. */
int64_t scratch_bytes() const { return scratch_bytes_; }
int64_t scratch_bytes(int r) const {
return r > 0 && r < scratch_regions_ ? scratch_bytes1_ : scratch_bytes_;
}
int scratch_regions() const { return scratch_regions_; }
int64_t bytes() const { return bytes_; }
bool live() const { return base_ != nullptr; }
@@ -48,6 +55,8 @@ private:
int64_t scratch_off_ = 0;
int64_t scratch_bytes_ = 0;
int64_t scratch_pitch_ = 0; /* scratch_bytes_ padded to RAD_ALIGN_UNIT */
int64_t scratch_bytes1_ = 0; /* each region past 0 */
int64_t scratch_pitch1_ = 0;
int scratch_regions_ = 1;
};
+58 -9
View File
@@ -3,6 +3,8 @@
*/
#include <vector>
#include "ctx.h"
#include "kvstream/bind.h"
#include "kvstream/stage.h"
#include "xp_state.h"
#include "../device/device.h"
@@ -153,13 +155,20 @@ int Ctx::bind_arena() {
int64_t dev_bytes = 0, total = 0;
arena_plan_bytes(P, &dev_bytes, &total);
RAD_TRY(arena_.init(dev_bytes, P.scratch_bytes, RAD_MEM_DEVICE, std::max(P.scratch_regions, 1)));
RAD_TRY(arena_.init(dev_bytes, P.scratch_bytes, RAD_MEM_DEVICE, std::max(P.scratch_regions, 1),
P.scratch_bytes_lane1));
/* The arena is in no pool and scales with max_tok, so core/mem/vram_budget.cpp charges it by
* name rather than leaving it to --gpu-headroom-mib. This log line must agree with that
* charge. */
RAD_INFO("arena: %s device + %d x %s scratch = %s, charged to the VRAM budget before it was "
"split", humanb(dev_bytes).c_str(), arena_.scratch_regions(),
humanb(P.scratch_bytes).c_str(), humanb(total).c_str());
if (arena_.scratch_regions() > 1)
RAD_INFO("arena: %s device + %s scratch + %s for the second lane = %s, charged to the VRAM "
"budget before it was split", humanb(dev_bytes).c_str(),
humanb(P.scratch_bytes).c_str(), humanb(arena_.scratch_bytes(1)).c_str(),
humanb(total).c_str());
else
RAD_INFO("arena: %s device + %s scratch = %s, charged to the VRAM budget before it was "
"split", humanb(dev_bytes).c_str(), humanb(P.scratch_bytes).c_str(),
humanb(total).c_str());
if (host_hw > 0) {
/* RAD_MEM_HOST_MAPPED, not RAD_MEM_HOST: nothing copies between the two arenas, so device
@@ -320,10 +329,20 @@ 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;
p.n_opd_required = -1;
if (oi.schema) {
/* One past the last required operand: an issue may leave out the optional ones after
* it. */
for (int o = 0; o < oi.schema->n_operands; ++o)
if (!oi.schema->operands[o].optional) p.n_opd_required = o + 1;
if (p.n_opd_required < 0) p.n_opd_required = 0;
}
/* Matched by name once here, not on the issue path; see OpPlan::billed. */
p.billed = (oi.op == "all_reduce");
p.collective = p.billed;
p.lora_site = oi.lora_site;
p.order = oi.anchor > 0 && (size_t)oi.anchor < P.ops.size() ? P.ops[(size_t)oi.anchor].index
: oi.index;
for (const Band& b : oi.bands) band_table_.push_back(b.hi);
@@ -754,6 +773,21 @@ const RadRouting* Ctx::last_routing(int layer) const {
return route_[(size_t)layer].reported >= 0 ? &route_[(size_t)layer].routing : nullptr;
}
const int32_t* Ctx::route_counts_device(int layer, int64_t* n_expert) const {
if (n_expert) *n_expert = 0;
if (layer < 0 || (size_t)layer >= route_.size()) return nullptr;
const RouteSlot& s = route_[(size_t)layer];
/* No step gate: route_report lands at the END of the block's passes (heat consumes it a
* step later), but the reported buffer is the block's own ecnt, whose CONTENT the router
* kernel rewrote this pass -- and the file stager's trigger runs after that router on the
* same stream, so a stream-ordered copy reads this pass's counts. The counts are indexed
* by the rank's local expert slot (the kernel subtracts expert_base), which is also what
* the mover's units carry. */
if (!s.routing.expert_count || s.reported < 0) return nullptr;
if (n_expert) *n_expert = s.routing.n_expert ? s.routing.n_expert : route_n_expert_;
return s.routing.expert_count;
}
/* ================================================================== profiling (spec §16) */
int Ctx::bind_profiling() {
@@ -899,6 +933,7 @@ int Ctx::lane_join(int from, int to) {
RAD_TRY(rad_event_record(lane_ev_[from], fs));
RAD_TRY(rad_event_wait(ts, lane_ev_[from]));
scratch_open_[from] = false; /* `to` is now behind every scratch user `from` issued */
if (from == 1 && to == 0) lane1_pending_ = false;
return RAD_OK;
}
@@ -909,15 +944,19 @@ int Ctx::lane_join(int from, int to) {
* field added to RadBatch changes its size: decide whether the key must read it, then update the
* size here. `agen_b` and `vgen_b` are set only on generator passes, which are never recorded
* (below). */
static_assert(sizeof(void*) != 8 || sizeof(RadBatch) == 360,
static_assert(sizeof(void*) != 8 || sizeof(RadBatch) == 408,
"RadBatch changed: check that Ctx::pass_key reads every new field a pass depends on");
static_assert(sizeof(void*) != 8 || sizeof(RadKVGroupBatch) == 72,
static_assert(sizeof(void*) != 8 || sizeof(RadKVGroupBatch) == 80,
"RadKVGroupBatch changed: check that Ctx::pass_key reads every new field");
uint64_t Ctx::pass_key(const RadBatch* b) const {
/* Not recordable: encoder passes are shaped by their media, and passes carrying encoder rows
* issue the scatter only when they have some. */
if (b->enc || b->n_mm_rows > 0) return 0;
/* A pass carrying a request's words for the plugin is shaped by them (a head issues per
* sequence from their counts), and such a step samples a prompt's first token, which is not
* the repeating decode pass. */
if (b->n_plugin_words > 0) return 0;
/* A generator pass is shaped by what RadBatch::gen_b, agen_b or vgen_b carries, which no key
* below reads. */
if (b->gen) return 0;
@@ -933,7 +972,7 @@ uint64_t Ctx::pass_key(const RadBatch* b) const {
mix((uint64_t)b->n_checkpoints); mix((uint64_t)b->n_seq_decode);
mix((uint64_t)b->n_tok_decode); mix((uint64_t)b->max_q_len_decode);
mix((uint64_t)b->max_q_len_prefill); mix((uint64_t)b->n_draft_out); mix((uint64_t)b->n_ahead);
mix((uint64_t)b->rope_mixed); ptr(b->rope_pos);
mix((uint64_t)b->rope_mixed); ptr(b->rope_pos); mix((uint64_t)b->score_only);
ptr(b->token_ids); ptr(b->positions); ptr(b->cu_seqlens); ptr(b->seq_ids);
ptr(b->out_ids); ptr(b->q_lens); ptr(b->ctx_lens); ptr(b->num_accepted);
ptr(b->spec_parent); ptr(b->checkpoint_tok); ptr(b->checkpoint_slot); ptr(b->draft_out_ids);
@@ -947,6 +986,8 @@ uint64_t Ctx::pass_key(const RadBatch* b) const {
mix((uint64_t)k.group); ptr(k.slot_mapping); ptr(k.block_table);
mix((uint64_t)k.block_table_pitch); ptr(k.seqused); ptr(k.state_index);
mix((uint64_t)k.state_index_pitch); mix((uint64_t)k.block_size); mix((uint64_t)k.max_blocks);
/* A streamed group's view by the memory it names, never its address (kvstream_view_key). */
mix(kvstream_view_key(k.stream));
}
mix((uint64_t)level_);
mix(dense_epoch_);
@@ -1219,6 +1260,12 @@ int Ctx::play_pass(PassTape& t) {
rc = xp_ ? xp_step_run(st.a) : RAD_OK;
lane_ = l0;
break;
case kTapeKvStage:
case kTapeKvStageAfter:
lane_ = st.lane;
rc = kvstage_run(this, st.a, st.b, st.kind == kTapeKvStageAfter);
lane_ = l0;
break;
}
if (rc < 0) {
if (step_status_ >= 0) step_status_ = rc;
@@ -1310,7 +1357,6 @@ int Ctx::run_pass(const RadBatch* b) {
}
int Ctx::run_step(const RadBatch* b) {
if (!b) return RAD_E_INVAL;
if (!arch_step_) {
RAD_WARN("Ctx::run_step: no architecture step function was installed");
@@ -1327,6 +1373,7 @@ int Ctx::run_step(const RadBatch* b) {
step_status_ = RAD_OK;
step_fail_.clear();
prof_n_ = 0;
kvstream_enter(this, b);
{
const int rc = run_pass(b);
if (rc < 0 && step_status_ >= 0) step_status_ = rc;
@@ -1364,7 +1411,9 @@ void Ctx::flush_issued() {
for (size_t r = 0; r < unflushed_.size(); ++r) {
const uint32_t i = unflushed_[r];
if (i < plans_.size() && i < program_->ops.size() && plans_[i].issued)
program_->ops[i].issued = true;
/* /graph reads this same bool from the HTTP thread: an atomic_ref store keeps that
* pair a relaxed exchange rather than a data race (ctx.h OpInfo::issued). */
std::atomic_ref<bool>(program_->ops[i].issued).store(true, std::memory_order_relaxed);
else
unflushed_[w++] = i;
}
+81 -7
View File
@@ -75,10 +75,14 @@ struct OpPlan {
int32_t band_off = 0; /* into Ctx::band_table_ */
int32_t n_bands = 0;
int32_t plan_off = 0; /* into Ctx::issue_table_, band * RAD_N_DOMAINS + domain */
/* The schema's operand count, cached so the arity check avoids a cold OpInfo. -1 when the op
* has no schema. */
int32_t n_opd_schema = -1;
bool issued = false; /* did the run phase ever issue it (spec §16's graph dump) */
/* The schema's operand count, cached so the arity check avoids a cold OpInfo, -1 when the op
* has no schema; and the count without its trailing optional operands, which an issue may
* leave out. */
int32_t n_opd_schema = -1;
int32_t n_opd_required = -1;
bool issued = false; /* did the run phase ever issue it (spec §16's graph dump);
the step path and the HTTP graph dump meet on it through
std::atomic_ref (Ctx::flush_issued, rad_graph.cpp) */
/* Whether issuing it puts bytes on the interconnect. Set at bind from the resolved rows
* (rad_kernel_collective) and the conventional all_reduce. The weight stager's copies share
* the link and give way to it while it runs (Ctx::issue_body). */
@@ -88,6 +92,9 @@ struct OpPlan {
bool billed = false;
/* Runtime LoRA: this gemm's row in Program::lora_sites, -1 for every op that is not one. */
int32_t lora_site = -1;
/* Its position in the declared order, or its anchor's for a core-appended op: what the second
* lane's window (Program::lane1_w0..lane1_w1) is checked against. */
int32_t order = 0;
};
/* ------------------------------------------------------------------ routing handoff */
@@ -138,6 +145,23 @@ struct RouteSlot {
* 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
*/
/* One of a streamed group's two views of its allocation (kvstream/bind.h). `depth` is the stripe
* count it presents: 0 for the ring's `n_layers`, 1 for the stage, where every layer aliases
* offset 0. */
struct KVViewState {
int64_t layer_stride = 0;
int64_t bytes = 0;
int64_t depth = 0; /* 0: n_layers; 1: every layer at offset 0 */
int64_t shape0 = 0; /* the operand's [blocks] extent for this view */
};
/* A byte range of one layer's row in a streamed group's mirror and stage (kvstream/stage.h,
* "Volume"): both are laid out by block id, so one range is the same offsets in either. */
struct KVStageRun {
int64_t off = 0;
int64_t bytes = 0;
};
struct KVPoolBinding {
void* base = nullptr;
int64_t layer_stride = 0; /* bytes between one layer's cache and the next */
@@ -149,8 +173,21 @@ struct KVPoolBinding {
std::vector<int32_t> layer_slot;
uint32_t rank = 0; /* 0 when the group has no plan: the operand stays a flat span */
int64_t shape[RAD_MAX_RANK] = {0};
/* The active view's stripe count, as KVViewState::depth. */
int64_t depth = 0;
/* Both views of a streamed group's allocation; the stage only when the plan's depth is 1. The
* active fields above are set from one of them before each pass (kvstream_enter). */
KVViewState ring;
KVViewState stage;
bool has_stage = false;
/* The ranges of a layer's mirror row a staged pass copies (kvstream/stage.h, "Volume"), set
* each step. Empty copies the whole row. */
std::vector<KVStageRun> stage_runs;
};
/* The KV stage's driver (kvstream/stage.cpp), declared here for Ctx::tape_kv_stage. */
int kvstage_run(Ctx* c, int group, int layer, bool after);
struct CtxDesc {
Program* program = nullptr;
int rank = 0;
@@ -210,6 +247,19 @@ public:
int rank() const { return rank_; }
/* 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. */
bool recording() const { return rec_ != nullptr; }
/* A KV stage call while recording: a host step that re-runs at every play, because its DMA
* list is not a queue packet (kvstream/stage.cpp; xprefetch.cpp does the same). */
int tape_kv_stage(bool after, int group, int layer) {
TapeStep st;
st.kind = (uint8_t)(after ? kTapeKvStageAfter : kTapeKvStage);
st.a = group;
st.b = layer;
return tape_host(st, [&] { return kvstage_run(this, group, layer, after); });
}
/* This rank's device ordinal, for the calls that name a card rather than a stream. */
int device() const { return device_; }
int world_size() const { return world_size_; }
RadStream stream() const { return stream_; }
Program* program() const { return program_; }
@@ -227,6 +277,16 @@ public:
void* weight_ptr(rad_weight w);
void* buf_ptr(rad_buf b);
/* The group-local position of model layer `layer` in the binding's layer_slot, or -1: the
* index of its host mirror row (rad_kv_layer_index). */
int64_t kv_layer_index(rad_kvgroup g, int layer) const;
/* The group's pool binding, for the view switch and the stage. */
const KVPoolBinding* kv_binding(rad_kvgroup g) const {
return g < kv_.size() ? &kv_[(size_t)g] : nullptr;
}
KVPoolBinding* kv_binding(rad_kvgroup g) {
return g < kv_.size() ? &kv_[(size_t)g] : nullptr;
}
/* ---------------------------------------------------------- routing (spec §5.5) */
int route_report(int layer, const RadRouting* r);
@@ -274,6 +334,11 @@ public:
/* Called by the drain, so the ring knows which banks are still unread. */
void mark_credited(int layer, int bank);
const RadRouting* last_routing(int layer) const;
/* The device pointer of `layer`'s expert counts for the current step, with `n_expert` set,
* or null when the layer has not reported this step (a routing-aware file stager then
* reads the layer whole). The pointer is stream-ordered behind the router: a copy on the
* compute stream at the stager's trigger sees this pass's counts. */
const int32_t* route_counts_device(int layer, int64_t* n_expert) const;
/* ---------------------------------------------------------- the placement seam */
/* Change an op's execution site. Refuses with RAD_E_NOKERNEL, naming op and band, if the
@@ -288,6 +353,8 @@ public:
void dump_profile() const; /* spec §16, opt-in, with its caveat printed */
const char* step_error() const { return step_fail_.c_str(); }
int64_t stream_waits() const { return n_stream_waits_; }
/* Lane 1 has work lane 0 has not joined (lane1_pending_). */
bool lane1_pending() const { return lane1_pending_; }
/* Host synchronisations on the step path. Always zero unless per-op timing is on (spec §16);
* tests read it. Teardown's drain is not counted. */
int64_t host_syncs() const { return n_host_syncs_; }
@@ -430,7 +497,8 @@ private:
* issue. A difference means the key misses a dependency; the step fails, naming the first
* differing dispatch. */
enum TapeKind : uint8_t { kTapePlay = 0, kTapeTable = 1, kTapeHost = 2, kTapeRoute = 3,
kTapeXp = 4, kTapeXpMark = 5, kTapeXpStep = 6 };
kTapeXp = 4, kTapeXpMark = 5, kTapeXpStep = 6,
kTapeKvStage = 7, kTapeKvStageAfter = 8 };
/* A prefetch call (Ctx::xp_predict), run again where the pass made it. */
struct TapeXp {
RadPrefetchNext next{};
@@ -546,6 +614,9 @@ public:
/* Backs rad_step_fail(): stops the step like an operand rejection, with the caller's
* message. */
int step_fail(const char* what);
/* The device kernel `h` resolved to on this rank ("?" if it resolved none). For log
* attribution only. */
const char* ip_kernel_name(rad_op h) const;
private:
[[noreturn]] void fatal_issue(rad_op h, int64_t n, const char* why) const;
@@ -572,7 +643,6 @@ private:
* byte-compares the two results, finding kernels that are not a function of their inputs,
* which a host-vs-device comparison cannot detect. */
void oracle_repeat(rad_op h, const IssuePlan& dip, int64_t seq, int n_opd);
const char* ip_kernel_name(rad_op h) const;
/* The reference library's host plan for (op, band): the band's own host plan when a reference
* library won it, else one resolved from `registry_` on first use. Null when none exists. */
const IssuePlan* oracle_reference(rad_op h, int band);
@@ -619,7 +689,8 @@ private:
* 3. The buffer planner packs from one linear order, so two lanes can alias arena bytes
* through buffers with disjoint declared lifetimes. The architecture passes every buffer
* its second lane touches to `rad_buf_concurrent`, which makes it live for the whole
* program.
* program, or, where the architecture declares the second lane's window
* (rad_lane1_window_begin / _end), across the window and its own declared uses.
*
* 4. A slice must land in the same bucket-table band as the whole, or it picks a kernel with
* a different summation order and silently changes output. `--debug-graph` prints a model's
@@ -641,6 +712,9 @@ private:
bool own_lane1_ = false;
int lane_ = 0;
RadEvent lane_ev_[2] = { nullptr, nullptr };
/* An op was issued on lane 1 since lane 1 was last joined into lane 0; lane 0 joins it before
* an op outside the second lane's window (Ctx::issue_body). */
bool lane1_pending_ = false;
/* The last device op on each lane that touched host-domain memory. A host op runs at issue on
* this thread and must be ordered behind every earlier device op that touched the host arena;
* on each lane those complete no later than the last one. So a device op with a host-domain
+68 -11
View File
@@ -19,6 +19,7 @@
#include <cstdlib>
#include "ctx.h"
#include "device/device.h"
#include "kvstream/bind.h"
#include "wtab.h"
#include <cstring>
@@ -592,6 +593,29 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
? "has no host kernel for this band, and the placement planner put "
"it on the host anyway"
: "has no device kernel for this band");
/* The second lane's window (rad_lane1_window_begin): its concurrent buffers are live only across
* it, so lane 1 runs nothing outside it, and lane 0 joins lane 1 before it runs an op outside
* it, on either side: a transient of such an op may share bytes with a concurrent buffer. An op
* that names no buffer (prefetch_beside's weight read) touches nothing the window keeps live,
* so it may run on lane 1 anywhere. */
bool names_buf = false;
for (int i = 0; i < n_opd && !names_buf; ++i) names_buf = opd[i].kind == RAD_OPK_BUF;
if (program_ && program_->lane1_w1 >= 0 && names_buf) {
const bool outside = p.order < program_->lane1_w0 || p.order > program_->lane1_w1;
if (lane_ == 1 && outside)
return abort_step_msg(h, RAD_E_STATE,
fmt("issued on the second lane outside its declared window (ops "
"%d..%d, this one %d): the buffers it may touch there are "
"live only across the window",
(int)program_->lane1_w0, (int)program_->lane1_w1, (int)p.order));
if (lane_ == 0 && lane1_pending_ && outside) {
const int js = lane_join(1, 0);
if (js < 0)
return abort_step_msg(h, js, "joining the second lane outside its window failed");
}
}
if (lane_ == 1 && names_buf) lane1_pending_ = true;
/* The row's DIV on the ranged parameter held at the band's upper bound, maybe not here. */
if (ip.ranged_div > 1 && n % ip.ranged_div != 0)
return abort_step_msg(h, RAD_E_SHAPE,
@@ -603,13 +627,23 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
return abort_step_msg(h, RAD_E_INVAL,
fmt("issued with %d operands; the runtime carries at most %d",
n_opd, MAX_OPERANDS));
if (p.n_opd_schema >= 0 && n_opd != p.n_opd_schema)
/* A count below the schema is legal only when every dropped slot is a *trailing optional*
* operand (rad_abi.h: "an absent optional operand is a null RadTensor.data" -- the shims
* branch on exactly that: r4d_opt(), rad_args_have(), libref's finish()). A count below the
* required floor shifts positions or drops a required operand, and operands are positional,
* so a miscount is silent numerical garbage. */
if (p.n_opd_schema >= 0 && (n_opd > p.n_opd_schema || n_opd < p.n_opd_required))
return abort_step_msg(h, RAD_E_SCHEMA,
fmt("issued with %d operands; the op's schema declares %d. Operands "
"are positional, so a miscount is silent numerical garbage",
n_opd, (int)p.n_opd_schema));
fmt("issued with %d operands; the op's schema declares %d "
"(%d required, only trailing optional operands may be omitted). "
"Operands are positional, so a miscount is silent numerical "
"garbage",
n_opd, (int)p.n_opd_schema, (int)p.n_opd_required));
RadTensor* t = tbuf_;
/* The schema slots the issue stopped short of: absent operands, null tensors rather than
* 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_ */
for (int i = 0; i < n_opd; ++i) {
@@ -783,7 +817,7 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
const int64_t layer = (o.offset >= 0 && (size_t)o.offset < b.layer_slot.size())
? b.layer_slot[(size_t)o.offset]
: -1;
const int64_t off = layer * b.layer_stride;
const int64_t off = kv_binding_offset(b, layer);
if (layer < 0 || (b.bytes && off + b.layer_stride > b.bytes))
return abort_step_msg(h, RAD_E_INVAL,
fmt("operand %d asks KV group %u for layer %lld, which is "
@@ -817,8 +851,9 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
}
}
/* The rest of RadArgs was filled in at prepare; args.t already points at tbuf_. */
ip.args.n_t = n_opd;
/* The rest of RadArgs was filled in at prepare; args.t already points at tbuf_. There is one
* 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);
p.issued = true;
++n_issues_;
@@ -833,7 +868,7 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
/* The oracle snapshots every operand before the launch, so the host kernel sees the same
* input bytes even for an in-place op. */
const IssuePlan* horacle = oracle_ ? oracle_before(h, b, n_opd) : nullptr;
const IssuePlan* horacle = oracle_ ? oracle_before(h, b, ip.args.n_t) : nullptr;
/* ============================== a host launch is a join ==============================
*
@@ -874,7 +909,18 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
* correctness. That also covers lane 0 before lane 1 exists, since a lane built later has
* nothing ordering it behind lane 0's earlier work. */
if (ip.args.scratch_bytes > 0 && dom != RAD_DOMAIN_HOST && arena_.scratch_regions() > 1) {
/* Per-lane regions: nothing to order. */
/* Per-lane regions: nothing to order. Region 1 holds what an op the second lane may issue
* asked for at declare (Program::scratch_bytes_lane1); a larger request there comes from an
* op with a transient buffer outside rad_buf_concurrent, which breaks Ctx::lane1_'s rule 3
* in its buffers too, so it is refused by name rather than let overrun the region. */
if (ip.args.scratch_bytes > arena_.scratch_bytes(lane_)) {
return abort_step_msg(h, RAD_E_SCRATCH,
fmt("kernel %s at n=%lld asks for %lld bytes of scratch on lane %d, whose region "
"holds %lld: an op on the second lane may touch only buffers named to "
"rad_buf_concurrent (Ctx::lane1_ rule 3)",
ip.row && ip.row->info ? ip.row->info->name : "?", (long long)n,
(long long)ip.args.scratch_bytes, lane_, (long long)arena_.scratch_bytes(lane_)));
}
ip.args.scratch = scratch_take(lane_, ip.args.scratch_bytes);
} else if (ip.args.scratch_bytes > 0 && dom != RAD_DOMAIN_HOST) {
ip.args.scratch = scratch_take(0, ip.args.scratch_bytes);
@@ -1039,7 +1085,7 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
if (er < 0) return abort_step(h, b, dom, ip, n, er);
host_touch_pending_[l] = true;
}
if (horacle) oracle_after(h, *horacle, ip, n_opd);
if (horacle) oracle_after(h, *horacle, ip, ip.args.n_t);
return RAD_OK;
}
@@ -1048,7 +1094,7 @@ void* Ctx::scratch_take(int region, int64_t bytes) {
constexpr int64_t kAlign = 256;
const int64_t need = (bytes + kAlign - 1) / kAlign * kAlign;
int64_t off = scratch_cur_[region];
if (off + need > arena_.scratch_bytes()) off = 0;
if (off + need > arena_.scratch_bytes(region)) off = 0;
scratch_cur_[region] = off + need;
return (char*)arena_.scratch(region) + off;
}
@@ -1221,6 +1267,17 @@ int rad_step_fail(RadCtx* c, const char* what) {
}
const RadBatch* rad_batch(RadCtx* c) { return c ? static_cast<rad::Ctx*>(c)->batch() : nullptr; }
int64_t rad::Ctx::kv_layer_index(rad_kvgroup g, int layer) const {
if (g >= kv_.size() || !kv_[g].base || layer < 0) return -1;
const std::vector<int32_t>& ls = kv_[g].layer_slot;
if ((size_t)layer >= ls.size()) return -1;
return ls[(size_t)layer];
}
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_world_size(RadCtx* c) { return c ? static_cast<rad::Ctx*>(c)->world_size() : 1; }
RadStream rad_stream(RadCtx* c) { return c ? static_cast<rad::Ctx*>(c)->stream() : nullptr; }
+5 -1
View File
@@ -1,6 +1,7 @@
/* kvbind.cpp -- see kvbind.h. */
#include "kvbind.h"
#include "kvstream/bind.h"
#include "mem/kv.h"
namespace rad {
@@ -12,6 +13,7 @@ void bind_kv_pools(const Program& p, const std::function<const KVGroupPlan*(int3
const KVGroupPlan* gp = plan_of((int32_t)g);
if (!gp) continue;
KVPoolBinding& b = (*out)[g];
/* A paged group's are then set from its active view by kv_bind_views. */
b.base = gp->base;
b.layer_stride = gp->layer_stride();
b.bytes = gp->pool_bytes;
@@ -34,10 +36,12 @@ void bind_kv_pools(const Program& p, const std::function<const KVGroupPlan*(int3
case RAD_KV_WINDOW:
case RAD_KV_RING:
b.rank = 4;
b.shape[0] = gp->n_blocks;
/* Set again per view by kv_bind_views. */
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;
kv_bind_views(*gp, &b);
break;
case RAD_KV_LINEAR:
b.rank = 4;
+1 -1
View File
@@ -385,7 +385,7 @@ bool Ctx::oracle_unrelayout(rad_op h, const IssuePlan& hip, const IssuePlan& dip
w.layout_tag.c_str(), ki->unrelayout ? "RadShapeFn" : "RadUnrelayoutFn");
return false;
}
if (!o.tab[i] && hk && !w.widen) {
if (!o.tab[i] && hk && !w.widen && !w.narrow) {
RadTensor pt[RAD_ENC_MAX_PLANES];
weight_planes(w, pt);
RadLayout hl{};
+19 -5
View File
@@ -31,12 +31,14 @@ int TierExec::configure(Registry* reg, KVManager* kv, IdleTiers* tiers,
for (int32_t g : groups) {
const KVGroupPlan* p = kv->plan(g);
if (!p || !p->paged()) continue;
/* A streamed group's host mirror is its tier (docs/KV-STREAMING.md §4.1). */
if (p->streamed()) continue;
GroupInfo gi;
gi.g = g;
gi.n_layers = p->n_layers;
gi.frag = p->layer_bytes_per_block();
gi.layer_stride = p->layer_stride();
gi.n_blocks = p->n_blocks;
gi.n_blocks = p->pool_blocks();
gi.base = p->base;
gi.replicated = p->replicated;
if (p->zero) {
@@ -85,11 +87,20 @@ int TierExec::configure(Registry* reg, KVManager* kv, IdleTiers* tiers,
verify_ = std::getenv("RADIANCE_DEBUG_TIER_VERIFY") != nullptr;
verify_rep_ = verify_ && !leader_ && rep_bytes_ > 0;
/* A group whose blocks are shorter than an entry is listed once per block it holds there. */
size_t n_groups = 0;
for (size_t i = 0; i < gi_.size(); ++i) {
bool seen = false;
for (size_t j = 0; j < i && !seen; ++j) seen = gi_[j].g == gi_[i].g;
if (!seen) ++n_groups;
}
const std::string blocks =
n_groups != gi_.size() ? fmt(" in %zu blocks", gi_.size()) : std::string();
char buf[400];
std::snprintf(buf, sizeof buf,
"kv tier transfer: %zu paged group(s), %s an entry%s%s%s, batches of %d through "
"gather_rows/scatter_rows at u8",
gi_.size(), humanb(entry_bytes_).c_str(),
"kv tier transfer: %zu paged group(s), %s an entry%s%s%s%s, batches of %d "
"through gather_rows/scatter_rows at u8",
n_groups, humanb(entry_bytes_).c_str(), blocks.c_str(),
rep_bytes_ > 0 ? " (" : "",
rep_bytes_ > 0 ? humanb(rep_bytes_).c_str() : "",
rep_bytes_ > 0 ? " of it replicated on every rank and held once a slot)" : "",
@@ -109,6 +120,8 @@ int TierExec::slot_layout(const std::vector<const KVManager*>& ranks,
for (int32_t g : groups) {
const KVGroupPlan* p0 = ranks[0]->plan(g);
if (!p0 || !p0->paged()) continue;
/* Skipped as in configure(), so the slot layout and the gather offsets agree. */
if (p0->streamed()) continue;
bool replicated = false;
for (size_t i = 0; i < ranks.size(); ++i) {
const KVGroupPlan* p = ranks[i]->plan(g);
@@ -139,7 +152,8 @@ int TierExec::slot_layout(const std::vector<const KVManager*>& ranks,
return RAD_E_STATE;
}
L.rep_bytes += p0->bytes_per_block;
L.replicated.push_back(p0->name);
if (std::find(L.replicated.begin(), L.replicated.end(), p0->name) == L.replicated.end())
L.replicated.push_back(p0->name);
}
int64_t slot = L.rep_bytes;
for (size_t i = 0; i < ranks.size(); ++i) {
+3 -2
View File
@@ -46,8 +46,9 @@ namespace rad {
class TierExec {
public:
~TierExec();
/* `groups` is PrefixCache::cached_groups(): the paged groups an entry holds a block in, in the
* order of the entry's `blocks` vector. The staging layout is derived from them here only.
/* `groups` is PrefixCache::entry_groups(): the group of each block an entry holds, in the
* order of the entry's `blocks` vector (a group with blocks shorter than the entry is listed
* once per block). The staging layout is derived from them here only.
* `max_batch` is the staging buffer in entries, `max_copy` the most entries per copy out and
* `max_chain` the longest restore chain; the index buffers are sized from the last two. */
int configure(Registry* reg, KVManager* kv, IdleTiers* tiers,
+1 -1
View File
@@ -202,7 +202,7 @@ void Ctx::xp_serve(XpState& x) {
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) {
if (rad_xp_list(x.device, r.mark, n, src, dst, bytes, x.done + r.g, r.seq, 0) == RAD_OK) {
++x.lists;
if (r.mark) x.marks.emplace_back(r.mark, x.lists);
} else {