radiance 1.13.0

New models:
- Tencent Hy-Memory (HYV3) from its BF16, FP8 and GGUF checkpoints, with its native tool calls
- M2XFP4: metadata-augmented MXFP4 weights for Qwen3.8-27B and its DFlash2 drafter (top-1 89.1% ->
  92.4% against plain MXFP4), its quantiser and recipe, and ParoQuant's M2XFP4 checkpoints
- Gemma 4 E2B/E4B audio input; NVIDIA-Nemotron-3.5-Bolt-E4B in int8 and 4-bit, on two cards by
  default; Ornith-1.5-122B compose files

Speed:
- Weight reads beside the decode all-reduces (qwen35_fp8, gemma3; --weight-prefetch, on by default):
  the 27B MXFP4 with DFlash2 61.2 -> 67.9 tok/s at c1, TranslateGemma 27B +13%
- Head-256 split-KV decode attention at 256 workgroups and without bank conflicts (27B: +3-5% a
  step at 25-41K context), and the prefill KV split for small launches (a short turn over a long
  context decodes the other sequences 27% faster in that step)
- MXFP4 decode gate_up, activation and fp8 quantiser in one launch (27B, Gemma 3 up to 64 rows:
  TranslateGemma +2-5% at 2-8 streams)
- ParoQuant int4/int5 tiled GEMMs 6-9% faster
- Speculation: a step's tokens are sent before the drafter's passes end, no step waits behind one
  that ends its requests, and the MTP head's first draft no longer collapses after short chats in
  the prefix cache

Features:
- --kv-resident N: KV streaming for a context bigger than VRAM (qwen4exp_fp8, GLM-5.3)
- MiniMax-H3: reference media and keyframe conditioning with the VAE encoders
- Krea 2 rebalance presets balanced, detail and subtle
- The dashboard's request history; a stall watch that reports a frozen step's thread and stack
- rad-tune at the served configuration, collectives measured as the exchange; Gemma 4 E2B/E4B's
  per-layer embeddings read ahead off the step path
- A GPTQ calibration tap and recipe for Gemma 4 31B's w4a8 container

Fixes:
- The two-rank all-reduce checks that a peer's push has landed before reducing it
- z-lab's DFlash drafter on Gemma 4 31B keeps drafting after a prefix-cache hit
- MiniMax-H3's modulation rows

Changes: Plugin ABI 31: out-of-tree plugins must be rebuilt. RADIANCE_PREFETCH_BESIDE is
--weight-prefetch now; RADIANCE_NO_HUGE_PAGES, RADIANCE_IDS_EARLY, RADIANCE_ATTN_BAND_SPLIT,
R4D_PREFILL_SPLITS, RAD_PLE_TIMING and RAD_PLE_CACHE_ROWS are gone.
This commit is contained in:
Deadcode committed 2026-10-27 16:47:35 +01:00
198 files changed
+20904 -3240

No files matched your search

