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

+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