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

+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;