unlimitedocr: tiled/base e2e parity, per-segment tower layout, n-gram whitelist

The pass packer now keeps a view and its one-cell separator in one pass, and
RadBatch carries each segment's grid host-side (enc_seg_h/enc_seg_w) so the
DeepEncoder no longer reads device coordinates to pick a geometry. The tower
lays out a line of n tiles as kMap rows of n*kMap features plus one newline
cell, accepts an earlier chunk of a longer line, and emits the learned
view_seperator for an explicit 4x4 separator rather than any square segment.

The device sam_attn resamples a rel_pos table that is not 2*tile-1 rows on
read (the 127-row global tables serve a 40-grid block as 79), matching
libref/libavx. The n-gram ban gains the reference's optional whitelist
(5th operand, OAI keys, generation_config alias) with range/dtype checks.

Gates: tiled e2e stage cosines 0.9994-1.0, det/text 0.9901 with every
coordinate within 1 px; two-page 0.9917 within 2 px; device selftest
sam_attn (incl. 127->79) and ngram whitelist (1344 columns) 0 mismatches.
This commit is contained in:
Juup committed 2026-10-20 07:04:01 +00:00
1 parent fad4ba7f1a
commit 52637ec186
37 files changed
+401566 -778

No files matched your search

+2
View File
@@ -75,6 +75,8 @@ ABI_FIELD(RadBatch, gen)
ABI_FIELD(RadBatch, gen_b)
ABI_FIELD(RadBatch, agen_b)
ABI_FIELD(RadBatch, vgen_b)
ABI_FIELD(RadBatch, enc_seg_h)
ABI_FIELD(RadBatch, enc_seg_w)
ABI_STRUCT(RadBufDecl)
ABI_FIELD(RadBufDecl, dtype)
ABI_FIELD(RadBufDecl, rank)
+169
View File
@@ -460,4 +460,173 @@ TEST(rswa_advance_keeps_the_ring_span_and_slots) {
CHECK_EQ(slot[0], -1);
}
/* The plan's P4 gate "flat KV bytes after prefill+128" at the KV-manager level, at the geometry
* R-SWA deploys at (block 16, W 128) and the P4a prompt size (a 176-token prompt = the 11-block
* table of the fault). The scheduler arms `visible_lo` = the prompt size at admission; the floor
* here is block-aligned so the visible set is exactly [0, P) U the last W positions, count P + W.
* The decode runs far past prefill + W and pins, every step:
* - the visible set is exactly [0, P) plus the newest W positions, and its count is P + W;
* - the block table is flat once the ring fills: ceil(P/B) reference + W/B ring blocks, never
* one more (the sequence's KV bytes stop growing after prefill + 128);
* - every ring write lands where adv_groups maps it (core/sched/advance_impl.h): block
* ring_pos/B + ((p - ring_pos)/B) % ring_blocks -- so the manager's rule and the card's rule
* are checked against the same table and positions;
* - no write ever lands on a slot index >= table_len * block: the table is allocated from a
* fresh pool so its physical ids are 0..len-1 (the min-heap), which makes that bound literal;
* the un-ring'ed linear mapping runs past it from position 304 on, which is the R-SWA fault
* class (used past the ring floor walking into the builder's -1 padding). */
TEST(rswa_flat_kv_bytes_after_prefill_plus_128) {
const int64_t B = 16, W = 128, P = 176; /* P is block-aligned: the set is exact */
const int64_t ring_blocks = W / B; /* 8 */
const int64_t prefill_blocks = P / B; /* 11: the P4a table */
const int64_t flat_blocks = prefill_blocks + ring_blocks; /* 19 = 304 tokens */
const KVGroupInfo grp = window_group(B, W);
const std::vector<KVGroupInfo> g = groups_of(grp);
Config cfg = window_config();
Pools pools;
CHECK_OK(configure_pools(pools, cfg));
KVManager kv;
CHECK_OK(kv.declare_runtime_window(G_WIN, W));
CHECK_OK(kv.configure(g, cfg, pools.kv()));
CHECK_OK(kv.add_sequence(1));
CHECK_OK(kv.set_window(1, P, W));
const Ring r{ &kv, KVGeom::of(g), G_WIN };
const SeqWindow w = r.window();
CHECK_EQ(w.visible_lo, P);
CHECK_EQ(w.ring_pos, P); /* aligned floor: the ring starts at P */
CHECK_EQ(w.ring_blocks, ring_blocks);
CHECK_EQ(w.ring_span(B), W);
/* Prefill: 11 blocks, identity physical ids (fresh min-heap pool, one sequence). */
CHECK_OK(kv.ensure(1, P));
const std::vector<int32_t> bt0 = kv.block_table(1, G_WIN);
REQUIRE_EQ((long long)bt0.size(), prefill_blocks);
for (int64_t b = 0; b < prefill_blocks; ++b) CHECK_EQ(bt0[(size_t)b], (int32_t)b);
std::map<int32_t, int64_t> content;
for (int64_t p = 0; p < P; ++p) {
const int32_t s = r.slot(p);
REQUIRE(s >= 0);
CHECK(s < prefill_blocks * B);
content[s] = p;
}
/* Decode far past prefill + W. */
const int64_t L = 1000;
int64_t bad_step = -1, bad_map = -1, bad_pad = -1, bad_size = -1;
int32_t max_slot = -1;
for (int64_t p = P; p < P + L; ++p) {
CHECK_OK(kv.ensure(1, p + 1, p));
const int64_t n = p + 1;
const std::vector<int32_t>& bt = kv.block_table(1, G_WIN);
const int64_t table_len = (int64_t)bt.size();
/* Table length: the reference's 11 blocks, plus the ring's filling one block at a time,
* flat at 19 once the newest W positions span the whole ring. It never exceeds 19. */
const int64_t want_blocks =
n <= w.ring_pos ? (n + B - 1) / B
: w.ring_pos / B + std::min(ring_blocks, (n - w.ring_pos + B - 1) / B);
if (table_len != want_blocks) bad_size = n;
CHECK(table_len <= flat_blocks);
if (n >= w.ring_pos + w.ring_span(B)) {
CHECK_EQ(table_len, flat_blocks);
CHECK_EQ(kv.held_blocks(G_WIN), flat_blocks);
}
/* The write itself: the ring rule, and never off the table. */
const int64_t bi = w.ring_pos / B + ((p - w.ring_pos) / B) % ring_blocks;
const int32_t s = r.slot(p);
REQUIRE(s >= 0);
if (s != (int32_t)(bt[(size_t)bi] * B + p % B)) bad_map = n;
if (bi >= table_len || s >= table_len * B) bad_pad = n;
if (s > max_slot) max_slot = s;
content[s] = p;
/* The visible set: exactly [0, P) plus the newest W positions; count P + min(n - P, W),
* flat P + W once the ring is full. */
std::set<int64_t> held, want;
for (const auto& kvp : content) held.insert(kvp.second);
for (int64_t q = 0; q < P; ++q) want.insert(q);
for (int64_t q = std::max(w.ring_pos, n - w.ring_span(B)); q < n; ++q) want.insert(q);
if (held != want) bad_step = n;
CHECK_EQ((long long)held.size(), P + std::min(n - P, W));
}
CHECK_EQ(bad_step, -1ll);
CHECK_EQ(bad_map, -1ll);
CHECK_EQ(bad_pad, -1ll);
CHECK_EQ(bad_size, -1ll);
CHECK(max_slot < flat_blocks * B); /* 303 < 304: no write leaves the flat KV */
CHECK_EQ((long long)kv.block_table(1, G_WIN).size(), flat_blocks);
CHECK_EQ(kv.first_block_pos(1, G_WIN), 0ll);
/* The fault class: the linear rule the un-ring'ed advance used maps the same positions past
* the 19-block table from position 304 (the second ring lap) on, where the table has nothing
* -- the slot lookup returns -1 into the builder's padding. */
const Ring r_lin{ &kv, KVGeom::of(g), G_WIN };
for (int64_t p = 304; p < P + L; ++p)
CHECK_EQ(r_lin.geo.slot(G_WIN, kv.block_table(1, G_WIN), 0, p), -1);
/* The ring rule keeps every one of them on a real slot, cycling over the ring span. */
for (int64_t p = w.ring_pos; p < P + L; ++p) {
CHECK(r.slot(p) >= 0);
CHECK_EQ(r.slot(p), r.slot(p + w.ring_span(B))); /* one lap: same slot, in place */
if (p + 1 < P + L) CHECK(r.slot(p) != r.slot(p + 1));
}
/* Cross-check with the card's rule (adv_groups) on the manager's own table: the same positions
* through the slab path must produce the manager's slots, and `used` must stop at the table. */
{
const std::vector<int32_t>& bt = kv.block_table(1, G_WIN);
const int32_t tlen = (int32_t)bt.size();
std::vector<char> slab(32768, 0);
const int64_t pos_off = 0, slot_off = (int64_t)L * 4;
const int64_t bt_off = slot_off + (int64_t)L * 4;
const int64_t first_off = bt_off + (int64_t)tlen * 4;
const int64_t rpos_off = first_off + 8, tlen_off = rpos_off + 8, used_off = tlen_off + 8;
const int64_t grp_off = (used_off + 8 + 7) & ~(int64_t)7; /* AdvGroup holds int64 */
AdvanceArgs a;
a.slab = slab.data();
a.pos_off = pos_off; a.grp_off = grp_off; a.n_groups = 1;
int32_t* pos = reinterpret_cast<int32_t*>(slab.data() + pos_off);
for (int64_t j = 0; j < L; ++j) pos[j] = (int32_t)(P + j);
std::memcpy(slab.data() + bt_off, bt.data(), (size_t)tlen * 4);
*reinterpret_cast<int32_t*>(slab.data() + first_off) = 0;
*reinterpret_cast<int32_t*>(slab.data() + rpos_off) = (int32_t)w.ring_pos;
*reinterpret_cast<int32_t*>(slab.data() + tlen_off) = tlen;
AdvGroup* ag = reinterpret_cast<AdvGroup*>(slab.data() + grp_off);
ag->block_size = (int32_t)B; ag->paged = 1; ag->pitch = tlen;
ag->slot_off = slot_off; ag->used_off = used_off; ag->bt_off = bt_off;
ag->first_off = first_off; ag->rpos_off = rpos_off; ag->tlen_off = tlen_off;
ag->ring = 1; ag->ring_blocks = (int32_t)ring_blocks;
adv_groups(a, 0, 0, (int32_t)P, (int32_t)L);
CHECK_EQ(*reinterpret_cast<int32_t*>(slab.data() + used_off), (int32_t)(flat_blocks * B));
const int32_t* slot = reinterpret_cast<const int32_t*>(slab.data() + slot_off);
int64_t mismatches = 0, negatives = 0;
for (int64_t j = 0; j < L; ++j) {
if (slot[j] != r.slot(P + j)) ++mismatches;
if (slot[j] < 0) ++negatives;
CHECK(slot[j] < tlen * B); /* every write inside the flat KV bytes */
}
CHECK_EQ(mismatches, 0ll);
CHECK_EQ(negatives, 0ll);
/* Without the ring the same advance walks off the padded table (the P4a fault). */
ag->ring = 0;
adv_groups(a, 0, 0, (int32_t)P, (int32_t)L);
CHECK_EQ(*reinterpret_cast<int32_t*>(slab.data() + used_off), (int32_t)(P + L));
CHECK_EQ(slot[304 - P], -1); /* position 304: bt[19] is padding */
}
/* The reference is untouched by a thousand ring laps, and free returns the flat set. */
const std::vector<int32_t>& bt = kv.block_table(1, G_WIN);
for (int64_t p = 0; p < P; ++p) {
const int32_t slot = (int32_t)(bt[(size_t)(p / B)] * B + p % B);
REQUIRE(content.count(slot) > 0);
CHECK_EQ(content[slot], p);
}
const int64_t free0 = kv.free_blocks(G_WIN);
kv.free_sequence(1);
CHECK_EQ(kv.free_blocks(G_WIN), free0 + flat_blocks);
}
RAD_TEST_MAIN()
+458
View File
@@ -0,0 +1,458 @@
"""mkuocrtilegoldens.py tile|e2e|multi -- goldens for the Unlimited-OCR 640-tile geometry and
for multi-page requests, every number from the checkpoint's own code (CODEDIR's deepencoder.py
and modeling_unlimitedocr.py as shipped, weights from MODELDIR's safetensors).
tile (out: OUTDIR) the 640x640 tile reference for a 1024x1024 document:
sam_pos40.npz/.json model.sam_model.pos_embed [1,64,64,768] through get_abs_pos_sam to 40
(F.interpolate bicubic antialias in fp32, cast back bf16): 40x40x768 of
bf16 bit patterns as raw uint16.
clip_pos10.npz/.json model.vision_model.embeddings.position_embedding.weight [257,1024]
through get_abs_pos(..., 101): cls row passthrough + 16x16 resampled to
10x10, 101x1024 of bf16 raw uint16.
tile0.pix.bf16 the FIRST dynamic_preprocess crop (the picture resized to 1280x1280,
crop [0:640,0:640]), normalized (x/255-0.5)/0.5 to bf16, staged the way
Processor::append (core/mm/processor.cpp:1102) stages a 40x44 grid: 40
patch rows of 44 patch columns, the last 4 columns zeros, each patch
(channel, y, x) row-major, 40*44*768 bf16 raw uint16.
tile0.npz the DeepEncoder stage taps over that one crop, the uocr_ref.py key set
(st_x0, st_pre/attn/b 0..11, st_full0..2, st_n0..3, st_map, st_map2,
sam, clip, fuse, proj, rows, image, patches, crop_rgb); the stage taps
carry the script's first-256-rows range.
rows.bin the 110 layout rows (10 feature rows of 10 proj rows + image_newline)
as raw bf16, view_seperator excluded.
tile0.json shapes of every artifact, the crop derivation, the verification cosines.
e2e (out: OUTDIR/e2e_document.{json,txt})
the checkpoint's infer() on document.png at its defaults (base 1024, tile 640, crop_mode,
greedy, ngram 35/128) for 200 max tokens, with the prompt ids and the per-picture layout
it built.
multi (out: OUTDIR/multi_document_screenshot.{json,txt})
the checkpoint's infer_multi() on document.png + screenshot.png at image_size 640, greedy,
ngram 35/128, 200 max tokens, with the per-page token/row layout.
CPU only: CUDA is disabled at import; the checkpoint's .cuda() calls are patched to identity.
"""
import json
import math
import os
import sys
import types
os.environ["CUDA_VISIBLE_DEVICES"] = ""
import numpy as np # noqa: E402
import torch # noqa: E402
torch.Tensor.cuda = lambda self, *a, **k: self
torch.nn.Module.cuda = lambda self, *a, **k: self
try:
torch.cuda.empty_cache = lambda: None
except Exception:
pass
MODELDIR = "/home/juup/models/Unlimited-OCR"
CODEDIR = "/tmp/kilo/uocr"
IMGDIR = "/tmp/kilo/uocr-images"
TILE_DIR = "/tmp/kilo/uocr-ref-tile"
MULTI_DIR = "/tmp/kilo/uocr-ref-multi"
sys.path.insert(0, CODEDIR)
import deepencoder as de # noqa: E402
PATCH, DS = 16, 4
BASE, TILE = 1024, 640
IMAGE_TOKEN_ID = 128815
def uocr_pkg():
"""the checkpoint's remote code as a package (its relative imports need one)."""
pkg = types.ModuleType("uocr")
pkg.__path__ = [MODELDIR]
sys.modules["uocr"] = pkg
import importlib
return importlib.import_module("uocr.modeling_unlimitedocr")
def build_vision():
from safetensors.torch import load_file
sd = load_file(os.path.join(MODELDIR, "model-00001-of-000001.safetensors"))
w = {}
for k, v in sd.items():
for p, m in (("model.sam_model.", "sam"), ("model.vision_model.", "clip"),
("model.projector.", "proj")):
if k.startswith(p):
w[(m, k[len(p):])] = v
if k == "model.image_newline":
w[("newline", "")] = v
if k == "model.view_seperator":
w[("sep", "")] = v
del sd
sam = de.build_sam_vit_b()
vision = de.build_clip_l()
proj = de.MlpProjector(de.adict(projector_type="linear", input_dim=2048, n_embed=1280))
sam.load_state_dict({k: v for (m, k), v in w.items() if m == "sam"}, strict=True)
vision.load_state_dict({k: v for (m, k), v in w.items() if m == "clip"}, strict=False)
proj.load_state_dict({k: v for (m, k), v in w.items() if m == "proj"}, strict=True)
for m in (sam, vision, proj):
m.eval().to(torch.bfloat16)
return sam, vision, proj, w[("newline", "")], w[("sep", "")]
def u16(t):
return t.view(torch.int16).detach().cpu().numpy().astype(np.uint16)
def cosine(a, b):
a = a.double().flatten()
b = b.double().flatten()
return float((a @ b) / (a.norm() * b.norm()))
def load_gate_image(path):
im = uocr_pkg().load_image(path)
return im.convert("RGB")
# --------------------------------------------------------------------- tile
def tile_crop(M):
"""the first 640 crop infer(crop_mode=True) feeds as images_crop_list[0], verbatim:
dynamic_preprocess(image) at its defaults, then the crop. Returns (crop, derivation)."""
im = load_gate_image(os.path.join(IMGDIR, "document.png"))
crops, ratio = M.dynamic_preprocess(im)
w, h = im.size
box = (0, 0, TILE, TILE)
derivation = {
"source": os.path.join(IMGDIR, "document.png"),
"source_size_wh": [w, h],
"aspect": w / h,
"crop_ratio_cols_rows": [int(ratio[0]), int(ratio[1])],
"resized_to_wh": [TILE * ratio[0], TILE * ratio[1]],
"resize": "PIL Image.resize(BICUBIC) (the call's default resample)",
"crop_box_xyxy": list(box),
"crop_count": len(crops),
}
return crops[0], ratio, crops, derivation
def transform(im):
"""BasicImageTransform(mean=.5,std=.5) -> bf16, the model's own."""
M = uocr_pkg()
tr = M.BasicImageTransform(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5), normalize=True)
return tr(im).to(torch.bfloat16)
def stage_engine(x, q, cols, extra):
"""the Processor::append staging: rows of (cols+extra) patch columns, the last `extra` all
zeros, each patch (channel, y, x); bf16 bit patterns as raw uint16 [q, cols+extra, 3,P,P]."""
c, h, w = x.shape
grid = x.reshape(c, q, PATCH, cols, PATCH).permute(1, 3, 0, 2, 4)
out = torch.zeros(q, cols + extra, c, PATCH, PATCH, dtype=x.dtype)
out[:, :cols] = grid
return out
def tile_forward(sam, vision, proj, newline, sep, X):
"""the DeepEncoder over one 640 crop, the checkpoint's own ops, taps in uocr_ref.py layouts."""
out = {}
t = sam.patch_embed(X)
pos40 = de.get_abs_pos_sam(sam.pos_embed, X.size(2) // PATCH)
t = t + pos40
out["x0"] = t.reshape(-1, 768)
H = W = X.size(2) // PATCH
for i, blk in enumerate(sam.blocks):
sc = t
h = blk.norm1(t)
if blk.window_size > 0:
hp, pad_hw = de.window_partition(h, blk.window_size)
a = blk.attn(hp)
a = de.window_unpartition(a, blk.window_size, pad_hw, (H, W))
else:
a = blk.attn(h)
out["attn%d" % i] = a.reshape(-1, 768)
out["pre%d" % i] = (sc + a).reshape(-1, 768)
t = sc + a
t = t + blk.mlp(blk.norm2(t))
out["b%d" % i] = t.reshape(-1, 768)
if i in (0, 1, 2):
out["full%d" % i] = t.reshape(-1, 768)
mm = t.permute(0, 3, 1, 2).contiguous()
n0 = sam.neck[0](mm)
n1 = sam.neck[1](n0)
n2 = sam.neck[2](n1)
n3 = sam.neck[3](n2)
out["map"] = n3.flatten(2).permute(0, 2, 1)[0]
out["n0"] = n0.flatten(2).permute(0, 2, 1)[0]
out["n1"] = n1.flatten(2).permute(0, 2, 1)[0]
out["n2"] = n2.flatten(2).permute(0, 2, 1)[0]
out["n3"] = n3.flatten(2).permute(0, 2, 1)[0]
out["map2"] = sam.net_2(n3).flatten(2).permute(0, 2, 1)[0]
m1 = sam.net_3(sam.net_2(n3))
m2 = vision(X, m1)
sam_rows = m1.flatten(2).permute(0, 2, 1)
clip_rows = m2[:, 1:]
fuse = torch.cat((clip_rows, sam_rows), dim=-1)
pf = proj(fuse)
h = w = int(pf.shape[1] ** 0.5)
g = pf.view(h, w, -1)
g = torch.cat([g, newline.view(1, 1, -1).expand(h, 1, -1)], dim=1).view(-1, pf.shape[-1])
rows = torch.cat([g, sep.view(1, -1)], dim=0)
return out, dict(pos40=pos40, sam=sam_rows[0], clip=clip_rows[0], fuse=fuse[0], proj=pf[0],
layout110=g, rows=rows)
def clip_pos_rows(vision, tgt_grid):
pos = vision.embeddings.position_embedding(vision.embeddings.position_ids)
return de.get_abs_pos(pos, tgt_grid * tgt_grid + 1)
def cmd_tile():
out = sys.argv[2] if len(sys.argv) > 2 else TILE_DIR
os.makedirs(out, exist_ok=True)
M = uocr_pkg()
crop, ratio, crops, derivation = tile_crop(M)
x = transform(crop)
q = TILE // PATCH
with torch.inference_mode():
# A1: the SAM absolute table at the 40 grid.
sam, vision, proj, newline, sep = build_vision()
pos40 = de.get_abs_pos_sam(sam.pos_embed, q)
np.savez(os.path.join(out, "sam_pos40.npz"), pos=u16(pos40[0]))
json.dump({"pos": {"shape": [q, q, 768], "dtype": "bf16 raw uint16",
"source": "model.sam_model.pos_embed [1,64,64,768]",
"op": "get_abs_pos_sam: F.interpolate bicubic antialias fp32 "
"align_corners=False, cast back bf16"}},
open(os.path.join(out, "sam_pos40.json"), "w"), indent=1)
# A2: the CLIP absolute table at the 10 grid (cls row 0 passthrough).
pos10 = clip_pos_rows(vision, 10)
np.savez(os.path.join(out, "clip_pos10.npz"), pos=u16(pos10[0]))
json.dump({"pos": {"shape": [101, 1024], "dtype": "bf16 raw uint16",
"source": "model.vision_model.embeddings.position_embedding.weight "
"[257,1024]",
"op": "get_abs_pos(..., 101): row 0 passthrough, rows 1: as 16x16 "
"resampled to 10x10 (bicubic antialias fp32, cast bf16), cls "
"concatenated first"}},
open(os.path.join(out, "clip_pos10.json"), "w"), indent=1)
# B: the engine-staged tile pixels (40 rows x 44 cols, 4 zero columns).
staged = stage_engine(x, q, q, 4)
staged.view(torch.int16).detach().cpu().numpy().astype(np.uint16).tofile(
os.path.join(out, "tile0.pix.bf16"))
stages, fin = tile_forward(sam, vision, proj, newline, sep, x.unsqueeze(0))
p = np.array(crop, dtype=np.uint8)
patches = torch.nn.functional.unfold(x.unsqueeze(0), kernel_size=16, stride=16)[0].t()
np.savez(os.path.join(out, "tile0.npz"),
image=x.to(torch.float32).numpy().astype(np.float16),
patches=patches.float().numpy().astype(np.float32),
crop_rgb=p,
rows=fin["rows"].float().numpy().astype(np.float32),
sam=fin["sam"].float().numpy().astype(np.float32),
clip=fin["clip"].float().numpy().astype(np.float32),
fuse=fin["fuse"].float().numpy().astype(np.float32),
proj=fin["proj"].float().numpy().astype(np.float32),
newline=newline.float().numpy().astype(np.float32),
sep=sep.float().numpy().astype(np.float32),
**{"st_" + k: v[:256].float().numpy().astype(np.float32)
for k, v in stages.items()})
fin["layout110"].view(torch.int16).detach().cpu().numpy().astype(np.uint16).tofile(
os.path.join(out, "rows.bin"))
# VERIFY: the staged pixels reproduce the crop, and st_x0 is the staged crop through
# patch_embed + the 40 table.
raw = np.fromfile(os.path.join(out, "tile0.pix.bf16"), dtype=np.uint16)
rec = torch.from_numpy(raw.astype(np.int16)).view(torch.bfloat16).view(q, q + 4, 3,
PATCH, PATCH)
bits_equal = bool(torch.equal(rec[:, :q].permute(2, 0, 3, 1, 4).reshape(3, TILE, TILE), x))
X2 = rec[:, :q].permute(2, 0, 3, 1, 4).reshape(1, 3, TILE, TILE).contiguous()
x0b = sam.patch_embed(X2) + de.get_abs_pos_sam(sam.pos_embed, q)
x0b = x0b.reshape(-1, 768)
verif = {"staged_bits_equal_to_transform": bits_equal,
"cos_x0_from_pix_vs_stage0": cosine(x0b, stages["x0"]),
"bit_equal_x0_from_pix_vs_stage0": bool(torch.equal(x0b, stages["x0"])),
"stage_cosines": {}, "stage_bit_equal": {}}
stages2, fin2 = tile_forward(sam, vision, proj, newline, sep, X2)
for k in stages:
verif["stage_cosines"]["st_" + k] = cosine(stages2[k], stages[k])
verif["stage_bit_equal"]["st_" + k] = bool(torch.equal(stages2[k], stages[k]))
for k in ("sam", "clip", "fuse", "proj", "rows"):
verif["stage_cosines"][k] = cosine(fin2[k], fin[k])
verif["stage_bit_equal"][k] = bool(torch.equal(fin2[k], fin[k]))
manifest = {
"crop_derivation": derivation,
"artifacts": {
"sam_pos40.npz:pos": [q, q, 768], "clip_pos10.npz:pos": [101, 1024],
"tile0.pix.bf16": [q, q + 4, 3, PATCH, PATCH],
"rows.bin": [110, 1280],
"tile0.npz": {"image": [3, 640, 640], "patches": [1600, 768],
"crop_rgb": [640, 640, 3], "rows": [111, 1280],
"sam": [100, 1024], "clip": [100, 1024], "fuse": [100, 2048],
"proj": [100, 1280], "newline": [1280], "sep": [1280],
"st_x0/st_pre*/st_attn*/st_b*": [256, 768],
"st_full0..2": [1600, 768], "st_n0..3": [256, 256],
"st_map": [256, 1024], "st_map2": [256, 512]},
},
"notes": {
"window_pad": "40 % 14 = 12 -> window_partition pads to 42x42 (bottom/right zeros), "
"9 windows of 14x14; unpartition crops back to 40x40",
"global_rel_pos": "blocks 2/5/8/11 are global over 40x40: get_rel_pos resizes the "
"127-row table (input 64x64) to 2*40-1 = 79 rows, linear",
"rows_bin": "110 rows of 10x10 proj rows + image_newline every 10, raw bf16; the "
"npz rows key adds the view_seperator row (111 rows, fp32)",
"pix_layout": "Processor::append (processor.cpp:1102): py rows of gw=44 patch cols, "
"cols 40..43 zeros, patch = (channel, y, x) of (x/255-0.5)/0.5 bf16",
},
"verify": verif,
}
json.dump(manifest, open(os.path.join(out, "tile0.json"), "w"), indent=1)
print("crop:", json.dumps(derivation))
print("staged bits equal:", bits_equal, " x0 cos:", verif["cos_x0_from_pix_vs_stage0"],
" x0 bit-equal:", verif["bit_equal_x0_from_pix_vs_stage0"])
for k, v in verif["stage_cosines"].items():
print("cos %-12s %.9f" % (k, v))
print("wrote", out)
# --------------------------------------------------------------------- e2e / multi
def capture_generate(model, max_new_tokens=200):
"""wrap model.generate to record the prefill tensors infer()/infer_multi() built. The cap is
forced through max_new_tokens: the checkpoint's generation_config.json ships max_new_tokens
32768, which transformers makes take precedence over the max_length infer() passes."""
box = {"max_new_tokens": max_new_tokens}
orig = model.generate
def gen(*a, **kw):
kw = dict(kw)
kw.pop("max_length", None)
kw["max_new_tokens"] = max_new_tokens
ids = kw.get("input_ids", a[0] if a else None)
box["input_ids"] = ids[0].tolist()
imgs = kw.get("images")
box["images_crop_shape"] = list(imgs[0][0].shape)
box["images_ori_shape"] = list(imgs[0][1].shape)
box["images_spatial_crop"] = kw["images_spatial_crop"].tolist()
box["seq_mask_true"] = int(kw["images_seq_mask"].sum())
out = orig(*a, **kw)
box["output_ids"] = out[0].tolist()
return out
model.generate = gen
return box
def load_full():
from transformers import AutoTokenizer, AutoModel
tok = AutoTokenizer.from_pretrained(MODELDIR, trust_remote_code=True)
m = AutoModel.from_pretrained(MODELDIR, trust_remote_code=True, use_safetensors=True,
torch_dtype=torch.bfloat16).eval()
return tok, m
def gen_report(tok, box, prompt_len):
full = box["output_ids"]
gen = full[prompt_len:]
rep = {
"prompt_token_ids_len": prompt_len,
"generation_cap_max_new_tokens": box.get("max_new_tokens"),
"input_ids": box["input_ids"],
"images_spatial_crop": box["images_spatial_crop"],
"images_crop_shape": box["images_crop_shape"],
"images_ori_shape": box["images_ori_shape"],
"image_seq_mask_true_count": box["seq_mask_true"],
"generated_len": len(gen),
"first_24_generated_ids": gen[:24],
"first_24_generated_text": tok.decode(gen[:24], skip_special_tokens=False),
"first_12_generated_ids": gen[:12],
"full_generated_ids": gen,
"eos_token_id": tok.eos_token_id,
"ended_with_eos": bool(gen and gen[-1] == tok.eos_token_id),
"decoded_raw": tok.decode(gen, skip_special_tokens=False),
}
stop = "<|end▁of▁sentence|>"
txt = tok.decode(gen, skip_special_tokens=True)
if txt.endswith(stop):
txt = txt[:-len(stop)]
rep["decoded_strip_stop"] = txt
return rep, txt
def cmd_e2e():
out = sys.argv[2] if len(sys.argv) > 2 else TILE_DIR
tok, model = load_full()
box = capture_generate(model)
M = uocr_pkg()
img = os.path.join(IMGDIR, "document.png")
im = load_gate_image(img)
crops, ratio = M.dynamic_preprocess(im)
nq_b, nq = BASE // PATCH // DS, TILE // PATCH // DS
global_tokens = (nq_b + 1) * nq_b + 1
local_tokens = (nq * ratio[0] + 1) * nq * ratio[1]
model.infer(tok, prompt="<image>document parsing.", image_file=img,
output_path=os.path.join(out, "hfout"), base_size=BASE, image_size=TILE,
crop_mode=True, max_length=200, no_repeat_ngram_size=35, ngram_window=128,
temperature=0.0, save_results=False)
rep, txt = gen_report(tok, box, len(box["input_ids"]))
rep["picture"] = img
rep["infer_args"] = {"prompt": "<image>document parsing.", "base_size": BASE,
"image_size": TILE, "crop_mode": True, "max_length": 200,
"no_repeat_ngram_size": 35, "ngram_window": 128, "temperature": 0.0}
rep["layout"] = {
"num_tiles": len(crops), "grid_cols_x_rows": [int(ratio[0]), int(ratio[1])],
"token_segments": {"global": global_tokens, "local": local_tokens,
"total_image_tokens": global_tokens + local_tokens},
"row_segments": {"local_rows": (ratio[1] * nq) * (ratio[0] * nq + 1),
"global_rows": nq_b * (nq_b + 1), "separator_rows": 1},
}
assert rep["layout"]["token_segments"]["total_image_tokens"] == box["seq_mask_true"]
json.dump(rep, open(os.path.join(out, "e2e_document.json"), "w"), indent=1, ensure_ascii=False)
open(os.path.join(out, "e2e_document.txt"), "w").write(rep["decoded_raw"])
print("first12", rep["first_12_generated_ids"])
print("generated_len", rep["generated_len"])
print(txt[:400])
print("wrote", os.path.join(out, "e2e_document.json"))
def cmd_multi():
out = sys.argv[2] if len(sys.argv) > 2 else MULTI_DIR
tok, model = load_full()
box = capture_generate(model)
pages = [os.path.join(IMGDIR, "document.png"), os.path.join(IMGDIR, "screenshot.png")]
model.infer_multi(tok, prompt="<image>Multi page parsing.", image_files=pages,
output_path=os.path.join(out, "hfout"), image_size=TILE, max_length=200,
no_repeat_ngram_size=35, ngram_window=128, temperature=0.0,
save_results=False)
rep, txt = gen_report(tok, box, len(box["input_ids"]))
nq = TILE // PATCH // DS
per_tokens = (nq + 1) * nq + 1
rep["pages"] = pages
rep["infer_args"] = {"prompt": "<image>Multi page parsing.", "image_size": TILE,
"max_length": 200, "no_repeat_ngram_size": 35, "ngram_window": 128,
"temperature": 0.0}
rep["layout"] = {
"num_pages": len(pages),
"per_page": {"resized_to": [TILE, TILE], "tokens": per_tokens,
"grid_rows_x_cols": [nq, nq], "feature_rows": (nq + 1) * nq,
"view_seperator_rows": 1, "rows_per_page": (nq + 1) * nq + 1},
"inter_page": "every page carries its own trailing image_token_id token; the rows of page "
"i end with the view_seperator row, page i+1 follows in the same image run",
"total_image_tokens": per_tokens * len(pages),
"total_rows": ((nq + 1) * nq + 1) * len(pages),
}
assert rep["layout"]["total_image_tokens"] == box["seq_mask_true"]
json.dump(rep, open(os.path.join(out, "multi_document_screenshot.json"), "w"), indent=1,
ensure_ascii=False)
open(os.path.join(out, "multi_document_screenshot.txt"), "w").write(rep["decoded_raw"])
print("input_len", rep["prompt_token_ids_len"], "mask_true", box["seq_mask_true"])
print("first12", rep["first_12_generated_ids"])
print(txt[:400])
print("wrote", os.path.join(out, "multi_document_screenshot.json"))
if __name__ == "__main__":
cmd = sys.argv[1]
{"tile": cmd_tile, "e2e": cmd_e2e, "multi": cmd_multi}[cmd]()
+87 -4
View File
@@ -28,6 +28,8 @@
#include "rad_builder.h"
#include "rad_plugin.h"
#include "uocr_golden.h"
#include "uocr_resample_golden.h"
#include "../arch/common/rad_resample.h"
#include <algorithm>
#include <cmath>
@@ -1613,15 +1615,20 @@ TEST(unlimitedocr_runs_follow_the_reference_layout) {
CHECK_EQ(uocr_tokens(c, gundam, 3, 2), (int64_t)273 + (int64_t)(10 * 3 + 1) * 20);
CHECK_EQ(uocr_tokens(c, gundam, 4, 3), (int64_t)273 + (int64_t)(10 * 4 + 1) * 30);
/* A request may restate the global view's side, but not cut crops at another tile or pad a
* page to a side that is not whole merged patches. */
/* A request may restate the global view's side, but only at a grid the DeepEncoder serves
* (64/40), and not cut crops at another tile or pad a page to a side that is not whole merged
* patches. */
bool crop = false;
int32_t bs = 0, is = 0;
ImageMode b2048;
b2048.kind = ImageMode::Gundam;
b2048.base_size = 2048;
CHECK_EQ(uocr_mode(c, b2048, &crop, &bs, &is, &why), RAD_OK);
CHECK_EQ(uocr_tokens(c, b2048, 1, 1), (int64_t)(32 + 1) * 32 + 1);
CHECK_EQ(uocr_mode(c, b2048, &crop, &bs, &is, &why), RAD_E_INVAL);
ImageMode b640;
b640.kind = ImageMode::Gundam;
b640.base_size = 640;
REQUIRE_EQ(uocr_mode(c, b640, &crop, &bs, &is, &why), RAD_OK);
CHECK_EQ(uocr_tokens(c, b640, 1, 1), (int64_t)(10 + 1) * 10 + 1);
ImageMode tile512;
tile512.kind = ImageMode::Gundam;
tile512.image_size = 512;
@@ -1655,4 +1662,80 @@ TEST(unlimitedocr_runs_follow_the_reference_layout) {
CHECK_EQ(pos[0], (int32_t)(1 + 273 + 100));
}
/* The DeepEncoder's 40-tower absolute position tables are the 64/16 checkpoint tables resampled
* with torch's bicubic + antialias (arch/common/rad_resample.h), computed host-side in
* fill_tables() and rounded to bf16. Every golden here is torch's F.interpolate(mode="bicubic",
* 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) {
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];
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];
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]);
const double rr = d / std::fmax(std::fabs((double)want[i]), 1e-30);
if (d > a) a = d;
if (rr > r) r = rr;
}
std::fprintf(stderr, " %dx%d -> %dx%d: max abs %.3g, max rel %.3g\n", ih, iw, oh, ow, a, r);
if (a > worst_abs) worst_abs = a;
if (r > worst_rel) worst_rel = r;
}
std::fprintf(stderr, " synthetic fp32: worst abs %.3g, worst rel %.3g (target < 1e-4)\n",
worst_abs, worst_rel);
CHECK(worst_abs < 1e-4);
/* A checkpoint table, bf16 in and bf16 out, exactly as fill_tables() does it: decode the
* stored bf16, resample in fp32, round back. Reports the last-bit count and the max abs the
* bf16 table would carry. */
auto bf16_case = [&](const uint16_t* src_bits, int ih, int iw, int oh, int ow, int ch,
const uint16_t* want_bits, size_t off, const char* tag,
size_t* mism, double* absmax) {
std::vector<float> f((size_t)ih * iw * ch);
for (size_t i = 0; i < f.size(); ++i) f[i] = rad_bf16_to_f32(src_bits[i]);
std::vector<float> g((size_t)oh * ow * ch);
rad::arch::resample_bicubic_aa(f.data(), ih, iw, oh, ow, ch, g.data());
size_t m = 0;
double a = 0.0;
for (size_t i = 0; i < g.size(); ++i) {
const uint16_t got = rad_f32_to_bf16(g[i]);
const uint16_t want = want_bits[off + i];
if (got != want) ++m;
const double d = std::fabs(rad_bf16_to_f32(got) - rad_bf16_to_f32(want));
if (d > a) a = d;
}
std::fprintf(stderr, " %s: %zu/%zu bf16 mismatches, max abs %.3g\n", tag, m, g.size(), a);
*mism = m;
*absmax = a;
};
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);
/* 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",
&clip_mism, &clip_abs);
}
/* The bf16 tables are a report, not a gate: bf16 carries ~3 decimal digits, so a last-bit
* difference on a fraction of entries is representable, not a bug. The fp32 CHECK above is
* the strict signal on the resample arithmetic. */
(void)sam_mism;
(void)clip_mism;
}
RAD_TEST_MAIN()
+186 -18
View File
@@ -14,11 +14,13 @@
#include "rad_test.h"
#include "rad_abi.h"
#include "../libref/ref_common.h"
#include "../core/sample/host_ref.h" /* the host chain, for the whitelist's op-for-op form */
#include "rad_sample.h"
#include "rad_philox.h"
#include "rad_runtime.h" /* RAD_VGEOM_* */
#include <algorithm>
#include <cmath>
#include <deque>
#include <string>
#include <thread>
@@ -5104,8 +5106,10 @@ TEST(op_sample_pick_draws_the_specified_uniform) {
/* ================================================================== the n-gram ban */
/* Unlimited-OCR's SlidingWindowNoRepeatNgramProcessor, ported straight from
* modeling_unlimitedocr.py:353-383 as the oracle's second formulation. `s` is the row's history
* oldest first; the result marks every global token id it bans. */
static std::vector<char> ref_ngram_banned(const std::vector<int32_t>& s, int n, int window) {
* oldest first; `whitelist` is its `whitelist_token_ids`, removed from the banned set after it is
* built (line 379). The result marks every global token id it bans. */
static std::vector<char> ref_ngram_banned(const std::vector<int32_t>& s, int n, int window,
const std::vector<int32_t>& whitelist = {}) {
std::vector<char> banned(256, 0);
if (n <= 0 || (int64_t)s.size() < (int64_t)n) return banned;
const int64_t len = (int64_t)s.size();
@@ -5122,13 +5126,19 @@ static std::vector<char> ref_ngram_banned(const std::vector<int32_t>& s, int n,
const int32_t tok = s[(size_t)(idx + n - 1)];
if (tok >= 0 && tok < (int32_t)banned.size()) banned[(size_t)tok] = 1;
}
for (int32_t id : whitelist)
if (id >= 0 && id < (int32_t)banned.size()) banned[(size_t)id] = 0;
return banned;
}
/* The op over one row: returns the banned global ids it wrote as -infinity, and whether every other
* column is bit-for-bit its input. */
* column is bit-for-bit its input. `whitelist` ids arrive as the bitmask operand (a set bit marks
* an exempt column); an empty list passes an all-zero plane, and `no_operand` passes no 5th
* operand at all -- the default serving form. */
static std::vector<int32_t> ref_ngram_op(const std::vector<int32_t>& s, int n, int window,
int n_vocab, bool* untouched_out) {
int n_vocab, bool* untouched_out,
const std::vector<int32_t>& whitelist = {},
bool no_operand = false) {
const int64_t H = 8; /* the history plane's extent in these cases */
T lg(RAD_F32, {1, n_vocab});
std::vector<float> in((size_t)n_vocab);
@@ -5143,8 +5153,16 @@ static std::vector<int32_t> ref_ngram_op(const std::vector<int32_t>& s, int n, i
sp[0].hist_off = 0;
sp[0].hist_len = (int32_t)std::min<size_t>(s.size(), (size_t)H);
T ng(RAD_I32, {1, 2}); ng.n({ n, window });
const int64_t words = (n_vocab + 31) / 32;
T wl(RAD_I32, {1, words});
std::vector<int64_t> wv((size_t)words, 0);
for (int32_t id : whitelist)
if (id >= 0 && id < n_vocab) wv[(size_t)(id >> 5)] |= 1LL << (id & 31);
wl.n(wv);
A a; a.t(lg).t(sp.operand()).t(hist).t(ng).i("M", 1).i("n_vocab", n_vocab);
A a; a.t(lg).t(sp.operand()).t(hist).t(ng);
if (!no_operand) a.t(wl);
a.i("M", 1).i("n_vocab", n_vocab);
if (run("sample_ngram_ban", a) != RAD_OK) return { -99 };
std::vector<int32_t> banned;
@@ -5164,14 +5182,18 @@ static std::vector<int32_t> ref_ngram_op(const std::vector<int32_t>& s, int n, i
* longer than n cover the early exits;
* - 200 random histories over five ids, lengths 1..24, n 1..8 and windows 0..16, where the
* window boundary falls inside repeated runs;
* - 300 of those shapes repeated with a random whitelist of 0..32 ids (some outside the
* vocabulary), asserting `banned.difference_update(self.whitelist)`: the whitelist removes
* bans and bans nothing, and every column it spares keeps its input bits;
* - the named shapes: an n-gram whose last token is the window's last (idx == search_end - 1),
* an n-gram that starts at search_start while an earlier copy starts before it, n == 1 (the
* empty prefix, every window token banned) and n == 0 (off). */
* empty prefix, every window token banned) and n == 0 (off), each once with a whitelist. */
TEST(op_sample_ngram_ban_matches_the_reference_processor) {
int64_t trials = 0, mismatches = 0, bans = 0;
int64_t trials = 0, mismatches = 0, bans = 0, wl_trials = 0, wl_bans = 0;
bool all_untouched = true;
auto trial = [&](const std::vector<int32_t>& s_in, int n, int window) {
auto trial = [&](const std::vector<int32_t>& s_in, int n, int window,
const std::vector<int32_t>& whitelist = {}, bool wl_case = false) {
/* The engine's plane holds the LAST H tokens of the sequence (build_step truncates the
* oldest), so the oracle and the op must both see that span. */
const std::vector<int32_t> s = s_in.size() > 8
@@ -5179,11 +5201,12 @@ TEST(op_sample_ngram_ban_matches_the_reference_processor) {
: s_in;
const int n_vocab = 8;
bool untouched = true;
const std::vector<int32_t> got = ref_ngram_op(s, n, window, n_vocab, &untouched);
const std::vector<int32_t> got = ref_ngram_op(s, n, window, n_vocab, &untouched, whitelist);
if (got.size() == 1 && got[0] == -99) { ++mismatches; return; }
const std::vector<char> want = ref_ngram_banned(s, n, window);
const std::vector<char> want = ref_ngram_banned(s, n, window, whitelist);
++trials;
bans += (int64_t)got.size();
if (wl_case) { ++wl_trials; wl_bans += (int64_t)got.size(); }
all_untouched = all_untouched && untouched;
int64_t live = 0;
for (int id = 0; id < n_vocab; ++id) live += want[(size_t)id] ? 1 : 0;
@@ -5219,6 +5242,30 @@ TEST(op_sample_ngram_ban_matches_the_reference_processor) {
trial(s, n, w);
}
/* The same random shapes with random whitelists: 0..32 ids over a range wider than the
* vocabulary, so exempt tokens, non-banned tokens and out-of-vocabulary ids all occur. */
for (int it = 0; it < 300; ++it) {
rs = rs * 1664525u + 1013904223u;
const int64_t len = 1 + (int64_t)((rs >> 8) % 24u);
std::vector<int32_t> s((size_t)len);
for (int64_t i = 0; i < len; ++i) {
rs = rs * 1664525u + 1013904223u;
s[(size_t)i] = (int32_t)((rs >> 12) % 5u);
}
rs = rs * 1664525u + 1013904223u;
const int n = 1 + (int)((rs >> 8) % 8u);
rs = rs * 1664525u + 1013904223u;
const int w = (int)((rs >> 8) % 17u);
rs = rs * 1664525u + 1013904223u;
const int k = (int)((rs >> 8) % 33u); /* 0..32 ids, empty included */
std::vector<int32_t> wl((size_t)k);
for (int j = 0; j < k; ++j) {
rs = rs * 1664525u + 1013904223u;
wl[(size_t)j] = (int32_t)((rs >> 12) % 12u); /* ids 8..11 are out of vocabulary */
}
trial(s, n, w, wl, true);
}
/* The named shapes. [4,1,2, 4,1,2, 4,1,2] with n 3 and window 6: the newest complete n-gram
* starts exactly at search_end - 1, and the earlier copy at search_start bans the same token;
* window 3 moves search_start so that only the spanning copy is searched. */
@@ -5228,31 +5275,60 @@ TEST(op_sample_ngram_ban_matches_the_reference_processor) {
trial({ 1, 1, 1, 1, 1, 1 }, 1, 3); /* n 1: the entire window is banned */
trial({ 1, 1, 1, 1, 1, 1 }, 0, 3); /* off */
trial({ 7, 2, 7, 2, 7 }, 2, 0); /* window 0: the whole span */
/* The same shapes with whitelists: the banned token exempted (ban vanishes), a token that
* would not be banned exempted (inert), an out-of-vocabulary id (inert) and n 0 with a
* whitelist (still off). */
trial({ 4, 1, 2, 4, 1, 2, 4, 1, 2 }, 3, 6, { 2 }, true); /* a non-banned id: inert */
trial({ 4, 1, 2, 4, 1, 2, 4, 1, 2 }, 3, 6, { 4 }, true); /* the banned id: ban vanishes */
trial({ 4, 1, 2, 4, 1, 2, 4, 1, 2 }, 3, 6, { 4, 2 }, true);
trial({ 1, 1, 1, 1, 1, 1 }, 1, 3, { 1 }, true); /* n 1, the whole window exempted */
trial({ 1, 1, 1, 1, 1, 1 }, 1, 3, { 7 }, true); /* out of vocabulary: inert */
trial({ 1, 1, 1, 1, 1, 1 }, 0, 3, { 1 }, true); /* off stays off with a whitelist */
trial({ 7, 2, 7, 2, 7 }, 2, 0, { 7, 2 }, true); /* every banned token exempted */
/* The whitelist as a plain bitmask must agree with the same case with the operand absent
* (the reference's empty whitelist): an all-zero plane bans exactly what no plane bans. */
{
bool u1 = true, u2 = true;
const std::vector<int32_t> s = { 4, 1, 2, 4, 1, 2, 4, 1 };
const std::vector<int32_t> a = ref_ngram_op(s, 3, 0, 8, &u1);
const std::vector<int32_t> b = ref_ngram_op(s, 3, 0, 8, &u2, {}, true);
CHECK(a == b);
CHECK(!a.empty());
}
CHECK(trials > 2500);
CHECK(mismatches == 0);
CHECK(bans > 0);
CHECK(wl_trials >= 300);
/* The whitelist bites: random whitelists leave bans on the table AND remove some, so a
* kernel that ignored the plane would fail the sweeps above, not merely agree with them. */
CHECK(wl_bans > 0);
/* Every column the reference does not ban is bit-for-bit its input: the op writes -infinity
* and nothing else, so penalties and temperature see the same numbers. */
CHECK(all_untouched);
}
/* Off is the default, and off must be invisible to greedy decoding: sample_ngram_ban writes
* nothing for a row with ngram_ban_n 0, so the argmax over the same row is the same token. With
* the ban on, the outcome changes exactly when the ban covers the argmax's token. */
* nothing for a row with ngram_ban_n 0 -- with a whitelist plane present as well, the reference's
* empty-whitelist default -- so the argmax over the same row is the same token and the logits are
* bit-identical. With the ban on, the outcome changes exactly when the ban covers the argmax's
* token, and the whitelist moves it back. */
TEST(op_sample_ngram_ban_off_leaves_greedy_decoding_unchanged) {
/* Token 5 is the clear maximum. Its id appears 4 times in the history, so both the ban and the
* penalties have something to do; the ban is off here. */
T hist(RAD_I32, {1, 8}); hist.n({ 5, 1, 5, 2, 5, 3, 5, 1 });
auto greedy = [&](int n, int window, std::vector<float>* after) {
auto greedy = [&](int n, int window, std::vector<float>* after, int wl_id = -1) {
T lg(RAD_F32, {1, 8});
lg.f({ 0.0f, 0.1f, 0.2f, 0.3f, 0.4f, 4.0f, 0.5f, 0.6f });
SP sp(1);
sp[0].hist_off = 0;
sp[0].hist_len = 8;
T ng(RAD_I32, {1, 2}); ng.n({ n, window });
A a; a.t(lg).t(sp.operand()).t(hist).t(ng).i("M", 1).i("n_vocab", 8);
T wl(RAD_I32, {1, 1});
wl.n({ wl_id >= 0 ? (int64_t)1 << wl_id : 0 });
A a; a.t(lg).t(sp.operand()).t(hist).t(ng).t(wl).i("M", 1).i("n_vocab", 8);
CHECK_OK(run("sample_ngram_ban", a));
T tk(RAD_I32, {1});
A b; b.t(lg).t(sp.operand()).t(tk).i("M", 1).i("n_vocab", 8);
@@ -5263,19 +5339,96 @@ TEST(op_sample_ngram_ban_off_leaves_greedy_decoding_unchanged) {
};
std::vector<float> off_logits;
CHECK_EQ(greedy(0, 0, &off_logits), 5);
/* Bit-identical to the input: the stage did not run. */
CHECK_EQ(greedy(0, 0, &off_logits, 5), 5);
/* Bit-identical to the input: the stage did not run, whitelist plane present or not. */
static const float kIn[8] = { 0.0f, 0.1f, 0.2f, 0.3f, 0.4f, 4.0f, 0.5f, 0.6f };
for (int64_t i = 0; i < 8; ++i) CHECK(std::memcmp(&off_logits[(size_t)i], &kIn[i], 4) == 0);
std::vector<float> off_plain;
CHECK_EQ(greedy(0, 0, &off_plain), 5);
CHECK(off_plain == off_logits);
/* The history's prefix (5,1) is followed by token 5 at positions 0 and 2 in [5,1,5,2,5,3,5,1]:
* with n 2 the ban covers 5, so greedy moves to the next best (token 7). */
CHECK_EQ(greedy(2, 8, nullptr), 7);
/* The whitelist removes 5 from the banned set (the reference's difference_update), and greedy
* is back on the maximum. */
CHECK_EQ(greedy(2, 8, nullptr, 5), 5);
/* A ban that only names other tokens leaves the argmax alone: with n 2 and a one-token window,
* search_start == search_end - 1 is impossible (window 1 < n), so nothing is banned. */
CHECK_EQ(greedy(2, 1, nullptr), 5);
}
/* The host chain (core/sample/host_ref.cpp) reproduces the reference op for op: the banned set,
* then the whitelist removed from it, then -inf -- and off (ngram_ban_n 0) leaves the logits
* bit-identical through the greedy chain, whitelist plane present or not. */
TEST(host_ngram_ban_whitelist_matches_the_reference) {
using namespace rad;
const std::vector<float> in = { 0.0f, 0.1f, 0.2f, 0.3f, 0.4f, 4.0f, 0.5f, 0.6f };
const std::vector<int32_t> hist = { 5, 1, 5, 2, 5, 3, 5, 1 };
auto bit = [](std::vector<uint32_t>& v, int id) { v[(size_t)(id >> 5)] |= 1u << (uint32_t)(id & 31); };
/* The bare ban: token 5 (the prefix (1) is followed by 5 in the window) gets -infinity, every
* other candidate keeps its input bits. */
{
CandidateSet s;
s.from_logits(in.data(), 8);
host_ngram_ban(s, hist.data(), 8, 2, 8);
int64_t banned = 0;
for (const Candidate& c : s.c) {
if (std::isinf(c.logit) && c.logit < 0.0f) { ++banned; CHECK_EQ(c.id, 5); }
else CHECK(std::memcmp(&c.logit, &in[(size_t)c.id], 4) == 0);
}
CHECK_EQ(banned, 1LL);
}
/* The whitelist bit for the banned token: banned.difference_update, nothing written. */
{
std::vector<uint32_t> wl(1, 0);
bit(wl, 5);
CandidateSet s;
s.from_logits(in.data(), 8);
host_ngram_ban(s, hist.data(), 8, 2, 8, wl.data(), 1);
for (const Candidate& c : s.c) CHECK(std::memcmp(&c.logit, &in[(size_t)c.id], 4) == 0);
}
/* A bit for a token that is not banned is inert; a bit past the plane marks nothing, so the
* ban stands. */
{
std::vector<uint32_t> wl(1, 0);
bit(wl, 3);
CandidateSet s;
s.from_logits(in.data(), 8);
host_ngram_ban(s, hist.data(), 8, 2, 8, wl.data(), 1);
bool five = false;
for (const Candidate& c : s.c) {
if (c.id == 5) { five = std::isinf(c.logit) && c.logit < 0.0f; continue; }
CHECK(std::memcmp(&c.logit, &in[(size_t)c.id], 4) == 0);
}
CHECK(five);
}
/* Off is invisible to the whole greedy chain: ngram_ban_n 0 with the whitelist input set and
* with it clear take the same token over bit-identical logits. */
{
std::vector<uint32_t> wl(1, 0);
bit(wl, 5);
SamplingParams sp;
sp.temp = 0.0f; /* greedy */
HostRefInput plain;
plain.history = hist.data();
plain.n_history = 8;
HostRefInput with = plain;
with.ngram_whitelist = wl.data();
with.ngram_whitelist_words = 1;
CandidateSet a, b;
a.from_logits(in.data(), 8);
b.from_logits(in.data(), 8);
CHECK_EQ(host_sample_into(a, sp, plain), 5);
CHECK_EQ(host_sample_into(b, sp, with), 5);
for (size_t i = 0; i < a.c.size(); ++i) {
CHECK(std::memcmp(&a.c[i].logit, &in[(size_t)a.c[i].id], 4) == 0);
CHECK(std::memcmp(&b.c[i].logit, &in[(size_t)b.c[i].id], 4) == 0);
}
}
}
/* ================================================================== failure modes */
/* Nothing that did not do the work returns RAD_OK. The engine turns these into a named abort
* rather than a silent fallback (spec §17). */
@@ -8693,10 +8846,14 @@ namespace {
struct SamIn {
int64_t gh = 1, gw = 1, win = 0, nh = 1, hd = 1, nseq = 1;
std::vector<float> q, k, v, rh, rw; /* [M, nh*hd] and [2*L-1, hd], row-major */
int64_t raw_rows = 0; /* 0: the geometry's own 2*tile-1; else the staged rows */
std::vector<float> q, k, v, rh, rw; /* [M, nh*hd] and [tab(), hd], row-major */
int64_t W() const { return nh * hd; }
int64_t rows() const { return nseq * gh * gw; }
int64_t tab() const { return 2 * (win > 0 ? win : (gh > gw ? gh : gw)) - 1; }
int64_t tab() const {
if (raw_rows > 0) return raw_rows;
return 2 * (win > 0 ? win : (gh > gw ? gh : gw)) - 1;
}
};
/* A deterministic draw in [-1, 1]: index-driven, so a wrong pitch or row map reads other numbers. */
@@ -8927,6 +9084,17 @@ TEST(op_sam_attn_global_and_non_square) {
CHECK_EQ(rc, (int)RAD_OK);
CHECK_EQ(bad, 0LL);
CHECK(maxd < 2e-3f);
/* The production case the tower hits: a 40x40 global block whose wanted rel_pos rows are 79,
* served from the checkpoint's 127-row tables (both axes resize). */
SamIn p40;
p40.gh = p40.gw = 40; p40.win = 0; p40.nh = 2; p40.hd = 8; p40.raw_rows = 127;
sam_fill(p40, 0x2545f491u);
CHECK_EQ(p40.tab(), 127LL);
sam_cmp(sam_run(p40, 0, &rc), sam_oracle(p40), &maxd, &bad);
CHECK_EQ(rc, (int)RAD_OK);
CHECK_EQ(bad, 0LL);
CHECK(maxd < 2e-3f);
}
/* Two segments: each is one tile (window 0). The second segment's rows are computed from its own
+276
View File
@@ -0,0 +1,276 @@
#!/home/juup/.venvs/hfref312/bin/python
"""resample_golden.py -- emit tests/uocr_resample_golden.h 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
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).
It then loads the Unlimited-OCR checkpoint (shard resolved through the checkpoint's
model.safetensors.index.json), reads
model.sam_model.pos_embed [1,64,64,768] bf16
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:
SAM [40,40,768]; CLIP [101,1024] with the cls row at index 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.
"""
import itertools
import json
import os
import sys
import numpy as np
import torch
import torch.nn.functional as F
from safetensors.torch import safe_open
SIZES = [(64, 64, 40, 40), (24, 24, 20, 20), (8, 8, 5, 5), (16, 16, 10, 10), (16, 20, 10, 13)]
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")
SAM_TENSOR = "model.sam_model.pos_embed"
CLIP_TENSOR = "model.vision_model.embeddings.position_embedding.weight"
# The emulation mirrors torch 2.14's separable AA kernel exactly (see the emulation
# section); the C++ header mirrors the same algorithm.
def torch_resample(hwc, oh, ow):
"""[h,w,C] fp32 -> torch bicubic+antialias -> [oh,ow,C] fp32, as the tower permutes."""
x = torch.from_numpy(hwc).permute(2, 0, 1).unsqueeze(0)
y = F.interpolate(x, size=(oh, ow), mode="bicubic", antialias=True, align_corners=False)
return y[0].permute(1, 2, 0).contiguous().numpy()
# ---------------------------------------------------------------- rad_resample.h emulation
#
# Mirrors torch 2.14's upsample_bicubic2d_aa_kernel_impl -> upsample_separable_Nd
# (UpSampleKernel.cpp): HelperInterpCubic::aa_filter (Keys a=-0.5), separable W pass
# first then H pass, per-axis float scale/center/taps and
# _compute_indices_min_size_weights_aa. float32 is used exactly where ATen uses
# scalar_t = float and double where the expression promotes.
import math
def cubic_kernel(fa):
"""HelperInterpCubic::aa_filter<float> (Keys a = -0.5), elementwise fp32."""
ax = np.abs(np.float32(fa)).astype(np.float32)
r1 = ((np.float32(1.5) * ax - np.float32(2.5)) * ax) * ax + np.float32(1.0)
r2 = ((np.float32(-0.5) * ax + np.float32(2.5)) * ax - np.float32(4.0)) * ax + np.float32(2.0)
return np.where(ax < np.float32(1.0), r1,
np.where(ax < np.float32(2.0), r2, np.float32(0.0))).astype(np.float32)
def make_axis(in_n, out_n):
scale = np.float32(in_n / out_n)
support = (np.float32(np.float64(np.float32(4) * 0.5) * float(scale))
if scale >= 1.0 else np.float32(2.0))
max_taps = int(math.ceil(float(support))) * 2 + 1
invscale = np.float32(1.0 / float(scale)) if scale >= 1.0 else np.float32(1.0)
w = np.zeros((out_n, max_taps), np.float32)
idx = np.zeros((out_n, max_taps), np.int64)
size = np.zeros(out_n, np.int64)
for i in range(out_n):
center = np.float32(float(scale) * (i + 0.5))
xmin = max(int(float(center) - float(support) + 0.5), 0)
xsize = min(int(float(center) + float(support) + 0.5), in_n) - xmin
xsize = min(max(int(xsize), 0), max_taps)
for j in range(xsize):
d = np.float32(np.float32(j + xmin) - center)
fa = np.float32((float(d) + 0.5) * float(invscale))
w[i, j] = float(cubic_kernel(fa))
idx[i, j] = xmin + j
total = np.float32(0.0)
for j in range(xsize):
total = np.float32(total + w[i, j])
if total != 0:
for j in range(xsize):
w[i, j] = np.float32(w[i, j] / total)
size[i] = xsize
return w, idx, size
def emu_resample(src_hwc, ih, iw, oh, ow, ch, cfg=None):
wy, iy, sy = make_axis(ih, oh)
wx, ix, sx = make_axis(iw, ow)
inter = src_hwc.astype(np.float32)
if iw != ow: # W (horizontal) pass first
tmp = np.zeros((ih, ow, ch), np.float32)
for oy in range(ih):
for ox in range(ow):
acc = inter[oy, ix[ox, 0]] * wx[ox, 0]
for j in range(1, int(sx[ox])):
acc = (acc + inter[oy, ix[ox, j]] * wx[ox, j]).astype(np.float32)
tmp[oy, ox] = acc
inter = tmp
if ih != oh: # H (vertical) pass second
out = np.zeros((oh, ow, ch), np.float32)
for ox in range(ow):
for oy in range(oh):
acc = inter[iy[oy, 0], ox] * wy[oy, 0]
for j in range(1, int(sy[oy])):
acc = (acc + inter[iy[oy, j], ox] * wy[oy, j]).astype(np.float32)
out[oy, ox] = acc
inter = out
return inter
def ulps(a, b):
ia = np.ascontiguousarray(a, np.float32).view(np.int32).astype(np.int64)
ib = np.ascontiguousarray(b, np.float32).view(np.int32).astype(np.int64)
oa = np.where(ia < 0, -np.int64(2147483648) - ia, ia)
ob = np.where(ib < 0, -np.int64(2147483648) - ib, ib)
return np.abs(oa - ob)
def report(tag, got, want):
d = ulps(got, want)
exact = int((d == 0).sum())
n = d.size
rel = np.abs(got.astype(np.float64) - want.astype(np.float64)) / np.maximum(np.abs(want.astype(np.float64)), 1e-30)
print(f" {tag}: {exact}/{n} bit-exact ({100.0 * exact / n:.4f}%), "
f"max ULP {int(d.max())}, max rel {rel.max():.3g}", flush=True)
return exact == n
# ---------------------------------------------------------------- header 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 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 bits(t):
return (t.detach().cpu().view(torch.int16).numpy().astype(np.uint32) & 0xFFFF).astype(np.uint16)
def bf16_round_bits(f32):
u = np.ascontiguousarray(f32, np.float32).view(np.uint32)
u = u + np.uint32(0x7FFF) + ((u >> np.uint32(16)) & np.uint32(1))
return (u >> np.uint32(16)).astype(np.uint16)
def main():
torch.set_num_threads(1)
ins, outs = [], []
all_ok = True
gen = torch.Generator().manual_seed(SEED)
first = True
for (ih, iw, oh, ow) in SIZES:
x = torch.randn(ih, iw, CH, generator=gen, dtype=torch.float32)
xn = x.numpy()
y = torch_resample(xn, oh, ow)
all_ok &= report(f"{ih}x{iw}->{oh}x{ow} (emulation vs torch)", emu_resample(xn, ih, iw, oh, ow, CH), y)
ins.append(xn)
outs.append(y)
shard = json.load(open(os.path.join(CKPT, "model.safetensors.index.json")))["weight_map"]
with safe_open(os.path.join(CKPT, shard[SAM_TENSOR]), framework="pt") as h:
sam = h.get_tensor(SAM_TENSOR)
clip = h.get_tensor(CLIP_TENSOR)
assert tuple(sam.shape) == (1, 64, 64, 768), sam.shape
assert tuple(clip.shape) == (257, 1024), clip.shape
sam_src = sam[0] # [64,64,768] bf16
sam_out = F.interpolate(sam_src.permute(2, 0, 1).unsqueeze(0).to(torch.float32),
size=(40, 40), mode="bicubic", antialias=True,
align_corners=False)[0].permute(1, 2, 0).to(torch.bfloat16)
grid = clip[1:] # [256,1024] bf16
grid_out = F.interpolate(grid.view(1, 16, 16, 1024).permute(0, 3, 1, 2).to(torch.float32),
size=(10, 10), mode="bicubic", antialias=True,
align_corners=False).permute(0, 2, 3, 1).to(torch.bfloat16)
clip_out = torch.cat([clip[:1], grid_out.reshape(100, 1024)], dim=0) # [101,1024]
def bf16_emu(src_bits_u16, ih, iw, oh, ow, ch):
f32 = (src_bits_u16.astype(np.uint32) << 16).view(np.float32).reshape(ih, iw, ch)
return f32, emu_resample(f32, ih, iw, oh, ow, ch)
sam_bits = bits(sam_src)
samf, samg = bf16_emu(sam_bits, 64, 64, 40, 40, 768)
all_ok &= report("sam 64->40 fp32 vs torch (pre-bf16)", samg, sam_out.float().numpy())
sam_bf_mism = int((bf16_round_bits(samg).reshape(-1) != bits(sam_out).reshape(-1)).sum())
print(f" sam 64->40 bf16: {sam_bf_mism} bf16 mismatches", flush=True)
clip_bits = bits(clip)
grid_bits = clip_bits[1:].reshape(16, 16, 1024)
cf, cg = bf16_emu(grid_bits, 16, 16, 10, 10, 1024)
all_ok &= report("clip 16->10 fp32 vs torch (pre-bf16)", cg, grid_out.reshape(10, 10, 1024).float().numpy())
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))
print(f"wrote {OUT} ({os.path.getsize(OUT) / 1e6:.1f} MB); "
f"emulation {'FULLY matches' if all_ok else 'DIVERGES from'} torch", flush=True)
return 0 if all_ok else 1
if __name__ == "__main__":
sys.exit(main())
+2
View File
@@ -4621,6 +4621,8 @@ TEST(every_request_key_is_served_refused_or_ignored_as_its_list_says) {
{ "session_id", { "s", none } }, { "n_probs", { 2, none } },
/* The windowed no-repeat-ngram ban and Unlimited-OCR's picture mode. */
{ "ngram_ban_n", { 35, none } }, { "ngram_window", { 128, none } },
{ "ngram_whitelist", { json::parse(R"([4,5])"), none } },
{ "no_repeat_ngram_whitelist", { json::parse(R"([4,5])"), none } },
{ "images_config", { "gundam", none } },
{ "messages", { json::parse(R"([{"role":"user","content":"yo"}])"), none } },
{ "tools", { json::parse(R"([{"type":"function","function":{"name":"f"}}])"), none } },
File diff suppressed because it is too large. Load diff