+84
View File
@@ -0,0 +1,84 @@
/* bind.cpp -- see bind.h. */
#include "kvstream/bind.h"
#include "kvstream/plan.h"
namespace rad {
void kv_bind_views(const KVGroupPlan& p, KVPoolBinding* b) {
if (!b || !p.paged()) return;
b->base = p.base;
b->ring.layer_stride = p.layer_stride();
b->ring.bytes = kv_ring_bytes(p, p.pool_blocks());
b->ring.depth = 0;
b->ring.shape0 = p.pool_blocks();
b->has_stage = p.depth == 1;
if (b->has_stage) {
b->stage.layer_stride = p.n_blocks * p.layer_bytes_per_block();
b->stage.bytes = b->stage.layer_stride;
b->stage.depth = 1;
b->stage.shape0 = p.n_blocks;
}
kv_binding_enter(*b, KVView::Ring);
}
int64_t kv_binding_offset(const KVPoolBinding& b, int64_t layer) {
return b.depth == 1 ? 0 : layer * b.layer_stride;
}
KVView kv_pass_view(int phase, int64_t n_tok, int64_t n_seq, int n_spec) {
/* The serial drafter's history pass is labelled decode but runs over a prefill chunk's tokens,
* whose union no ring bound covers, so it stages. */
if (phase != RAD_PHASE_DECODE) return KVView::Stage;
const int64_t rows = (int64_t)n_seq * (1 + (n_spec > 0 ? n_spec : 0));
return n_tok > rows ? KVView::Stage : KVView::Ring;
}
void kv_binding_enter(KVPoolBinding& b, KVView view) {
const KVViewState& v = (view == KVView::Stage && b.has_stage) ? b.stage : b.ring;
b.layer_stride = v.layer_stride;
b.bytes = v.bytes;
b.depth = v.depth;
b.shape[0] = v.shape0;
}
namespace {
template <typename T>
T* on_rank(const void* base_r, const void* base_0, T* p0) {
return p0 ? (T*)((char*)base_r + ((char*)p0 - (char*)base_0)) : nullptr;
}
} /* namespace */
uint64_t kvstream_view_key(const RadKVStream* v) {
if (!v) return 0;
uint64_t h = 0x9e3779b97f4a7c15ull;
auto mix = [&](uint64_t x) {
h ^= x + 0x9e3779b97f4a7c15ull + (h << 6) + (h >> 2);
h *= 0xbf58476d1ce4e5b9ull;
};
auto p = [&](const void* q) { mix((uint64_t)(uintptr_t)q); };
p(v->host); p(v->res); p(v->slot_block); p(v->slot_state);
p(v->ctl);
mix((uint64_t)v->block_bytes); mix((uint64_t)v->host_layer_stride);
mix((uint64_t)v->slots); mix((uint64_t)v->host_bytes);
return h | 1;
}
const RadKVStream* kvstream_step_view(RadKVStream* out, const RadKVStream* src, bool per_rank,
const void* kv0, const void* kvr) {
if (!src) return nullptr;
*out = *src;
/* Rebase a follower's maps into its own pool by the offset its arena buffers take. */
if (!per_rank && kv0 && kvr) {
out->res = on_rank(kvr, kv0, src->res);
out->slot_block = on_rank(kvr, kv0, src->slot_block);
out->slot_state = on_rank(kvr, kv0, src->slot_state);
out->ctl = on_rank(kvr, kv0, src->ctl);
}
return out;
}
} /* namespace rad */
+49
View File
@@ -0,0 +1,49 @@
/* bind.h -- the two views of a streamed group's one pool allocation.
*
* The stage view aliases every layer to offset 0 by reporting depth 1; `layer_slot` keeps each
* layer's group-local position, because that is also its row in the host mirror
* (docs/KV-STREAMING.md §3.5.1).
*
* A pass takes a view from its phase and row shape, before it is recorded or replayed. A decode
* pass of at most 1 + n_spec rows a sequence takes the ring: its selection is rewritten to ring
* slots and misses are copied in. Every other pass (prefill, mixed, and a decode-classified pass
* with more rows a sequence, such as the serial drafter's history pass) takes the stage, the
* group's context at block-id addressing, where no selection can overflow. `phase`, `n_tok`,
* `n_seq` and `n_spec` are in the pass key, so a recorded pass replays against its view.
*/
#pragma once
#include "mem/kv.h"
#include "runtime/ctx.h"
namespace rad {
enum class KVView { Ring, Stage };
/* Fill both views from the carved plan and make the ring active. A non-paged group is left
* untouched. */
void kv_bind_views(const KVGroupPlan& p, KVPoolBinding* b);
/* A layer's offset in the active view: 0 at depth 1. The `off + layer_stride <= bytes` bound in
* issue.cpp holds for both views. */
int64_t kv_binding_offset(const KVPoolBinding& b, int64_t layer);
/* The view a pass with this phase and row shape takes (see the header). */
KVView kv_pass_view(int phase, int64_t n_tok, int64_t n_seq, int n_spec);
/* Make `view` active; the stage falls back to the ring when the group has none. */
void kv_binding_enter(KVPoolBinding& b, KVView view);
/* One rank's step view of a group's ring and mirror, copied into `out`; null when the group does
* not stream. With `per_rank`, `src` is that rank's own manager's view: its maps live in that
* rank's KV pool and its mirror is that rank's pinned allocation. Without (tests), `src` is rank
* 0's and its map pointers are rebased from rank 0's pool (`kv0`) into this rank's (`kvr`). The
* addresses are fixed at bring-up. */
const RadKVStream* kvstream_step_view(RadKVStream* out, const RadKVStream* src, bool per_rank,
const void* kv0, const void* kvr);
/* A step view's identity for Ctx::pass_key: the memory a kernel reads, never the struct's address.
* The batch copies the view into one of the builder's rotating Out slots, so keying on its address
* would make every streamed decode step a new pass that never replays. */
uint64_t kvstream_view_key(const RadKVStream* v);
} /* namespace rad */
+183
View File
@@ -0,0 +1,183 @@
/* bringup.cpp -- see bringup.h. */
#include "kvstream/bringup.h"
#include "device/device.h"
#include "engine_hostmem.h"
#include "kvstream/plan.h"
#include <algorithm>
#include <cstring>
namespace rad {
/* The ops whose only job is the host mirror or the ring. `kv_store` and the fused
* `qk_norm_rope_gate_kv_store` serve resident groups too. */
static const char* const kStreamOnlyOps[] = {
"kv_store_streamed",
"qk_norm_rope_gate_kv_store_streamed",
"kv_resolve",
};
bool kvstream_op_gated(const RadBuildCtx& ctx, const char* op) {
if (!op) return false;
if (ctx.kv_stream_ok != 0 && ctx.kv_resident_blocks > 0) return false; /* a ring is carved */
for (const char* s : kStreamOnlyOps)
if (std::strcmp(s, op) == 0) return true;
return false;
}
int kvstream_configure(const Config& cfg, int64_t ctx, const std::vector<KVGroupInfo>& groups,
const Program& prog, KVStreamSetup* out) {
*out = KVStreamSetup{};
if (cfg.kv_resident <= 0) return RAD_OK;
/* On Flash-Next the group is `kv_attn`. The indexer's `kv_qsa_bkey` is full too, but qsa_score
* reads it over the whole history every step, so it is dense-read and stays resident
* (docs/KV-STREAMING.md §2). A model with only windowed groups has nothing to stream. */
int32_t g = kv_stream_group(groups, &prog);
/* With no streamed path anywhere, the widest full group is still chosen, so the warning below
* can name it and the op it lacks. */
if (g < 0) g = kv_stream_group(groups);
if (g < 0) return RAD_OK;
const KVGroupInfo& gi = groups[(size_t)g];
const int64_t bs = gi.block_size > 0 ? gi.block_size : 1;
/* A ring that covers the context is not a refusal: the group stays a resident pool. */
const KVStreamRing shape = kvstream_ring_shape(cfg, ctx, bs);
out->asked_tokens = cfg.kv_resident;
out->context_tokens = ctx * cfg.max_seqs;
out->group_name = gi.name;
out->ring_blocks = shape.ring_blocks;
out->ring_tokens = shape.ring_blocks * bs;
out->block_size = bs;
out->ctx_blocks = shape.ctx_blocks;
if (!shape.streams()) return RAD_OK;
/* Before anything is allocated: the group needs the ops its streamed path issues (KVStreamOps).
* The gated fp8 attention (rad_block_attn_gated_fp8.h) and GLM-5.3's MLA block
* (rad_block_glm_mla.h) declare both. Without them the flag is ignored and the configuration is
* exactly the one without it. */
const KVStreamOps ops = kvstream_ops(prog, &gi);
if (!ops.streams()) {
/* A packed cache (fp8_v4, k6_v4) is declared to the core as plain E4M3, so the dtype check
* below cannot see it; its architecture declares the resolve but no store row. The
* operator's answer is then the cache layout, not the model. */
if ((cfg.kv_cache_dtype == "fp8_v4" || cfg.kv_cache_dtype == "k6_v4") && ops.resolve &&
!ops.store && !ops.folded)
RAD_WARN("--kv-resident %lld ignored: group '%s' has a %s cache, and the streamed store "
"has no writer for that layout (E4M3 and bf16 only); the group stays "
"resident",
(long long)cfg.kv_resident, gi.name.c_str(), cfg.kv_cache_dtype.c_str());
else
RAD_WARN("--kv-resident %lld ignored: architecture '%s' declares no %s for group '%s', "
"so the group stays resident",
(long long)cfg.kv_resident,
prog.meta.arch_id && *prog.meta.arch_id ? prog.meta.arch_id : "(unnamed)",
ops.missing(), gi.name.c_str());
*out = KVStreamSetup{};
return RAD_OK;
}
/* The streamed store has E4M3 and bf16 rows only. Packed layouts were ignored above; this
* refuses a core dtype no architecture ships a full group in (f32, f16). */
if (gi.decl.dtype != RAD_F8E4M3 && gi.decl.dtype != RAD_BF16) {
RAD_ERR("--kv-resident %lld: group '%s' has a %s cache, and the streamed store has E4M3 "
"and bf16 rows only (--kv-cache-dtype fp8 or bf16); leave --kv-resident off",
(long long)cfg.kv_resident, out->group_name.c_str(),
rad_dtype_name(gi.decl.dtype));
return RAD_E_INVAL;
}
KVStreamRing ring;
kvstream_ring(cfg, ctx, bs, ops.sel_pitch, &ring);
if (ring.raised_blocks > 0) {
/* The line names the floor that bound: one decode step's selection (a correctness bound) or
* kStreamFloorTokens (a cost bound). */
const int64_t asked_blocks = (out->asked_tokens + bs - 1) / bs;
const int64_t step = kvstream_ceiling_blocks(cfg, ops.sel_pitch);
if (ring.by_union && step > asked_blocks) {
RAD_WARN("--kv-resident %lld raised to %lld tokens: one decode step can select %lld "
"blocks of %lld tokens (--max-num-seqs %lld x %lld rows x %lld), and the ring "
"must hold them",
(long long)out->asked_tokens, (long long)(ring.ring_blocks * bs),
(long long)step, (long long)bs,
(long long)(cfg.max_seqs > 0 ? cfg.max_seqs : 1),
(long long)(1 + (cfg.n_spec > 0 ? cfg.n_spec : 0)),
(long long)ops.sel_pitch);
} else {
RAD_WARN("--kv-resident %lld raised to %lld tokens: a ring under %lld tokens (%lld "
"blocks of %lld) misses more than it saves",
(long long)out->asked_tokens, (long long)(ring.ring_blocks * bs),
(long long)kStreamFloorTokens, (long long)ring.raised_blocks, (long long)bs);
}
}
/* The raised ring may cover the whole context, which does not stream. */
out->ring_blocks = ring.ring_blocks;
out->ring_tokens = ring.ring_blocks * bs;
out->raised_tokens = ring.raised_blocks > 0 ? ring.ring_blocks * bs : 0;
out->raised_by_union = ring.raised_blocks > 0 && ring.by_union;
out->group = ring.streams() ? g : -1;
/* Prefill takes the stage and never resolves: above `qsa_exact_to` a launch selects a chunk's
* union, which no ring could hold. The stage is the group's context one layer deep, addressed
* by block id (kvstream/bind.h says which passes take it). */
out->stage_blocks = ring.streams() ? ring.ctx_blocks : 0;
return RAD_OK;
}
void kvstream_host_add(KVStreamHostUse* use, const KVManager& kv) {
const KVStreamCost c = kv.stream_cost();
use->sum.groups += c.groups;
use->sum.host_bytes += c.host_bytes;
use->sum.map_bytes += c.map_bytes;
use->max_rank_bytes = std::max(use->max_rank_bytes, c.host_bytes);
}
int kvstream_host_gate(const KVStreamHostUse& use, int n_ranks, int64_t still, int64_t headroom) {
if (use.sum.host_bytes <= 0) return RAD_OK;
std::string why;
if (lockable_room(use.sum.host_bytes, still, headroom, false, &why)) return RAD_OK;
RAD_ERR("kv streaming: the host mirror for %lld streamed KV group(s) needs up to %s of "
"pinned host memory a rank (%s over %d ranks), and %s. It holds one full context a "
"sequence: lower --max-model-len or --max-num-seqs, or set --kv-resident 0 "
"(--host-pool-mib sizes the experts' tier, not this one)",
(long long)use.sum.groups, humanb(use.max_rank_bytes).c_str(),
humanb(use.sum.host_bytes).c_str(), n_ranks, why.c_str());
return RAD_E_NOMEM;
}
int kvstream_fill(KVManager& kv) {
/* After the carve, which backs an elastic pool's range; drained before the first pass reads the
* maps. */
RadStream st = nullptr;
int rc = rad_stream_create(&st, 0);
if (rc == RAD_OK) rc = kv.init_stream(st);
if (rc == RAD_OK) rc = rad_stream_sync(st);
rad_stream_destroy(st);
return rc;
}
void kvstream_report(const KVStreamSetup& s, const KVStreamHostUse& host, int n_ranks) {
const int64_t flag = s.raised_tokens > 0 ? s.raised_tokens : s.asked_tokens;
if (s.raised_tokens > 0 && s.block_size > 0)
RAD_INFO("kv streaming: --kv-resident %lld became %lld tokens (%lld -> %lld blocks of "
"%lld tokens), %s",
(long long)s.asked_tokens, (long long)s.raised_tokens,
(long long)((s.asked_tokens + s.block_size - 1) / s.block_size),
(long long)(s.raised_tokens / s.block_size), (long long)s.block_size,
s.raised_by_union ? "the blocks one decode step can select"
: "the floor below which misses cost more than the ring saves");
if (host.sum.groups > 0)
RAD_INFO("kv streaming: %lld group(s) stream (%s): up to %s of pinned host mirror a "
"rank (%s over %d), %s of ring maps in the KV pools",
(long long)host.sum.groups, s.group_name.c_str(),
humanb(host.max_rank_bytes).c_str(), humanb(host.sum.host_bytes).c_str(), n_ranks,
humanb(host.sum.map_bytes).c_str());
if (s.stage_blocks > 0)
RAD_INFO("kv streaming: prefill staging, group '%s' ring %lld blocks, one-layer stage %lld "
"blocks (one layer of its %lld-block context); decode passes use the ring",
s.group_name.c_str(), (long long)s.ring_blocks,
(long long)s.stage_blocks, (long long)s.ctx_blocks);
if (s.group < 0 && s.asked_tokens > 0 && s.ctx_blocks > 0)
RAD_INFO("kv streaming: nothing streams: --kv-resident %lld covers group '%s''s "
"%lld-token context (%lld blocks), so the group stays resident; below %lld "
"tokens it would stream",
(long long)flag, s.group_name.c_str(), (long long)s.context_tokens,
(long long)s.ctx_blocks, (long long)s.context_tokens);
}
} /* namespace rad */
+78
View File
@@ -0,0 +1,78 @@
/* bringup.h -- the engine side of a streamed group's bring-up (docs/KV-STREAMING.md §4.1).
*
* `--kv-resident N` is the only switch: absent or 0 nothing streams, and a ring that covers the
* group's context streams nothing either, so the group keeps the resident path at no cost. This
* module chooses the group, refuses what cannot stream, applies the ring's floors, gates the host
* mirrors against host RAM, fills the maps and reports, so core/engine_bringup.cpp makes one call
* at each seam.
*/
#pragma once
#include "mem/kv.h"
#include <string>
#include <vector>
namespace rad {
struct Config;
/* What --kv-resident resolved to. `group` is -1 when nothing streams; the other fields then say
* what was asked and why, for the report. */
struct KVStreamSetup {
int32_t group = -1; /* the group that streams; -1 when none does */
std::string group_name; /* the group that would have */
int64_t asked_tokens = 0; /* --kv-resident as given */
int64_t raised_tokens = 0; /* the ring a floor raised it to; 0 when not raised */
bool raised_by_union = false; /* raised to the decode-step bound, not the floor */
int64_t context_tokens = 0; /* --max-model-len x --max-num-seqs */
int64_t ring_tokens = 0; /* the carved ring, in tokens */
int64_t ring_blocks = 0; /* the carved ring, in blocks */
int64_t block_size = 0; /* the group's page, in tokens */
int64_t ctx_blocks = 0; /* the group's id space, in blocks */
int64_t stage_blocks = 0; /* the stage view's depth in blocks; 0 when none */
};
/* The host mirrors summed over the ranks; `max_rank_bytes` is the largest one rank pins (an uneven
* tensor-parallel split gives ranks different shards). */
struct KVStreamHostUse {
KVStreamCost sum;
int64_t max_rank_bytes = 0;
};
/* Whether `op` must not be declared: the streamed-only ops (kv_store_streamed, its folded form,
* kv_resolve) exist only for a carved ring, so a run that carves none must not have them in its
* graph. False when the architecture streams (RadBuildCtx::kv_stream_ok) and --kv-resident asks
* for a ring. Every architecture's rad_op_declared check then falls through to its resident path. */
bool kvstream_op_gated(const RadBuildCtx& ctx, const char* op);
/* Read --kv-resident against rank 0's declarations and fill `out`; RAD_OK with group -1 when
* nothing streams.
*
* - The group is kv_stream_group's. A ring that covers its context streams nothing.
* - An architecture with no streamed path for the group (kvstream_ops: no kv_resolve, or no
* streamed store, as for a packed fp8_v4 / k6_v4 cache) ignores the flag with one warning
* naming the missing op or the layout; `out` is then exactly the no-flag configuration.
* - A core dtype other than E4M3 or bf16 is refused: the streamed store has rows for those only.
* - A ring below the decode-step bound or kStreamFloorTokens is raised, with one warning.
* --kv-resident itself is left as given; `out` holds both numbers for the report. */
int kvstream_configure(const Config& cfg, int64_t ctx, const std::vector<KVGroupInfo>& groups,
const Program& prog, KVStreamSetup* out);
/* Add one rank's stream_cost() to `use`. */
void kvstream_host_add(KVStreamHostUse* use, const KVManager& kv);
/* The host-RAM gate for the mirrors, checked once before any rank pins one. A mirror is one full
* context of the group per sequence per rank, the largest host allocation after the experts'
* pool, so it is checked against everything still to be pinned after it (`still`). A refusal
* names --max-model-len and --max-num-seqs, which size it; --host-pool-mib sizes the experts' pool
* and cannot make room here. */
int kvstream_host_gate(const KVStreamHostUse& use, int n_ranks, int64_t still, int64_t headroom);
/* After the carve: fill the maps on a bring-up stream and drain it. */
int kvstream_fill(KVManager& kv);
/* The startup lines: the raised ring, which group streams and what it took on both tiers, the
* stage, or which context a ring given by the flag covers. */
void kvstream_report(const KVStreamSetup& s, const KVStreamHostUse& host, int n_ranks);
} /* namespace rad */
+141
View File
@@ -0,0 +1,141 @@
/* carve.cpp -- see carve.h. */
#include "kvstream/carve.h"
#include "kvstream/mirror.h"
#include "kvstream/plan.h"
#include "mem/kv.h"
namespace rad {
int64_t kvstream_maps_charged(const std::vector<KVGroupPlan>& plans, const KVStreamStore& st,
int64_t max_ctx, int64_t max_seqs) {
return st.cost(plans, max_ctx, max_seqs).map_bytes;
}
bool kvstream_dense(const KVGroupPlan& p, const std::vector<KVGroupPlan>& plans,
const KVStreamStore& st) {
if (!p.paged() || p.zero || p.kind != RAD_KV_FULL || !p.dense_read) return false;
for (const auto& q : plans)
if (!q.zero && q.paged() && st.windowed(q.index)) return true;
return false;
}
int64_t kvstream_dense_charged(const std::vector<KVGroupPlan>& plans, const KVStreamStore& st,
int64_t max_ctx, int64_t max_seqs) {
int64_t bytes = 0;
for (const auto& p : plans) {
if (!kvstream_dense(p, plans, st)) continue;
bytes += align_up(kv_context_blocks(p.block_size, max_ctx, max_seqs) * p.bytes_per_block,
RAD_ALIGN_UNIT);
}
return bytes;
}
void kvstream_split_windows(const std::vector<KVGroupPlan>& plans, const KVStreamStore& st,
int64_t max_ctx, int64_t max_seqs, int64_t* remaining,
std::vector<int64_t>* out) {
for (const auto& p : plans) {
if (!p.paged() || p.zero || !st.windowed(p.index)) continue;
const int64_t slots = st.resident_blocks(p);
*remaining -= kv_pool_bytes(p, slots, st.context_blocks(p, max_ctx, max_seqs));
(*out)[p.index] = slots;
}
/* The maps, which the probe cannot reserve yet, or the pool it sizes falls short by them. */
*remaining -= kvstream_maps_charged(plans, st, max_ctx, max_seqs);
/* A dense-read group's floor is every sequence's context, fixed by the configuration. */
for (const auto& p : plans) {
if (!kvstream_dense(p, plans, st)) continue;
const int64_t blocks = kv_context_blocks(p.block_size, max_ctx, max_seqs);
*remaining -= align_up(blocks * p.bytes_per_block, RAD_ALIGN_UNIT);
(*out)[p.index] = blocks;
}
}
int kvstream_window_fit(const std::vector<KVGroupPlan>& plans, const KVStreamStore& st,
int64_t fixed, int64_t budget, int64_t max_ctx, int64_t max_seqs) {
int64_t window_bytes = 0;
int64_t window_groups = 0;
for (const auto& p : plans) {
if (!p.paged() || p.zero || !st.windowed(p.index)) continue;
if (p.kind != RAD_KV_FULL) {
RAD_ERR("KV group '%s' is a %s group and streaming is set for it: only a full "
"attention group streams (a window's block ids are its window's, not its "
"context's)",
p.name.c_str(), kv_kind_name(p.kind));
return RAD_E_INVAL;
}
window_bytes += kv_pool_bytes(p, st.resident_blocks(p),
st.context_blocks(p, max_ctx, max_seqs));
++window_groups;
}
const int64_t map_bytes = kvstream_maps_charged(plans, st, max_ctx, max_seqs);
const int64_t dense_bytes = kvstream_dense_charged(plans, st, max_ctx, max_seqs);
int64_t dense_groups = 0;
for (const auto& p : plans) if (kvstream_dense(p, plans, st)) ++dense_groups;
if (fixed + window_bytes + map_bytes + dense_bytes > budget) {
RAD_ERR("the resident KV windows and dense-read groups do not fit vram_kv:\n"
" resident windows %10s (%lld group(s) streaming)\n"
" ring maps %10s (the streamed groups' residency maps)\n"
" dense-read groups %10s (%lld group(s) at %lld sequences x %lld tokens)\n"
" linear/conv state %10s (%lld sequences)\n"
" vram_kv %10s\n"
" short by %10s\n"
"Lower --kv-resident (the ring) or --max-model-len / --max-num-seqs (the one-layer "
"stage and the dense-read floor), or give the cache more of the card: a smaller "
"--gpu-headroom-mib or a larger --host-pool-mib.",
humanb(window_bytes).c_str(), (long long)window_groups,
humanb(map_bytes).c_str(), humanb(dense_bytes).c_str(), (long long)dense_groups,
(long long)max_seqs, (long long)max_ctx, humanb(fixed).c_str(),
(long long)max_seqs, humanb(budget).c_str(),
humanb(fixed + window_bytes + map_bytes + dense_bytes - budget).c_str());
return RAD_E_NOMEM;
}
return RAD_OK;
}
int kvstream_apply(std::vector<KVGroupPlan>& plans, const KVStreamStore& st,
int64_t max_ctx, int64_t max_seqs) {
for (auto& p : plans) {
if (!p.paged()) continue;
if (st.windowed(p.index) && !p.zero) {
/* The split gave a streamed group its window; its ids run over its context. */
p.n_blocks = st.context_blocks(p, max_ctx, max_seqs);
p.n_slots = st.resident_blocks(p);
/* A ring that covers the context never reaches here (kvstream_ring), so the group has a
* stage. */
p.depth = p.streamed() ? 1 : 0;
} else {
p.n_slots = p.n_blocks;
}
if (p.n_slots > p.n_blocks) p.n_slots = p.n_blocks;
/* A streamed group has no tier entry (its mirror is its tier), so replication, which
* describes the tier slot, does not apply. */
if (p.streamed()) p.replicated = false;
/* An unbacked block id would be written past the layer stride: fluent wrong output, so
* refuse here. RAD_E_INVAL, since RAD_E_STATE reads as "called in the wrong phase". */
if (p.streamed()) {
const KVStreamStore::Map* m = st.map(p.index);
const int64_t need = p.n_blocks * p.bytes_per_block;
if (!m || !m->host || !m->res || m->host_bytes < need) {
RAD_ERR("KV group '%s' streams (%lld of its %lld blocks resident) but has no host "
"mirror of %s and residency map to hold the rest: an engine bug",
p.name.c_str(), (long long)p.n_slots, (long long)p.n_blocks,
humanb(need).c_str());
return RAD_E_INVAL;
}
}
}
return RAD_OK;
}
std::string kvstream_report_line(const KVGroupPlan& p) {
return fmt(" %-14s %-6s streaming: %7lld blocks resident in vram_kv at "
"+%lld = %9s, %7lld blocks = %9s mirrored in pinned host memory, "
"maps %s\n", "", "", (long long)p.pool_blocks(),
(long long)p.pool_offset, humanb(p.pool_bytes).c_str(),
(long long)p.n_blocks,
humanb(p.n_blocks * p.bytes_per_block).c_str(),
humanb(kvstream_map_bytes(p.n_blocks, p.pool_blocks(), p.n_layers)).c_str());
}
} /* namespace rad */
+58
View File
@@ -0,0 +1,58 @@
/* carve.h -- the streamed groups' part of KVManager::carve() (docs/KV-STREAMING.md §4.1, §4.2):
* the resident windows and dense-read floors leave the budget before the other groups split the
* rest; after the split each paged group's n_slots (and a streamed group's context and depth) is
* written, refusing a streamed group with nothing to back its other blocks; and the pool report
* gains a line naming both tiers. Arithmetic on the plans only.
*/
#pragma once
#include <cstdint>
#include <string>
#include <vector>
namespace rad {
struct KVGroupPlan;
class KVStreamStore;
/* Bytes the streamed groups' maps take from the KV pool (KVStreamStore::cost). They are reserved
* before carve(), so the budget probe, which cannot reserve them, charges them in paged_split()
* and the carve adds them back to its budget: both then see the same bytes. */
int64_t kvstream_maps_charged(const std::vector<KVGroupPlan>& plans, const KVStreamStore& st,
int64_t max_ctx, int64_t max_seqs);
/* Whether `p` is a dense-read group (rad_kv_group_dense_read: an indexer's block keys, read over
* the whole history every step) while a sibling streams. Its pool must then hold every sequence's
* context, since the sibling's mirror is sized for max_seqs. False when nothing streams: the cache
* is then sized for one full-length sequence. */
bool kvstream_dense(const KVGroupPlan& p, const std::vector<KVGroupPlan>& plans,
const KVStreamStore& st);
/* The dense-read groups' full contexts in bytes, rounded as reserve() rounds them. */
int64_t kvstream_dense_charged(const std::vector<KVGroupPlan>& plans, const KVStreamStore& st,
int64_t max_ctx, int64_t max_seqs);
/* Take the streamed groups' windows, their maps and the dense-read groups' full contexts out of
* the split before the other groups share the rest: `remaining` loses their bytes and
* `out[group]` becomes the window's depth (or the dense-read context) in blocks. A streamed
* group's context lives in host memory, so it does not compete for the pool. */
void kvstream_split_windows(const std::vector<KVGroupPlan>& plans, const KVStreamStore& st,
int64_t max_ctx, int64_t max_seqs, int64_t* remaining,
std::vector<int64_t>* out);
/* Refuse windows and dense-read floors that do not fit `budget`, before anything is split.
* Otherwise the other groups would be left zero blocks and refused for a small pool, pointing the
* operator at the wrong flag. The fixed costs were checked by the caller. A window group cannot
* stream: its ids are its window's, not its context's. */
int kvstream_window_fit(const std::vector<KVGroupPlan>& plans, const KVStreamStore& st,
int64_t fixed, int64_t budget, int64_t max_ctx, int64_t max_seqs);
/* After the split: write every paged group's n_slots (its carve unless it streams) and, for a
* streamed group, its context as n_blocks and its depth. Refuses a streamed group whose host
* mirror or residency map is missing. */
int kvstream_apply(std::vector<KVGroupPlan>& plans, const KVStreamStore& st,
int64_t max_ctx, int64_t max_seqs);
/* The pool report's extra line for a streamed group, whose pool is smaller than its context. */
std::string kvstream_report_line(const KVGroupPlan& p);
} /* namespace rad */
+196
View File
@@ -0,0 +1,196 @@
/* mirror.cpp -- see mirror.h. */
#include "kvstream/mirror.h"
#include <sys/mman.h>
#include "kvstream/plan.h"
#include <algorithm>
#include <cstdlib>
#include <cstring>
namespace rad {
namespace {
int64_t ceil_div(int64_t a, int64_t b) { return b > 0 ? (a + b - 1) / b : 0; }
/* Each array starts 8-byte aligned: `ctl`'s counters are read as u64 pairs, and an odd block
* count or ring depth would misalign the next array. The pool base is RAD_ALIGN_UNIT aligned. */
int64_t align8(int64_t n) { return (n + 7) & ~(int64_t)7; }
/* The maps' one layout, shared by alloc(), init() and kvstream_map_bytes(). */
struct MapLayout {
int64_t res_bytes = 0, slot_block_bytes = 0, slot_state_bytes = 0, ctl_bytes = 0;
int64_t res = 0, slot_block = 0, slot_state = 0, ctl = 0;
int64_t bytes = 0; /* the whole reservation */
};
MapLayout map_layout(int64_t blocks, int64_t slots, int64_t layers) {
if (layers < 1) layers = 1;
MapLayout l;
l.res_bytes = layers * blocks * (int64_t)sizeof(int32_t);
l.slot_block_bytes = layers * slots * (int64_t)sizeof(int32_t);
l.slot_state_bytes = layers * slots * 2 * (int64_t)sizeof(int32_t);
l.ctl_bytes = 16 * (int64_t)sizeof(int32_t);
l.res = 0; /* res, block -> slot, one map a layer */
l.slot_block = l.res + align8(l.res_bytes); /* slot_block, slot -> block */
l.slot_state = l.slot_block + align8(l.slot_block_bytes);/* slot_state: epoch, heat */
l.ctl = l.slot_state + align8(l.slot_state_bytes);/* ctl, shared by the layers */
l.bytes = l.ctl + align8(l.ctl_bytes);
return l;
}
} /* namespace */
int64_t kvstream_map_bytes(int64_t blocks, int64_t slots, int64_t layers) {
return map_layout(blocks, slots, layers).bytes;
}
void KVStreamStore::cap(int32_t group, int64_t tokens) {
if (group < 0) return;
if ((size_t)group >= resident_tokens_.size()) resident_tokens_.resize((size_t)group + 1, 0);
resident_tokens_[(size_t)group] = tokens > 0 ? tokens : 0;
}
bool KVStreamStore::windowed(int32_t group) const {
return group >= 0 && (size_t)group < resident_tokens_.size() &&
resident_tokens_[(size_t)group] > 0;
}
int64_t KVStreamStore::resident_blocks(const KVGroupPlan& p) const {
const size_t g = (size_t)p.index;
if (g >= resident_tokens_.size() || resident_tokens_[g] <= 0 || p.block_size <= 0) return 0;
return ceil_div(resident_tokens_[g], p.block_size);
}
int64_t KVStreamStore::context_blocks(const KVGroupPlan& p, int64_t max_ctx,
int64_t max_seqs) const {
return kv_context_blocks(p.block_size, max_ctx, max_seqs);
}
void KVStreamStore::set_map(int32_t group, const Map& m) {
if (group < 0) return;
if ((size_t)group >= maps_.size()) maps_.resize((size_t)group + 1);
maps_[(size_t)group] = m;
}
const KVStreamStore::Map* KVStreamStore::map(int32_t group) const {
if (group < 0 || (size_t)group >= maps_.size()) return nullptr;
return &maps_[(size_t)group];
}
const RadKVStream* KVStreamStore::view(const KVGroupPlan* p, int32_t group) const {
/* A ring that covers the context is never capped, so such a group gets null here. */
if (!p || !p->streamed() || !windowed(group)) return nullptr;
const Map* m = map(group);
return m && m->host && m->res ? m : nullptr;
}
KVStreamCost KVStreamStore::cost(const std::vector<KVGroupPlan>& plans, int64_t max_ctx,
int64_t max_seqs) const {
KVStreamCost c;
for (const auto& p : plans) {
if (!windowed(p.index) || p.zero || p.kind != RAD_KV_FULL) continue;
const int64_t blocks = context_blocks(p, max_ctx, max_seqs);
const int64_t slots = std::min(resident_blocks(p), blocks);
if (blocks <= 0 || slots <= 0) continue;
c.host_bytes += blocks * p.bytes_per_block;
c.map_bytes += kvstream_map_bytes(blocks, slots, p.n_layers);
++c.groups;
}
return c;
}
int KVStreamStore::alloc(const std::vector<KVGroupPlan>& plans, int64_t max_ctx, int64_t max_seqs,
MemAllocator& host_alloc, Pool& kv_pool) {
for (const auto& p : plans) {
if (!windowed(p.index) || p.zero || p.kind != RAD_KV_FULL) continue;
const int64_t blocks = context_blocks(p, max_ctx, max_seqs);
const int64_t slots = std::min(resident_blocks(p), blocks);
if (blocks <= 0 || slots <= 0) continue;
Map m;
m.slots = slots;
m.block_bytes = p.layer_bytes_per_block();
m.host_layer_stride = blocks * m.block_bytes;
m.host_bytes = blocks * p.bytes_per_block;
m.host = static_cast<uint8_t*>(host_alloc.alloc(m.host_bytes, RAD_MEM_HOST_MAPPED));
if (!m.host) {
RAD_ERR("KV group '%s': the host mirror of %s (%lld blocks of %s) could not be "
"allocated", p.name.c_str(), humanb(m.host_bytes).c_str(), (long long)blocks,
humanb(p.bytes_per_block).c_str());
release(host_alloc);
return RAD_E_NOMEM;
}
/* A block nothing has written is still copied in on a miss, so its bytes must be defined. */
std::memset(m.host, 0, (size_t)m.host_bytes);
/* One reservation for all of the group's maps, from the KV pool so its report names them. */
const int64_t layers = p.n_layers > 0 ? p.n_layers : 1;
const MapLayout lay = map_layout(blocks, slots, layers);
const int64_t map_bytes = lay.bytes;
std::string what = "kv_stream_maps:" + p.name;
char* at = static_cast<char*>(kv_pool.reserve(what, map_bytes, RAD_ALIGN_UNIT, nullptr));
if (!at) {
RAD_ERR("KV group '%s': its residency map and ring bookkeeping (%s) did not fit the "
"KV pool", p.name.c_str(), humanb(map_bytes).c_str());
host_alloc.free(m.host, RAD_MEM_HOST_MAPPED);
release(host_alloc);
return RAD_E_NOMEM;
}
/* Residency is per layer, because the resolve copies one layer's block: a group-wide map
* would call a block resident in a layer whose bytes were never copied. The control
* block is the group's. */
m.res = reinterpret_cast<int32_t*>(at + lay.res);
m.slot_block = reinterpret_cast<int32_t*>(at + lay.slot_block);
m.slot_state = reinterpret_cast<int32_t*>(at + lay.slot_state);
m.ctl = reinterpret_cast<int32_t*>(at + lay.ctl);
set_map(p.index, m);
}
return RAD_OK;
}
int KVStreamStore::init(const std::vector<KVGroupPlan>& plans, RadStream s) {
if (!s) {
RAD_ERR("kv streaming: the maps must be filled on a stream, and none was given");
return RAD_E_INVAL;
}
for (const auto& p : plans) {
const Map* m = map(p.index);
if (!m || !m->host || !m->res) continue;
/* The state a resolve expects (libref/ref_kvstream.cpp): both maps -1, slot state and
* control block 0. Every block starts absent. */
const MapLayout lay = map_layout((int64_t)p.n_blocks, m->slots,
p.n_layers > 0 ? p.n_layers : 1);
int rc = RAD_OK;
rc = rad_memset_async(m->res, 0xff, lay.res_bytes, s);
if (rc == RAD_OK) rc = rad_memset_async(m->slot_block, 0xff, lay.slot_block_bytes, s);
if (rc == RAD_OK) rc = rad_memset_async(m->slot_state, 0, lay.slot_state_bytes, s);
if (rc == RAD_OK) rc = rad_memset_async(m->ctl, 0, lay.ctl_bytes, s);
if (rc != RAD_OK) {
RAD_ERR("KV group '%s': the residency map could not be initialised: %s",
p.name.c_str(), rad_dev_last_error());
return rc;
}
}
return RAD_OK;
}
void KVStreamStore::release(MemAllocator& host_alloc) {
for (auto& m : maps_) {
if (!m.host) continue;
host_alloc.free(m.host, RAD_MEM_HOST_MAPPED);
/* Cleared, so a second call is a no-op. */
m = Map{};
}
}
KVStreamStats KVStreamStore::stats(const std::vector<KVGroupPlan>& plans) const {
KVStreamStats st;
st.misses = misses_;
st.bytes_in = bytes_in_;
for (const auto& p : plans)
if (p.streamed()) st.resident_blocks += p.pool_blocks();
return st;
}
} /* namespace rad */
+101
View File
@@ -0,0 +1,101 @@
/* mirror.h -- a streamed group's host mirror and residency maps (docs/KV-STREAMING.md §4.1).
*
* A streamed group's device pool backs a resident window, not its context. Every block lives in a
* pinned host mirror laid out layer-major and block-indexed like the pool, and a device residency
* map gives each block's ring slot (-1 when absent). KVStreamStore owns the window caps, the
* mirrors, the maps and their sizing, so mem/kv.{h,cpp} keeps one member and one call per method.
* Only init() touches a device: it fills the maps on the stream it is given.
*/
#pragma once
#include "mem/pools.h"
#include <cstdint>
#include <vector>
namespace rad {
struct KVGroupPlan;
/* What the streamed groups need, before anything is taken: `host_bytes` of pinned mirror (each rank
* its own shard) and `map_bytes` of residency map, reverse map, slot state and control block, all
* taken from the KV pool itself and budgeted with it. Valid between plan_groups() and carve(). */
struct KVStreamCost {
int64_t groups = 0;
int64_t host_bytes = 0;
int64_t map_bytes = 0;
};
/* The resolve's counters for the metrics; zeros on a server that does not stream. */
struct KVStreamStats {
int64_t resident_blocks = 0;
uint64_t misses = 0; /* blocks placed in the ring by resolve launches */
uint64_t bytes_in = 0; /* bytes those placements copied from the host mirror */
};
/* Bytes of one streamed group's maps: the residency map (one entry a block, per layer), the
* ring's reverse map and slot state (per layer), and the shared control block. */
int64_t kvstream_map_bytes(int64_t blocks, int64_t slots, int64_t layers);
/* The streamed groups' state by group handle: window caps, mirrors, maps and the resolve's
* counters. A group's Map is the ABI's RadKVStream, so the run phase reads the fields alloc()
* fills. Empty on a manager that does not stream. */
class KVStreamStore {
public:
using Map = RadKVStream;
/* The tokens of `group`'s context its device pool backs; 0 (the default) is all of it. Only the
* named group: its neighbours (an indexer's block keys, read over the whole history) stay
* resident. */
void cap(int32_t group, int64_t tokens);
/* Whether cap() narrowed `group` to a window: its block ids run over the context and only
* `n_slots` of them are in device memory. */
bool windowed(int32_t group) const;
/* The window in whole blocks; at least one, since a pool that holds nothing cannot run. */
int64_t resident_blocks(const KVGroupPlan& p) const;
/* Blocks the group's context addresses (kv_context_blocks). The block table is already pitched
* for them, whether the pool backs them or not. */
int64_t context_blocks(const KVGroupPlan& p, int64_t max_ctx, int64_t max_seqs) const;
void set_map(int32_t group, const Map& m);
const Map* map(int32_t group) const;
/* The ABI view of a streamed group, or null for a resident one. Its addresses are fixed from
* bring-up, which lets a recorded pass that reads it replay. */
const RadKVStream* view(const KVGroupPlan* p, int32_t group) const;
KVStreamCost cost(const std::vector<KVGroupPlan>& plans, int64_t max_ctx, int64_t max_seqs) const;
/* Take the mirror and the maps for every streamed group. Call after plan_groups() and before
* carve(), which refuses a streamed group with no map and whose paged split must see the maps'
* bytes gone. The mirror is zeroed: a block nothing has written yet is still read on a miss.
* The maps are filled by init() after the carve backs the pool. On failure the mirrors taken
* so far are released. */
int alloc(const std::vector<KVGroupPlan>& plans, int64_t max_ctx, int64_t max_seqs,
MemAllocator& host_alloc, Pool& kv_pool);
/* Fill the maps as a resolve expects them: `res` and `slot_block` -1, `slot_state` and `ctl`
* zero. Call after carve(), then sync `s` before the first pass. */
int init(const std::vector<KVGroupPlan>& plans, RadStream s);
/* Free the mirrors; the maps go with the KV pool. Safe twice and after a failed bring-up. */
void release(MemAllocator& host_alloc);
KVStreamStats stats(const std::vector<KVGroupPlan>& plans) const;
/* Charged by the engine, which reads the resolve's counters where a step has drained. */
void note_traffic(int64_t misses, int64_t bytes) {
if (misses > 0) misses_ += (uint64_t)misses;
if (bytes > 0) bytes_in_ += (uint64_t)bytes;
}
private:
std::vector<int64_t> resident_tokens_; /* by group handle: its pool's depth in tokens */
std::vector<Map> maps_; /* set_map(), by group handle */
uint64_t misses_ = 0; /* note_traffic() */
uint64_t bytes_in_ = 0;
};
} /* namespace rad */
+186
View File
@@ -0,0 +1,186 @@
/* plan.cpp -- see plan.h. */
#include "kvstream/plan.h"
#include <algorithm>
namespace rad {
int64_t kv_pool_bytes(const KVGroupPlan& p, int64_t slots, int64_t context_blocks) {
if (!p.paged()) return p.n_states * p.bytes_per_state;
const int64_t ring = kv_ring_bytes(p, slots);
if (slots <= 0 || slots >= context_blocks) return ring;
return std::max(ring, context_blocks * p.layer_bytes_per_block());
}
int64_t kv_pool_bytes(const KVGroupPlan& p) {
return kv_pool_bytes(p, p.pool_blocks(), p.n_blocks);
}
int64_t kv_ceiling_bytes(const KVGroupPlan& p, int64_t blocks, int64_t slots) {
if (!p.paged() || p.block_size <= 0) return 0;
if (slots <= 0 || slots >= blocks) return blocks * p.bytes_per_block;
return kv_pool_bytes(p, slots, blocks);
}
namespace {
/* Both overloads' rule: from group 1 on, the widest full group that owns bytes, is neither zero
* nor dense-read, and passes the caller's test. */
bool kv_stream_candidate(int32_t kind, bool zero, bool dense_read, int64_t bytes_per_block) {
return kind == RAD_KV_FULL && !zero && !dense_read && bytes_per_block > 0;
}
template <class Candidate>
int32_t kv_stream_widest(size_t n, const Candidate& candidate) {
int32_t best = -1;
int64_t widest = 0;
for (size_t g = 1; g < n; ++g) {
int64_t bytes = 0;
if (!candidate(g, &bytes)) continue;
if (bytes > widest) {
widest = bytes;
best = (int32_t)g;
}
}
return best;
}
} /* namespace */
int32_t kv_stream_group(const KVManager& kv, const Program* prog) {
const std::vector<KVGroupPlan>& ps = kv.plans();
return kv_stream_widest(ps.size(), [&](size_t g, int64_t* bytes) {
const KVGroupPlan& p = ps[g];
if (!kv_stream_candidate(p.kind, p.zero, p.dense_read, p.bytes_per_block)) return false;
const KVGroupInfo* gi = g < prog->kv_groups.size() ? &prog->kv_groups[g] : nullptr;
if (!kvstream_ops(*prog, gi).streams()) return false;
*bytes = p.bytes_per_block;
return true;
});
}
int32_t kv_stream_group(const std::vector<KVGroupInfo>& gs, const Program* prog) {
return kv_stream_widest(gs.size(), [&](size_t g, int64_t* bytes) {
const KVGroupInfo& gi = gs[g];
if (!kv_stream_candidate(gi.decl.kind, gi.zero, gi.dense_read, gi.bytes_per_block))
return false;
if (prog && !kvstream_ops(*prog, &gi).streams()) return false;
*bytes = gi.bytes_per_block;
return true;
});
}
int64_t kvstream_ceiling_blocks(const Config& cfg, int64_t sel_pitch) {
if (sel_pitch <= 0 || cfg.max_seqs <= 0) return 0;
/* One selection per row; a verify step is 1 + n_spec rows a sequence. */
const int64_t rows = cfg.max_seqs * (1 + (cfg.n_spec > 0 ? cfg.n_spec : 0));
return rows * sel_pitch;
}
KVStreamOps kvstream_ops(const Program& prog, const KVGroupInfo* group) {
KVStreamOps ops;
/* Whether a declaration has a kernel in some domain: an op no row matched keeps a placeholder band
* with both domains null (Builder::op_resolved asks the same). */
const auto resolved = [](const OpInfo& o) {
for (const Band& b : o.bands)
for (int d = 0; d < RAD_N_DOMAINS; ++d)
if (b.dom[d]) return true;
return false;
};
/* The group's per-layer block pitch, which kv_resolve states as `block_bytes`. */
const int64_t n_bound = group && !group->layers.empty() ? (int64_t)group->layers.size() : 1;
const int64_t layer_bytes =
group && group->bytes_per_block > 0 ? group->bytes_per_block / n_bound : 0;
for (const OpInfo& op : prog.ops) {
/* A declaration with no kernel issues nothing (a packed cache layout has no streamed store
* row); counting it would stream a group whose mirror is never written. */
if (!resolved(op)) continue;
const bool is_resolve = op.op == "kv_resolve";
const bool is_store = op.op == "kv_store_streamed" ||
op.op == "qk_norm_rope_gate_kv_store_streamed";
if (!is_resolve && !is_store) continue;
/* A declaration stating another group's geometry does not stream this one; one stating
* none is taken at its word. */
long long stated = 0;
if (is_resolve && layer_bytes > 0 && op.base.get_i("block_bytes", &stated) &&
stated != layer_bytes)
continue;
if (is_store && group && group->block_size > 0 &&
op.base.get_i("block_size", &stated) && stated != group->block_size)
continue;
if (is_resolve) {
long long pitch = 0;
if (!op.base.get_i("sel_pitch", &pitch) || pitch <= 0) continue;
/* Every layer of the group declares the same pitch; the first wins. */
if (!ops.resolve) ops.sel_pitch = (int64_t)pitch;
ops.resolve = true;
} else if (op.op == "kv_store_streamed") {
ops.store = true;
} else {
ops.folded = true;
}
}
return ops;
}
KVStreamRing kvstream_ring_shape(const Config& cfg, int64_t ctx, int64_t block_size) {
KVStreamRing out;
const int64_t bs = block_size > 0 ? block_size : 1;
out.ctx_blocks = kv_context_blocks(bs, ctx, cfg.max_seqs);
out.ring_blocks = cfg.kv_resident > 0 ? (cfg.kv_resident + bs - 1) / bs : 0;
/* The floor, at most the context: a context under it streams nothing. */
if (out.ring_blocks > 0) {
out.floor_blocks = (kStreamFloorTokens + bs - 1) / bs;
if (out.floor_blocks > out.ctx_blocks) out.floor_blocks = out.ctx_blocks;
if (out.ring_blocks < out.floor_blocks) {
out.ring_blocks = out.floor_blocks;
out.raised_blocks = out.floor_blocks;
}
}
if (out.ring_blocks > out.ctx_blocks) out.ring_blocks = out.ctx_blocks;
return out;
}
void kvstream_ring(const Config& cfg, int64_t ctx, int64_t block_size, int64_t sel_pitch,
KVStreamRing* out) {
*out = kvstream_ring_shape(cfg, ctx, block_size);
if (!out->streams()) return; /* absent, 0, or a ring that covers the context */
/* The decode-step bound is always positive here: a group reaches this only when kvstream_ops
* found a kv_resolve with a sel_pitch, and --max-num-seqs is at least 1. Silent, because this
* runs on every rank's probe and again in bring-up; kvstream_configure prints the one line. */
const int64_t ceiling = kvstream_ceiling_blocks(cfg, sel_pitch);
if (out->ring_blocks < ceiling) {
out->ring_blocks = ceiling < out->ctx_blocks ? ceiling : out->ctx_blocks;
out->raised_blocks = out->ring_blocks;
out->by_union = true;
}
}
/* `cfg.kv_streams` is set by kvstream_cap_probe only when a group really streams. */
int64_t kvstream_prefix_host_off(Config& cfg) {
if (!cfg.kv_streams || cfg.prefix_cache_mib <= 0) return 0;
const int64_t was = cfg.prefix_cache_mib;
cfg.prefix_cache_mib = 0;
return was;
}
int kvstream_cap_probe(KVManager& probe, Config& cfg, const Program& prog, int64_t ctx) {
cfg.kv_streams = false;
if (cfg.kv_resident <= 0) return RAD_OK;
const int32_t g = kv_stream_group(probe, &prog);
if (g < 0) return RAD_OK;
const KVGroupPlan* p = probe.plan(g);
if (!p || p->block_size <= 0) return RAD_OK;
/* No streamed path: priced as without the flag. kvstream_configure warns, once. */
const KVStreamOps ops =
kvstream_ops(prog, g < (int32_t)prog.kv_groups.size() ? &prog.kv_groups[(size_t)g] : nullptr);
if (!ops.streams()) return RAD_OK;
KVStreamRing ring;
/* The raised ring, so the budget and the carve take the same depth. */
kvstream_ring(cfg, ctx, p->block_size, ops.sel_pitch, &ring);
if (!ring.streams()) return RAD_OK;
cfg.kv_streams = true;
probe.cap_resident_tokens(g, ring.ring_blocks * p->block_size);
return RAD_OK;
}
} /* namespace rad */
+120
View File
@@ -0,0 +1,120 @@
/* plan.h -- the KV streaming policy, as arithmetic on a KVGroupPlan. Nothing here touches a device.
*
* A streamed group has two device views over one allocation (docs/KV-STREAMING.md §4.1):
*
* ring n_slots blocks deep, `n_layers` layer stripes, addressed through the residency map;
* stage n_blocks blocks deep, one layer stripe, addressed by block id.
*
* The allocation is max(ring, stage), never the sum. The plan's `depth` is the staged view's stripe
* count (1); the ring keeps the group's `n_layers` stripes.
*
* The VRAM budget is resolved from the plan's ceiling before cap_resident_tokens() runs, so
* kvstream_cap_probe() must teach the budget probe the streamed plan first; otherwise the pool is
* sized for the whole cache and streaming frees nothing.
*/
#pragma once
#include "mem/kv.h"
namespace rad {
/* Bytes of the ring view: `slots` blocks, every layer. Inline so that a caller that only lays out a
* view (kvstream/bind.cpp, linked by tests with weak device fakes) need not link KVManager. */
inline int64_t kv_ring_bytes(const KVGroupPlan& p, int64_t slots) {
return slots > 0 ? slots * p.bytes_per_block : 0;
}
/* Blocks the group's context addresses: `max_seqs` sequences of `max_ctx` tokens, each rounded up
* to whole blocks. The one definition of the id space, for the mirror's size and the ring decision
* alike. */
inline int64_t kv_context_blocks(int64_t block_size, int64_t max_ctx, int64_t max_seqs) {
if (block_size <= 0) return 0;
const int64_t seqs = max_seqs > 0 ? max_seqs : 1;
const int64_t ctx = max_ctx > 0 ? max_ctx : 0;
return seqs * ((ctx + block_size - 1) / block_size);
}
/* The group's one allocation: max(ring, stage) for `slots` resident blocks of `context_blocks`.
* `slots >= context_blocks` is a group that does not stream: `slots` blocks of every layer. The
* one-argument form is the carved plan's. A stateful group is its states. */
int64_t kv_pool_bytes(const KVGroupPlan& p, int64_t slots, int64_t context_blocks);
int64_t kv_pool_bytes(const KVGroupPlan& p);
/* The pool cost ceiling() sums for `blocks` blocks of context and `slots` resident blocks:
* blocks * bytes_per_block unless the group streams. */
int64_t kv_ceiling_bytes(const KVGroupPlan& p, int64_t blocks, int64_t slots);
/* The group --kv-resident streams: the widest paged full group, not dense-read (a step reads those
* over the whole history), for which the program declares a streamed path (kvstream_ops). -1 when
* there is none. */
int32_t kv_stream_group(const KVManager& kv, const Program* prog);
/* The same choice from a rank's declarations, before the plans exist. With no program the
* declared-path test is skipped. */
int32_t kv_stream_group(const std::vector<KVGroupInfo>& groups, const Program* prog = nullptr);
/* What --kv-resident makes of one group. */
struct KVStreamRing {
int64_t ring_blocks = 0; /* the ring: the flag in whole blocks, raised to the floors */
int64_t raised_blocks = 0; /* the depth a floor raised the flag to; 0 when not raised */
int64_t floor_blocks = 0; /* kStreamFloorTokens in blocks, at most the context */
bool by_union = false; /* the raise was the decode-step bound, not kStreamFloorTokens */
int64_t ctx_blocks = 0; /* max_seqs x ceil(ctx / block_size): the group's context */
/* A ring that covers the context does not stream: the group keeps the resident path, with no
* mirror, maps, stage or resolve, and a null RadKVStream. */
bool streams() const { return ring_blocks > 0 && ring_blocks < ctx_blocks; }
};
/* The blocks one decode step's selections can name, which the ring must hold: `max_seqs x
* (1 + n_spec)` rows of at most `sel_pitch` distinct blocks each. A decode-classified pass with
* more rows a sequence than that (the serial drafter's history pass) takes the stage and is not
* counted. 0 when the program declares no kv_resolve. */
int64_t kvstream_ceiling_blocks(const Config& cfg, int64_t sel_pitch);
/* The streamed ops the program declares for `group` (null: any group). A streamed group needs
* `kv_resolve`, which rewrites `sel` from block ids to ring slots, and a store that writes the host
* mirror (`kv_store_streamed`, or its fold into the prologue). Without the resolve the attention
* reads block ids as ring slots, past the ring; without the store a miss copies zeros. A
* declaration whose stated geometry (`block_bytes` on the resolve, `block_size` on the store)
* belongs to another group does not count, nor does one that resolved to no kernel (a packed cache
* layout has no streamed store row). */
struct KVStreamOps {
bool resolve = false; /* kv_resolve with this group's layer bytes and a sel_pitch */
bool store = false; /* kv_store_streamed */
bool folded = false; /* qk_norm_rope_gate_kv_store_streamed */
int64_t sel_pitch = 0; /* the blocks one selection row can name */
bool streams() const { return resolve && (store || folded); }
/* The first op missing, for the startup line; null when streams(). */
const char* missing() const {
if (!resolve) return "kv_resolve";
if (!store && !folded) return "kv_store_streamed";
return nullptr;
}
};
KVStreamOps kvstream_ops(const Program& prog, const KVGroupInfo* group);
/* The depth a ring is never carved below, in tokens (at most the group's context): below it the
* misses of a decode step cost more than the VRAM the ring gives back (docs/KV-STREAMING.md §3.9).
* A floor, not a default: --kv-resident 0 is still off. */
constexpr int64_t kStreamFloorTokens = 32768;
/* The ring and the id space from the flag and kStreamFloorTokens alone, so a caller can tell a
* model with no streamed path from a ring below the decode-step bound. */
KVStreamRing kvstream_ring_shape(const Config& cfg, int64_t ctx, int64_t block_size);
/* kvstream_ring_shape, then raised to kvstream_ceiling_blocks: a ring below what one decode step
* can select would serve a selection table that no longer addresses the pool. Never refuses; the
* caller prints the one warning. `block_size` is the group's page (1 when unknown). */
void kvstream_ring(const Config& cfg, int64_t ctx, int64_t block_size, int64_t sel_pitch,
KVStreamRing* out);
/* Turn the prefix cache's host tier off when a group streams: no entry holding a streamed group
* can be demoted to it. Returns the MiB turned off, 0 when nothing changed. Call after
* kvstream_cap_probe, before anything is sized from --prefix-cache-mib. */
int64_t kvstream_prefix_host_off(Config& cfg);
/* Teach the budget probe the streamed plan (the ring from --kv-resident, the stage from the
* context) before probe.ceiling(ctx), and set `cfg.kv_streams` when a group streams. A model with
* no streamed path is left exactly as without the flag. */
int kvstream_cap_probe(KVManager& probe, Config& cfg, const Program& prog, int64_t ctx);
} /* namespace rad */
+361
View File
@@ -0,0 +1,361 @@
/* stage.cpp -- see stage.h, which states the ordering rule. */
#include "kvstream/stage.h"
#include "device/device.h"
#include "kvstream/bind.h"
#include "runtime/wtab.h"
#include <algorithm>
#include <cstdlib>
namespace rad {
namespace {
/* The layer staged most recently on this rank thread; reset at every pass. */
thread_local int g_last_layer = -1;
/* What the pass staged, reported at the next pass's start. */
struct PassStage {
uint64_t layers = 0, bytes = 0;
int64_t tokens = 0, ctx = 0, live_row = 0; /* live_row: the history one layer reads */
int64_t bound_blocks = 0; /* the manager's bound the copy was clamped to */
int phase = -1;
};
thread_local PassStage g_pass;
/* Waits out a stage list still in flight (defined beside g_pipe). */
static void stage_pipe_drain(Ctx* c);
bool trace_stage() {
static const bool on = std::getenv("RADIANCE_KV_STAGE_TRACE") != nullptr;
return on;
}
/* Under RADIANCE_KV_STAGE_TRACE, one line per pass that staged: the bytes it moved against the
* bytes of history it could read. */
void report_pass() {
if (!g_pass.layers || !trace_stage()) return;
const double live = (double)g_pass.live_row * (double)g_pass.layers;
RAD_INFO("kv streaming: stage pass phase=%d tokens=%lld ctx=%lld: %llu layers, %.1f MiB moved, "
"%.1f MiB of live history (%.1fx), bound %lld blocks",
g_pass.phase, (long long)g_pass.tokens, (long long)g_pass.ctx,
(unsigned long long)g_pass.layers, (double)g_pass.bytes / (1024.0 * 1024.0),
live / (1024.0 * 1024.0), live > 0.0 ? (double)g_pass.bytes / live : 0.0,
(long long)g_pass.bound_blocks);
}
} /* namespace */
/* A pass visits its layers in order and may ask for one layer once per attention launch, so a
* layer is staged once and a consecutive repeat is already done. */
static void kvstage_begin_pass() {
report_pass();
g_last_layer = -1;
g_pass = PassStage();
}
void kvstream_enter(Ctx* c, const RadBatch* b) {
kvstage_begin_pass();
if (!c || !b) return;
g_pass.tokens = b->n_tok;
g_pass.ctx = b->max_ctx_len;
g_pass.phase = b->phase;
for (int i = 0; i < b->n_kv_groups; ++i) {
if (!b->kv[i].stream) continue;
KVPoolBinding* kb = c->kv_binding(b->kv[i].group);
if (!kb || !kb->has_stage) continue;
const bool was_stage = kb->depth == 1;
kv_binding_enter(*kb, kv_pass_view(b->phase, b->n_tok, b->n_seq, b->n_spec));
/* Back on the ring after a staged pass, the residency maps describe bytes the stage has
* overwritten. A staged pass copies whole layers to the pool at block-id identity (block b
* at base + b * block_bytes), which overlaps the ring's slots of other layers, and the
* copy leaves the maps alone: a decode that trusts them reads another layer's, or another
* request's, KV without a fault. The maps are reset, so the first ring pass resolves every
* live block from the mirror as a request's first pass does. `slots < blocks` holds for
* every stream with a stage: bringup gives a stream whose ring covers its context no
* mirror, no resolve and no stage. */
if (was_stage && kb->depth == 0) {
const RadKVStream* st = b->kv[i].stream;
const int64_t bb = st->block_bytes;
const int64_t blocks = bb > 0 ? st->host_layer_stride / bb : 0;
const int64_t layers = st->host_layer_stride > 0
? st->host_bytes / st->host_layer_stride : 0;
if (blocks > 0 && layers > 0 && st->slots > 0 && st->slots < blocks) {
/* A list of the pass that just ended lands before the refill, not after it. */
stage_pipe_drain(c);
(void)rad_memset_async(st->res, 0xff,
layers * blocks * (int64_t)sizeof(int32_t), c->stream());
(void)rad_memset_async(st->slot_block, 0xff,
layers * st->slots * (int64_t)sizeof(int32_t),
c->stream());
(void)rad_memset_async(st->slot_state, 0,
layers * st->slots * 2 * (int64_t)sizeof(int32_t),
c->stream());
}
}
/* The history one layer can read, up to the longest sequence's end, for the report. */
if (kb->stage.bytes > 0 && b->kv[i].block_size > 0 && b->kv[i].stream->block_bytes > 0) {
const int64_t reach = b->max_ctx_len + b->max_q_len;
const int64_t live_blocks = (reach + b->kv[i].block_size - 1) / b->kv[i].block_size;
const int64_t row = std::min(live_blocks * b->kv[i].stream->block_bytes, kb->stage.bytes);
if (row > g_pass.live_row) g_pass.live_row = row;
if (kb->stage_live_bytes > 0) {
const int64_t bound = kb->stage_live_bytes / b->kv[i].stream->block_bytes;
if (bound > g_pass.bound_blocks) g_pass.bound_blocks = bound;
}
}
}
}
/* The allocator's high-water mark in bytes of one layer (stage.h, "Volume"). */
void kvstream_bound_live(Ctx* c, const KVManager& kv) {
if (!c) return;
for (int g = 0; g < kv.n_groups(); ++g) {
KVPoolBinding* b = c->kv_binding(g);
if (!b || !b->has_stage) continue;
const RadKVStream* st = kv.stream_view(g);
if (!st || st->block_bytes <= 0) continue;
const int64_t blocks = kv.held_top_blocks(g);
b->stage_live_bytes = blocks > 0 ? blocks * st->block_bytes : 0;
}
}
namespace {
/* A staged layer's copy: from its mirror row (by group-local position, not model layer) to the
* pool base, where both views start. */
struct StageSrc {
void* dst = nullptr;
const uint8_t* src = nullptr;
int64_t bytes = 0;
};
bool stage_src(Ctx* ctx, int group, const RadKVGroupBatch* kvb, int layer, StageSrc* o) {
const KVPoolBinding* b = ctx->kv_binding(group);
const RadKVStream* st = kvb ? kvb->stream : nullptr;
if (!b || !st) return false;
const int64_t li = ctx->kv_layer_index(group, layer);
if (!st->host || st->block_bytes <= 0 || st->host_layer_stride <= 0 || li < 0) return false;
o->dst = b->base;
o->src = st->host + li * st->host_layer_stride;
o->bytes = b->bytes;
/* Only up to the held bound (stage.h, "Volume"). */
if (b->stage_live_bytes > 0 && b->stage_live_bytes < o->bytes) o->bytes = b->stage_live_bytes;
if (o->bytes <= 0 || o->bytes > st->host_layer_stride) o->bytes = st->host_layer_stride;
return o->bytes > 0;
}
/* Whether the card has the DMA queue the pipelined path needs. */
bool dma_stage(Ctx* c) {
static const bool on = rad_xp_supported(c->device()) != 0;
return on;
}
/* The one list in flight per rank thread: the layer it fills and the ride it waits on. */
struct StagePipe {
RadEvent done = nullptr;
int inflight = -1; /* the layer the outstanding list fills */
int group = -1;
void* mark = nullptr;
int64_t bytes = 0; /* what that list was told to move, for the pass's counter */
};
thread_local StagePipe g_pipe;
thread_local bool g_warned_ride = false;
/* A list handed over by arm_and_submit() is normally waited for by the next kvstage_wait or
* consumed by kvstage_next, but a pass can end with one in flight. On the transition back to the
* ring such a list, still writing base + 0, would land on the ring's layer-0 slots after the
* refill the map reset causes, and `res` would call another layer's bytes resident. */
static void stage_pipe_drain(Ctx* c) {
if (g_pipe.inflight < 0) return;
(void)rad_event_wait(c->stream(), g_pipe.done);
g_pipe.inflight = -1;
g_pipe.group = -1;
g_pipe.bytes = 0;
rad_ride_release(g_pipe.mark, nullptr, 0);
g_pipe.mark = nullptr;
}
/* Arm the completion word in stream order and hand the list over. The arm (a 1 written by the
* weight table's patch dispatch, runtime/wtab.h) is also what completes the list's ride, so the
* list cannot write its 0 before the 1 the wait looks for. */
bool arm_and_submit(Ctx* c, int group, int layer, const StageSrc& s, void* mark) {
uint32_t* word = nullptr;
if (!g_pipe.done || rad_event_dma(g_pipe.done, c->stream(), &word) < 0) return false;
WtabPatch arm;
arm.n = 1;
arm.dst[0] = (void**)(void*)word;
arm.val[0] = (void*)(uintptr_t)1;
if (wtab_patch(arm, c->stream()) < 0) return false;
const uint64_t src = (uint64_t)(uintptr_t)s.src, dst = (uint64_t)(uintptr_t)s.dst;
const uint64_t bytes = (uint64_t)s.bytes;
/* No yield: the compute stream waits on this copy, so yielding the link to a hold whose release
* is behind that wait would deadlock (docs/KV-STREAMING.md §6.1). */
if (rad_xp_list(c->device(), mark, 1, &src, &dst, &bytes, word, 0, RAD_XP_NO_YIELD) != RAD_OK)
return false;
g_pipe.inflight = layer;
g_pipe.group = group;
g_pipe.mark = mark;
g_pipe.bytes = s.bytes;
if (trace_stage())
RAD_INFO("kv streaming: handed over layer %d (%lld bytes), behind %lld", layer,
(long long)s.bytes, (long long)rad_xp_behind(c->device()));
return true;
}
/* The copy on the compute stream: for a backend with no DMA queue, and when no ride is spare. */
int serial_stage(Ctx* c, const StageSrc& s) {
RadStream st = c->stream();
const int rc = (s.bytes & 15) == 0
? rad_memcpy_ranges_async(s.dst, s.src, s.bytes, nullptr, 0, st)
: rad_memcpy_async(s.dst, s.src, s.bytes, st);
return rc;
}
void count_stage(Ctx* c, int layer, int64_t bytes) {
g_last_layer = layer;
g_pass.layers += 1;
g_pass.bytes += (uint64_t)bytes;
if (trace_stage() && c->rank() == 0)
RAD_INFO("kv streaming: stage layer %d (%lld bytes)", layer, (long long)bytes);
}
/* While recording, a host tape step that re-runs the arm and the submit at every play. */
int stage_issue_host(Ctx* c, int group, int layer, bool after) {
if (c->recording())
return c->tape_kv_stage(after, group, layer);
return kvstage_run(c, group, layer, after);
}
} /* namespace */
/* Before the layer's store: wait for the pipelined copy, or copy now. 1 when staged, 0 when the
* group has no stage view. A failure fails the step and returns 1, so the caller stops rather
* than read an unstaged layer. */
static int kvstage_wait(Ctx* c, int group, const RadKVGroupBatch* kvb, int layer) {
if (!c || !kvb || !kvb->stream) return 0;
const KVPoolBinding* b = c->kv_binding(group);
if (!b || !b->has_stage || b->depth != 1) return 0;
if (layer == g_last_layer) return 1;
return stage_issue_host(c, group, layer, false);
}
/* After every attention launch of `layer`: start the copy of the group's next layer, riding the
* next dispatch on the compute stream. Nothing reads the stage again before the next layer's
* wait. */
static int kvstage_next(Ctx* c, int group, int layer) {
if (!c) return 0;
const KVPoolBinding* b = c->kv_binding(group);
if (!b || !b->has_stage || b->depth != 1) return 0;
return stage_issue_host(c, group, layer, true);
}
int kvstage_run(Ctx* c, int group, int layer, bool after) {
if (!c) return 0;
const RadBatch* b = c->batch();
const RadKVGroupBatch* kvb = nullptr;
if (b)
for (int i = 0; i < b->n_kv_groups; ++i)
if ((int)b->kv[i].group == group) { kvb = &b->kv[i]; break; }
if (!kvb || !kvb->stream) return 0;
const KVPoolBinding* kb = c->kv_binding(group);
if (!kb || !kb->has_stage || kb->depth != 1) return 0;
if (!after) {
/* Make `layer`'s row whole. A pipelined list was handed over at the layer before; its
* wait is a barrier on the compute stream. */
if (g_pipe.inflight >= 0 && (g_pipe.inflight != layer || g_pipe.group != group)) {
/* A list for a layer this pass does not read (one an earlier pass started): it must
* land before anything rewrites the buffer. */
(void)rad_event_wait(c->stream(), g_pipe.done);
g_pipe.inflight = -1;
g_pipe.bytes = 0;
rad_ride_release(g_pipe.mark, nullptr, 0);
g_pipe.mark = nullptr;
}
if (g_pipe.inflight == layer && g_pipe.group == group) {
if (rad_event_wait(c->stream(), g_pipe.done) < 0) {
rad_step_fail(c, "kv streaming: the compute stream could not wait for the stage copy "
"the DMA engine is filling; the layer's attention would read the "
"previous layer's bytes");
return 1;
}
const int64_t moved = g_pipe.bytes;
g_pipe.inflight = -1;
g_pipe.bytes = 0;
rad_ride_release(g_pipe.mark, nullptr, 0);
g_pipe.mark = nullptr;
count_stage(c, layer, moved);
return 1;
}
StageSrc s;
if (!stage_src(c, group, kvb, layer, &s)) {
rad_step_fail(c, "kv streaming: a layer needs its prefill stage but the group has no host "
"mirror row for it, so the attention would read an unstaged layer");
return 1;
}
/* Nothing pipelined (the pass's first layer): copy now and wait, in the layer's prologue. */
if (dma_stage(c)) {
if (!g_pipe.done && rad_event_create_local(&g_pipe.done) < 0) g_pipe.done = nullptr;
void* mark = nullptr;
if (g_pipe.done && rad_ride(c->stream(), &mark) == RAD_OK) {
if (arm_and_submit(c, group, layer, s, mark)) {
const bool ok = rad_event_wait(c->stream(), g_pipe.done) >= 0;
g_pipe.inflight = -1;
rad_ride_release(mark, nullptr, 0);
if (ok) {
count_stage(c, layer, s.bytes);
return 1;
}
} else {
rad_ride_release(mark, nullptr, 0);
}
}
}
if (serial_stage(c, s) < 0) {
rad_step_fail(c, "kv streaming: the prefill stage copy failed; the layer's attention "
"would read the previous layer's bytes");
return 1;
}
count_stage(c, layer, s.bytes);
return 1;
}
/* The group's next bound layer, if any. */
int next = -1;
const auto& ls = kb->layer_slot;
for (int l = layer + 1; l < (int)ls.size(); ++l)
if (c->kv_layer_index(group, l) >= 0) { next = l; break; }
if (next < 0 || !dma_stage(c)) return 0;
if (!g_pipe.done && rad_event_create_local(&g_pipe.done) < 0) g_pipe.done = nullptr;
if (!g_pipe.done) return 0;
StageSrc s;
if (!stage_src(c, group, kvb, next, &s)) return 0;
/* No spare ride: the next layer's wait copies it on the compute stream. */
void* mark = nullptr;
if (rad_ride(c->stream(), &mark) != RAD_OK) {
if (!g_warned_ride) {
g_warned_ride = true;
RAD_INFO("rank %d: kv streaming: no spare ride for the stage's DMA list, so its layer "
"copies serially", c->rank());
}
return 0;
}
if (!arm_and_submit(c, group, next, s, mark)) {
rad_ride_release(mark, nullptr, 0);
return 0;
}
return 0;
}
} /* namespace rad */
extern "C" int rad_kv_stage_layer(RadCtx* c, rad_kvgroup group, const RadKVGroupBatch* kvb,
int layer) {
using namespace rad;
if (!c || !kvb || !kvb->stream) return 0;
return kvstage_wait(static_cast<Ctx*>(c), group, kvb, layer);
}
extern "C" int rad_kv_stage_next(RadCtx* c, rad_kvgroup group, int layer) {
using namespace rad;
if (!c) return 0;
return kvstage_next(static_cast<Ctx*>(c), group, layer);
}
+80
View File
@@ -0,0 +1,80 @@
/* stage.h -- the one-layer prefill stage: per pass and layer, copy the live part of the layer's
* mirror row into the group's stage view, on the card's DMA engine, one layer ahead.
*
* Ordering rule. Every layer aliases offset 0 of the stage, which is safe only because for each
* layer L these happen in order:
*
* 1. the stage copy of L has landed;
* 2. L's store writes this chunk's tokens into the stage (the copy reads the mirror, which does
* not hold them yet, so a copy landing later would put older bytes back over them);
* 3. L's attention reads the stage;
* 4. the copy of L+1 starts.
*
* The copy is a DMA list, which holds no CU slot, so the order cannot rest on one stream's issue
* order:
*
* - 1 before 2: the compute stream waits on an event the list itself completes (rad_event_dma
* hands the list the event's completion word as its `done`), issued immediately before L's
* store. The wait is a barrier packet, so nothing between it and the store can pass it.
* - 4 after 3: the list polls a ride (rad_ride) taken on the compute stream after every
* attention launch of L (rad_kv_stage_next), so it starts when L's reads are done and crosses
* the link under L's MLP and L+1's projections.
*
* What breaks it:
*
* - taking the ride before all of L's attention launches (a prefill layer's attention is issued
* in `qsa_gq_rows`-wide chunks, so the seam is after the loop, not in the resolve);
* - waiting for the copy after the layer's store instead of before it;
* - arming the completion word from the host instead of in stream order: an older 0 would then
* release this layer's wait early, or a fresh 1 cut the previous wait short;
* - the copy on lane 1, or on a second stream with no recorded event pair (docs/KV-STREAMING.md
* §3.5.1);
* - replaying a recorded pass without re-running the arm and the submit: the list is not a
* queue packet, so Ctx::tape_kv_stage re-runs them with the tape paused, as xprefetch.cpp does.
*
* The hazard pass sees the same byte range for every aliased layer, and it never sees the DMA
* copy at all, so the barriers above are the copy's whole ordering (core/runtime/issue.cpp,
* haz_mark).
*
* Volume. The copy moves the mirror row up to the highest block id the pass can read, not the
* whole row (`n_blocks * block_bytes` is the context allocation). The bound is
* KVManager::held_top_blocks, one past the highest held block (kvstream_bound_live, per step), and
* it must never be low: the attention would read whatever the previous layer left there, which is
* fluent wrong text, not a fault. It is an upper bound because
*
* - every id a block table holds is held, and the held histogram counts sequence and
* cache-retained blocks alike;
* - the stage is identity-addressed from block 0, so copying [0, bound) covers every id below
* it, dense or not;
* - it is re-read every step, after the step's blocks are ensured, so a block a chunk appends or
* a speculative token's block is inside it; a partial block is copied whole and its unwritten
* tail is the mirror's zeros.
*
* Allocation is not assumed ascending: a retained or restored block can sit above a free one. The
* bound counts every held block, so a server with a long cached conversation stages more than one
* request reads; 0 (nothing held) stages the whole row.
*
* A backend with no DMA queue (the host backend, a test) copies on the compute stream, in the same
* order.
*/
#pragma once
#include "mem/kv.h"
#include "runtime/ctx.h"
namespace rad {
/* Select the view of every streamed group the pass names and reset the stage's per-pass state.
* Called before each pass (core/runtime/ctx.cpp). Not in bind.h, so a caller that only builds a
* step's view (core/sched/batch.cpp) does not link the driver. */
void kvstream_enter(Ctx* c, const RadBatch* b);
/* Set every streamed group's stage bound from `kv` (rank 0's manager, which hands out the ids) for
* the step about to run. Called for every rank from Engine::prepare_release, with the ranks parked
* and the step's blocks ensured. */
void kvstream_bound_live(Ctx* c, const KVManager& kv);
/* The driver, also re-run by a recorded pass (Ctx::tape_kv_stage). `after` is the call after the
* layer's attention (rad_kv_stage_next) rather than before its store. */
int kvstage_run(Ctx* c, int group, int layer, bool after);
} /* namespace rad */