Archived
radiance 1.7.0
- every model serves without a GPU: libavx covers every op, so `--kernels libavx` alone serves every shipped container - Qwen3-ASR (zivius): speech to text on /v1/audio/transcriptions and live over /v1/realtime - /v1/messages works with Claude Code as it ships (gearwave00001) - a long agent conversation keeps its cached history when the client rewrites its last turn (manueloverride) - a stream's first event goes out with the first token, so llama-benchy measures prefill right - opt-in --prefill-interleave (Smellyyyy, baKon) and --prefill-span (keptn42) - four-rank TP releases the link early; four-rank selftests and docs/TP4.md (goodman-b) - NVFP4 and FP8 compressed-tensors imports (devmilan); tools/rad-export for finetunes and LoRA adapters (baKon) - many fixes, among them lost tokens on stop strings under concurrency, keep-alive, MiniCPM5 tool arguments and the CPU's vision and audio encoders - plugin ABI 17 and changed op schemas: out-of-tree plugins must be rebuilt
This commit is contained in:
1 parent
b068190326
commit
1e968f6e1d
739 files changed
+128447
-84632
No files matched your search
+188
-304
@@ -1,4 +1,4 @@
|
||||
/* batch.cpp -- building the step batch once. See batch.h for why.
|
||||
/* batch.cpp -- builds the step batch once per step. See batch.h.
|
||||
*/
|
||||
#include "batch.h"
|
||||
#include "mm/processor.h"
|
||||
@@ -11,35 +11,27 @@
|
||||
|
||||
namespace rad {
|
||||
|
||||
/* Staging arrays are carved out of one slab per set rather than allocated one by one: the copies
|
||||
* are still per array (each carries only the prefix this step used, and those lengths differ by an
|
||||
* order of magnitude between a decode step and a prefill chunk), but the allocator is called twice
|
||||
* at init instead of two dozen times and every array in a set shares one mapping. */
|
||||
/* Alignment of each staging array carved from a set's slab. One slab per set means a couple of
|
||||
* allocations at init instead of two dozen, with every array sharing one mapping. */
|
||||
static const int64_t k_carve_align = 256;
|
||||
|
||||
/* The longest range a build's upload names: one round of the workgroup that copies it, whose loads
|
||||
* are all in flight before its first store (rad_memcpy_ranges_async). */
|
||||
/* Longest range in a build's upload: one round of the copying workgroup, which issues all its
|
||||
* loads before its first store (rad_memcpy_ranges_async). */
|
||||
static const int64_t k_range_max = 16384;
|
||||
|
||||
/* A HOST-SIDE BOUND, ROUNDED UP ONTO A COARSE GRID: to a multiple of `min_q`, and above 64 of
|
||||
* 1/32 to 1/64 of the value's power of two if that is coarser -- so ~3% over at a long context and
|
||||
* at most `min_q` over at a short one.
|
||||
/* Rounds a host-side bound up to a multiple of `min_q`, or above 64 to 1/32..1/64 of the value's
|
||||
* power of two if that is coarser: ~3% slack at long context, at most `min_q` at short.
|
||||
*
|
||||
* `max_ctx_len` and the block-table pitch are ceilings -- a kernel reads each row's own length off
|
||||
* the card -- and they are the only arguments of a decode pass that move while a request runs:
|
||||
* attention and the QSA indexer size their grids by them. Exact, they change the pass's arguments
|
||||
* every step or two; rounded, a pass is the same dispatches with the same arguments for many steps
|
||||
* at a time, which is what lets a recorded pass be played instead of issued (see Ctx::run_step).
|
||||
* The price is grid slack that exits on its first compare, and at a short context, where the
|
||||
* floor is most of the bound, the whole attention term is small. */
|
||||
/* THE FLOOR IS 1024 TOKENS. Every crossing re-records each kind of pass a step runs, twice -- the
|
||||
* recording and the audit before its first play -- at a few hundred microseconds of a rank thread
|
||||
* each, and at a 256-token floor a short-context decode crosses often enough to spend a tenth of
|
||||
* its rank threads recording. It is not higher because a block may choose its PATH by this bound
|
||||
* and not only its grid: rad_block_attn_gated_fp8.h keeps the cheaper dense attention while the
|
||||
* bound says every sequence is inside the indexer's budget, and a floor at that budget takes the
|
||||
* dense path away from every short context -- a verify step's attention at eight sequences takes
|
||||
* 48 us a layer at 2048 instead of 15. */
|
||||
* `max_ctx_len` and the block-table pitch are ceilings (kernels read each row's length from the
|
||||
* card) and the only decode-pass arguments that move as a request runs. Rounded, a pass keeps the
|
||||
* same arguments for many steps, so a recorded pass can be replayed (Ctx::run_step); the cost is
|
||||
* grid slack that exits on its first compare.
|
||||
*
|
||||
* Floor of 1024 tokens: every crossing re-records each pass kind twice (recording plus audit), a
|
||||
* few hundred microseconds of rank thread each, which a 256 floor makes frequent at short context.
|
||||
* Not higher, because a block may pick its path by this bound: rad_block_attn_gated_fp8.h keeps
|
||||
* dense attention while every sequence is inside the indexer's budget; with a 2048 floor, a
|
||||
* verify step's attention at eight sequences costs 48 us a layer instead of 15. */
|
||||
static const int64_t k_bound_tokens = 1024;
|
||||
|
||||
static inline int64_t bound_bucket(int64_t v, int64_t min_q) {
|
||||
@@ -52,8 +44,8 @@ static inline int64_t bound_bucket(int64_t v, int64_t min_q) {
|
||||
return (v + q - 1) / q * q;
|
||||
}
|
||||
|
||||
/* A negative device status inside build() aborts the step; there is nothing to fall back to and a
|
||||
* partially staged batch is worse than no batch. */
|
||||
/* A negative device status inside build() aborts the step: there is no fallback, and a partially
|
||||
* staged batch is worse than none. */
|
||||
#define RAD_TRY_NULL(expr) \
|
||||
do { int _s = (expr); \
|
||||
if (_s < 0) { RAD_ERR("step batch: %s -> %s", #expr, rad_strerror(_s)); \
|
||||
@@ -67,14 +59,11 @@ static T* carve(char* base, int64_t& off, int64_t n) {
|
||||
return base ? reinterpret_cast<T*>(base + o) : nullptr;
|
||||
}
|
||||
|
||||
/* The full token sequence of a request is prompt ++ output ++ draft, and n_computed indexes into
|
||||
* it. One accessor for all three keeps prefill, decode, recompute-after-preemption and speculative
|
||||
* verify on the same path: a preempted request re-prefills its own generated output because that
|
||||
* is simply the tail of the same sequence, and a verify reads past the committed end into the
|
||||
* drafter's proposal. No special case anywhere. */
|
||||
/* Token i of prompt ++ output ++ draft, the sequence n_computed indexes. One accessor keeps
|
||||
* prefill, decode, recompute after preemption and speculative verify on one path. */
|
||||
static inline int32_t token_at(const StepEntry& e, int64_t i) {
|
||||
/* A placeholder entry -- a drafter context row whose request has already gone -- has no
|
||||
* tokens, and the pass it belongs to reads none. */
|
||||
/* A placeholder entry (a drafter context row whose request is gone) has no tokens, and its
|
||||
* pass reads none. */
|
||||
if (!e.req) return 0;
|
||||
const Request& r = *e.req;
|
||||
int64_t np = (int64_t)r.prompt.size();
|
||||
@@ -87,23 +76,19 @@ static inline int32_t token_at(const StepEntry& e, int64_t i) {
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ set layout */
|
||||
/* Walked with null bases to measure and with real ones to assign. Keeping both in one function is
|
||||
* what stops them drifting, which is the classic way a hand-carved slab ends up with two arrays
|
||||
* sharing bytes. Every array is carved in PAIRS, host and device at the same offset, including the
|
||||
* host-only ones: that is what lets one copy of a prefix move a whole build, and it puts the
|
||||
* block tables -- the only part whose size moves from build to build -- last. */
|
||||
/* Called with null bases to measure and with real ones to assign, so the two cannot drift. Every
|
||||
* array is carved as a host/device pair at the same offset, host-only ones included, so one copy
|
||||
* of a prefix moves a whole build. The block tables, whose size varies per build, go last. */
|
||||
void BatchBuilder::carve(Set& s, char* h) {
|
||||
char* const d = s.dev.empty() ? nullptr : static_cast<char*>(s.dev[0]);
|
||||
const int64_t T = max_tok_, S = max_seqs_;
|
||||
/* The most logit rows one step can want: one per sequence, or one per verified draft position
|
||||
* per sequence at a speculative step. It is what bounds Geom::max_logit_rows on the plugin
|
||||
* side, and the two have to agree or the plugin gathers into a buffer smaller than out_ids. */
|
||||
/* ...or one row a TOKEN, which an MTP history pass is: it gathers the trunk`s hidden state
|
||||
* for every position the step just computed, and names those rows through the same array. */
|
||||
/* Most logit rows one step can want: one per verified position per sequence, or one per
|
||||
* token for an MTP history pass. Must agree with Geom::max_logit_rows on the plugin side, or
|
||||
* the plugin gathers into a buffer smaller than out_ids. */
|
||||
int64_t O = S * (1 + (cfg_.n_spec > 0 ? (int64_t)cfg_.n_spec : 0));
|
||||
if (O < T) O = T;
|
||||
/* ...and in the KL mode a row at every token as well, after the sampled ones
|
||||
* (Request::score). RadBuildCtx::max_out_rows says the same number to the plugin. */
|
||||
/* KL mode adds a row at every token after the sampled ones (Request::score); keep in sync
|
||||
* with RadBuildCtx::max_out_rows. */
|
||||
if (cfg_.kld()) O = T + S;
|
||||
|
||||
int64_t oh = 0, od = 0;
|
||||
@@ -111,7 +96,7 @@ void BatchBuilder::carve(Set& s, char* h) {
|
||||
*ph = ::rad::carve<int32_t>(h, oh, n);
|
||||
*pd = ::rad::carve<int32_t>(d, od, n);
|
||||
};
|
||||
/* Twice the step: its own tokens, then up to a step of the prompt that follows
|
||||
/* Twice the step: its own tokens, then up to a step of the following prompt
|
||||
* (RadBatch::n_ahead). */
|
||||
pair(&s.h_tok, &s.d_tok, 2 * T);
|
||||
pair(&s.h_pos, &s.d_pos, T);
|
||||
@@ -135,14 +120,12 @@ void BatchBuilder::carve(Set& s, char* h) {
|
||||
pair(&g.h_used, &g.d_used, S);
|
||||
pair(&g.h_sidx, &g.d_sidx, S * g.sidx_pitch);
|
||||
}
|
||||
/* THE ROTARY PLANES AND THE ENCODER-ROW TARGETS, only for a program with an encoder: nothing
|
||||
* else can move a rotary position off the token index, and a text-only deployment should not
|
||||
* upload twelve bytes a token of copies of `positions` every step. */
|
||||
/* Rotary planes and encoder-row targets, only for a program with an encoder; nothing else
|
||||
* moves a rotary position off the token index. */
|
||||
pair(&s.h_rope, &s.d_rope, mm_on_ ? 3 * T : 0);
|
||||
pair(&s.h_mmrow, &s.d_mmrow, mm_on_ ? T : 0);
|
||||
/* Host-only: derived metadata is copied into the arena the buffer plan already placed. Carved
|
||||
* in the pair anyway, so the device offsets stay the host's -- a few kilobytes of slab nobody
|
||||
* reads. */
|
||||
/* Host-only (derived metadata is copied into the planned arena), but carved on both sides to
|
||||
* keep device offsets equal to host offsets. */
|
||||
{
|
||||
int32_t* unused = nullptr;
|
||||
char* hd = ::rad::carve<char>(h, oh, derived_bytes_);
|
||||
@@ -150,18 +133,14 @@ void BatchBuilder::carve(Set& s, char* h) {
|
||||
s.h_derived = hd;
|
||||
pair(&s.h_convslot, &unused, S * (int64_t)kvgeom_.g.size());
|
||||
}
|
||||
/* ---- the block tables, LAST ------------------------------------------------------------
|
||||
/* ---- the block tables, last ------------------------------------------------------------
|
||||
*
|
||||
* A group's table is carved for the worst step -- max_seqs rows of max_ctx/block_size entries
|
||||
* -- because the slab has to hold one. At a long context and a small block that is over a
|
||||
* megabyte per paged group, and a model may declare several: the tables are nearly the whole
|
||||
* slab. A build fills n_seq rows of `pitch`, THIS step's longest table, and the device reads
|
||||
* them at that pitch (block_table_pitch below).
|
||||
*
|
||||
* ON THE CARD each group's rows have a FIXED place in this region, so the rows a build leaves
|
||||
* alone are still there for the next one (BtMirror). IN THE HOST SPAN the region is the
|
||||
* build's payload and range list instead, sized by what changed: the carve's host half only
|
||||
* says where the payload starts. */
|
||||
* Each group's table is carved for the worst step (max_seqs rows of max_ctx/block_size
|
||||
* entries), nearly the whole slab at long context. A build fills n_seq rows at `pitch`, this
|
||||
* step's longest table, and the device reads them at that pitch (block_table_pitch below).
|
||||
* On the card each group's rows have a fixed place, so rows a build leaves alone persist
|
||||
* (BtMirror). In the host span this region holds the payload and range list, sized by what
|
||||
* changed; the host half of the carve only marks where the payload starts. */
|
||||
{
|
||||
int64_t bt_n = 0;
|
||||
s.bt_base = od;
|
||||
@@ -185,9 +164,8 @@ void BatchBuilder::size_set(Set& s, const std::vector<KVGroupInfo>& groups) {
|
||||
s.groups[gi].block_size = e.block_size;
|
||||
int64_t mb = 1;
|
||||
if (e.paged) {
|
||||
/* A WINDOW row holds the window behind the step's first query AND the step's own
|
||||
* tokens (KVManager::ensure keeps both), so it is sized for a whole chunk past the
|
||||
* window -- plus the speculative lookahead, which a verify row carries on top. */
|
||||
/* A window row holds the window behind the step's first query plus the step's own
|
||||
* tokens (KVManager::ensure keeps both), plus a verify row's speculative lookahead. */
|
||||
const int64_t wspan = e.window + max_tok_ + 2 * ((int64_t)std::max(cfg_.n_spec, 0) + 1);
|
||||
int64_t span = (e.kind == RAD_KV_WINDOW && e.window > 0 && wspan < max_ctx_)
|
||||
? wspan : max_ctx_;
|
||||
@@ -202,8 +180,7 @@ void BatchBuilder::size_set(Set& s, const std::vector<KVGroupInfo>& groups) {
|
||||
int BatchBuilder::alloc_set(Set& s, const std::vector<KVGroupInfo>& groups) {
|
||||
size_set(s, groups);
|
||||
|
||||
/* ONE SLAB PER RANK, on that rank's card. rad_dev_alloc has no device argument and uses the
|
||||
* current one, so the bind is part of the allocation. */
|
||||
/* One slab per rank, on its card. rad_dev_alloc uses the current device, hence the bind. */
|
||||
s.dev.assign(ranks_.size(), nullptr);
|
||||
for (size_t r = 0; r < ranks_.size(); ++r) {
|
||||
RAD_TRY(rad_dev_set(ranks_[r].device));
|
||||
@@ -216,9 +193,8 @@ int BatchBuilder::alloc_set(Set& s, const std::vector<KVGroupInfo>& groups) {
|
||||
}
|
||||
RAD_TRY(rad_dev_set(ranks_[0].device));
|
||||
|
||||
/* THE RING HOLDS THREE WORST-CASE BUILDS, which is the most a host running ahead of the card
|
||||
* can have in flight before a long-context prefill has to wait for its own upload two builds
|
||||
* back; a decode build's span is its fixed prefix and a few rows of tables, so hundreds fit. */
|
||||
/* The ring holds three worst-case builds before a long-context prefill waits on an upload two
|
||||
* builds back. A decode build's span is far smaller, so hundreds fit. */
|
||||
int64_t worst_pay = 0;
|
||||
for (const Group& g : s.groups) worst_pay += max_seqs_ * g.max_blocks * (int64_t)sizeof(int32_t);
|
||||
const int64_t worst_ranges = worst_pay / k_range_max + max_seqs_ * (int64_t)s.groups.size() + 1;
|
||||
@@ -234,8 +210,7 @@ int BatchBuilder::alloc_set(Set& s, const std::vector<KVGroupInfo>& groups) {
|
||||
ring_.first = 0;
|
||||
ring_.live = 0;
|
||||
|
||||
/* Local: the host waits on these only to know an upload has READ its span, which a card-wide
|
||||
* release says as well as a system-wide one. */
|
||||
/* Local events suffice: the host waits on them only to know an upload has read its span. */
|
||||
ev_.assign(kFlights, std::vector<RadEvent>(ranks_.size(), nullptr));
|
||||
ev_free_.clear();
|
||||
ev_free_.reserve(kFlights);
|
||||
@@ -291,10 +266,9 @@ void BatchBuilder::free_set(Set& s) {
|
||||
for (Out& o : out_) { o.kv.clear(); o.batch.clear(); }
|
||||
}
|
||||
|
||||
/* A SPAN OF THE RING, contiguous, of `need` bytes. A span that would run past the end starts over
|
||||
* at zero. Every flight overlapping the span is retired first -- its uploads have run, on every
|
||||
* rank -- oldest first, which is the order they were issued in and so the order the card
|
||||
* finishes them. */
|
||||
/* A contiguous span of `need` bytes, wrapping to zero if it would run past the end. Every flight
|
||||
* overlapping it is retired first (its uploads have run on every rank), oldest first, which is
|
||||
* issue order and so completion order. */
|
||||
int BatchBuilder::reserve(int64_t need, int64_t* off) {
|
||||
if (need > ring_.bytes) {
|
||||
RAD_ERR("step batch staging: a build of %s does not fit the %s ring",
|
||||
@@ -320,15 +294,14 @@ int BatchBuilder::reserve(int64_t need, int64_t* off) {
|
||||
if (!clash) break;
|
||||
RAD_TRY(retire_oldest());
|
||||
}
|
||||
/* And a flight needs an event row: out of rows is out of flights. */
|
||||
/* A flight also needs a free event row. */
|
||||
while (ev_free_.empty() || ring_.live == kFlights) RAD_TRY(retire_oldest());
|
||||
*off = at;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* THE SAME ARRAY ON ANOTHER RANK'S SLAB. Every slab is carved by the same walk() from the same
|
||||
* sizes, so an array's offset is rank-independent: the byte offset off rank 0's base, re-applied
|
||||
* to rank r's. */
|
||||
/* The same array on another rank's slab. Every slab has the same carve, so the byte offset from
|
||||
* rank 0's base applies to rank r's. */
|
||||
template <class T>
|
||||
static inline T* on_rank(void* base_r, void* base_0, T* p0) {
|
||||
return p0 ? (T*)((char*)base_r + ((char*)p0 - (char*)base_0)) : nullptr;
|
||||
@@ -343,8 +316,8 @@ int BatchBuilder::init(Program& prog, const Config& cfg, const ChunkGeometry& ge
|
||||
kvgeom_ = kvg;
|
||||
ranks_ = ranks;
|
||||
if (ranks_.empty()) return RAD_E_INVAL;
|
||||
/* A null stream is the default stream and is legal; a null Program is not -- a derived
|
||||
* buffer would have no arena to land in. */
|
||||
/* A null stream (the default stream) is legal; a null Program is not, since derived buffers
|
||||
* need its arena. */
|
||||
for (const RankIO& r : ranks_)
|
||||
if (!r.prog) return RAD_E_INVAL;
|
||||
RAD_TRY(layout(prog, cfg));
|
||||
@@ -353,25 +326,20 @@ int BatchBuilder::init(Program& prog, const Config& cfg, const ChunkGeometry& ge
|
||||
out_last_ = -1;
|
||||
if (mm_on_) RAD_TRY(alloc_media());
|
||||
|
||||
/* THE RESERVATION AND WHAT ACTUALLY CROSSES ARE DIFFERENT NUMBERS, so the line says both.
|
||||
* Nearly all of the slab is block-table rectangles carved for the worst step, and a step
|
||||
* copies only the rows it filled -- an operator reading the reservation alone would price
|
||||
* the per-step cost far above what it is. */
|
||||
RAD_INFO("step batch: %s pinned staging ring + %s device slab a rank, %d KV group(s), "
|
||||
"%d derived buffer(s); of the slab, %s is block tables carved for the worst step "
|
||||
"and only the filled rows cross",
|
||||
/* Report both the reservation and the block-table share of it: tables are carved for the
|
||||
* worst step, but a step uploads only the rows it filled. */
|
||||
RAD_INFO("step batch: %s pinned staging ring + %s device slab a rank (%s of it block "
|
||||
"tables), %d KV group(s), %d derived buffer(s)",
|
||||
humanb(ring_.bytes).c_str(), humanb(set_.dev_bytes).c_str(),
|
||||
(int)prog.kv_groups.size(), (int)derived_.size(),
|
||||
humanb(set_.dev_bytes - set_.bt_base).c_str());
|
||||
humanb(set_.dev_bytes - set_.bt_base).c_str(), (int)prog.kv_groups.size(),
|
||||
(int)derived_.size());
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* WHAT init() WILL ALLOCATE ON EVERY RANK'S CARD, before any of it exists: the VRAM budget is
|
||||
* resolved before the builder is, and a reservation it does not charge comes out of
|
||||
* --gpu-headroom-mib -- the room a kernel's first launch allocates from, where running out is a
|
||||
* fault inside the HIP runtime rather than an error. The slab's block tables grow with
|
||||
* --max-num-seqs and the media staging with --max-num-batched-tokens, so neither is small enough
|
||||
* to leave to the headroom. The same layout() and carve walk as init(), so the two cannot drift. */
|
||||
/* What init() will allocate on every rank's card, for the VRAM budget, which is resolved before
|
||||
* the builder. An uncharged reservation would eat --gpu-headroom-mib, where running out faults
|
||||
* inside the HIP runtime; the block tables grow with --max-num-seqs and the media staging with
|
||||
* --max-num-batched-tokens. Uses the same layout() and carve as init(). */
|
||||
int64_t BatchBuilder::device_bytes(Program& prog, const Config& cfg, const KVGeom& kvg) {
|
||||
BatchBuilder b;
|
||||
b.prog_ = &prog;
|
||||
@@ -395,17 +363,14 @@ int BatchBuilder::layout(Program& prog, const Config& cfg) {
|
||||
}
|
||||
if (kvgeom_.g.size() != prog.kv_groups.size()) return RAD_E_INVAL;
|
||||
|
||||
/* The block-table staging rectangle. A sequence never holds more blocks than its context (or
|
||||
* its window, which is the whole point of declaring one: a 4K-window layer in a 128K context
|
||||
* needs a row 32x shorter). The +1 is because a window's blocks are not aligned to the
|
||||
* window's start, so it can straddle one extra block. */
|
||||
/* Block-table rows are sized by context, or by window for a window group (size_set). The +1
|
||||
* block there is because a window is not block-aligned and can straddle one extra block. */
|
||||
max_ctx_ = cfg.max_ctx > 0 ? cfg.max_ctx : prog.meta.n_ctx_train;
|
||||
if (max_ctx_ <= 0) max_ctx_ = cfg.max_tok;
|
||||
|
||||
/* The conv rolling window: width-1 entries of history plus room for the whole speculative
|
||||
* window, and a rejection then reads back at the slot the last accepted token left (spec §10).
|
||||
* The state tensor's own extent (conv_window_entries), so the cursor derived from it stays
|
||||
* inside the slot the kernels index. */
|
||||
/* Conv rolling window: width-1 entries of history plus the whole speculative window, so a
|
||||
* rejection reads back at the slot the last accepted token left (spec §10). Taken from the
|
||||
* state tensor's extent (conv_window_entries) so the derived cursor stays inside the slot. */
|
||||
conv_window_.assign(prog.kv_groups.size(), 1);
|
||||
conv_group_ = -1;
|
||||
n_conv_ = 0;
|
||||
@@ -458,11 +423,9 @@ int BatchBuilder::layout(Program& prog, const Config& cfg) {
|
||||
d.buf = &b;
|
||||
d.off = derived_bytes_;
|
||||
|
||||
/* WHICH CONV GROUP THIS ONE IS ABOUT. `conv_state_index` is the derivation that reads a
|
||||
* rolling window, and a model may declare several of different depths -- so the buffer
|
||||
* names its group and 0 means "the only one of its kind". With more than one conv group
|
||||
* and no name the answer is a guess between two windows, and the wrong depth produces a
|
||||
* plausible cursor pointing at history the kernel never wrote. Refused instead. */
|
||||
/* `conv_state_index` reads a rolling window, and conv groups may differ in depth, so the
|
||||
* buffer names its group; 0 means the only conv group. With several conv groups and no
|
||||
* name, refuse: the wrong depth yields a cursor into history never written. */
|
||||
if (std::strcmp(d.name, "conv_state_index") == 0) {
|
||||
if (b.decl.kv != 0) {
|
||||
if (b.decl.kv >= prog.kv_groups.size() ||
|
||||
@@ -475,10 +438,9 @@ int BatchBuilder::layout(Program& prog, const Config& cfg) {
|
||||
} else if (n_conv_ == 1) {
|
||||
d.conv_grp = conv_group_;
|
||||
} else {
|
||||
RAD_ERR("derived buffer '%s' runs 'conv_state_index' and names no KV group, but "
|
||||
"%d RAD_KV_CONV groups are declared. Set RadBufDecl::kv -- a cursor "
|
||||
"computed against the wrong window's depth points at history that was "
|
||||
"never written.", b.name.c_str(), n_conv_);
|
||||
RAD_ERR("derived buffer '%s' runs 'conv_state_index' with %d RAD_KV_CONV "
|
||||
"groups declared; set RadBufDecl::kv to the one it reads",
|
||||
b.name.c_str(), n_conv_);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
@@ -486,13 +448,10 @@ int BatchBuilder::layout(Program& prog, const Config& cfg) {
|
||||
derived_bytes_ = align_up(derived_bytes_ + n * (int64_t)sizeof(int32_t), k_carve_align);
|
||||
}
|
||||
|
||||
/* Two layers declaring the same derivation get two BufferInfos and two arena slots -- that is
|
||||
* what the buffer plan produced -- but they share ONE computation: run_derivations computes
|
||||
* each distinct derivation once per step and copies the result to every destination. The cost
|
||||
* §8 is about is the recomputation, not the bytes.
|
||||
*
|
||||
* SORTED BY (derivation, GROUP), because two buffers running one derivation over different
|
||||
* conv groups are different answers and the sharing rule below is "same as the previous". */
|
||||
/* Buffers declaring the same derivation keep separate arena slots but share one computation
|
||||
* per step (run_derivations copies the result; §8). Sorted by (derivation, group), since
|
||||
* run_derivations shares a result only with the previous entry and different conv groups
|
||||
* give different answers. */
|
||||
std::sort(derived_.begin(), derived_.end(),
|
||||
[](const Derived& a, const Derived& b) {
|
||||
return a.fn_index != b.fn_index ? a.fn_index < b.fn_index
|
||||
@@ -505,8 +464,7 @@ int BatchBuilder::layout(Program& prog, const Config& cfg) {
|
||||
|
||||
/* ------------------------------------------------------------------ media staging */
|
||||
BatchBuilder::MediaBytes BatchBuilder::media_bytes() {
|
||||
/* The larger of the two encoders' passes, field by field: they run one at a time. Both write
|
||||
* rows of the model's embedding width. */
|
||||
/* The larger of the two encoders' passes, field by field, since they run one at a time. */
|
||||
enc_patches_ = enc_pix_elems_ = enc_segs_ = 0;
|
||||
n_embd_ = 0;
|
||||
for (const RadEncoderDecl* e : { &prog_->encoder, &prog_->audio_encoder }) {
|
||||
@@ -514,7 +472,7 @@ BatchBuilder::MediaBytes BatchBuilder::media_bytes() {
|
||||
n_embd_ = std::max<int64_t>(n_embd_, e->n_embd);
|
||||
enc_patches_ = std::max<int64_t>(enc_patches_, e->max_patches);
|
||||
enc_pix_elems_ = std::max<int64_t>(enc_pix_elems_, e->max_patches * e->patch_dim);
|
||||
/* The most segments one pass can hold: a segment is at least one output row. */
|
||||
/* Most segments one pass can hold; a segment is at least one output row. */
|
||||
enc_segs_ = std::max<int64_t>(enc_segs_, e->max_patches / (e->merge > 0 ? e->merge : 1) + 1);
|
||||
}
|
||||
MediaBytes m;
|
||||
@@ -580,10 +538,9 @@ void BatchBuilder::free_media() {
|
||||
mm_ev_live_ = false;
|
||||
}
|
||||
|
||||
/* THE ENCODER ROWS OF ONE ENTRY. A row reads its embedding at token `ctx_len + j + shift` -- the
|
||||
* draft head's history pass shifts its tokens one ahead, and its embeddings with them -- and the
|
||||
* rows that land in a media run take that run's encoder row instead. Consecutive tokens of one run
|
||||
* are consecutive rows of its item, so a run is one copy. */
|
||||
/* Row j reads its embedding at token `ctx_len + j + shift` (the draft head's history pass shifts
|
||||
* by one); rows inside a media run take that run's encoder row instead. Consecutive tokens of a
|
||||
* run are consecutive rows of its item, so each run is one copy. */
|
||||
int64_t BatchBuilder::stage_mm_rows(const StepEntry& e, int64_t k, int64_t shift, int64_t n_rows,
|
||||
int32_t* rows) {
|
||||
const mm::PromptMedia& pm = *e.req->media;
|
||||
@@ -600,7 +557,7 @@ int64_t BatchBuilder::stage_mm_rows(const StepEntry& e, int64_t k, int64_t shift
|
||||
(unsigned long long)e.seq);
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
/* The rest of this run inside this entry, and inside the prompt. */
|
||||
/* The rest of this run within this entry and the prompt. */
|
||||
int64_t take = std::min<int64_t>((int64_t)run->tok + run->n - ti, e.n_tokens - j);
|
||||
take = std::min<int64_t>(take, prompt - ti);
|
||||
const int64_t row = (int64_t)run->row0 + (ti - run->tok);
|
||||
@@ -631,20 +588,16 @@ int BatchBuilder::run_derivations(const StepPlan& plan, Set& s) {
|
||||
in.n_seq = (int64_t)plan.e.size();
|
||||
in.state_chunk = geo_.state_chunk;
|
||||
|
||||
/* derived_ is sorted by derivation, so "the same one as the previous entry" is the whole
|
||||
* sharing rule and it needs no map. IT IS A PAIR NOW: two buffers running the same derivation
|
||||
* over DIFFERENT KV GROUPS are different answers, and sharing them would give one group the
|
||||
* other's cursors. */
|
||||
/* derived_ is sorted by (derivation, group), so an entry matching the previous one on both
|
||||
* reuses its result. Different groups never share. */
|
||||
int last_fn = -1;
|
||||
int32_t last_grp = -1;
|
||||
const Derived* last = nullptr;
|
||||
for (Derived& d : derived_) {
|
||||
int32_t* host = (int32_t*)(s.h_derived + d.off);
|
||||
|
||||
/* THE GROUP'S OWN SLOTS AND ITS OWN WINDOW. `conv_state_index` computes a cursor inside a
|
||||
* rolling window, so the depth has to be that group's: one number shared across groups
|
||||
* fits only one of them, and the wrong depth produces a plausible cursor pointing at
|
||||
* history the kernel never wrote. */
|
||||
/* The group's own slots and window depth; `conv_state_index` computes a cursor inside
|
||||
* that group's rolling window. */
|
||||
const int32_t grp = d.conv_grp;
|
||||
in.conv_slot = (grp >= 0) ? s.h_convslot + (int64_t)grp * max_seqs_ : nullptr;
|
||||
in.conv_window = (grp >= 0 && grp < (int32_t)conv_window_.size()) ? conv_window_[grp] : 1;
|
||||
@@ -667,9 +620,7 @@ int BatchBuilder::run_derivations(const StepPlan& plan, Set& s) {
|
||||
last = &d;
|
||||
}
|
||||
|
||||
/* INTO EVERY RANK'S ARENA, on that rank's stream. A derived buffer is an ordinary
|
||||
* transient the core fills, so it lives in the per-rank arena the buffer plan placed --
|
||||
* copying only into rank 0's leaves every other rank reading whatever its arena held. */
|
||||
/* Copy into every rank's arena on that rank's stream; each rank has its own slot. */
|
||||
for (const RankIO& io : ranks_) {
|
||||
if (d.handle >= io.prog->buffers.size()) return RAD_E_STATE;
|
||||
void* dst = io.prog->buffers[d.handle].ptr;
|
||||
@@ -685,16 +636,15 @@ int BatchBuilder::run_derivations(const StepPlan& plan, Set& s) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
|
||||
/* ------------------------------------------------------------------ per-group fill */
|
||||
int BatchBuilder::build_groups(const StepPlan& plan, const IKVManager& kv, Set& s, Out& o) {
|
||||
const int64_t n_seq = (int64_t)plan.e.size();
|
||||
int32_t* const pay = s.bt_h0; /* the payload: the table entries this build restages */
|
||||
int32_t* const pay = s.bt_h0; /* payload: the table entries this build restages */
|
||||
int64_t np = 0;
|
||||
ranges_.clear();
|
||||
/* `n` entries of the payload from word `src` to word `dst` of the card's table region, as
|
||||
* ranges of at most k_range_max bytes. A run that continues the last range extends it, which
|
||||
* is what makes a whole restage of consecutive rows a handful of ranges and not one a row. */
|
||||
/* Stage `n` payload words from word `src` to word `dst` of the card's table region, as ranges
|
||||
* of at most k_range_max bytes. A run continuing the last range extends it, so consecutive
|
||||
* whole rows become a few ranges instead of one per row. */
|
||||
auto stage = [&](int64_t dst, int64_t src, int64_t n) {
|
||||
int64_t db = s.bt_base + dst * (int64_t)sizeof(int32_t);
|
||||
int64_t sb = s.bt_base + src * (int64_t)sizeof(int32_t);
|
||||
@@ -713,8 +663,8 @@ int BatchBuilder::build_groups(const StepPlan& plan, const IKVManager& kv, Set&
|
||||
}
|
||||
};
|
||||
|
||||
/* Every group's row, not just the first: a sequence with no state in a group must read -1
|
||||
* there, and a stale slot from the previous step is the worst possible value. */
|
||||
/* Reset every group's row: a sequence with no state in a group must read -1, not a stale slot
|
||||
* from the previous step. */
|
||||
for (int64_t gi = 0; gi < (int64_t)kvgeom_.g.size(); ++gi)
|
||||
for (int64_t i = 0; i < n_seq; ++i) s.h_convslot[gi * max_seqs_ + i] = -1;
|
||||
|
||||
@@ -722,9 +672,8 @@ int BatchBuilder::build_groups(const StepPlan& plan, const IKVManager& kv, Set&
|
||||
Group& g = s.groups[gi];
|
||||
const KVGeom::G& L = kvgeom_.g[gi];
|
||||
|
||||
/* THIS STEP's pitch, which build() measured before it sized the span. RadKVGroupBatch
|
||||
* carries it, so the device reads the rows at the width they were staged. A new pitch
|
||||
* moves every row, so nothing the card holds is where this build reads it. */
|
||||
/* This step's pitch, set by build() before it sized the span and passed in
|
||||
* RadKVGroupBatch. A new pitch moves every row, invalidating the mirror. */
|
||||
const int64_t pitch = pitch_[gi];
|
||||
BtMirror& m = bt_mirror_[gi];
|
||||
if (L.paged && m.pitch != pitch) {
|
||||
@@ -738,19 +687,17 @@ int BatchBuilder::build_groups(const StepPlan& plan, const IKVManager& kv, Set&
|
||||
|
||||
int64_t first = 0;
|
||||
if (L.paged) {
|
||||
/* The block table is the MANAGER's, read by sequence id. Request::blocks is not
|
||||
* the source of truth: two allocators disagreeing about what a sequence owns is
|
||||
* the bug where a freed sequence's blocks are handed out from under it. */
|
||||
/* The manager's block table, by sequence id; Request::blocks is not the source
|
||||
* of truth (see IKVManager). */
|
||||
const std::vector<int32_t>& bt = kv.block_table(e.seq, (int32_t)gi);
|
||||
first = kv.first_block_pos(e.seq, (int32_t)gi);
|
||||
for (int32_t j = 0; j < e.n_tokens; ++j)
|
||||
g.h_slot[t + j] = kvgeom_.slot((int)gi, bt, first, (int64_t)e.ctx_len + j);
|
||||
/* THE ROW, FROM WHAT THE CARD ALREADY HOLDS OF IT. The same sequence in the same
|
||||
* row keeps every entry below the lowest one the manager changed and below the end
|
||||
* of both the old and the new table; a decode step's row is then nothing, or the
|
||||
* one block it appended. Anything else -- a new sequence, one that moved rows -- is
|
||||
* the whole row, and its copies in other rows stop being current, since its marks
|
||||
* are taken here. The marks are taken for every row either way. */
|
||||
/* Restage relative to what the card holds (BtMirror). The same sequence in the
|
||||
* same row keeps entries below the first changed one and below the end of both
|
||||
* old and new tables, so a decode step stages nothing or one appended block. A
|
||||
* new or moved sequence restages the whole row, and its copies in other rows go
|
||||
* unknown. Change marks are taken for every row. */
|
||||
const int64_t nb = std::min<int64_t>((int64_t)bt.size(), pitch);
|
||||
const int64_t chg = kv.take_table_changes(e.seq, (int32_t)gi);
|
||||
int64_t lo = 0, hi = pitch;
|
||||
@@ -764,7 +711,9 @@ int BatchBuilder::build_groups(const StepPlan& plan, const IKVManager& kv, Set&
|
||||
if (lo < hi) {
|
||||
int32_t* w = pay + np;
|
||||
const int64_t nc = nb > lo ? nb - lo : 0;
|
||||
std::memcpy(w, bt.data() + lo, (size_t)nc * sizeof(int32_t));
|
||||
/* Guarded: an empty table's data() may be null, and memcpy's source must
|
||||
* not be, even for zero bytes. */
|
||||
if (nc > 0) std::memcpy(w, bt.data() + lo, (size_t)nc * sizeof(int32_t));
|
||||
std::fill(w + nc, w + (hi - lo), -1);
|
||||
stage(g.bt_fix + i * pitch + lo, np, hi - lo);
|
||||
np += hi - lo;
|
||||
@@ -772,43 +721,27 @@ int BatchBuilder::build_groups(const StepPlan& plan, const IKVManager& kv, Set&
|
||||
m.seq[(size_t)i] = e.seq;
|
||||
m.len[(size_t)i] = nb;
|
||||
} else {
|
||||
/* A linear or conv group owns one state instance per sequence, so every token of
|
||||
* the sequence maps to it and the "block table" row is that slot -- a kernel that
|
||||
* only reads block tables then needs no second path. */
|
||||
/* A linear or conv group has one state slot per sequence; every token maps to it
|
||||
* and the block-table row is that slot, so table-reading kernels need no second
|
||||
* path. */
|
||||
int32_t st = kv.state_slot(e.seq, (int32_t)gi);
|
||||
for (int32_t j = 0; j < e.n_tokens; ++j) g.h_slot[t + j] = st;
|
||||
pay[np + i] = st;
|
||||
/* EVERY conv group, at its own row. This array feeds `DeriveInput::conv_slot`
|
||||
* and NOTHING ELSE -- a conv KERNEL reads its slot from
|
||||
* RadKVGroupBatch::state_index, which is filled per group a few lines below and
|
||||
* always has been. See the note at conv_window_ in init(). */
|
||||
/* Every conv group, at its own row. Feeds only DeriveInput::conv_slot; conv
|
||||
* kernels read RadKVGroupBatch::state_index (see conv_window_ in batch.h). */
|
||||
if (kvgeom_.g[gi].kind == RAD_KV_CONV)
|
||||
s.h_convslot[(int64_t)gi * max_seqs_ + i] = st;
|
||||
}
|
||||
s.h_first[(int64_t)gi * max_seqs_ + i] = (int32_t)first;
|
||||
t += e.n_tokens;
|
||||
|
||||
/* THE TOKENS THIS SEQUENCE ACTUALLY HOLDS, WHICH IS NOT min(length, window).
|
||||
*
|
||||
* `seqused` is a count from index 0 of the BLOCK TABLE, and the table of a windowed
|
||||
* group is REBASED at `first_block_pos` once the window slides -- kvgeom_.slot() above
|
||||
* subtracts exactly that. So the count the kernel needs is the held span, and the held
|
||||
* span is a whole number of BLOCKS: recycling leaves `window_blocks` of them, whose
|
||||
* last one is partially filled by however far past a block boundary the sequence has
|
||||
* got. `min(length, window)` reports the full window every time and therefore claims
|
||||
* up to block_size - 1 positions that were never written this pass -- and they are the
|
||||
* ones at the END of the table, which every attention kernel reads as the NEWEST
|
||||
* context. Their bytes are whatever the recycled block held.
|
||||
*
|
||||
* A NON-CAUSAL windowed group is where this bites: every query row attends to those
|
||||
* stale slots at full weight, and acceptance falls off a cliff at exactly the context
|
||||
* where the window first slides. A causal group hides the same defect, because a stale
|
||||
* slot past the query is masked anyway.
|
||||
*
|
||||
* No clamp to `window` any more: block granularity means the held span can exceed the
|
||||
* window by less than a block, and dropping that from the FRONT of the count would
|
||||
* drop the NEWEST tokens rather than the oldest. Attending to a few extra old
|
||||
* positions is what paging a sliding window costs, and it is what vLLM does too. */
|
||||
/* Tokens the sequence holds in this table, not min(length, window). `seqused` counts
|
||||
* from index 0 of the block table, which a window group rebases at `first_block_pos`
|
||||
* (as slot() does above). min(length, window) would claim up to block_size - 1
|
||||
* unwritten slots at the end of the table, read as the newest context; a non-causal
|
||||
* window group would attend to them. Do not clamp to `window` either: the held span
|
||||
* may exceed it by under a block, and clamping would drop the newest tokens. Attending
|
||||
* a few extra old positions is the cost of paging a window (vLLM does the same). */
|
||||
int64_t used = (int64_t)e.ctx_len + e.n_tokens - first;
|
||||
if (used < 0) used = 0;
|
||||
g.h_used[i] = (int32_t)used;
|
||||
@@ -819,8 +752,7 @@ int BatchBuilder::build_groups(const StepPlan& plan, const IKVManager& kv, Set&
|
||||
(int)g.sidx_pitch);
|
||||
}
|
||||
}
|
||||
/* A state group's rows are one slot a sequence: restaged whole, since they are n_seq
|
||||
* words and one range. */
|
||||
/* A state group's rows are one slot per sequence: n_seq words, restaged whole. */
|
||||
if (!L.paged) {
|
||||
stage(g.bt_fix, np, n_seq);
|
||||
np += n_seq;
|
||||
@@ -852,8 +784,7 @@ int BatchBuilder::build_groups(const StepPlan& plan, const IKVManager& kv, Set&
|
||||
b.block_size = L.block_size;
|
||||
b.max_blocks = pitch;
|
||||
|
||||
/* The bytes cross in build()'s one slab copy: a group's arrays are carved out of
|
||||
* the same slab as everything else and there is nothing group-shaped about them. */
|
||||
/* The group's arrays are uploaded with the rest of the slab in build(). */
|
||||
}
|
||||
}
|
||||
pay_words_ = np;
|
||||
@@ -870,10 +801,9 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
|
||||
return nullptr;
|
||||
}
|
||||
if (plan.spec_is_tree) {
|
||||
/* spec_parent is in the ABI and its pool is allocated, but no drafter in v1 emits a tree,
|
||||
* so the parent chain and the positions a tree implies are not written. Saying so beats
|
||||
* filling the array with the linear-chain answer, which would verify a tree against the
|
||||
* wrong causal mask and produce fluent wrong text. */
|
||||
/* spec_parent is in the ABI and allocated, but no drafter emits a tree, so tree parents
|
||||
* and positions are not written. Filling in the linear-chain answer would verify a tree
|
||||
* against the wrong causal mask. */
|
||||
RAD_ERR("tree-layout speculation was requested but is not implemented in this build");
|
||||
return nullptr;
|
||||
}
|
||||
@@ -881,7 +811,7 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
|
||||
Set& s = set_;
|
||||
const int64_t n_seq = (int64_t)plan.e.size();
|
||||
|
||||
/* THE CONTEXT BOUND, rounded (see bound_bucket), before anything that derives from it. */
|
||||
/* The context bound, rounded (see bound_bucket), before anything that derives from it. */
|
||||
int32_t max_ctx = 0, max_q = 0;
|
||||
for (const StepEntry& e : plan.e) {
|
||||
if (e.ctx_len > max_ctx) max_ctx = e.ctx_len;
|
||||
@@ -889,20 +819,15 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
|
||||
}
|
||||
const int64_t ctx_bound = std::min<int64_t>(bound_bucket(max_ctx, k_bound_tokens), max_ctx_);
|
||||
|
||||
/* THE BLOCK-TABLE PITCH OF EVERY GROUP FIRST, because it sizes the build's span of the ring:
|
||||
* the span is the fixed prefix and exactly the rows build_groups will pack. The pitch is a
|
||||
* property of THIS STEP, not of the deployment -- a rectangle wide enough for max_ctx would be
|
||||
* megabytes staged and copied on every decode step to carry a few hundred live entries.
|
||||
/* Every group's block-table pitch comes first because it sizes the ring span. The pitch is
|
||||
* per step, not max_ctx wide, so decode does not stage megabytes of empty rows.
|
||||
*
|
||||
* IT IS A FUNCTION OF THE CONTEXT BOUND, so the two move on the same step. Both are in a
|
||||
* recorded pass's key, and rounded separately they cross their buckets on different steps --
|
||||
* every crossing of either is a pass recorded again, so twice the recordings for nothing. A
|
||||
* row holds the sequence's context plus this step's tokens plus the scheduler's draft
|
||||
* lookahead, which is at most two speculative windows, and the pitch is that rounded up to
|
||||
* the bound's own grid. A table longer than that (none is, today) takes its own rounded
|
||||
* length, which is correct and only costs the alignment. */
|
||||
* It derives from the context bound so both cross their buckets on the same step (both key a
|
||||
* recorded pass; separate rounding would double the re-recordings). A row holds context plus
|
||||
* this step's tokens plus at most two speculative windows of draft lookahead, rounded up to
|
||||
* the bound's grid. A longer table takes its own rounded length. */
|
||||
const int64_t reach = ctx_bound + max_q + 2 * ((int64_t)std::max(plan.n_spec, 0) + 1);
|
||||
int64_t pay_need = 0; /* the payload if every row were restaged whole */
|
||||
int64_t pay_need = 0; /* payload if every row were restaged whole */
|
||||
for (size_t gi = 0; gi < s.groups.size(); ++gi) {
|
||||
int64_t pitch = 1;
|
||||
if (kvgeom_.g[gi].paged) {
|
||||
@@ -920,9 +845,9 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
|
||||
pitch_[gi] = pitch;
|
||||
pay_need += n_seq * pitch * (int64_t)sizeof(int32_t);
|
||||
}
|
||||
/* THE SPAN: the fixed prefix, the payload, and the range list behind it, each at its bound --
|
||||
* a range a row or state group plus one a k_range_max of payload. What the build turns out to
|
||||
* use is usually far less, and only that is held once it is known. */
|
||||
/* The span: fixed prefix, payload and range list, each at its bound (one range per row or
|
||||
* state group plus one per k_range_max of payload). Only what the build uses is held once
|
||||
* known. */
|
||||
const int64_t max_ranges = pay_need / k_range_max + n_seq * (int64_t)s.groups.size() + 1;
|
||||
int64_t off = 0;
|
||||
const int64_t need = align_up(s.bt_base + align_up(pay_need, 16) +
|
||||
@@ -935,8 +860,8 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
|
||||
|
||||
/* ---------------------------------------------------------- tokens, positions, boundaries */
|
||||
int64_t k = 0;
|
||||
/* PER HALF as well as overall: a mixed step`s max_q is its prefill chunk, and a block that
|
||||
* issues the decode rows separately must not select their kernel band with it. */
|
||||
/* Also per half: a mixed step's max_q is its prefill chunk, which must not select the kernel
|
||||
* band for separately issued decode rows. */
|
||||
int32_t max_q_dec = 0, max_q_pf = 0;
|
||||
int n_ck = 0;
|
||||
int64_t n_out = 0, n_dout = 0;
|
||||
@@ -952,26 +877,24 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
|
||||
}
|
||||
for (int64_t i = 0; i < n_seq; ++i) {
|
||||
const StepEntry& e = plan.e[(size_t)i];
|
||||
/* The advance indexes the card's StepSlots by this, and there are max_seqs of them. */
|
||||
/* The advance indexes the card's max_seqs StepSlots by this. */
|
||||
if (e.card < 0 || e.card >= max_seqs_) {
|
||||
RAD_ERR("step plan row %lld: sequence %llu has card index %d, outside the %lld step "
|
||||
"slots", (long long)i, (unsigned long long)e.seq, (int)e.card,
|
||||
(long long)max_seqs_);
|
||||
return nullptr;
|
||||
}
|
||||
/* THE MTP HEAD READS ONE POSITION AHEAD. Its index i pairs the trunk`s hidden state at i
|
||||
* with the EMBEDDING OF THE TOKEN AT i + 1, and predicts i + 2 (rad_block_mtp_fp8.h). The
|
||||
* shift is applied once, here, so that no kernel and no plugin carries it -- and
|
||||
* token_at() reaches the drafter`s own earlier rounds through `draft` exactly as a verify
|
||||
* step reaches its proposal. StepPlan::tok_shift says how far, because it is the HEAD's
|
||||
* indexing and not the draft round's: DFlash2 is a draft pass that shifts by nothing. */
|
||||
/* Token shift (StepPlan::tok_shift): the MTP head pairs hidden state i with the token
|
||||
* at i + 1 and predicts i + 2 (rad_block_mtp_fp8.h). Applied only here, so no kernel or
|
||||
* plugin carries it; token_at() reaches earlier draft rounds through `draft`. DFlash2
|
||||
* passes use 0. */
|
||||
const int64_t shift = plan.tok_shift;
|
||||
for (int32_t j = 0; j < e.n_tokens; ++j) {
|
||||
s.h_tok[k + j] = token_at(e, (int64_t)e.ctx_len + j + shift);
|
||||
s.h_pos[k + j] = e.ctx_len + j;
|
||||
}
|
||||
/* THE ROTARY POSITION OF EACH ROW, at the row's own position -- the draft head's rows
|
||||
* rotate at the index they write, not at the token they embed. Planes of n_tok. */
|
||||
/* Rotary position of each row at its own position (draft-head rows rotate at the index
|
||||
* they write, not the token they embed). Three planes of n_tok. */
|
||||
if (mm_on_) {
|
||||
const mm::RopeLayout* rl =
|
||||
(e.req && e.req->media && !e.req->media->rope.empty()) ? &e.req->media->rope : nullptr;
|
||||
@@ -986,7 +909,7 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
|
||||
if (v[1] != v[0] || v[2] != v[0]) rope_mixed = 1;
|
||||
}
|
||||
if (e.req && e.req->media && !e.req->media->items.empty()) {
|
||||
/* The staging is the last upload's until that upload has run. */
|
||||
/* Wait until the last upload from the staging has run. */
|
||||
if (mm_ev_live_) {
|
||||
if (rad_event_sync(mm_ev_) < 0) return nullptr;
|
||||
mm_ev_live_ = false;
|
||||
@@ -997,23 +920,16 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
|
||||
}
|
||||
}
|
||||
if (e.ckpt_tok >= 0 && e.ckpt_slot >= 0) {
|
||||
/* checkpoint_tok indexes THIS STEP's tokens, so it is the sequence's base plus the
|
||||
* offset the scheduler chose -- which the chunk split guarantees is the last token of
|
||||
* a checkpoint interval (§7.3). */
|
||||
/* checkpoint_tok indexes this step's tokens: the sequence's base plus the offset the
|
||||
* scheduler chose, the last token of a checkpoint interval (§7.3). */
|
||||
s.h_cktok[n_ck] = (int32_t)(k + e.ckpt_tok);
|
||||
s.h_ckslot[n_ck] = e.ckpt_slot;
|
||||
++n_ck;
|
||||
}
|
||||
/* Which of this step's tokens the sampler wants logits for. `produces_token` is the
|
||||
* scheduler's answer to "is this entry's last token the sequence's last" -- false for the
|
||||
* middle chunk of a long prefill, which therefore contributes no row and does not touch
|
||||
* the lm_head at all. At a speculative verify every drafted position needs a distribution
|
||||
* to accept against, so the entry contributes 1 + n_spec rows and not one. */
|
||||
/* AN MTP PASS NAMES ITS OWN ROWS, and they are rows of the PREVIOUS step: the head
|
||||
* gathers the trunk`s hidden state for the positions it continues from, and which those
|
||||
* are is not a function of this batch at all. One per token of the pass, consecutive from
|
||||
* `hidden_row` -- which is a single row for a draft round and a whole chunk for a history
|
||||
* pass. See StepEntry::hidden_row. */
|
||||
/* Rows the sampler wants logits for. An entry with `hidden_row` names its own rows
|
||||
* (StepEntry::hidden_row), consecutive from it. Otherwise a `produces_token` entry gives
|
||||
* 1 + n_spec rows (every drafted position needs a distribution), and a mid-prefill chunk
|
||||
* gives none. */
|
||||
if (e.hidden_row >= 0) {
|
||||
const int32_t nr = e.hidden_n > 0 ? e.hidden_n : e.n_tokens;
|
||||
for (int32_t j = 0; j < nr; ++j) s.h_out[n_out++] = e.hidden_row + j;
|
||||
@@ -1022,13 +938,9 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
|
||||
for (int32_t j = 0; j <= e.n_spec; ++j) s.h_out[n_out++] = first + j;
|
||||
}
|
||||
if (e.draft_out) s.h_dout[n_dout++] = (int32_t)(k + e.n_tokens - 1);
|
||||
/* RADIANCE_DFLASH_TRACE prints what a drafter pass actually consumes -- the pass kind, the
|
||||
* absolute positions, and the token ids at them. A block-diffusion drafter reads an ANCHOR
|
||||
* the target has already chosen followed by mask ids, and every way of getting that wrong
|
||||
* (an anchor one token stale, a mask id that is an ordinary token, a position base that
|
||||
* disagrees with the KV the context pass wrote) produces the same symptom from outside:
|
||||
* acceptance near zero and output still exactly correct. So it is printed rather than
|
||||
* reasoned about. */
|
||||
/* RADIANCE_DFLASH_TRACE logs each drafter pass's kind, positions and token ids. A wrong
|
||||
* anchor, mask id or position base shows only as near-zero acceptance with correct
|
||||
* output. */
|
||||
static const bool trace = std::getenv("RADIANCE_DFLASH_TRACE") != nullptr;
|
||||
if (trace && plan.draft_pass != 0) {
|
||||
std::string ln = fmt("df %s seq %d pos %d..%d tok",
|
||||
@@ -1053,11 +965,9 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
/* THE SCORED ROWS (Request::score), after every row the sampler reads: a row at each token of
|
||||
* a scoring entry's prefill chunk, in entry order, which is the order Engine::score_rows walks
|
||||
* to map them back to a request and a position. They come after so that nothing indexing the
|
||||
* sampled rows -- the sampler, the card's acceptance (dev_out) -- sees them at all. A trunk
|
||||
* pass only: a draft pass's rows are the head's, not the model's. */
|
||||
/* Scored rows (Request::score): one per token of a scoring entry's prefill chunk, in entry
|
||||
* order (the order Engine::score_rows maps back). Appended after the sampled rows so the
|
||||
* sampler and the card's acceptance (dev_out) never see them. Trunk passes only. */
|
||||
if (cfg_.kld() && plan.draft_pass == 0 && plan.tok_shift == 0) {
|
||||
int64_t at = 0;
|
||||
for (int64_t i = 0; i < n_seq; ++i) {
|
||||
@@ -1073,11 +983,10 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
|
||||
}
|
||||
}
|
||||
|
||||
/* THE PROMPT THAT FOLLOWS: the last sequence's next tokens, up to a step of them, after this
|
||||
* step's own (RadBatch::n_ahead). Only on a trunk pass whose last entry is a prefill chunk with
|
||||
* more of its sequence still to run -- a draft pass's tokens are shifted and it reads no such
|
||||
* data -- and bounded by the tokens the request has, so a re-prefill after preemption reads
|
||||
* its own output as the prompt's continuation, as token_at does. */
|
||||
/* Up to a step of the last sequence's following tokens, after this step's own
|
||||
* (RadBatch::n_ahead). Only on a trunk pass whose last entry is a prefill chunk, bounded by
|
||||
* the tokens the request has; like token_at, a re-prefill after preemption continues into its
|
||||
* own output. */
|
||||
int64_t n_ahead = 0;
|
||||
if (n_seq > 0 && plan.draft_pass == 0 && plan.tok_shift == 0) {
|
||||
const StepEntry& e = plan.e[(size_t)(n_seq - 1)];
|
||||
@@ -1089,8 +998,8 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
|
||||
}
|
||||
}
|
||||
|
||||
/* From here the manager's change marks are taken, so a build that stops before its upload
|
||||
* is issued on every rank leaves the card's tables unknown to the next one. */
|
||||
/* build_groups consumes the manager's change marks, so any failure before every rank's
|
||||
* upload is issued must forget_tables(). */
|
||||
if (int st = build_groups(plan, kv, s, o); st < 0) {
|
||||
forget_tables();
|
||||
RAD_ERR("step batch: build_groups -> %s", rad_strerror(st));
|
||||
@@ -1105,41 +1014,21 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
|
||||
return nullptr;
|
||||
}
|
||||
RadCopyRange* const rng = reinterpret_cast<RadCopyRange*>(ring_.host + off + rng_at);
|
||||
std::memcpy(rng, ranges_.data(), (size_t)n_rng * sizeof(RadCopyRange));
|
||||
if (n_rng > 0) std::memcpy(rng, ranges_.data(), (size_t)n_rng * sizeof(RadCopyRange));
|
||||
const int64_t used = align_up(rng_at + n_rng * (int64_t)sizeof(RadCopyRange), k_carve_align);
|
||||
|
||||
/* ---------------------------------------------------------- ONE COPY PER RANK
|
||||
/* ---------------------------------------------------------- one copy per rank
|
||||
*
|
||||
* carve() lays out the host span and every rank's device slab in the same order, at the same
|
||||
* sizes, aligning the OFFSET and not the pointer. So below bt_base the device slab is a
|
||||
* byte-for-byte mirror of the host span, and a whole step's staging -- the token and position
|
||||
* arrays, the per-sequence arrays, and every KV group's slot map, seqused and state index --
|
||||
* crosses in one transfer, with the block-table entries that changed riding the same dispatch
|
||||
* as ranges.
|
||||
* Below bt_base the device slab mirrors the host span byte for byte (carve() aligns offsets,
|
||||
* not pointers), so a step's whole staging crosses in one transfer, with changed block-table
|
||||
* entries as ranges in the same dispatch. Copying per array would move fewer bytes, but a
|
||||
* decode step has about 2 KB live across dozens of arrays, where per-transfer dispatch cost
|
||||
* dominates; the unused tail costs a few microseconds of DMA. Since everything crosses every
|
||||
* step, `num_accepted` needs no gate.
|
||||
*
|
||||
* One copy per ARRAY would carry only the prefix the step used, which is the right trade when
|
||||
* the arrays are full and the wrong one when they are not. A decode step has about two
|
||||
* kilobytes of live staging spread over dozens of arrays -- one per array, per KV group, per
|
||||
* rank -- and at that size the bytes are the smallest part of the cost: each transfer costs a
|
||||
* dispatch plus the dependent gap behind it, which together dominate the DMA.
|
||||
*
|
||||
* The over-copy is the unused tail of the arrays sized by max_num_batched_tokens. At a full
|
||||
* prefill chunk it is nothing at all -- the same bytes cross either way and only the launch
|
||||
* count differs -- and at decode a few microseconds of DMA buys back dozens of dispatches.
|
||||
*
|
||||
* It also removes the need for a gate on `num_accepted`: the kernels read that operand
|
||||
* whenever the DEPLOYMENT speculates, not only when the step drafted, so copying it
|
||||
* conditionally leaves them reading the arena on exactly the step that had something to roll
|
||||
* back. Everything in the slab crosses on every step.
|
||||
*
|
||||
* AND IT STAYS ON THE COMPUTE STREAM, which is not an oversight. Moving it to a third,
|
||||
* staging stream -- so that a producer on the second lane could see its batch without
|
||||
* queueing behind compute -- is substantially SLOWER at every concurrency, byte-identical.
|
||||
* Sharing the queue is load-bearing: the split has to pay for two orderings the queue gives
|
||||
* away, and the one that hurts is the copy waiting on the event that says the step which last
|
||||
* read this slab is done -- it cannot start until the previous step has drained, where riding
|
||||
* the compute stream lets it issue in line. That is three cross-stream round-trips a step a
|
||||
* rank against a prize of a few percent. Do not rebuild the staging stream. */
|
||||
* The copy stays on the compute stream. A separate staging stream is slower at every
|
||||
* concurrency: the copy must wait on an event for the step that last read the slab, adding
|
||||
* cross-stream round-trips, while on the compute stream it issues in line. Do not move it. */
|
||||
for (size_t r = 0; r < ranks_.size(); ++r) {
|
||||
const int st = rad_memcpy_ranges_async(s.dev[r], ring_.host + off, s.bt_base, rng, n_rng,
|
||||
ranks_[r].stream);
|
||||
@@ -1150,13 +1039,12 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
|
||||
}
|
||||
}
|
||||
|
||||
/* Derived metadata reads the host staging, so it runs after the fills and before the event. */
|
||||
/* Derivations read the host staging: after the fills, before the event. */
|
||||
RAD_TRY_NULL(run_derivations(plan, s));
|
||||
|
||||
/* ---------------------------------------------------------- encoder rows
|
||||
* Behind the slab on every rank's stream, so the rows are on the card before any kernel of the
|
||||
* pass reads them: rank 0 takes the staged rows, every other rank the zeros that make the
|
||||
* vocabulary reduction count each row once. */
|
||||
* Behind the slab on every rank's stream. Rank 0 gets the staged rows, the others zeros, so the
|
||||
* vocabulary reduction counts each row once. */
|
||||
if (n_mm > 0) {
|
||||
const int64_t bytes = n_mm * n_embd_ * (int64_t)sizeof(uint16_t);
|
||||
for (size_t r = 0; r < ranks_.size(); ++r) {
|
||||
@@ -1200,11 +1088,9 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
|
||||
B.kv = o.kv[r].data();
|
||||
B.draft_pass = plan.draft_pass;
|
||||
B.n_spec = plan.n_spec;
|
||||
/* PASSED WHENEVER THE DEPLOYMENT SPECULATES, not only on the steps that drafted. A step that
|
||||
* declines to draft still FOLLOWS one that did, and the linear kernels need to know how much
|
||||
* of that step survived before they can start. Gating this on the step's own draft count
|
||||
* makes the kernels fall back to their absent-operand default of 1 on exactly the step that
|
||||
* had something to roll back. */
|
||||
/* Passed whenever the deployment speculates, not only on steps that drafted: a step
|
||||
* without drafts may follow one that had drafts, and the linear kernels need its accepted
|
||||
* count instead of their absent-operand default of 1. */
|
||||
B.num_accepted = cfg_.n_spec > 0 ? on_rank(base, b0, s.d_acc) : nullptr;
|
||||
B.spec_parent = nullptr; /* a linear chain; the tree case is refused above */
|
||||
B.rope_pos = mm_on_ ? on_rank(base, b0, s.d_rope) : nullptr;
|
||||
@@ -1224,8 +1110,8 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
|
||||
B.checkpoint_slot = n_ck ? on_rank(base, b0, s.d_ckslot) : nullptr;
|
||||
B.n_ahead = n_ahead;
|
||||
}
|
||||
/* THE FLIGHT, behind everything that reads this span: the upload, and the derivation copies
|
||||
* run_derivations issued above. */
|
||||
/* Record the flight behind everything reading this span: the upload and the derivation
|
||||
* copies. */
|
||||
const int ev = ev_free_.back();
|
||||
ev_free_.pop_back();
|
||||
for (size_t r = 0; r < ranks_.size(); ++r) {
|
||||
@@ -1245,8 +1131,6 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
|
||||
return &o.batch[0];
|
||||
}
|
||||
|
||||
/* The batch the last build produced for one rank. Same numbers as build()'s return; different
|
||||
* device pointers, because each rank reads its own slab. */
|
||||
const RadBatch* BatchBuilder::batch_for(int rank) const {
|
||||
if (out_last_ < 0) return nullptr;
|
||||
const Out& o = out_[out_last_];
|
||||
@@ -1315,9 +1199,9 @@ const RadBatch* BatchBuilder::build_encoder(const std::vector<EncoderPart>& part
|
||||
if (seg_p > max_seg) max_seg = seg_p;
|
||||
}
|
||||
}
|
||||
/* Coordinates in planes of n_patch, which is what makes planes 0 and 1 a dense [2, n_patch]. */
|
||||
/* Coordinates in planes of n_patch, so planes 0 and 1 form a dense [2, n_patch]. */
|
||||
{
|
||||
std::vector<int32_t> tmp;
|
||||
std::vector<int32_t>& tmp = enc_coord_tmp_;
|
||||
int64_t at = 0;
|
||||
for (const EncoderPart& p : parts) {
|
||||
const mm::Item& it = *p.item;
|
||||
|
||||
Reference in new issue
Block a user