review: apply the Unlimited-OCR code-review findings

The 2a1ca01..f308216 range's 45 review findings (12 performance, 33 quality)
are applied: ABI 23 for the RadBatch append, the fused q|k|v projection, the
batched patch-embed GEMM and pitched layout copies, the sam_attn w-dot hoist
with an alignment-gated vector row path and NaN poisoning for malformed
segments, the fused quick_gelu act, and the R-SWA/scheduler/drafting gates.

Quality items: stale comments corrected, env reads hoisted, the ngram_window
negative refusal, the parts-form chat template instruction, the whitelist
fallback warning, and the segmented R-SWA refusal of the fixed/runtime window
mix.

The 3.2 MB generated resample header becomes a 9.6 MB little-endian blob
(tests/data/golden/uocr_resample_golden.bin) read by a small loader;
resample_golden.py emits and round-trip-verifies it.

One perf-med item (AVX2 bicubic passes/LUT patch staging in the processor) is
left as the follow-up the review itself recommends; the code says why.

Verified: ninja -C build-review -k 0; host ctest 89/89; GPU r4d_selftest
0 failures, kbench/kbench_moe and the card tests pass.
This commit is contained in:
Juup committed 2026-10-20 07:06:18 +00:00
1 parent 1f661bf2e0
commit 859efc7208
35 files changed
+799 -399093

No files matched your search

