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

+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