+7 -2
View File
@@ -16,8 +16,13 @@ extern "C" {
* rad_builder.h, rad_runtime.h, rad_device.h, rad_encoding.h, rad_quant.h or rad_sample.h. Every
* kind of plugin reports it, and a plugin that does not report exactly this version is refused at
* load with both versions printed. A new optional export (e.g. rad_plugin_reference) is not a
* change of shape: a plugin without it gets the default. */
#define RAD_ABI_VERSION 24u
* change of shape: a plugin without it gets the default.
*
* 25: `RadBatch` grew `enc_seg_h`/`enc_seg_w` (336 -> 352 bytes). Appending a trailing pair is a
* shape change like `lora_slot`'s (version 18): a plugin built against this header passes the size
* it was compiled with, and a plugin built before the append reads only the fields it knows, so
* both sides need the version to tell them apart. */
#define RAD_ABI_VERSION 25u
/* ================================================================== plugin identity */
/* One value per plugin, not flags (QUANT is 3). RAD_PLUGIN_QUANT is a quantiser plugin:
+139 -86
View File
@@ -77,6 +77,7 @@
#include <arch/rad_arch.h>
#include <arch/rad_resample.h>
#include <atomic>
#include <cstdio>
#include <cstdlib>
#include <cstring>
@@ -161,7 +162,7 @@ struct DeepEncoder {
rad_weight w_n2 = 0, b_n2 = 0, w_fc1 = 0, b_fc1 = 0, w_fc2 = 0, b_fc2 = 0;
rad_op op_n1 = 0, op_qkv = 0, op_attn = 0, op_out = 0;
rad_op op_cadd = 0, op_madd = 0; /* the residual adds, rounded apart from the GEMM */
rad_op op_n2 = 0, op_fc1 = 0, op_scale = 0, op_qg = 0, op_fc2 = 0;
rad_op op_n2 = 0, op_fc1 = 0, op_qg = 0, op_fc2 = 0;
void copy_weights_from(const ClipLayerT<Geom64>& o) {
w_n1 = o.w_n1; b_n1 = o.b_n1; w_qkv = o.w_qkv; b_qkv = o.b_qkv; w_out = o.w_out;
b_out = o.b_out; w_n2 = o.w_n2; b_n2 = o.b_n2; w_fc1 = o.w_fc1; b_fc1 = o.b_fc1;
@@ -187,12 +188,14 @@ struct DeepEncoder {
rad_op op_unf_net2 = 0, op_net2 = 0, op_unf_net3 = 0, op_net3 = 0;
rad_op op_cls = 0, op_cmap = 0, op_ids_clip = 0, op_cpos = 0, op_cadd = 0, op_playr = 0;
rad_op op_ccopy = 0; /* pre_layrnorm output into the residual stream */
rad_op op_fuse_clip = 0, op_fuse_sam = 0, op_proj = 0, op_line = 0;
rad_op op_fuse_clip = 0, op_fuse_sam = 0, op_proj = 0;
rad_op op_dbg1024 = 0, op_dbg1280 = 0, op_dbg768 = 0, op_dbg256 = 0;
rad_op op_newline = 0, op_sep = 0;
/* activations, one view's, reused by every view a pass carries. */
rad_buf b_x = 0, b_h = 0, b_qkv = 0, b_att = 0, b_ff = 0, b_sampos = 0;
rad_buf b_nlrow = 0; /* the newline row, computed once, pitched into the layout */
rad_buf b_pixstg = 0; /* a tile's patch rows, packed for the single patch-embed GEMM */
/* The windowed path's padded grid: h gathered into window_partition's order with the pad
* rows zero (so the qkv linear yields the reference's bias on them), then qkv, then
* attention. `hw`/`attw` hold kSamTokP rows. */
@@ -200,7 +203,7 @@ struct DeepEncoder {
rad_buf b_ids_pad = 0, b_ids_real = 0; /* pad position -> real row (-1 pad); the inverse */
rad_buf b_n0 = 0, b_n1 = 0, b_unf3 = 0, b_n2 = 0, b_n3 = 0;
rad_buf b_unf_2 = 0, b_map2 = 0, b_unf_3 = 0, b_map = 0;
rad_buf b_c = 0, b_ch = 0, b_cq = 0, b_ca = 0, b_cf = 0, b_cg = 0, b_cg2 = 0;
rad_buf b_c = 0, b_ch = 0, b_cq = 0, b_ca = 0, b_cf = 0, b_cg2 = 0;
rad_buf b_cpos = 0, b_fuse = 0, b_projbuf = 0;
rad_buf b_ct = 0; /* a CLIP block's projection output, before its residual add */
/* CLIP's pre_layrnorm output: the first layer's norm1 reads this, every later one the
@@ -212,10 +215,11 @@ struct DeepEncoder {
* the gathers read them as plain operands). The 64 tower gathers straight from the
* checkpoint's weight planes and leaves these null. */
rad_buf b_pos_tab = 0, b_cpos_tab = 0;
rad_buf p_one = 0, p_one_c = 0, p_c1702 = 0, p_out = 0; /* shared planes, set by declare */
rad_buf p_one = 0, p_one_c = 0, p_out = 0; /* shared planes, set by declare */
int dbg = 0, dbg_row = 0; /* RAD_UNLIMITEDOCR_DBG / _ROW: dump one stage, from a row */
mutable uint32_t tabs_done = 0; /* bit per rank: the resampled tables are staged */
mutable uint32_t ids_done = 0; /* bit per rank: the window index tables are staged */
static constexpr int64_t kGrid = G::kGrid;
static constexpr int64_t kMap = G::kMap;
@@ -228,7 +232,7 @@ struct DeepEncoder {
static constexpr int64_t kSegView = G::kSegView;
int declare(RadBuilder* b, Names& nm, DeepEncoder& w, rad_buf out,
rad_buf one, rad_buf one_c, rad_buf c1702);
rad_buf one, rad_buf one_c);
void fill_tables(RadCtx* c, const DeepEncoder& w) const;
void view(RadCtx* c, const RadBatch* batch, int64_t patch0, int64_t gw, int64_t t,
int64_t n, int64_t rowbase, bool tap, const DeepEncoder& w) const;
@@ -247,16 +251,33 @@ struct DeepEncoder {
rad_weight w_proj = 0, b_proj = 0, w_newline = 0, w_sep = 0;
/* shared constants: the three 1-row planes and their fills, issued by every pass. */
rad_op op_fill_one = 0, op_fill_one_c = 0, op_fill_1702 = 0;
rad_buf b_one = 0, b_one_c = 0, b_c1702 = 0;
rad_op op_fill_one = 0, op_fill_one_c = 0;
rad_buf b_one = 0, b_one_c = 0;
rad_buf b_out = 0;
int64_t max_patches = 0;
int64_t max_views40 = 0;
int64_t max_views64 = 0;
bool on = false;
/* The stage taps belong to the first pass only. step()/fill_tables() run on the rank's own
* step thread (one thread per DeepEncoder), so the check-then-set needs no atomic. */
mutable bool tapped_ = false;
* step thread (one thread per DeepEncoder), so the check-then-set is safe as it stands; the
* atomic makes it safe by construction too (debug-only path, so the cost is irrelevant). The
* holder wraps the assignment in a relaxed store so the struct stays assignable: declare()
* resets a rank's Model with `m = Model{}`, which a bare std::atomic<bool> member deletes. */
struct TapFlag {
mutable std::atomic<bool> v{false};
TapFlag() = default;
TapFlag(const TapFlag& o) : v(o.v.load(std::memory_order_relaxed)) {}
TapFlag& operator=(const TapFlag& o) {
v.store(o.v.load(std::memory_order_relaxed), std::memory_order_relaxed);
return *this;
}
TapFlag& operator=(bool x) {
v.store(x, std::memory_order_relaxed);
return *this;
}
operator bool() const { return v.load(std::memory_order_relaxed); }
};
mutable TapFlag tapped_;
/* ------------------------------------------------------------------ stage taps
* RADIANCE_DEBUG_MM_BUFFERS names intermediate stages (comma separated; a name matches a tag
@@ -264,9 +285,13 @@ struct DeepEncoder {
* file a stage, for a stage-by-stage comparison against a reference encoder. The copy is
* issued on the pass's stream behind the producing op and synced, so it reads the op's output
* (unlike the after-pass dump in core/engine_mm.cpp, which sees each buffer's last writer). */
static const char* tap_dir() {
static const char* const dir = std::getenv("RADIANCE_DEBUG_MM_DUMP");
return dir;
}
static bool tap_names(const char** list, size_t* n) {
static const char* const env = std::getenv("RADIANCE_DEBUG_MM_BUFFERS");
static const char* const dir = std::getenv("RADIANCE_DEBUG_MM_DUMP");
const char* const dir = tap_dir();
*list = env;
*n = 0;
if (!env || !*env || !dir || !*dir) return false;
@@ -298,8 +323,7 @@ struct DeepEncoder {
(size_t)(rows * cols * 2), rad_stream(c)) < 0) return;
rad_stream_sync(rad_stream(c));
char path[512];
std::snprintf(path, sizeof path, "%s/tap.%s.bf16", std::getenv("RADIANCE_DEBUG_MM_DUMP"),
tag);
std::snprintf(path, sizeof path, "%s/tap.%s.bf16", tap_dir(), tag);
if (FILE* f = std::fopen(path, "wb")) {
std::fwrite(h.data(), sizeof(uint16_t), h.size(), f);
std::fclose(f);
@@ -536,7 +560,6 @@ struct DeepEncoder {
* exactly what corrupted the cu_seqlens tables while they were declared at the bottom). */
b_one = decl_b(b, "v.one", RAD_BF16, {1, kNEmbd});
b_one_c = decl_b(b, "v.one.clip", RAD_BF16, {1, kClipW});
b_c1702 = decl_b(b, "v.one.1702", RAD_BF16, {1, kClipFf});
op_fill_one = rw(b, RAD_OP(b, "fill",
RAD_PARAMS(RAD_INT("M", 1), RAD_INT("n", kNEmbd),
RAD_STR("dtype", "bf16"), RAD_F64("value", 1.0)),
@@ -547,13 +570,8 @@ struct DeepEncoder {
RAD_STR("dtype", "bf16"), RAD_F64("value", 1.0)),
RAD_NOWEIGHTS),
{}, {b_one_c});
op_fill_1702 = rw(b, RAD_OP(b, "fill",
RAD_PARAMS(RAD_INT("M", 1), RAD_INT("n", kClipFf),
RAD_STR("dtype", "bf16"), RAD_F64("value", 1.702)),
RAD_NOWEIGHTS),
{}, {b_c1702});
RAD_ARCH_TRY(t64.declare(b, nm, *this, b_out, b_one, b_one_c, b_c1702));
RAD_ARCH_TRY(t40.declare(b, nm, *this, b_out, b_one, b_one_c, b_c1702));
RAD_ARCH_TRY(t64.declare(b, nm, *this, b_out, b_one, b_one_c));
RAD_ARCH_TRY(t40.declare(b, nm, *this, b_out, b_one, b_one_c));
if (!ctx->shape_probe) {
RadEncoderDecl e{};
e.name = "deepencoder";
@@ -640,7 +658,6 @@ struct DeepEncoder {
/* Shared constants. */
RAD_ISSUE(c, op_fill_one, RAD_B(b_one));
RAD_ISSUE(c, op_fill_one_c, RAD_B(b_one_c));
RAD_ISSUE(c, op_fill_1702, RAD_B(b_c1702));
/* Walk the segments, writing each one's output rows where the pass's row block puts it. */
const bool do_tap = !tapped_;
bool tapped_view = false;
@@ -670,12 +687,12 @@ struct DeepEncoder {
/* ------------------------------------------------------------------ tower declare */
template <typename G>
int DeepEncoder::Tower<G>::declare(RadBuilder* b, Names& nm, DeepEncoder& w, rad_buf out,
rad_buf one, rad_buf one_c, rad_buf c1702) {
rad_buf one, rad_buf one_c) {
static_assert(G::kGrid == DeepEncoder::Geom64::kGrid ||
G::kGrid == DeepEncoder::Geom40::kGrid, "the tower serves two grids");
const bool is40 = G::kGrid == DeepEncoder::Geom40::kGrid;
const char* sfx = is40 ? "40" : "64";
p_one = one; p_one_c = one_c; p_c1702 = c1702; p_out = out;
p_one = one; p_one_c = one_c; p_out = out;
char bn[64];
#define RAD_VN(fmtv) std::snprintf(bn, sizeof bn, fmtv, sfx)
@@ -708,7 +725,6 @@ int DeepEncoder::Tower<G>::declare(RadBuilder* b, Names& nm, DeepEncoder& w, rad
RAD_VN("v%s.cq"); b_cq = decl_b(b, bn, RAD_BF16, {kClipTok, 3 * DeepEncoder::kClipW});
RAD_VN("v%s.ca"); b_ca = decl_b(b, bn, RAD_BF16, {kClipTok, DeepEncoder::kClipW});
RAD_VN("v%s.cf"); b_cf = decl_b(b, bn, RAD_BF16, {kClipTok, DeepEncoder::kClipFf});
RAD_VN("v%s.cg"); b_cg = decl_b(b, bn, RAD_BF16, {kClipTok, DeepEncoder::kClipFf});
RAD_VN("v%s.cg2"); b_cg2 = decl_b(b, bn, RAD_BF16, {kClipTok, DeepEncoder::kClipFf});
RAD_VN("v%s.ct"); b_ct = decl_b(b, bn, RAD_BF16, {kClipTok, DeepEncoder::kClipW});
RAD_VN("v%s.cp"); b_cp = decl_b(b, bn, RAD_BF16, {kClipTok, DeepEncoder::kClipW});
@@ -717,6 +733,8 @@ int DeepEncoder::Tower<G>::declare(RadBuilder* b, Names& nm, DeepEncoder& w, rad
RAD_VN("v%s.fuse"); b_fuse = decl_b(b, bn, RAD_BF16, {kMap * kMap, DeepEncoder::kFused});
RAD_VN("v%s.proj"); b_projbuf = decl_b(b, bn, RAD_BF16, {kMap * kMap, DeepEncoder::kNEmbd});
RAD_VN("v%s.nlrow"); b_nlrow = decl_b(b, bn, RAD_BF16, {1, DeepEncoder::kNEmbd});
RAD_VN("v%s.pixstg"); b_pixstg = decl_b(b, bn, RAD_BF16, {kSamTok, DeepEncoder::kPatchDim});
/* One cu_seqlens table each, {0, tokens}, one segment: `iota` writes both entries. The three
* unfolds read b_cu_sam through their cu_div (kSamTok/kGrid rows a grid row; net_3's divides
@@ -751,10 +769,11 @@ int DeepEncoder::Tower<G>::declare(RadBuilder* b, Names& nm, DeepEncoder& w, rad
b_cpos_tab = decl_b(b, bn, RAD_BF16, {kClipTok, DeepEncoder::kClipW}, RAD_BUF_PERSIST);
}
/* ---- SAM stem. The patch embed is one GEMM a grid row (the staged rows carry kDown
* zero patch columns nothing reads), then the position table added in: a row gather, from
* the 64x64 plane at the 64 grid (exact, unchanged) and the staged 40x40 resample at 40. */
op_patch = rw(b, gemm_b(b, kGrid, DeepEncoder::kSamW, DeepEncoder::kPatchDim, "none",
/* ---- SAM stem. The patch embed is one GEMM over the whole staged tile (the processor
* stages kDown zero patch columns at the end of each row, skipped by the pitched pack into
* `pixstg`), then the position table added in: a row gather, from the 64x64 plane at the 64
* grid (exact, unchanged) and the staged 40x40 resample at 40. */
op_patch = rw(b, gemm_b(b, kSamTok, DeepEncoder::kSamW, DeepEncoder::kPatchDim, "none",
w.w_patch, w.b_patch), {}, {b_x});
op_ids_sam = rw(b, RAD_OP(b, "iota",
RAD_PARAMS(RAD_INT("M", kSamTok), RAD_INT("start", 0), RAD_INT("step", 1)),
@@ -933,19 +952,16 @@ int DeepEncoder::Tower<G>::declare(RadBuilder* b, Names& nm, DeepEncoder& w, rad
{b_ch});
l.op_fc1 = rw(b, gemm_b(b, kClipTok, DeepEncoder::kClipFf, DeepEncoder::kClipW, "none",
l.w_fc1, l.b_fc1), {b_ch}, {b_cf});
/* quick_gelu: fc1's output times sigmoid(1.702 * itself). */
l.op_scale = rw(b, RAD_OP(b, "mul",
RAD_PARAMS(RAD_RANGE("M", 1, kClipTok),
RAD_INT("n", DeepEncoder::kClipFf),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{b_cf, p_c1702}, {b_cg});
/* quick_gelu: fc1's output times sigmoid(1.702 * itself), fused into one act. The
* kernel rounds the scaled value to bf16 before the sigmoid, which is exactly the
* store the unfused mul did, so the fusion is bit-identical to the pair it replaces
* (and saves a 257x4096 bf16 round-trip per layer x 24 layers x tile). */
l.op_qg = rw(b, RAD_OP(b, "act_mul",
RAD_PARAMS(RAD_RANGE("M", 1, kClipTok),
RAD_INT("n", DeepEncoder::kClipFf),
RAD_STR("act", "sigmoid"), RAD_STR("dtype", "bf16")),
RAD_STR("act", "quick_gelu"), RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{b_cg, b_cf}, {b_cg2});
{b_cf, b_cf}, {b_cg2});
l.op_fc2 = rw(b, gemm_b(b, kClipTok, DeepEncoder::kClipW, DeepEncoder::kClipFf, "none",
l.w_fc2, l.b_fc2), {b_cg2}, {b_ct});
l.op_madd = rw(b, RAD_OP(b, "add",
@@ -993,14 +1009,8 @@ int DeepEncoder::Tower<G>::declare(RadBuilder* b, Names& nm, DeepEncoder& w, rad
RAD_NOWEIGHTS),
{b_projbuf}, {p_out});
/* A projected map line into its place among the layout rows. */
op_line = rw(b, RAD_OP(b, "cast",
RAD_PARAMS(RAD_INT("M", kMap), RAD_INT("n", DeepEncoder::kNEmbd),
RAD_STR("from", "bf16"), RAD_STR("to", "bf16")),
RAD_NOWEIGHTS),
{b_projbuf}, {p_out});
/* ---- the two layout rows. */
/* ---- the two layout rows. A projected map line reaches its layout rows as a pitched
* copy in view(); the newline row is computed once here and pitched out by segment(). */
op_newline = rw(b, RAD_OP(b, "mul_weight",
RAD_PARAMS(RAD_INT("M", 1), RAD_INT("n", DeepEncoder::kNEmbd),
RAD_STR("dtype", "bf16")),
@@ -1058,7 +1068,18 @@ void DeepEncoder::Tower<G>::fill_tables(RadCtx* c, const DeepEncoder& w) const {
return;
}
/* CLIP: row 0 is the class row, rows 1: are the 16x16 grid -> cls + a 10x10 resample. */
/* CLIP: row 0 is the class row, rows 1: are the 16x16 grid -> cls + a 10x10 resample.
* f/g are the SAM resample's buffers, reused here as the CLIP resample's scratch; that is
* safe only while SAM's f covers CLIP's source grid and SAM's g covers CLIP's map. Pinned
* so retuning a geometry fails at compile time, not as a heap overrun. */
static_assert((size_t)DeepEncoder::Geom64::kGrid * DeepEncoder::Geom64::kGrid *
DeepEncoder::kSamW >=
(size_t)DeepEncoder::kClipSrcMap * DeepEncoder::kClipSrcMap *
DeepEncoder::kClipW,
"fill_tables reuses SAM's f scratch for the CLIP source grid");
static_assert((size_t)kGrid * kGrid * DeepEncoder::kSamW >=
(size_t)kMap * kMap * DeepEncoder::kClipW,
"fill_tables reuses SAM's g scratch for the CLIP map grid");
std::vector<uint16_t> cout((size_t)kClipTok * DeepEncoder::kClipW);
std::memcpy(cout.data(), hclip.data(), (size_t)DeepEncoder::kClipW * sizeof(uint16_t));
const size_t ngrid = (size_t)(csrc * csrc * DeepEncoder::kClipW);
@@ -1084,14 +1105,22 @@ void DeepEncoder::Tower<G>::view(RadCtx* c, const RadBatch* batch, int64_t patch
* each row `gw` patches wide (the last kDown columns are the newline column, never read). */
const char* pix = (const char*)batch->enc_pixels + (patch0 + t * kGrid) * DeepEncoder::kPatchDim * 2;
/* The patch embed, one grid row at a time: the kDown zero patch columns the processor
* stages at the end of each row are skipped, not read. */
for (int64_t r = 0; r < kGrid; ++r)
RAD_ISSUE_N(c, op_patch, kGrid,
RAD_P_T2(pix + (r * gw) * DeepEncoder::kPatchDim * 2,
RAD_BF16, kGrid, DeepEncoder::kPatchDim),
RAD_W(w.w_patch), RAD_W(w.b_patch), RAD_NONE,
brow_slice(b_x, r * kGrid, kGrid, DeepEncoder::kSamW));
/* The patch embed: one pitched copy packs the tile's grid rows out of the line's rows (the
* kDown zero patch columns at each row's end are the copy's dead space, skipped like the
* old per-row GEMMs skipped them), then ONE GEMM over M = kGrid*kGrid replaces the launch
* of kGrid M=kGrid GEMMs. The copy rides the pass's stream, ordered with the ops. */
char* stg = (char*)rad_buf_ptr(c, b_pixstg);
const int64_t rowb = kGrid * DeepEncoder::kPatchDim * 2;
if (!stg ||
rad_memcpy_2d_async(stg, rowb, pix, gw * DeepEncoder::kPatchDim * 2, rowb, kGrid,
rad_stream(c)) < 0) {
rad_step_fail(c, "unlimitedocr: the patch rows of the DeepEncoder could not be packed");
return;
}
RAD_ISSUE(c, op_patch,
RAD_P_T2(stg, RAD_BF16, kSamTok, DeepEncoder::kPatchDim),
RAD_W(w.w_patch), RAD_W(w.b_patch), RAD_NONE,
brow_slice(b_x, 0, kSamTok, DeepEncoder::kSamW));
/* The position table, a row for a token (a gather, exact at 64 and from the staged
* resample at 40), added in. */
@@ -1281,9 +1310,7 @@ void DeepEncoder::Tower<G>::view(RadCtx* c, const RadBatch* batch, int64_t patch
RAD_W(l.b_n2), brows(b_ch, kClipTok));
RAD_ISSUE_N(c, l.op_fc1, kClipTok, brows(b_ch, kClipTok), RAD_W(l.w_fc1),
RAD_W(l.b_fc1), RAD_NONE, brows(b_cf, kClipTok));
RAD_ISSUE_N(c, l.op_scale, kClipTok, brows(b_cf, kClipTok), brows(p_c1702, 1),
brows(b_cg, kClipTok));
RAD_ISSUE_N(c, l.op_qg, kClipTok, brows(b_cg, kClipTok), brows(b_cf, kClipTok),
RAD_ISSUE_N(c, l.op_qg, kClipTok, brows(b_cf, kClipTok), brows(b_cf, kClipTok),
brows(b_cg2, kClipTok));
RAD_ISSUE_N(c, l.op_fc2, kClipTok, brows(b_cg2, kClipTok), RAD_W(l.w_fc2),
RAD_W(l.b_fc2), RAD_NONE, brows(b_ct, kClipTok));
@@ -1315,12 +1342,20 @@ void DeepEncoder::Tower<G>::view(RadCtx* c, const RadBatch* batch, int64_t patch
return;
}
/* The line's layout: tile t's map goes to columns [t*kMap, (t+1)*kMap) of every map row.
* The newline cell after the last tile belongs to the line, so segment() writes it once. */
for (int64_t m = 0; m < kMap; ++m) {
const int64_t dst = rowbase + m * (n * kMap + 1) + t * kMap;
RAD_ISSUE_N(c, op_line, kMap, brow_slice(b_projbuf, m * kMap, kMap, DeepEncoder::kNEmbd),
brow_slice(p_out, dst, kMap, DeepEncoder::kNEmbd));
/* The line's layout: tile t's map goes to columns [t*kMap, (t+1)*kMap) of every map row --
* a pitched copy of the projected tile into the plane (the layout pitch is the line's row
* count plus the newline column), one copy replacing kMap cast-launches. The newline cell
* after the last tile belongs to the line, so segment() writes it once. */
char* po = (char*)rad_buf_ptr(c, p_out);
const int64_t wbytes = kMap * DeepEncoder::kNEmbd * 2;
if (!po ||
rad_memcpy_2d_async(po + (rowbase + t * kMap) * DeepEncoder::kNEmbd * 2,
(n * kMap + 1) * DeepEncoder::kNEmbd * 2,
rad_buf_ptr(c, b_projbuf), wbytes, wbytes, kMap,
rad_stream(c)) < 0) {
rad_step_fail(c, "unlimitedocr: the projected map of the DeepEncoder could not be laid "
"out");
return;
}
}
@@ -1338,7 +1373,8 @@ void DeepEncoder::Tower<G>::segment(RadCtx* c, const RadBatch* batch, int64_t pa
/* window_partition's two index tables: padded position (r*kGridP + c) holds real row
* r*kGrid + c, every other padded row is the pad (gather -1 = a zero row, which the qkv
* linear turns into the qkv bias). Constants, written before the pass's ops. */
* linear turns into the qkv bias). The values are compile-time constants and the planes are
* PERSIST, so each rank stages them once, on its first segment. */
static const std::vector<int32_t> pad_idx = [] {
std::vector<int32_t> v((size_t)kSamTokP, -1);
for (int64_t r = 0; r < kGrid; ++r)
@@ -1353,33 +1389,50 @@ void DeepEncoder::Tower<G>::segment(RadCtx* c, const RadBatch* batch, int64_t pa
v[(size_t)(r * kGrid + cc)] = (int32_t)(r * kGridP + cc);
return v;
}();
void* p_pad = rad_buf_ptr(c, b_ids_pad);
void* p_real = rad_buf_ptr(c, b_ids_real);
if (!p_pad || !p_real) {
rad_step_fail(c, "unlimitedocr: the padded-grid index table of the DeepEncoder did not "
"bind");
return;
}
if (rad_memcpy_async(p_pad, pad_idx.data(),
(int64_t)(pad_idx.size() * sizeof(int32_t)),
rad_stream(c)) < 0 ||
rad_memcpy_async(p_real, real_idx.data(),
(int64_t)(real_idx.size() * sizeof(int32_t)),
rad_stream(c)) < 0) {
rad_step_fail(c, "unlimitedocr: could not stage the DeepEncoder's padded-grid index "
"table");
return;
const int rk = rad_rank(c);
if (rk >= 0 && rk < 32 && !(ids_done & (1u << rk))) {
void* p_pad = rad_buf_ptr(c, b_ids_pad);
void* p_real = rad_buf_ptr(c, b_ids_real);
if (!p_pad || !p_real) {
rad_step_fail(c, "unlimitedocr: the padded-grid index table of the DeepEncoder did not "
"bind");
return;
}
if (rad_memcpy_async(p_pad, pad_idx.data(),
(int64_t)(pad_idx.size() * sizeof(int32_t)),
rad_stream(c)) < 0 ||
rad_memcpy_async(p_real, real_idx.data(),
(int64_t)(real_idx.size() * sizeof(int32_t)),
rad_stream(c)) < 0) {
rad_step_fail(c, "unlimitedocr: could not stage the DeepEncoder's padded-grid index "
"table");
return;
}
ids_done |= (1u << rk);
}
for (int64_t t = 0; t < n; ++t) view(c, batch, patch0, gw, t, n, rowbase, tap && t == 0, w);
/* The line's newline cell closes each map line: one learned row after the last tile. Only
* the line's last chunk carries it; an earlier chunk ends at its last tile's map. */
if (nl)
for (int64_t m = 0; m < kMap; ++m)
RAD_ISSUE(c, op_newline, RAD_B(p_one), RAD_W(w.w_newline),
brow_slice(p_out, rowbase + m * (n * kMap + 1) + n * kMap, 1,
DeepEncoder::kNEmbd));
* the line's last chunk carries it; an earlier chunk ends at its last tile's map. The row
* is computed once and pitched to the line's map rows -- one launch, one copy. */
if (nl) {
char* nlrow = (char*)rad_buf_ptr(c, b_nlrow);
char* po = (char*)rad_buf_ptr(c, p_out);
if (!nlrow || !po) {
rad_step_fail(c, "unlimitedocr: a layout plane of the DeepEncoder did not bind");
return;
}
RAD_ISSUE(c, op_newline, RAD_B(p_one), RAD_W(w.w_newline), RAD_B(b_nlrow));
if (rad_memcpy_2d_async(po + (rowbase + n * kMap) * DeepEncoder::kNEmbd * 2,
(n * kMap + 1) * DeepEncoder::kNEmbd * 2, nlrow,
DeepEncoder::kNEmbd * 2, DeepEncoder::kNEmbd * 2, kMap,
rad_stream(c)) < 0) {
rad_step_fail(c, "unlimitedocr: the newline row of the DeepEncoder could not be "
"laid out");
return;
}
}
}
} /* namespace arch */
+4
View File
@@ -79,6 +79,10 @@ inline Axis make_axis(int in, int out) {
if (xsize > in) xsize = in;
xsize -= xmin;
if (xsize < 0) xsize = 0;
/* ATen's own `xsize = min(xsize, n)`, kept for parity. It cannot bind here: with
* xmin > 0 the window spans 2*support + 1 taps, at most a.n = 2*ceil(support) + 1
* (the bound ATen sized the slots from), and with xmin == 0 it spans fewer. So the
* clamp is a no-op safety net, never a silent tap truncation. */
if (xsize > a.n) xsize = a.n;
int* idx = &a.idx[(size_t)i * (size_t)a.n];
float* w = &a.w[(size_t)i * (size_t)a.n];
+39 -41
View File
@@ -15,9 +15,11 @@
* the reference rotates the projections straight;
* * the rotary is FULL head_dim (rot = head_dim = 128) and NeoX-half (`rotate_half` in the
* reference), not partial, not mrope;
* * q, k and v are three [1280, 1280] projections kept as three GEMMs and three contiguous
* operands, exactly as rad_block_attn_gated.h argues: a fused [k|v] row is not expressible as
* an operand a head-wise reader can walk.
* * q, k and v are three [1280, 1280] projections fused into ONE stacked-rows GEMM: the
* rank-local q|k|v weight rows are staged once into a PERSIST plane, and q, k and v are
* column views of one fused output plane (RadOperand::cols, abi/rad_runtime.h) that the
* rope, kv_store and attention readers walk by row pitch -- the rad_block_attn_gated.h
* argument against a fused [k|v] ROW no longer applies to the stacked-rows form.
*
* Everything the gated block gets right about paged KV is copied through unchanged: the attention
* declared BEFORE the store so block_size derives from the resolved kernel, the ranged `q_len`
@@ -35,9 +37,10 @@ struct AttnLlamaBF16 {
struct Wire {
rad_buf x = 0; /* [max_tok, n_embd] the residual stream */
rad_buf h = 0; /* [max_tok, n_embd] normed input, then the o output */
rad_buf q = 0; /* [max_tok, q_dim] rotated */
rad_buf k = 0; /* [max_tok, kv_dim] rotated */
rad_buf v = 0; /* [max_tok, kv_dim] */
rad_buf q = 0; /* [max_tok, q_dim + 2*kv_dim] fused q|k|v plane; q, k, v are the
* column views [0, q_dim), [q_dim, q_dim+kv_dim), [q_dim+kv_dim, ...) */
rad_buf k = 0; /* the same plane: the rope/kv_store readers take the k columns */
rad_buf v = 0; /* the same plane: the v columns */
rad_buf attn = 0; /* [max_tok, q_dim] */
};
@@ -55,8 +58,8 @@ struct AttnLlamaBF16 {
rad_kvgroup kv = 0;
int64_t n_rot = 0;
rad_weight w_norm = 0, w_q = 0, w_k = 0, w_v = 0, w_o = 0;
rad_op op_norm = 0, op_q = 0, op_k = 0, op_v = 0;
rad_weight w_norm = 0, w_qkv = 0, w_o = 0;
rad_op op_norm = 0, op_qkv = 0;
rad_op op_rope_q = 0, op_rope_k = 0;
rad_op op_attn = 0, op_kv_store = 0, op_o = 0, op_ar = 0, op_add = 0;
@@ -89,19 +92,18 @@ inline int AttnLlamaBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, in
}
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_norm.weight", l), src.norm));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_q.weight", l), src.q));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_k.weight", l), src.k));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_v.weight", l), src.v));
/* The convert-time q|k|v fusion, the gate_up form rad_block_mlp.h states: one weight, one
* GEMM, one movement unit; `row_parts` keeps the row-shard on q_local|k_local|v_local
* boundaries so the column views stay exact per rank. */
RAD_ARCH_TRY(map_concat(b, nm.f("blk.%d.attn_qkv.weight", l), { src.q, src.k, src.v }, 0));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_output.weight", l), src.o));
w_norm = decl_w(b, nm.f("blk.%d.attn_norm.weight", l), RAD_F32, {g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
w_q = decl_w(b, nm.f("blk.%d.attn_q.weight", l), RAD_BF16, {q_dim, g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l));
w_k = decl_w(b, nm.f("blk.%d.attn_k.weight", l), RAD_BF16, {kv_dim, g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l));
w_v = decl_w(b, nm.f("blk.%d.attn_v.weight", l), RAD_BF16, {kv_dim, g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l));
w_qkv = decl_w(b, nm.f("blk.%d.attn_qkv.weight", l), RAD_BF16,
{q_dim + 2 * kv_dim, g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l), 0,
{q_dim, kv_dim, kv_dim});
w_o = decl_w(b, nm.f("blk.%d.attn_output.weight", l), RAD_BF16, {g.n_embd, q_dim},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_COL, grp_layer(l));
@@ -112,21 +114,14 @@ inline int AttnLlamaBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, in
RAD_WEIGHTS(w_norm)),
{w.x}, {w.h});
op_q = rw(b, RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", q_dim),
RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_q)),
{w.h}, {w.q});
op_k = rw(b, RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", kv_dim),
RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_k)),
{w.h}, {w.k});
op_v = rw(b, RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", kv_dim),
RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_v)),
{w.h}, {w.v});
/* One GEMM over the fused [q|k|v] rows: N = q_dim + 2*kv_dim, the readers below take the
* q, k and v column views of `w.q`. Same K, same per-column tile as the three-GEMM form,
* so the bf16 outputs are bit-identical; the win is one launch, not arithmetic. */
op_qkv = rw(b, RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", q_dim + 2 * kv_dim),
RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_qkv)),
{w.h}, {w.q});
/* Full-head rotary, NeoX halves: the reference's rotate_half. The q call names n_head query
* heads and no kv heads (the buffers are separate); the k call names the kv heads. */
@@ -136,8 +131,9 @@ inline int AttnLlamaBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, in
{w.k}, {w.k});
/* Declared before kv_store so block_size derives from the resolved attention kernel (spec
* §7.2), pinned to RAD_KV_BLOCK for the same reason rad_arch.h states. P1 serves the plain
* causal rule; the R-SWA window is P4 and re-declares this op with its own rule. */
* §7.2), pinned to RAD_KV_BLOCK for the same reason rad_arch.h states. This op keeps the
* plain causal rule through the R-SWA ring: the ring's visible set is the block table's
* job (the runtime window prunes the table, not the kernel), so no re-declaration. */
op_attn = rw(b, RAD_OP(b, "attn_paged",
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1),
@@ -191,18 +187,20 @@ inline void AttnLlamaBF16::step(RadCtx* c, const RadBatch* batch) const {
const int64_t T = batch->n_tok;
RAD_ISSUE(c, op_norm, brows(w.x, T), RAD_W(w_norm), brows(w.h, T));
RAD_ISSUE(c, op_q, brows(w.h, T), RAD_W(w_q), brows(w.q, T));
RAD_ISSUE(c, op_k, brows(w.h, T), RAD_W(w_k), brows(w.k, T));
RAD_ISSUE(c, op_v, brows(w.h, T), RAD_W(w_v), brows(w.v, T));
RAD_ISSUE(c, op_qkv, brows(w.h, T), RAD_W(w_qkv), brows(w.q, T));
RAD_ISSUE(c, op_rope_q, brows(w.q, T), rope_posmc(g, batch, T));
RAD_ISSUE(c, op_rope_k, brows(w.k, T), rope_posmc(g, batch, T));
/* q, k and v are column views of the fused plane, walked by its row pitch: the rope,
* kv_store and attention kernels take the slice's pitch (r4d_rows_pitch). */
RAD_ISSUE(c, op_rope_q, bcol(w.q, 0, g.q_dim(), T), rope_posmc(g, batch, T));
RAD_ISSUE(c, op_rope_k, bcol(w.q, g.q_dim(), g.kv_dim(), T), rope_posmc(g, batch, T));
RAD_ISSUE(c, op_kv_store,
brows(w.k, T), brows(w.v, T), praw(slot, RAD_I32, T), kv_cache(kv, layer));
bcol(w.q, g.q_dim(), g.kv_dim(), T),
bcol(w.q, g.q_dim() + g.kv_dim(), g.kv_dim(), T),
praw(slot, RAD_I32, T), kv_cache(kv, layer));
RAD_ISSUE_N(c, op_attn, batch->max_q_len,
brows(w.q, T), kv_cache(kv, layer),
bcol(w.q, 0, g.q_dim(), T), kv_cache(kv, layer),
praw2(table, RAD_I32, batch->n_seq, kvb ? kvb->block_table_pitch : 0),
praw(used, RAD_I32, batch->n_seq),
RAD_NONE, RAD_NONE,
+18 -12
View File
@@ -76,7 +76,7 @@ struct Model {
/* the residual stream and the vocabulary edges */
rad_buf b_x = 0, b_h = 0, b_hout = 0, b_logits = 0;
/* attention */
rad_buf b_q = 0, b_k = 0, b_v = 0, b_attn = 0;
rad_buf b_qkv = 0, b_attn = 0;
/* dense feed-forward (layer 0) */
rad_buf b_gate_up = 0, b_ffn = 0;
/* routing -- one row per token */
@@ -279,9 +279,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
* serves. Prefix caching and speculation switch off for the group automatically (a runtime
* window's KV before the prompt end is not reusable and a draft cannot know where the ring
* starts). */
const int64_t win = rad_meta_geti(meta, "sliding_window_size", 0) > 0
? rad_meta_geti(meta, "sliding_window_size", 0)
: rad_meta_geti(meta, "sliding_window", 0);
const int64_t sw_size = rad_meta_geti(meta, "sliding_window_size", 0);
const int64_t win = sw_size > 0 ? sw_size : rad_meta_geti(meta, "sliding_window", 0);
RadKVGroupDecl fd{};
fd.kind = win > 0 ? RAD_KV_RING : RAD_KV_FULL;
fd.dtype = rad_kv_cache_dtype(ctx, RAD_BF16);
@@ -294,9 +293,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
/* ---- activation buffers. */
m.b_x = decl_b(b, nm.f("x"), g.act_dtype, {g.max_tok, g.n_embd});
m.b_h = decl_b(b, nm.f("h"), g.act_dtype, {g.max_tok, g.n_embd});
m.b_q = decl_b(b, nm.f("attn_q"), g.act_dtype, {g.max_tok, g.q_dim()});
m.b_k = decl_b(b, nm.f("attn_k"), g.act_dtype, {g.max_tok, g.kv_dim()});
m.b_v = decl_b(b, nm.f("attn_v"), g.act_dtype, {g.max_tok, g.kv_dim()});
m.b_qkv = decl_b(b, nm.f("attn_qkv"), g.act_dtype,
{g.max_tok, g.q_dim() + 2 * g.kv_dim()});
m.b_attn = decl_b(b, nm.f("attn_out"), g.act_dtype, {g.max_tok, g.q_dim()});
m.b_gate_up = decl_b(b, nm.f("gate_up"), g.act_dtype, {g.max_tok, 2 * g.n_ff});
@@ -387,7 +385,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
{m.b_x}, {m.b_x});
AttnLlamaBF16::Wire aw{};
aw.x = m.b_x; aw.h = m.b_h; aw.q = m.b_q; aw.k = m.b_k; aw.v = m.b_v; aw.attn = m.b_attn;
aw.x = m.b_x; aw.h = m.b_h; aw.q = m.b_qkv; aw.k = m.b_qkv; aw.v = m.b_qkv;
aw.attn = m.b_attn;
MlpBF16::Wire mw{};
mw.x = m.b_x; mw.h = m.b_h; mw.gate_up = m.b_gate_up; mw.ffn = m.b_ffn;
@@ -474,8 +473,15 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
else
rad_note(b, "R-SWA: the checkpoint states no sliding_window_size, so the KV group is a "
"plain full cache");
rad_note(b, "generation_config asks for SlidingWindowNoRepeatNgramProcessor n=35 -- the "
"plan's P5 sample_ngram_ban op; temp-0 parity checks run with it off");
/* Only when the container states the processor: gen-convert copies the checkpoint's
* generation_config into `generation.*`, so a checkpoint without it gets no note. */
const int64_t ng_n = rad_meta_geti(meta, "generation.no_repeat_ngram_size", 0);
if (ng_n > 0)
rad_note(b, "generation_config asks for SlidingWindowNoRepeatNgramProcessor n=%lld over "
"the last %lld tokens -- served by the sample_ngram_ban stage, overridable "
"per request (ngram_ban_n / ngram_window); temp-0 parity checks run with it off",
(long long)ng_n,
(long long)rad_meta_geti(meta, "generation.no_repeat_ngram_window_size", 0));
return RAD_OK;
}
@@ -540,6 +546,6 @@ static void step(RadCtx* c, const RadBatch* batch) {
#ifndef RAD_ARCH_NO_EXPORTS
RAD_ARCH_PLUGIN(unlimitedocr_bf16, "unlimitedocr", "", "0.1.0",
"baidu/Unlimited-OCR decoder: 12-layer Llama-MoE (64 experts top-6 + 2 shared), "
"bf16 weights and activations, full rotary MHA; text-only until the P2 vision "
"tower lands")
"bf16 weights and activations, full rotary MHA, with the DeepEncoder "
"(SAM ViT-B + CLIP ViT-L) vision tower")
#endif
+11 -6
View File
@@ -82,18 +82,19 @@ int Engine::run_encodes() {
ip->embd.assign((size_t)(ip->n_rows() * e.n_embd), 0);
/* Diagnostic: RADIANCE_DEBUG_MM_ROWS=<raw bf16 file> substitutes a reference encoder's
* rows for the tower's, to tell a tower difference from a language-model one. */
if (const char* rp = std::getenv("RADIANCE_DEBUG_MM_ROWS")) {
if (FILE* rf = std::fopen(rp, "rb")) {
static const char* const rows_ref = std::getenv("RADIANCE_DEBUG_MM_ROWS");
if (rows_ref) {
if (FILE* rf = std::fopen(rows_ref, "rb")) {
const size_t want = ip->embd.size() * sizeof(uint16_t);
const size_t got = std::fread(ip->embd.data(), 1, want, rf);
std::fclose(rf);
if (got == want) {
ip->encoded = true;
RAD_INFO("encoder: %zu row(s) taken from %s instead of the tower",
(size_t)ip->n_rows(), rp);
RAD_INFO("encoder: %zu row(s) taken from %s instead of the tower",
(size_t)ip->n_rows(), rows_ref);
continue;
}
RAD_ERR("encoder: %s holds %zu bytes, wanted %zu", rp, got, want);
RAD_ERR("encoder: %s holds %zu bytes, wanted %zu", rows_ref, got, want);
}
}
if (dump_dir && *dump_dir) dump(*ip, ".pix.bf16", ip->pixels.data(), ip->pixels.size());
@@ -146,7 +147,11 @@ int Engine::run_encodes() {
if (!sep) seg_grid = g;
}
if (seg == first) {
if (seg_grid == 0) seg_grid = it.seg_h(seg); /* a lone oversized segment */
/* Nothing of this item packed into the pass: its first segment did not fit
* a pass that already has content (a segment larger than the whole pass was
* refused above). `seg` addresses a real segment only below `it.n_seg`;
* a degenerate zero-segment item leaves seg_grid alone. */
if (seg_grid == 0 && seg < it.n_seg) seg_grid = it.seg_h(seg);
break;
}
parts.push_back({ &it, first, seg - first });
+10 -3
View File
@@ -42,6 +42,10 @@ SamplingParams GenSampling::onto(SamplingParams base) const {
return base;
}
/* The one-line statement of a served sampling configuration. The wording is pinned by
* gen_config_test.cpp (gen_config_reads_the_ngram_ban) -- change it there in the same change.
* It spells the values out for a log reader; `onto` fills the fields from defaults. The two
* share values, not logic, and the duplication of the ban clause is a string, not a rule. */
std::string GenSampling::describe(const SamplingParams& sp) {
char buf[320];
std::snprintf(buf, sizeof buf, "temperature %.2f, top_k %d%s, top_p %.2f, min_p %.2f",
@@ -132,11 +136,14 @@ bool gen_sampling_parse(const std::string& json_text, const char* src, GenSampli
* Values are warned about and dropped, like every other field here: an id is a vocabulary
* coordinate, so a negative one is not a value at all. */
it = j.find("no_repeat_ngram_whitelist");
if (it == j.end() || !it->is_array()) {
if (it != j.end())
if (it != j.end() && !it->is_array()) {
/* The legacy key is only a problem when nothing rescues it: a config that states a bad
* reference name beside a good sampler-spelled one reads the good one, silently. */
const auto own = j.find("ngram_whitelist");
if (own == j.end() || !own->is_array())
RAD_WARN("%s states a no_repeat_ngram_whitelist that is not an array; ignoring it",
src);
it = j.find("ngram_whitelist");
it = own;
}
if (it != j.end() && it->is_array()) {
for (const auto& v : *it) {
+29 -3
View File
@@ -2,6 +2,7 @@
#include "mem/kv.h"
#include <algorithm>
#include <cassert>
#include <cstring>
namespace rad {
@@ -352,7 +353,12 @@ int KVManager::declare_runtime_window(int32_t g, int64_t window_tokens) {
}
runtime_decl_[g] = window_tokens;
/* A plan built before the declaration (the engine's probes, or plan_groups() then declare)
* is updated in place; the next plan_groups() picks the declaration up on its own. */
* is updated in place; the next plan_groups() picks the declaration up on its own.
*
* A plan set shorter than `g` returns RAD_E_INVAL below with this store kept: deliberate.
* The declaration is the caller's standing intent (it survives forget(), whose vectors are
* emptied together and are not this map), and the short plan set is the probe ordering the
* declaration exists for -- the next plan_groups() applies it to a plan that has the group. */
if (!plans_.empty()) {
if (g >= (int32_t)plans_.size()) return RAD_E_INVAL;
KVGroupPlan& q = plans_[(size_t)g];
@@ -364,6 +370,10 @@ int KVManager::declare_runtime_window(int32_t g, int64_t window_tokens) {
fixed_ += align_up(max_seqs_ * q.ring_blocks_max() * q.bytes_per_block, RAD_ALIGN_UNIT);
if (counted) {
const int64_t was = q.window_blocks * q.bytes_per_block;
/* The plan counted this group's snapshot section, so both totals carry `was`.
* Saturating hides an accounting bug; surface it in debug builds. */
assert(window_ck_bytes_ >= was && checkpoint_bytes_ >= was &&
"runtime window: snapshot byte totals below the section being removed");
window_ck_bytes_ = window_ck_bytes_ > was ? window_ck_bytes_ - was : 0;
checkpoint_bytes_ = checkpoint_bytes_ > was ? checkpoint_bytes_ - was : 0;
}
@@ -975,6 +985,8 @@ int KVManager::preempt(uint64_t id) {
for (int32_t b : s->blocks[g]) drop_block((int32_t)g, b);
s->blocks[g].clear();
s->first_block_pos[g] = 0;
/* The runtime window goes with the blocks: re-admission re-arms it at the prompt end
* (the scheduler's admission path calls set_window again before the KV grows). */
s->win[g] = SeqWindow{};
s->dirty_from[g] = 0;
/* The recurrent state goes too (see preempt in kv.h, spec §7.1). */
@@ -994,8 +1006,9 @@ int KVManager::rollback(uint64_t id, int64_t n_tokens) {
/* Nothing to free; RAD_OK so "every draft accepted" needs no special path in the caller. */
if (n_tokens >= s->n_tokens) return RAD_OK;
/* A runtime-windowed sequence unwinds nothing: the ring's slots are reused once it is full,
* so the slots a rejected verify wrote may already hold newer keys. Speculation stays off for
* these requests (the scheduler never drafts for them); this refuses rather than corrupt. */
* so the slots a rejected verify wrote may already hold newer keys. The scheduler gates
* drafting on has_runtime_window, so this refuses rather than corrupts, and only a caller
* that drafts beside a runtime window can reach it. */
for (const SeqWindow& w : s->win)
if (w.set) return RAD_E_UNSUPPORTED;
@@ -1042,9 +1055,22 @@ int KVManager::set_window(uint64_t id, int64_t visible_lo, int64_t window_tokens
return RAD_E_STATE;
}
bool any = false;
/* With a declared runtime window in the program, arm exactly the declared groups: a plain
* fixed-window group beside them is carved for its fixed window, and arming it silently
* converts it. With none declared this is the caller-sizes-the-pool path kv.h states, and
* every windowed group arms as before. */
bool declared = false;
for (const KVGroupPlan& p : plans_)
if (p.kind == RAD_KV_WINDOW && p.runtime_win) declared = true;
for (size_t g = 0; g < plans_.size(); ++g) {
const KVGroupPlan& p = plans_[g];
if (p.kind != RAD_KV_WINDOW) continue;
if (declared && !p.runtime_win) {
RAD_ERR("sequence %llu: set_window meets fixed-window group '%s' beside a declared "
"runtime window; its pool is carved for its fixed window and the mix is not "
"supported", (unsigned long long)id, p.name.c_str());
return RAD_E_UNSUPPORTED;
}
SeqWindow w;
w.set = true;
w.window = window_tokens;
+5 -2
View File
@@ -271,7 +271,10 @@ public:
*
* A group that is not marked still accepts set_window() -- the caller then sizes the pool
* itself, e.g. by declaring the group's window as the whole context -- and each sequence's
* capacity is checked at set_window()/ensure() against the blocks actually carved. */
* capacity is checked at set_window()/ensure() against the blocks actually carved. Once any
* group is marked, set_window() arms only marked groups: a plain fixed-window group beside a
* declared runtime window is refused, not silently converted (its pool is carved for the
* fixed window). */
int declare_runtime_window(int32_t group, int64_t window_tokens);
/* Give a sequence a runtime window with `visible_lo` (its prefill length, image tokens
@@ -281,7 +284,7 @@ public:
* the reference is written linearly and no checkpoint can be reserved for it (a snapshot
* would describe a window the sequence no longer has).
*
* RAD_E_UNSUPPORTED no windowed group;
* RAD_E_UNSUPPORTED no windowed group, or the fixed/runtime-window mix above;
* RAD_E_INVAL a negative floor or a window of 0;
* RAD_E_STATE the sequence already holds tokens past the floor;
* RAD_E_FULL the reference plus the ring exceeds what this group carved. */
+39 -10
View File
@@ -485,7 +485,13 @@ int coeffs(int32_t in_size, int32_t out_size, std::vector<int32_t>* bounds,
/* One pass over an axis. `horizontal` reads rows [y0, y0 + rows) of `src` and writes w columns;
* `vertical` reads rows from `shift` on and writes h rows. Both accumulate in fixed point and
* round each output to eight bits, as Pillow does -- the intermediate's rounding is part of the
* function. */
* function.
*
* Perf note (review UNLIMITED-OCR-REVIEW, P med): these are scalar per-channel loops on a hot
* preprocessing path. The int32 fixed-point accumulation is order-stable per tap, so an AVX2
* implementation (stride-3 deinterleave + 8-lane int dot, in the libavx leg like the other
* bit-safe offloads) is bit-safe and pinned by the resample goldens -- a deliberate follow-up
* task, not a drive-by. The scalar order must not change. */
static void pass_horizontal(const Frame& src, int32_t y0, int32_t rows, int32_t w,
const std::vector<int32_t>& bh, const std::vector<int32_t>& kh,
int32_t ksh, int prec, Frame* out) {
@@ -829,18 +835,35 @@ void lfm2_grid(int64_t h, int64_t w, int32_t min_tiles, int32_t max_tiles, int32
* its `sorted(set(...), key=area)` visits after their wide transpose -- the order CPython's set
* has for the 2..32-tile range the checkpoint states. It comes from the reference itself
* (tests/mkuocrgolden.py dumps it); outside that range the wide side is taken as last. */
static constexpr int8_t kTallLast[][2] = {
{1, 3}, {1, 4}, {1, 5}, {1, 6}, {1, 7}, {1, 9}, {1, 13}, {1, 14},
{1, 16}, {1, 18}, {1, 20}, {1, 22}, {1, 27}, {1, 29}, {2, 3}, {2, 4},
{2, 5}, {2, 6}, {2, 7}, {2, 8}, {2, 9}, {2, 14}, {2, 15}, {2, 16},
{3, 5}, {3, 7}, {3, 9}, {4, 5}, {4, 6}, {4, 7}, {4, 8},
};
bool uocr_tall_last(int32_t c, int32_t r) {
static const int8_t kTallLast[][2] = {
{1, 3}, {1, 4}, {1, 5}, {1, 6}, {1, 7}, {1, 9}, {1, 13}, {1, 14},
{1, 16}, {1, 18}, {1, 20}, {1, 22}, {1, 27}, {1, 29}, {2, 3}, {2, 4},
{2, 5}, {2, 6}, {2, 7}, {2, 8}, {2, 9}, {2, 14}, {2, 15}, {2, 16},
{3, 5}, {3, 7}, {3, 9}, {4, 5}, {4, 6}, {4, 7}, {4, 8},
};
for (const auto& p : kTallLast)
if (p[0] == c && p[1] == r) return true;
return false;
}
/* One n defers at most its divisor pairs with c < n/c, at most the divisors below its square
* root. Over the 2..32-tile range the checkpoints state the table is built for, no n defers
* more than this; uocr_grid's deferred buffer is sized from it and the static_assert below
* keeps the bound checked against the table, not empirical. */
static constexpr int32_t deferred_pairs_max(int32_t max_n) {
int32_t best = 0;
for (int32_t n = 2; n <= max_n; ++n) {
int32_t cnt = 0;
for (const auto& p : kTallLast)
if (p[0] < p[1] && (int32_t)p[0] * (int32_t)p[1] == n) ++cnt;
if (cnt > best) best = cnt;
}
return best;
}
static_assert(deferred_pairs_max(32) <= 8,
"uocr_grid's 8-slot deferred buffer must cover the stated 2..32 tile range");
void uocr_grid(int64_t h, int64_t w, int32_t min_tiles, int32_t max_tiles, int32_t tile,
int32_t* cols, int32_t* rows) {
*cols = *rows = 1;
@@ -863,6 +886,9 @@ void uocr_grid(int64_t h, int64_t w, int32_t min_tiles, int32_t max_tiles, int32
for (int32_t c = 1; c <= n; ++c) {
if (n % c) continue;
if (c < n / c && uocr_tall_last(c, n / c)) {
/* Defensive: the static_assert proves 8 covers the stated 2..32 range. Beyond
* it the reference's tie order is not guaranteed, and a drop is a last resort
* against overflow, not a designed path. */
if (n_deferred < 8) deferred[n_deferred++] = c;
continue;
}
@@ -1075,6 +1101,9 @@ int Processor::image_unlimitedocr(const Frame& f, const ImageMode& mode,
if (crop) {
pad_bicubic(f, base_size, base_size, 127, &global);
} else if (image_size <= c.tile) {
/* The reference's multi-page path squares the page first, so a non-square page is
* aspect-distorted by this resize, and the pad below is a no-op by construction (the
* square already is the pad target). Square-first kept for reference parity. */
Frame sq;
resize_bicubic(f, image_size, image_size, &sq);
pad_bicubic(sq, image_size, image_size, 127, &global);
@@ -1106,8 +1135,8 @@ int Processor::image_unlimitedocr(const Frame& f, const ImageMode& mode,
/* One segment of `gh` x `gw` patches from (x0, y0) of `src`, of which the first `real_w`
* patches a row carry pixels; the rest are the newline column. */
auto append = [&](const Frame& src, int32_t x0, int32_t y0, int32_t gh, int32_t gw,
int32_t real_w) {
it->segments.push_back({ gh, gw, it->n_patch, real_w == 0 });
int32_t real_w, bool sep = false) {
it->segments.push_back({ gh, gw, it->n_patch, sep });
it->seg_at.push_back((int32_t)seg_row);
it->expand.insert(it->expand.end(), (size_t)(gh / M) * (size_t)(gw / M), c.tok_image);
seg_row += (int64_t)(gh / M) * (gw / M);
@@ -1149,7 +1178,7 @@ int Processor::image_unlimitedocr(const Frame& f, const ImageMode& mode,
}
append(global, 0, 0, g, g + 4, g);
/* The view separator: one output row, from a grid of exactly one merged cell and no pixels. */
append(global, 0, 0, M, M, 0);
append(global, 0, 0, M, M, 0, /*sep=*/true);
it->n_seg = (int32_t)it->segments.size();
it->grid_t = 1;
+8 -3
View File
@@ -943,10 +943,11 @@ int Sampler::build_greedy(int64_t n) {
cur_stage_ = greedy_stage_;
/* A drafter's rows run the argmax only, so the n-gram plane is cleared: `run` reads it from
* the staging, and a stale pair from an earlier request's build must not issue the ban over
* history that was not staged this step. The exemption plane goes with it: cleared for the
* rows `run` would upload, so no build that does issue the ban reads a stale exemption. */
* history that was not staged this step. The exemption plane needs no clear: `run` uploads
* it only beside an issued ban, every row that runs the ban has its words rewritten in full
* by the build that staged the pair (build_step), and rows below a zeroed pair are skipped
* by the op before they read a word. */
std::memset(ngram_stage_, 0, (size_t)cap * 2 * sizeof(int32_t));
std::memset(ngram_wl_stage_, 0, (size_t)n * mask_words_ * 4);
if (greedy_ready_) return RAD_OK;
for (int64_t i = 0; i < cap; ++i) {
DeviceSampleParams& p = greedy_stage_[i];
@@ -977,6 +978,10 @@ int Sampler::run(RadCtx* c, rad_buf logits, rad_buf out_tokens) {
any_penalty |= (p.flags & RAD_SP_PENALTY) != 0;
any_dry |= (p.flags & RAD_SP_DRY) != 0;
any_xtc |= (p.flags & RAD_SP_XTC) != 0;
/* The pair plane is read directly, not through cur_stage_: it is per-step staging the
* LAST builder filled (build_step writes a row's pair, build_greedy zeroes every pair),
* so it agrees with cur_stage_ by builder contract. A new builder must keep that
* contract: stage the pair with the params, zero it with the greedy ones. */
any_ngram |= ngram_stage_[2 * i] > 0;
if (p.flags & RAD_SP_GREEDY) any_greedy = true;
else {
+14 -12
View File
@@ -6,6 +6,7 @@
#include "device/device.h"
#include <algorithm>
#include <cassert>
#include <cstring>
#include <cstdlib>
@@ -689,6 +690,11 @@ int BatchBuilder::build_groups(const StepPlan& plan, const IKVManager& kv, Set&
}
int64_t t = 0;
/* The group's ring block count, read off the first armed sequence: declare_runtime_window
* fixes one W per group, so every armed sequence computes the same count. Collected here,
* with the table walk that already opens each window, so the group header below needs no
* second pass over the plan. */
int32_t ring_blocks = 0;
for (int64_t i = 0; i < n_seq; ++i) {
const StepEntry& e = plan.e[(size_t)i];
@@ -703,6 +709,10 @@ int BatchBuilder::build_groups(const StepPlan& plan, const IKVManager& kv, Set&
const std::vector<int32_t>& bt = kv.block_table(e.seq, (int32_t)gi);
first = kv.first_block_pos(e.seq, (int32_t)gi);
has_win = kv.runtime_window(e.seq, (int32_t)gi, &win);
if (has_win) {
assert(!ring_blocks || ring_blocks == (int32_t)win.ring_blocks);
ring_blocks = (int32_t)win.ring_blocks;
}
bt_len = (int64_t)bt.size();
table_end = bt_len * L.block_size;
for (int32_t j = 0; j < e.n_tokens; ++j) {
@@ -803,20 +813,12 @@ int BatchBuilder::build_groups(const StepPlan& plan, const IKVManager& kv, Set&
/* The runtime window (KVManager::set_window): the advance runs after this build and
* overwrites `used` and the slots, so it must reproduce the ring's mapping rather
* than the linear one (advance_impl.h). The floor and table length are per sequence
* (s.h_rpos / s.h_tlen), the ring's block count is the group's W. */
a.ring = 0;
a.ring_blocks = 0;
* (s.h_rpos / s.h_tlen), the ring's block count is the group's W, collected with the
* table walk above. */
a.ring = ring_blocks ? 1 : 0;
a.ring_blocks = ring_blocks;
a.rpos_off = (const char*)s.d_rpos - d0;
a.tlen_off = (const char*)s.d_tlen - d0;
for (int64_t i = 0; i < n_seq; ++i) {
const StepEntry& e = plan.e[(size_t)i];
SeqWindow w;
if (kv.runtime_window(e.seq, (int32_t)gi, &w)) {
a.ring = 1;
a.ring_blocks = (int32_t)w.ring_blocks;
break;
}
}
}
for (size_t r = 0; r < ranks_.size(); ++r) {
+4 -1
View File
@@ -2157,7 +2157,10 @@ int Scheduler::serial_begin(int* rounds, SerialRow* out, int max) {
* so the host bounds it by all of them. A mid-prompt chunk verified nothing. */
const int64_t vstart = (int64_t)e.ctx_len + e.n_tokens - 1 - e.n_spec;
const int64_t head_max = vstart + e.n_spec;
bool can_draft = may_draft && e.produces_token;
/* A runtime-window (R-SWA) sequence is never drafted for: its rollback refuses (the ring
* rewrites slots KVManager::rollback cannot unwind), so a rejected draft would only warn
* and waste the draft compute. This is the gate kv.cpp's rollback comment states. */
bool can_draft = may_draft && e.produces_token && !kv_->has_runtime_window(r.id);
/* Lookahead KV: round k writes the head's K and V at head + k - 1, past the committed end,
* so blocks must exist up to the furthest head acceptance could leave. The next verify
+6 -3
View File
@@ -909,9 +909,12 @@ static int parse_sampling(const json& b, const OaiLimits& lim, OaiRequest* r, Ap
i64 = r->sp.ngram_window;
if (!get_any(b, { "ngram_window", "no_repeat_ngram_window_size" }, &i64, nullptr, err))
return RAD_E_INVAL;
if (i64 > 131072) {
*err = err_bad("ngram_window", "must be at most 131072 tokens of history; 0 or less "
"searches the whole sequence");
if (i64 < 0 || i64 > 131072) {
/* The reference's negative window spelling belongs to generation_config, where it is
* normalized to 0; a request states the whole-sequence form as 0, matching the sampler's
* admission check (check_request refuses a negative window). */
*err = err_bad("ngram_window", "must be 0 (search the whole sequence) or a count of at "
"most 131072 history tokens");
return RAD_E_INVAL;
}
r->sp.ngram_window = (int)i64;
@@ -16,11 +16,23 @@
{%- set ns.at = loop.index0 -%}
{%- endif -%}
{%- endfor -%}
{%- if ns.last is not none and ns.last['content'] is string -%}
{%- for piece in ns.last['content'].split('<__media__>') -%}
{%- if not loop.last -%}{%- set ns.media = ns.media + 1 -%}{%- endif -%}
{%- if ((piece | replace('', '')) | trim) != '' -%}{%- set ns.text = true -%}{%- endif -%}
{%- endfor -%}
{%- if ns.last is not none -%}
{%- if ns.last['content'] is string -%}
{%- for piece in ns.last['content'].split('<__media__>') -%}
{%- if not loop.last -%}{%- set ns.media = ns.media + 1 -%}{%- endif -%}
{%- if ((piece | replace('', '')) | trim) != '' -%}{%- set ns.text = true -%}{%- endif -%}
{%- endfor -%}
{%- else -%}
{#- The OpenAI parts form counts the same way: media from the marker parts, text from any
non-empty text part (a client's U+FFFC object placeholder is whitespace). -#}
{%- for part in ns.last['content'] -%}
{%- if part['type'] == 'media_marker' -%}
{%- set ns.media = ns.media + 1 -%}
{%- elif part['type'] == 'text' and ((part['text'] | default('', true) | replace('', '')) | trim) != '' -%}
{%- set ns.text = true -%}
{%- endif -%}
{%- endfor -%}
{%- endif -%}
{%- endif -%}
{%- for message in messages -%}
{%- set mi = loop.index0 -%}
@@ -41,7 +53,11 @@
{%- endfor -%}
{%- endif -%}
{%- endfor -%}
{%- if ns.last is not none and ns.last['content'] is string and not ns.text -%}
{#- The instruction block serves both content forms: ns.media/ns.text above scanned the final
turn whichever it was. Output is whitespace-tight: every tag trims, the newline after
"Multi page parsing." is eaten by the next tag's `{%-`, and the rendered prompt ends with
the instruction verbatim -- keep the trims when reformatting this block. -#}
{%- if ns.last is not none and not ns.text -%}
{%- if ns.media > 1 -%}Multi page parsing.
{%- elif ns.media == 1 -%}document parsing.
{%- endif -%}
+4
View File
@@ -2590,6 +2590,10 @@ request (`ngram_ban_n`, `ngram_window`). It needs about 7 GiB on one card, so se
compose file takes `RADIANCE_GPU` and the model file's VRAM, with the vision tower on the card and
an fp8 KV cache.
The reference's `infer` opens its prompt with the BOS the chat template omits, and the chat path
supplies it; `/v1/completions` prompts are served exactly as sent (the reference has no
completions entry point), so prompt parity with the reference is a chat-endpoint property.
## 6. Operation
### 6.1 The dashboard
+2 -1
View File
@@ -273,7 +273,8 @@ weight.
**`act_mul`** is `silu_mul` with its halves in two operands, so the multiplier can be any tensor:
two column slices of a fused `gate_up`, or a gate and a separate per-layer input (EmbeddingGemma 2's
per-layer-embedding block multiplies `gelu_tanh(gate(x))` by one). `act` is `silu`, `gelu` (exact
erf), `gelu_tanh` or `sigmoid` (a GLU: `a` the gate half, `b` the value half). The activation is
erf), `gelu_tanh`, `sigmoid` (a GLU: `a` the gate half, `b` the value half) or `quick_gelu`
(`sigmoid` of the bf16-rounded `1.702 a`, the CLIP tower's fused form). The activation is
rounded to `y`'s dtype before the product, as the unfused pair stores it.
**`seg_mean`** is mean pooling over a ragged batch: row `s` of `y` is the mean of `x`'s rows
+1 -1
View File
@@ -58,7 +58,7 @@ std::vector<Case> build_cases() {
add("scale", { HI("M", 6), HI("n", 645), HS("dtype", dt) }, EB(6, 645, w, 2));
add("softmax", { HI("M", 6), HI("n", 645), HS("dtype", dt) }, EB(6, 645, w, 2));
add("gather_rows", { HI("M", 6), HI("n", 640), HS("dtype", dt) }, EB(6, 640, w, 2));
for (const char* act : { "silu", "gelu", "gelu_tanh", "sigmoid" })
for (const char* act : { "silu", "gelu", "gelu_tanh", "sigmoid", "quick_gelu" })
add("act_mul", { HI("M", 6), HI("n", 645), HS("act", act), HS("dtype", dt) },
EB(6, 645, w, 3));
add("mul_weight", { HI("M", 9), HI("n", 645), HS("dtype", dt) }, EB(9, 645, w, 2));
+18 -7
View File
@@ -117,16 +117,27 @@ AVX_KERNEL(mul_weight) {
* rather than the algebraically equal g / (1 + e^(-2z)), which differs by an ulp or two and after
* bf16 rounding measurably moves embeddings away from transformers'. vf_exp saturates, so the
* large-|g| limits come out as g and 0. erf has no vector form here, so gelu stays scalar. */
static inline float act_of(int act, float g) {
static inline float round1(uint32_t dt, float v) {
if (dt == RAD_F32) return v;
uint16_t t;
row_from_f32(dt, &v, &t, 1);
float r;
row_to_f32(dt, &t, &r, 1);
return r;
}
static inline float act_of(int act, float g, uint32_t dt) {
if (act == 0) return g / (1.0f + sc_exp(-g));
if (act == 1) return 0.5f * g * (1.0f + sc_erf(g * 0.70710678118654752f));
if (act == 3) return 1.0f / (1.0f + sc_exp(-g));
if (act == 4) // quick_gelu: sigmoid of the 1.702*g the unfused mul would have stored
return 1.0f / (1.0f + sc_exp(-round1(dt, g * round1(RAD_BF16, 1.702f))));
const float k0 = 0.7978845608028654f, k1 = 0.044715f;
return 0.5f * g * (1.0f + sc_tanh(k0 * (g + k1 * g * g * g)));
}
/* sy[0..n) = act(g[0..n)) for silu (0) and gelu_tanh (2); the tail is the scalar form. */
static inline void act_row(int act, const float* g, float* sy, int64_t n) {
static inline void act_row(int act, const float* g, float* sy, int64_t n, uint32_t dt) {
int64_t i = 0;
const vf one = vf_set1(1.0f);
if (act == 0) {
@@ -145,7 +156,7 @@ static inline void act_row(int act, const float* g, float* sy, int64_t n) {
vf_storeu(sy + i, vf_mul(vf_mul(half, x), vf_add(one, t)));
}
}
for (; i < n; ++i) sy[i] = act_of(act, g[i]);
for (; i < n; ++i) sy[i] = act_of(act, g[i], dt);
}
AVX_KERNEL(act_mul) {
@@ -155,8 +166,8 @@ AVX_KERNEL(act_mul) {
if (n <= 0) return RAD_E_SHAPE;
const int64_t rows = rows_of(Y, n);
if (rows <= 0 || numel(A) < rows * n || numel(B) < rows * n) return RAD_E_SHAPE;
static const char* kActs[] = { "silu", "gelu", "gelu_tanh", "sigmoid" };
const int act = p_enum(a, "act", kActs, 4, -1);
static const char* kActs[] = { "silu", "gelu", "gelu_tanh", "sigmoid", "quick_gelu" };
const int act = p_enum(a, "act", kActs, 5, -1);
if (act < 0) return RAD_E_INVAL;
AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN)
@@ -166,7 +177,7 @@ AVX_KERNEL(act_mul) {
float* sy = scratch_f32_c((size_t)n);
const float* g = in_row(A, rowoff(A, r, n), n, sa);
const float* u = in_row(B, rowoff(B, r, n), n, sb);
act_row(act, g, sy, n);
act_row(act, g, sy, n, Y->dtype);
/* sa is free once the activation is taken (g is sa or the tensor); sb may hold u, which
* is still needed. */
roundtrip(Y->dtype, sy, n, sa);
@@ -314,7 +325,7 @@ AVX_KERNEL(conv2d) {
if (gelu) {
/* The biased sum as y's dtype holds it, then the activation of the rounded value. */
const float* yr = in_row(Y, rowoff(Y, o0 + to, rout), rout, acc);
for (int64_t e = 0; e < rout; ++e) acc[e] = act_of(1, yr[e]);
for (int64_t e = 0; e < rout; ++e) acc[e] = act_of(1, yr[e], RAD_F32);
out_row(Y, rowoff(Y, o0 + to, rout), rout, acc);
}
}
+19 -8
View File
@@ -11,11 +11,13 @@
* values of their tile and take part in the softmax; `window` 0 is one tile over the segment.
*
* This is the same structure as libref's: one thread owns one output row and one head, the tile's
* keys are walked jh-major so the q.Rh dot is computed once a tile row, the softmax subtracts the
* tile maximum, and the output is rounded once. The dots are plain f32 loops over head_dim, which
* LLVM vectorises at every level; the tile is small enough that no blocking is needed. The tables
* are widened to f32 once a launch and resampled along dim 0 when a geometry's axes need it
* (get_rel_pos's linear interpolation).
* keys are walked jh-major so the q.Rh dot is computed once a tile row and the q.Rw dots are
* hoisted per query row (the hip kernel's hoist, bit-identical reuse), the softmax subtracts the
* tile maximum, and the output is rounded once. The dots stay scalar f32 loops over head_dim on
* purpose: the x86 leg is the no-GPU/harness path, and a SIMD reduction would reassociate the f32
* accumulation and break bit-parity with the libref oracle. The tables are widened to f32 once a
* launch and resampled along dim 0 when a geometry's axes need it (get_rel_pos's linear
* interpolation).
*/
#include "avx_vec.h"
#include "avx_common.h"
@@ -114,14 +116,23 @@ AVX_KERNEL(sam_attn) {
const int64_t qst = laststride(q);
for (int64_t c = 0; c < hd; ++c) qt[c] = ldt(q, qbase + c * qst);
/* The w rel-pos dot depends on (lw, jw) alone, not on jh: dot it once per query
* row and reuse it through the tile rows. The same scalar loop in the same order,
* so every reused value is bit-identical to the per-(jh, jw) recompute. */
std::vector<float> wr((size_t)tw);
for (int64_t jw = 0; jw < tw; ++jw) {
const float* rwrow = &Rw[(size_t)((lw - jw + tw - 1) * hd)];
float wv = 0.0f;
for (int64_t c = 0; c < hd; ++c) wv += qt[c] * rwrow[c];
wr[(size_t)jw] = wv;
}
for (int64_t jh = 0; jh < th; ++jh) {
const float* rhrow = &Rh[(size_t)((lh - jh + th - 1) * hd)];
float hr = 0.0f;
for (int64_t c = 0; c < hd; ++c) hr += qt[c] * rhrow[c];
for (int64_t jw = 0; jw < tw; ++jw) {
const float* rwrow = &Rw[(size_t)((lw - jw + tw - 1) * hd)];
float lgt = hr;
for (int64_t c = 0; c < hd; ++c) lgt += qt[c] * rwrow[c];
float lgt = hr + wr[(size_t)jw];
const int64_t kh = ty * th + jh, kw = tx * tw + jw;
if (kh < gh && kw < gw) {
const int64_t krow = base + kh * gw + kw;
+5 -1
View File
@@ -29,6 +29,7 @@
#include "rad_sample.h"
#include <cfloat>
#include <vector>
using namespace avx;
@@ -287,11 +288,14 @@ AVX_KERNEL(sample_ngram_ban) {
return ((word >> (uint32_t)(col % 32)) & 1u) != 0u;
};
const int64_t plen = n - 1, p0 = hl - plen;
/* The prefix is the same n-1 tokens compared at every search position: read once. */
std::vector<int64_t> pref((size_t)plen);
for (int64_t j = 0; j < plen; ++j) pref[(size_t)j] = tok_at(p0 + j);
for (int64_t idx = search_start; idx < search_end; ++idx) {
bool match = true;
for (int64_t j = 0; j < plen; ++j) {
if (tok_at(idx + j) != tok_at(p0 + j)) { match = false; break; }
if (tok_at(idx + j) != pref[(size_t)j]) { match = false; break; }
}
if (!match) continue;
const int64_t tok = tok_at(idx + plen);
+7 -3
View File
@@ -28,6 +28,8 @@ __device__ __forceinline__ float act_of(float g) {
if (ACT == 0) return g / (1.0f + expf(-g));
if (ACT == 1) return 0.5f * g * (1.0f + erff(g * 0.70710678118654752f));
if (ACT == 3) return 1.0f / (1.0f + expf(-g));
if (ACT == 4) // quick_gelu: sigmoid of the bf16-rounded 1.702*g, as the unfused mul stores it
return 1.0f / (1.0f + expf(-bf2f(f32_to_bf16(g * bf2f(f32_to_bf16(1.702f))))));
return 0.5f * g * (1.0f + tanhf(0.7978845608028654f * (g + 0.044715f * g * g * g)));
}
@@ -739,11 +741,11 @@ __global__ __launch_bounds__(kLrThreads) void attn_local_rel_kernel(
// ============================================================== launchers
// act: 0 silu, 1 gelu (erf), 2 gelu_tanh, 3 sigmoid.
// act: 0 silu, 1 gelu (erf), 2 gelu_tanh, 3 sigmoid, 4 quick_gelu (sigmoid(bf16(1.702*a))).
extern "C" int r4d_act_mul_bf16(long a, long b, long y, int M, int n, int act, int a_ld, int b_ld,
int y_ld, long stream) {
if (!a || !b || !y) return -1;
if (M <= 0 || n <= 0 || act < 0 || act > 3) return -2;
if (M <= 0 || n <= 0 || act < 0 || act > 4) return -2;
const dim3 grid((uint32_t)((n + kThreads - 1) / kThreads), grid_rows(M));
#define R4D_AM(A) \
hipLaunchKernelGGL(act_mul_kernel<A>, grid, dim3(kThreads), 0, (hipStream_t)stream, \
@@ -752,7 +754,8 @@ extern "C" int r4d_act_mul_bf16(long a, long b, long y, int M, int n, int act, i
if (act == 0) R4D_AM(0);
else if (act == 1) R4D_AM(1);
else if (act == 2) R4D_AM(2);
else R4D_AM(3);
else if (act == 3) R4D_AM(3);
else R4D_AM(4);
#undef R4D_AM
return hipGetLastError() == hipSuccess ? 0 : -4;
}
@@ -1033,6 +1036,7 @@ extern "C" int r4d_rad_act_mul(const RadArgs* a, RadStream s) {
else if (act && !std::strcmp(act, "gelu")) ai = 1;
else if (act && !std::strcmp(act, "gelu_tanh")) ai = 2;
else if (act && !std::strcmp(act, "sigmoid")) ai = 3;
else if (act && !std::strcmp(act, "quick_gelu")) ai = 4;
if (ai < 0) return R4D_NO(RAD_E_INVAL);
const long long n = r4d_geti_or(a, "n", r4d_dim(Y, (int)Y->rank - 1));
if (n <= 0) return R4D_NO(RAD_E_SHAPE);
+7 -4
View File
@@ -2694,7 +2694,8 @@ static const RadOpSchema kSchemas[] = {
"op, not gelu, because gated feed-forwards are trained with the tanh form and the "
"unary gelu is the exact erf one."),
SCHEMA("act_mul", pActMul, oBinary,
"y = act(a) * b, the activation (silu, gelu, gelu_tanh) rounded to y's dtype before "
"y = act(a) * b, the activation (silu, gelu, gelu_tanh, sigmoid or quick_gelu) rounded "
"to y's dtype before "
"the product: silu_mul with its two halves in two operands."),
SCHEMA("seg_mean", pSegMean, oSegMean,
"Row s of y is the mean of x's rows [cu_seqlens[s], cu_seqlens[s+1]), summed in f64 "
@@ -3797,9 +3798,8 @@ static const RadConstraint cAttnDecodeH128G1Fp8[] = {
static const RadConstraint cAttnDecodeH128G1Bf16[] = {
C_EQ("window", 0), C_EQ("head_dim", 128), C_EQ("gqa", 1), C_EQ("block_size", 16),
C_GE("causal", 0), C_LE("q_len", 64), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"),
};/* KEY RENAME. libr4d writes C_IN("q_dtype","bf16") and C_IN("kv_dtype","bf16"); docs/OPS.md's
* `attn_dense` has one `dtype` because nothing about a dense bf16 tower is mixed-precision. The
* predicate -- "bf16, and nothing else" -- is unchanged. */
};
/* Two queries per KV head at head_dim 128 (Qwen3-1.7B, Qwen3-ASR's decoder): the gqa8 pair's
* constraints with the ratio and the decode verify width changed together. A decode workgroup
* holds 64 (query, head) rows, so q_len <= 32 at gqa 2. */
@@ -3862,6 +3862,9 @@ static const RadConstraint cCastNarrow[] = {
* bidirectional with any window, or a text encoder's causal prompt. gqa 1 at 256 and 512 is
* attn_dense_small_h256's and the wide kernel's. */
/* Causal or not at head_dim 64: a vision tower's heads, and a codec's sliding causal layers. */
/* KEY RENAME. libr4d writes C_IN("q_dtype","bf16") and C_IN("kv_dtype","bf16"); docs/OPS.md's
* `attn_dense` has one `dtype` because nothing about a dense bf16 tower is mixed-precision. The
* predicate -- "bf16, and nothing else" -- is unchanged. */
static const RadConstraint cAttnDenseH64[] = {
C_EQ("head_dim", 64), C_EQ("gqa", 1), C_IN("dtype", "bf16"),
};
+148 -17
View File
@@ -36,6 +36,11 @@ namespace {
constexpr uint32_t kThreads = 128;
constexpr float kLog2e = 1.4426950408889634f;
/* Row loads stay scalar uint16: the operand contract allows any row pitch (the tower's q/k/v are
* column slices of one fused projection, and a tower may pad rows), so a 16-byte bf16x8 read
* would be misaligned for a pitch that is not a multiple of 8 elements. The register diet is the
* w-dot hoist below, not the load width. */
/* q . row(d) of a rel_pos table as the reference resized it to `want` rows: linear interpolation
* between the two source rows at align_corners=False's coordinate, clamped at the edges. With
* rows == want the source is row d itself (f == 0), so the direct read is unchanged bit for bit. */
@@ -65,8 +70,88 @@ __device__ inline float tab_dot(const uint16_t* __restrict__ tab, int rows, int
return s;
}
template <int HD>
__global__ __launch_bounds__(kThreads) void sam_attn_kernel(
/* Eight bf16 of a q/k/v/out row as one 16-byte uint4. VEC is only instantiated when the caller
* proved every involved pointer is 16-byte aligned and every row pitch a multiple of 8 elements
* (launch_sam_attn); otherwise the scalar uint16 path below runs, because the operand contract
* allows any pitch (the tower's q/k/v are column slices and may carry a filler column). The
* element order is the scalar order, so both paths produce bit-identical dots. */
__device__ inline void bf16x8_to_f32(uint4 u, float* f) {
const unsigned* w = (const unsigned*)&u;
#pragma unroll
for (int i = 0; i < 4; ++i) {
f[2 * i] = bf16_to_f32((uint16_t)(w[i] & 0xffffu));
f[2 * i + 1] = bf16_to_f32((uint16_t)(w[i] >> 16));
}
}
template <bool VEC, int HD>
__device__ inline void ld_row(const uint16_t* p, float* f) {
if (VEC) {
const uint4* u = (const uint4*)p;
#pragma unroll
for (int c8 = 0; c8 < HD / 8; ++c8) bf16x8_to_f32(u[c8], f + c8 * 8);
} else {
#pragma unroll
for (int c = 0; c < HD; ++c) f[c] = bf16_to_f32(p[c]);
}
}
template <bool VEC, int HD>
__device__ inline void st_row(uint16_t* p, const float* f) {
if (VEC) {
uint4 u[HD / 8];
uint16_t* b = (uint16_t*)u;
#pragma unroll
for (int c = 0; c < HD; ++c) b[c] = f32_to_bf16(f[c]);
uint4* o = (uint4*)p;
#pragma unroll
for (int c8 = 0; c8 < HD / 8; ++c8) o[c8] = u[c8];
} else {
#pragma unroll
for (int c = 0; c < HD; ++c) p[c] = f32_to_bf16(f[c]);
}
}
template <bool VEC, int HD>
__device__ inline float dot_row(const uint16_t* p, const float* qf) {
float s = 0.0f;
if (VEC) {
const uint4* u = (const uint4*)p;
#pragma unroll
for (int c8 = 0; c8 < HD / 8; ++c8) {
const unsigned* w = (const unsigned*)&u[c8];
#pragma unroll
for (int i = 0; i < 4; ++i) {
s += qf[c8 * 8 + 2 * i] * bf16_to_f32((uint16_t)(w[i] & 0xffffu));
s += qf[c8 * 8 + 2 * i + 1] * bf16_to_f32((uint16_t)(w[i] >> 16));
}
}
} else {
#pragma unroll
for (int c = 0; c < HD; ++c) s += qf[c] * bf16_to_f32(p[c]);
}
return s;
}
template <bool VEC, int HD>
__device__ inline void axpy_row(float* acc, const uint16_t* p, float pv) {
if (VEC) {
const uint4* u = (const uint4*)p;
#pragma unroll
for (int c8 = 0; c8 < HD / 8; ++c8) {
float f8[8];
bf16x8_to_f32(u[c8], f8);
#pragma unroll
for (int i = 0; i < 8; ++i) acc[c8 * 8 + i] += pv * f8[i];
}
} else {
#pragma unroll
for (int c = 0; c < HD; ++c) acc[c] += pv * bf16_to_f32(p[c]);
}
}
template <int HD, bool VEC>
__device__ inline void sam_attn_body(
const uint16_t* __restrict__ gq, const uint16_t* __restrict__ gk,
const uint16_t* __restrict__ gv, uint16_t* __restrict__ go,
const int* __restrict__ cu, const uint16_t* __restrict__ rh,
@@ -82,7 +167,18 @@ __global__ __launch_bounds__(kThreads) void sam_attn_kernel(
const int seq = b;
const int s0 = cu[seq];
if (cu[seq + 1] - s0 != gh * gw) return; // a segment is exactly one grid
if (cu[seq + 1] - s0 != gh * gw) {
// A segment that is not one grid is a tower bug, not a shape: the shim pre-checks the
// row count against the segment count, and this is the device-side guard. Write NaN over
// the segment's rows (the vit kernel's poison convention) so the corruption reaches the
// consumer -- a silent return would pass a garbage plane on as success.
const int n = cu[seq + 1] - s0;
for (int r = (int)threadIdx.x; r < n; r += (int)kThreads) {
uint16_t* op = go + (size_t)(s0 + r) * (size_t)o_ld + (size_t)head * HD;
for (int c = 0; c < HD; ++c) op[c] = (uint16_t)0x7fc0u; // bf16 NaN, as vit poisons
}
return;
}
const int keys = th * tw;
for (int r = (int)threadIdx.x; r < keys; r += (int)kThreads) {
@@ -93,21 +189,31 @@ __global__ __launch_bounds__(kThreads) void sam_attn_kernel(
const size_t qrow = (size_t)(s0 + ih * gw + iw);
const uint16_t* qp = gq + qrow * (size_t)q_ld + (size_t)head * HD;
float qf[HD];
#pragma unroll
for (int c = 0; c < HD; ++c) qf[c] = bf16_to_f32(qp[c]);
ld_row<VEC, HD>(qp, qf);
float acc[HD];
#pragma unroll
for (int c = 0; c < HD; ++c) acc[c] = 0.0f;
float m = -INFINITY, l = 0.0f;
/* The w rel-pos dots depend on (lw, jw) only: computed once for the query row when the
* tile is narrow (the windowed tiles are 14 wide), recomputed per key otherwise (a
* whole-grid tile of 64 columns would cost more registers than the dots save). */
float wr[16];
const bool wr_hoist = tw <= 16;
if (wr_hoist)
for (int jw = 0; jw < tw; ++jw)
wr[jw] = tab_dot<HD>(rw, rw_rows, 2 * tw - 1, lw - jw + tw - 1, qf);
for (int jh = 0; jh < th; ++jh) {
const float hr = tab_dot<HD>(rh, rh_rows, 2 * th - 1, lh - jh + th - 1, qf);
const int kh = ty * th + jh;
const bool hreal = kh < gh;
for (int jw = 0; jw < tw; ++jw) {
float s = hr + tab_dot<HD>(rw, rw_rows, 2 * tw - 1, lw - jw + tw - 1, qf);
float s = hr + (wr_hoist ? wr[jw]
: tab_dot<HD>(rw, rw_rows, 2 * tw - 1, lw - jw + tw - 1,
qf));
const int kw = tx * tw + jw;
const bool real = hreal && kw < gw;
@@ -115,9 +221,7 @@ __global__ __launch_bounds__(kThreads) void sam_attn_kernel(
if (real) {
const size_t krow = (size_t)(s0 + kh * gw + kw);
const uint16_t* kp = gk + krow * (size_t)k_ld + (size_t)head * HD;
float d = 0.0f;
#pragma unroll
for (int c = 0; c < HD; ++c) d += qf[c] * bf16_to_f32(kp[c]);
const float d = dot_row<VEC, HD>(kp, qf);
s += scale * d;
vp = gv + krow * (size_t)v_ld + (size_t)head * HD;
}
@@ -132,20 +236,34 @@ __global__ __launch_bounds__(kThreads) void sam_attn_kernel(
}
const float p = ex2((s - m) * kLog2e);
l += p;
if (real) {
#pragma unroll
for (int c = 0; c < HD; ++c) acc[c] += p * bf16_to_f32(vp[c]);
}
if (real) axpy_row<VEC, HD>(acc, vp, p);
}
}
const float inv = l > 0.0f ? 1.0f / l : 0.0f;
uint16_t* op = go + qrow * (size_t)o_ld + (size_t)head * HD;
#pragma unroll
for (int c = 0; c < HD; ++c) op[c] = f32_to_bf16(acc[c] * inv);
for (int c = 0; c < HD; ++c) acc[c] *= inv;
st_row<VEC, HD>(op, acc);
}
}
template <int HD>
__global__ __launch_bounds__(kThreads) void sam_attn_kernel(
const uint16_t* __restrict__ gq, const uint16_t* __restrict__ gk,
const uint16_t* __restrict__ gv, uint16_t* __restrict__ go,
const int* __restrict__ cu, const uint16_t* __restrict__ rh,
const uint16_t* __restrict__ rw, int rh_rows, int rw_rows,
int q_ld, int k_ld, int v_ld, int o_ld, int nhead, int gh, int gw, int th, int tw,
int nth, int ntw, int vec_rows, float scale) {
if (vec_rows)
sam_attn_body<HD, true>(gq, gk, gv, go, cu, rh, rw, rh_rows, rw_rows, q_ld, k_ld, v_ld,
o_ld, nhead, gh, gw, th, tw, nth, ntw, scale);
else
sam_attn_body<HD, false>(gq, gk, gv, go, cu, rh, rw, rh_rows, rw_rows, q_ld, k_ld, v_ld,
o_ld, nhead, gh, gw, th, tw, nth, ntw, scale);
}
int launch_sam_attn(const uint16_t* q, const uint16_t* k, const uint16_t* v, uint16_t* o,
const int* cu, const uint16_t* rh, const uint16_t* rw,
int rh_rows, int rw_rows,
@@ -155,9 +273,16 @@ int launch_sam_attn(const uint16_t* q, const uint16_t* k, const uint16_t* v, uin
const int nth = (gh + th - 1) / th, ntw = (gw + tw - 1) / tw;
const size_t blocks = (size_t)nseq * nth * ntw * nhead;
if (blocks == 0 || blocks > 0x7fffffff) return R4D_NO(RAD_E_SHAPE);
/* The 16-byte row loads are legal only when every q/k/v/out row starts on a 16-byte
* boundary: all four bases aligned, every row pitch a multiple of 8 bf16. The selftest's
* padded pitch and a slice with a filler column both fail this and take the scalar path. */
const uintptr_t addr_bits = (uintptr_t)q | (uintptr_t)k | (uintptr_t)v | (uintptr_t)o;
const bool vec_rows = (addr_bits & 15u) == 0 &&
((q_ld | k_ld | v_ld | o_ld) & 7) == 0;
hipLaunchKernelGGL((sam_attn_kernel<64>), dim3((uint32_t)blocks), dim3(kThreads), 0,
(hipStream_t)stream, q, k, v, o, cu, rh, rw, rh_rows, rw_rows,
q_ld, k_ld, v_ld, o_ld, nhead, gh, gw, th, tw, nth, ntw, scale);
q_ld, k_ld, v_ld, o_ld, nhead, gh, gw, th, tw, nth, ntw,
vec_rows ? 1 : 0, scale);
return hipGetLastError() == hipSuccess ? RAD_OK : R4D_NO(RAD_E_DEVICE);
}
@@ -167,8 +292,10 @@ int launch_sam_attn(const uint16_t* q, const uint16_t* k, const uint16_t* v, uin
//
// The shim checks what the kernel assumes: bf16 operands, rank 2 with dense columns and any row
// pitch (the tower's q/k/v are the three column slices of one fused projection), an i32 cu with one
// entry a segment plus the terminator, tables of exactly 2*tile-1 rows, head_dim 64. The segment
// lengths are the kernel's to check against cu (it cannot be read on the host at issue).
// entry a segment plus the terminator, tables of exactly 2*tile-1 rows, head_dim 64. The shim
// checks the row count against the segment count host-side; per-segment length is the kernel's to
// check, and a malformed segment writes NaN over its rows (the vit kernel's poison convention)
// so the corruption reaches the consumer instead of passing as success.
#define R4D_NEED(x) do { const int _s = (x); if (_s != RAD_OK) return R4D_NO(_s); } while (0)
@@ -212,6 +339,10 @@ extern "C" int r4d_rad_sam_attn(const RadArgs* a, RadStream s) {
if (cu->dtype != RAD_I32 || !r4d_contig(cu)) return R4D_NO(RAD_E_DTYPE);
const long long nseq = r4d_numel(cu) - 1;
if (nseq < 1) return R4D_NO(RAD_E_SHAPE);
/* The tower declares cu as one segment per grid, so the host-side row count pins the
* segment count. A mismatch is a malformed segment and fails at issue, not on the device
* (the kernel's per-segment guard poisons the visible rows for what this cannot see). */
if (qrows != nseq * gh * gw) return R4D_NO(RAD_E_SHAPE);
// The tables: [2*tile-1, head_dim] when the geometry has its own, else the checkpoint's rows
// (the 127-row global table at a 40 grid), resampled on read.
+24 -7
View File
@@ -18984,10 +18984,12 @@ static void sam_attn_case(const Plugin& pl) {
if (!r) { ok(what, false, "row absent"); return; }
/* tab_rows 0 means "2*tile-1, no resize". The third geometry is the production 40-grid global
* block: the checkpoint's 127-row tables serve the 79 rows that block wants. */
struct Geo { int64_t gh, gw, win, nh, hd, nseq, tab_rows; };
const Geo geos[3] = { { 16, 16, 14, 2, 64, 2, 0 }, { 16, 16, 0, 2, 64, 1, 0 },
{ 40, 40, 0, 2, 64, 1, 127 } };
* block: the checkpoint's 127-row tables serve the 79 rows that block wants. `pad` is the
* filler column in front of the row: 1 exercises any-pitch (scalar) rows, 0 a 16-byte-aligned
* dense pitch, which is what the kernel's uint4 row-load path requires -- both must agree. */
struct Geo { int64_t gh, gw, win, nh, hd, nseq, tab_rows, pad; };
const Geo geos[4] = { { 16, 16, 14, 2, 64, 2, 0, 1 }, { 16, 16, 14, 2, 64, 2, 0, 0 },
{ 16, 16, 0, 2, 64, 1, 0, 1 }, { 40, 40, 0, 2, 64, 1, 127, 1 } };
int64_t checked = 0, bad_total = 0;
float worst = 0.0f;
@@ -18995,8 +18997,9 @@ static void sam_attn_case(const Plugin& pl) {
const int64_t W = g.nh * g.hd, R = g.gh * g.gw, M = g.nseq * R;
const int64_t want = 2 * (g.win > 0 ? g.win : (g.gh > g.gw ? g.gh : g.gw)) - 1;
const int64_t tab = g.tab_rows > 0 ? g.tab_rows : want;
/* One filler column, so the row pitch is W + 1: q/k/v/out are all slices. */
const int64_t ld = W + 1;
/* A filler column gives the row pitch W + 1 (q/k/v/out are all slices); pad 0 keeps the
* dense pitch W, aligned for the vector row path. */
const int64_t ld = W + g.pad;
const float scale = 1.0f / std::sqrt((float)g.hd);
std::vector<uint16_t> q((size_t)(M * ld)), k((size_t)(M * ld)), v((size_t)(M * ld));
@@ -23457,7 +23460,7 @@ static void device_phase(const Plugin& pl) {
const RadKernelInfo* r = find(pl, "act_mul_bf16");
if (!r) ok("act_mul_bf16", false, "row absent");
else
for (const char* act : { "silu", "gelu", "gelu_tanh" }) {
for (const char* act : { "silu", "gelu", "gelu_tanh", "sigmoid", "quick_gelu" }) {
std::vector<RadTensor> ts = { T(nullptr, RAD_BF16, { 5, 645 }),
T(nullptr, RAD_BF16, { 5, 645 }),
T(nullptr, RAD_BF16, { 5, 645 }) };
@@ -23646,6 +23649,20 @@ static void device_phase(const Plugin& pl) {
for (size_t i = 0; i < g.size(); ++i)
want[i] = h_bf16(h_to_bf16(1.0f / (1.0f + std::exp(-g[i])))) * u[i];
check("act_mul_bf16 sigmoid numerics", down(dy, g.size()), want, 1e-2);
/* quick_gelu fuses mul-by-bf16(1.702) + sigmoid: the scale and the activation are
* both rounded to bf16 exactly as the unfused pair stored them. */
std::vector<RadParam> pq = { PI("M", M), PI("n", n), PS("act", "quick_gelu"),
PS("dtype", "bf16") };
if (r) run_case(r, ts, pq);
const float k1702 = h_bf16(h_to_bf16(1.702f));
std::vector<float> wantq(g.size());
for (size_t i = 0; i < g.size(); ++i) {
const float t = h_bf16(h_to_bf16(g[i] * k1702));
const float s = 1.0f / (1.0f + std::exp(-t));
wantq[i] = h_bf16(h_to_bf16(s)) * u[i];
}
check("act_mul_bf16 quick_gelu numerics", down(dy, g.size()), wantq, 1e-2);
}
if (sel("rmsnorm_bf16")) {
const RadKernelInfo* r = find(pl, "rmsnorm_bf16");
+9 -6
View File
@@ -386,8 +386,8 @@ int ref_act_mul(const RadArgs* a, RadStream) {
if (n <= 0) return RAD_E_SHAPE;
const int64_t rows = rows_of(Y, n);
if (rows <= 0 || numel(A) < rows * n || numel(B) < rows * n) return RAD_E_SHAPE;
static const char* kActs[] = { "silu", "gelu", "gelu_tanh", "sigmoid" };
const int act = p_enum(a, "act", kActs, 4, -1);
static const char* kActs[] = { "silu", "gelu", "gelu_tanh", "sigmoid", "quick_gelu" };
const int act = p_enum(a, "act", kActs, 5, -1);
if (act < 0) return RAD_E_INVAL;
REF_PAR_FOR(rows * n)
@@ -396,8 +396,13 @@ int ref_act_mul(const RadArgs* a, RadStream) {
const int64_t as = laststride(A), bs = laststride(B), ys = laststride(Y);
for (int64_t i = 0; i < n; ++i) {
const float g = ldt(A, ab + i * as);
/* quick_gelu is x * sigmoid(1.702 x) with the scaled value rounded to y's dtype
* first, exactly the unfused mul-then-act_mul pair this replaces. */
const float v = act == 0 ? act_silu(g) : act == 1 ? act_gelu(g)
: act == 2 ? act_gelu_tanh(g) : act_sigmoid(g);
: act == 2 ? act_gelu_tanh(g)
: act == 3 ? act_sigmoid(g)
: act_sigmoid(round_dt(Y->dtype,
g * round_dt(RAD_BF16, 1.702f)));
stt(Y, yb + i * ys, round_dt(Y->dtype, v) * ldt(B, bb + i * bs));
}
}
@@ -625,9 +630,7 @@ int ref_conv2d_unfold(const RadArgs* a, RadStream) {
if (T <= 0) continue;
const int64_t To = (T + 2 * pad - kh) / st + 1, o0 = t0 / st;
if (To <= 0) continue;
if (t0 + T > Min || (o0 + To) * Wo > Mout) {
return RAD_E_SHAPE;
}
if (t0 + T > Min || (o0 + To) * Wo > Mout) return RAD_E_SHAPE;
if (V && numel(V) < (t0 + T - 1) * vst + 1) return RAD_E_SHAPE;
REF_PAR_FOR(To * Wo * K)
+7 -2
View File
@@ -35,6 +35,7 @@
#include <algorithm>
#include <cfloat>
#include <unordered_map>
#include <vector>
using namespace ref;
@@ -315,13 +316,17 @@ int ref_sample_ngram_ban(const RadArgs* a, RadStream) {
const uint32_t word = (uint32_t)ld_int(wl->dtype, wl->data, wb + (col / 32) * ws);
return ((word >> (uint32_t)(col % 32)) & 1u) != 0u;
};
/* n == 1 bans every token in the window: the prefix is empty, as in the reference. */
/* n == 1 bans every token in the window: the prefix is empty, as in the reference.
* The prefix is read once, not per search position: it is the same n-1 tokens
* compared at every idx, and the row's history is short (the staged span). */
const int64_t plen = n - 1, p0 = hl - plen;
std::vector<int64_t> pref((size_t)plen);
for (int64_t j = 0; j < plen; ++j) pref[(size_t)j] = tok_at(p0 + j);
for (int64_t idx = search_start; idx < search_end; ++idx) {
bool match = true;
for (int64_t j = 0; j < plen; ++j) {
if (tok_at(idx + j) != tok_at(p0 + j)) { match = false; break; }
if (tok_at(idx + j) != pref[(size_t)j]) { match = false; break; }
}
if (!match) continue;
const int64_t tok = tok_at(idx + plen);
+3
View File
@@ -1395,6 +1395,9 @@ int ref_sam_attn_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out)
const int64_t gw = gi(p, n_p, "grid_w", 0);
const int64_t win = gi(p, n_p, "window", 0);
if (M <= 0 || hd <= 0 || nh <= 0 || gh <= 0 || gw <= 0 || win < 0) return RAD_E_UNSUPPORTED;
/* A shape hook answers "describe this geometry", so an unbuildable one spells E_UNSUPPORTED
* (the harness convention); the kernels' own launch checks report E_SHAPE for the same
* inputs. */
const int64_t W = nh * hd;
const int64_t S = n_seq_of(p, n_p);
const int64_t maxd = win > 0 ? win : (gh > gw ? gh : gw);
+4 -1
View File
@@ -52,6 +52,8 @@ set(RAD_TESTS_WITH_R4D_HOST relayout_parity_test r4d_ar_links_test)
# test binaries can run from anywhere.
set(RAD_CHAT_FIXTURES ${CMAKE_CURRENT_SOURCE_DIR}/data/chat)
set(RAD_MEDIA_FIXTURES ${CMAKE_CURRENT_SOURCE_DIR}/data/media)
# Checked-in golden blobs (tests/data/golden), read at test time (tests/uocr_resample_golden.h).
set(RAD_GOLDEN_FIXTURES ${CMAKE_CURRENT_SOURCE_DIR}/data/golden)
# libstdc++ before rad_core on every test's link line. lld extracts archive members to resolve a
# shared library's imports too: ROCm 10.1's libamdhip64 imports std::string::reserve, which g++-14
@@ -191,7 +193,8 @@ foreach(t ${RAD_TESTS})
target_link_libraries(${n} PRIVATE rad_legacy_toolparse)
endif()
target_compile_definitions(${n} PRIVATE RAD_CHAT_FIXTURES="${RAD_CHAT_FIXTURES}"
RAD_MEDIA_FIXTURES="${RAD_MEDIA_FIXTURES}")
RAD_MEDIA_FIXTURES="${RAD_MEDIA_FIXTURES}"
RAD_GOLDEN_FIXTURES="${RAD_GOLDEN_FIXTURES}")
# Normally inherited from rad_core; tests that do not link it still need the ABI headers.
target_include_directories(${n} PRIVATE ${CMAKE_SOURCE_DIR}/core ${CMAKE_SOURCE_DIR}/abi
${CMAKE_BINARY_DIR}/rad_include)
+4 -2
View File
@@ -1,4 +1,4 @@
/* abi_layout_table.h -- every abi/ struct's size and field offsets at RAD_ABI_VERSION 24 and
/* abi_layout_table.h -- every abi/ struct's size and field offsets at RAD_ABI_VERSION 25 and
* RAD_FORMAT_VER 2, as { type, field, offset, size } rows ("" is the struct itself). A snapshot
* of the headers on x86-64 Linux, which abi_layout_test.cpp holds the layout to; regenerate it
* from the test's printout only together with a version bump. */
@@ -24,7 +24,7 @@
{ "RadArgs", "instance", 48, 8 },
{ "RadArgs", "rank", 56, 4 },
{ "RadArgs", "world_size", 60, 4 },
{ "RadBatch", "", 0, 336 },
{ "RadBatch", "", 0, 352 },
{ "RadBatch", "phase", 0, 4 },
{ "RadBatch", "step", 4, 4 },
{ "RadBatch", "n_tok", 8, 8 },
@@ -72,6 +72,8 @@
{ "RadBatch", "gen_b", 312, 8 },
{ "RadBatch", "agen_b", 320, 8 },
{ "RadBatch", "vgen_b", 328, 8 },
{ "RadBatch", "enc_seg_h", 336, 8 },
{ "RadBatch", "enc_seg_w", 344, 8 },
{ "RadBufDecl", "", 0, 80 },
{ "RadBufDecl", "dtype", 0, 4 },
{ "RadBufDecl", "rank", 4, 4 },
+3 -3
View File
@@ -8,7 +8,7 @@
*
* Checked: a C translation unit (abi_c_test.c, strict C11) lays every struct out as C++ does; every
* struct's listed fields account for its size, so the list in abi_layout_rows.h is complete; and
* the layout agrees with the table below, taken at RAD_ABI_VERSION 24 and RAD_FORMAT_VER 2. Under
* the layout agrees with the table below, taken at RAD_ABI_VERSION 25 and RAD_FORMAT_VER 2. Under
* those versions a listed field may not move or change size, an ABI struct may only grow by fields
* past its old end, and an on-disk struct may not change at all. The table is a snapshot of the
* headers: nothing else states the layout. When it disagrees the test prints the live table.
@@ -57,8 +57,8 @@ std::vector<Row> cpp_rows() {
};
}
/* The layout at RAD_ABI_VERSION 24 / RAD_FORMAT_VER 2 (see the file header). */
constexpr uint32_t kTableAbi = 24, kTableFormat = 2;
/* The layout at RAD_ABI_VERSION 25 / RAD_FORMAT_VER 2 (see the file header). */
constexpr uint32_t kTableAbi = 25, kTableFormat = 2;
const AbiRow kTable[] = {
#include "abi_layout_table.h"
};
Binary file not shown.
+13 -11
View File
@@ -1733,14 +1733,17 @@ TEST(unlimitedocr_runs_follow_the_reference_layout) {
* antialias=True) on CPU fp32 (tests/resample_golden.py), so this pins the load-time position
* table number for number: a resample off by a row or a tap serves a slightly shifted picture. */
TEST(unlimitedocr_bicubic_antialias_resample_is_the_reference) {
uocr_golden::Golden gd;
std::string gerr;
if (!uocr_golden::load(&gd, &gerr)) ARTIFACT_MISSING(gerr);
const int CH = 3;
double worst_abs = 0.0, worst_rel = 0.0;
for (int k = 0; k < kResampleCases; ++k) {
const int ih = kResampleGeo[k][0], iw = kResampleGeo[k][1];
const int oh = kResampleGeo[k][2], ow = kResampleGeo[k][3];
for (int k = 0; k < gd.n_cases; ++k) {
const int ih = gd.geo[k][0], iw = gd.geo[k][1];
const int oh = gd.geo[k][2], ow = gd.geo[k][3];
std::vector<float> out((size_t)oh * ow * CH);
rad::arch::resample_bicubic_aa(kResampleIn[k], ih, iw, oh, ow, CH, out.data());
const float* want = kResampleOut[k];
rad::arch::resample_bicubic_aa(gd.in[k].data(), ih, iw, oh, ow, CH, out.data());
const float* want = gd.out[k].data();
double a = 0.0, r = 0.0;
for (size_t i = 0; i < out.size(); ++i) {
const double d = std::fabs((double)out[i] - (double)want[i]);
@@ -1782,18 +1785,17 @@ TEST(unlimitedocr_bicubic_antialias_resample_is_the_reference) {
size_t sam_mism = 0;
double sam_abs = 0.0;
bf16_case(kSamSrc, (int)kSamSrcDim[0], (int)kSamSrcDim[1], (int)kSamOutDim[0],
(int)kSamOutDim[1], (int)kSamSrcDim[2], kSamOut, 0, "sam 64->40 bf16", &sam_mism,
&sam_abs);
bf16_case(gd.sam_src.data(), 64, 64, 40, 40, 768, gd.sam_out.data(), 0, "sam 64->40 bf16",
&sam_mism, &sam_abs);
/* CLIP: rows 1: as a 16x16 grid resampled to 10x10; the cls row (index 0) passes through in
* front, so the golden's grid starts one channel-vector in. */
size_t clip_mism = 0;
double clip_abs = 0.0;
{
const int CW = (int)kClipSrcDim[1];
const uint16_t* grid_bits = kClipSrc + CW; /* skip the cls row */
bf16_case(grid_bits, 16, 16, 10, 10, CW, kClipOut, (size_t)CW, "clip 16->10 bf16",
const int CW = 1024;
const uint16_t* grid_bits = gd.clip_src.data() + CW; /* skip the cls row */
bf16_case(grid_bits, 16, 16, 10, 10, CW, gd.clip_out.data(), (size_t)CW, "clip 16->10 bf16",
&clip_mism, &clip_abs);
}
/* The bf16 tables are a report, not a gate: bf16 carries ~3 decimal digits, so a last-bit
+51 -60
View File
@@ -1,10 +1,10 @@
#!/home/juup/.venvs/hfref312/bin/python
"""resample_golden.py -- emit tests/uocr_resample_golden.h for rad_resample.h.
"""resample_golden.py -- emit tests/data/golden/uocr_resample_golden.bin for rad_resample.h.
Runs on CPU only (the host's GPUs serve production; torch is used with no CUDA).
For each geometry (64,64,40,40), (16,16,10,10), (16,16,20,20), (64,64,20,20),
(50,50,40,40) it draws a fixed-seed fp32 input (C=3, row-major [h, w, C]), computes
For each geometry (64,64->40,40), (24,24->20,20), (8,8->5,5), (16,16->10,10),
(16,20->10,13) it draws a fixed-seed fp32 input (C=3, row-major [h, w, C]), computes
torch's F.interpolate(..., mode="bicubic", antialias=True, align_corners=False) on the
[1, C, h, w] permute (the DeepEncoder's get_abs_pos_sam form), and emits input + output as
float literals (%.9g, exact fp32 round trip).
@@ -15,17 +15,25 @@ model.safetensors.index.json), reads
model.vision_model.embeddings.position_embedding.weight [257,1024] bf16
resamples them the way deepencoder.py does (SAM grid 64->40; CLIP rows 1: as a 16x16 grid
16->10 with row 0 (cls) passed through in front), casts back to bf16, and emits the source
and the torch output as uint16 bf16 bit patterns in the exact order the C++ produces them:
and the torch output as bf16 bit patterns in the exact order the C++ produces them:
SAM [40,40,768]; CLIP [101,1024] with the cls row at index 0.
The output is the little-endian blob tests/uocr_resample_golden.h loads:
u32 magic 'UOCR', u32 version=1, u32 n_cases, u32 pad
n_cases * { i32 ih, iw, oh, ow; i64 in_n, out_n }
per case: f32 in[in_n], f32 out[out_n]
u16 sam_src, sam_out, clip_src, clip_out
(round-trip verified against the written bytes before the script exits 0).
A numpy emulation of arch/common/rad_resample.h is checked against every golden and
reported; a variant sweep on the smallest geometry pins the knobs (pass order, filter
family, inv-scale placement, centre precision, edge handling) before the header is written.
family, inv-scale placement, centre precision, edge handling) before the blob is written.
"""
import itertools
import json
import os
import struct
import sys
import numpy as np
@@ -38,7 +46,8 @@ CH = 3
SEED = 20261019
MODELS = "/home/juup/models"
CKPT = os.path.join(MODELS, "Unlimited-OCR")
OUT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "uocr_resample_golden.h")
OUT = os.path.join(os.path.dirname(os.path.abspath(__file__)),
"data", "golden", "uocr_resample_golden.bin")
SAM_TENSOR = "model.sam_model.pos_embed"
CLIP_TENSOR = "model.vision_model.embeddings.position_embedding.weight"
@@ -149,32 +158,14 @@ def report(tag, got, want):
# ---------------------------------------------------------------- header emission
# ---------------------------------------------------------------- blob emission
def emit_floats(f, name, arr):
vals = np.ascontiguousarray(arr, np.float32).astype(np.float64).reshape(-1)
f.write(f"static const float {name}[] = {{\n")
line = " "
for v in vals:
item = "%.9gf," % float(v)
if len(line) + len(item) > 100:
f.write(line + "\n")
line = " "
line += " " + item
f.write(line + "\n};\n\n")
def pack_f32(arr):
return struct.pack("<%df" % arr.size, *np.ascontiguousarray(arr, np.float32).reshape(-1))
def emit_u16(f, name, arr):
vals = arr.reshape(-1)
f.write(f"static const uint16_t {name}[] = {{\n")
line = " "
for v in vals:
item = "0x%04x," % int(v)
if len(line) + len(item) > 100:
f.write(line + "\n")
line = " "
line += " " + item
f.write(line + "\n};\n\n")
def pack_u16(arr):
return struct.pack("<%dH" % arr.size, *arr.reshape(-1))
def bits(t):
@@ -236,38 +227,38 @@ def main():
clip_bf_mism = int((bf16_round_bits(cg).reshape(-1) != bits(grid_out.reshape(10, 10, 1024)).reshape(-1)).sum())
print(f" clip 16->10 bf16: {clip_bf_mism} bf16 mismatches", flush=True)
with open(OUT, "w") as f:
f.write("/* uocr_resample_golden.h -- GENERATED by resample_golden.py "
"(torch %s CPU, seed %d) from F.interpolate(bicubic, antialias=True) and the "
"Unlimited-OCR checkpoint; do not edit.\n"
" * fp32 random vectors per geometry, and the checkpoint's SAM pos_embed "
"(64x64x768 -> 40x40x768) and CLIP position_embedding (rows 1: as 16x16 -> "
"10x10, cls row 0 first) as bf16 bit patterns. */\n" % (torch.__version__, SEED))
f.write("#pragma once\n#include <cstdint>\n\n")
f.write("static const int32_t kResampleCases = %d;\n" % len(SIZES))
f.write("static const int32_t kResampleGeo[kResampleCases][4] = {")
f.write(", ".join("{%d, %d, %d, %d}" % s for s in SIZES))
f.write("}; /* in_h, in_w, out_h, out_w; C=3 */\n\n")
for k in range(len(SIZES)):
emit_floats(f, "kResampleIn%d" % k, ins[k])
emit_floats(f, "kResampleOut%d" % k, outs[k])
f.write("static const float* const kResampleIn[kResampleCases] = {%s};\n"
% ", ".join("kResampleIn%d" % k for k in range(len(SIZES))))
f.write("static const float* const kResampleOut[kResampleCases] = {%s};\n\n"
% ", ".join("kResampleOut%d" % k for k in range(len(SIZES))))
f.write("/* SAM pos_embed: interpolate [64,64,768] -> [40,40,768], bf16 bit patterns. */\n")
f.write("static const int32_t kSamSrcDim[3] = {64, 64, 768};\n")
f.write("static const int32_t kSamOutDim[3] = {40, 40, 768};\n")
emit_u16(f, "kSamSrc", sam_bits)
emit_u16(f, "kSamOut", bits(sam_out))
f.write("/* CLIP position_embedding: rows 1: as [16,16,1024] -> [10,10,1024], row 0 (cls)\n"
" * passthrough at index 0; output [101,1024], bf16 bit patterns. */\n")
f.write("static const int32_t kClipSrcDim[2] = {257, 1024};\n")
f.write("static const int32_t kClipOutDim[2] = {101, 1024};\n")
emit_u16(f, "kClipSrc", clip_bits)
emit_u16(f, "kClipOut", bits(clip_out))
os.makedirs(os.path.dirname(OUT), exist_ok=True)
blob = bytearray()
blob += struct.pack("<4I", 0x52434F55, 1, len(SIZES), 0)
for (ih, iw, oh, ow), x, y in zip(SIZES, ins, outs):
blob += struct.pack("<4i2q", ih, iw, oh, ow, x.size, y.size)
for x, y in zip(ins, outs):
blob += pack_f32(x)
blob += pack_f32(y)
for arr in (sam_bits, bits(sam_out), clip_bits, bits(clip_out)):
blob += pack_u16(arr)
with open(OUT, "wb") as f:
f.write(blob)
print(f"wrote {OUT} ({os.path.getsize(OUT) / 1e6:.1f} MB); "
# Round-trip: the loader in tests/uocr_resample_golden.h reads the same layout.
raw = bytes(blob)
assert struct.unpack_from("<4I", raw, 0) == (0x52434F55, 1, len(SIZES), 0)
off = 16
for (ih, iw, oh, ow), x, y in zip(SIZES, ins, outs):
assert struct.unpack_from("<4i2q", raw, off) == (ih, iw, oh, ow, x.size, y.size)
off += 32
for x, y in zip(ins, outs):
for v in (x, y):
got = np.frombuffer(raw, np.float32, v.size, off)
assert np.array_equal(got, np.ascontiguousarray(v, np.float32).reshape(-1))
off += 4 * v.size
for arr in (sam_bits, bits(sam_out), clip_bits, bits(clip_out)):
got = np.frombuffer(raw, np.uint16, arr.size, off)
assert np.array_equal(got, arr.reshape(-1))
off += 2 * arr.size
assert off == len(raw), (off, len(raw))
print(f"wrote {OUT} ({os.path.getsize(OUT) / 1e6:.1f} MB, round-trip verified); "
f"emulation {'FULLY matches' if all_ok else 'DIVERGES from'} torch", flush=True)
return 0 if all_ok else 1
+115 -398769
View File
File diff suppressed because it is too large. Load diff