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

+6
View File
@@ -243,6 +243,12 @@ typedef struct RadBatch {
/* A video generator's pass (rad_declare_video_generator; `gen` is one of its
* RAD_GEN_PASS_*): its payload. Null on every other step. */
const struct RadVideoGenBatch* vgen_b;
/* host: [enc_n_seg] each segment's grid in patches, the same values enc_coord planes 2 and 3
* carry. A plugin that has to pick a geometry before it issues ops (a tower with one set of
* position tables per grid) reads them here; they live as long as the pass. */
const int32_t* enc_seg_h;
const int32_t* enc_seg_w;
} RadBatch;
/* What a generator pass carries beside the step batch's own fields, which keep their meanings:
+1016 -677
View File
File diff suppressed because it is too large. Load diff
+163
View File
@@ -0,0 +1,163 @@
/* rad_resample.h -- fp32 bicubic resampling reproducing torch's
* F.interpolate(x, size=(n, m), mode="bicubic", antialias=True) on the CPU float32 kernel,
* operation for operation, for the Unlimited-OCR DeepEncoder's position tables.
*
* The reference resamples two fixed tables (deepencoder.py, cached at /tmp/kilo/uocr/):
* get_abs_pos_sam() permutes SAM's pos_embed [1,64,64,768] to (0,3,1,2), casts fp32 and
* interpolates to 40x40; get_abs_pos() takes CLIP position_embedding rows 1: as a 16x16 grid,
* interpolates to 10x10, and cats row 0 (cls) in front. Here the table is row-major [h, w, C]
* with C innermost and each of the C channels is interpolated over the (h, w) grid
* independently; the cls split/catenation is the caller's job.
*
* The float32 antialias path (upsample_bicubic2d_aa_kernel_impl ->
* upsample_separable_Nd_kernel_impl -> _compute_index_ranges_weights with antialias=true,
* aten/src/ATen/native/cpu/UpSampleKernel.cpp, torch v2.14.0) is mirrored operation for
* operation, scalar_t = float:
* per axis scale = (float)(in / out); support = scale >= 1 ? (interp_size/2) * scale =
* 2 * scale : 2; invscale = scale >= 1 ? 1 / scale : 1;
* the output-pixel centre center = scale * (i + 0.5f);
* the taps run over xmin = max((int64)(center - support + 0.5), 0) ..
* min((int64)(center + support + 0.5), in) - 1 -- truncating casts, so a negative
* start truncates toward zero before the clamp to 0; border taps are simply absent,
* the row normalization below absorbs the lost mass;
* each tap weight is aa_filter((j + xmin - center + 0.5) * invscale), the Keys cubic
* with a = -0.5 (torch's antialias filter is the Pillow-compatible -0.5 kernel; the
* -0.75 OpenCV-compatible one belongs to the non-antialias path);
* the axis weights are normalized by their float running sum total_w, exactly as
* _compute_indices_min_size_weights_aa divides wt_ptr[j] /= total_w;
* the resize is separable: the width pass over every input row first, then the height
* pass (the order upsample_separable_Nd_kernel_impl walks the dims), each tap
* accumulating acc = (float)(acc + w * v) in float.
* Golden-checked by tests/resample_golden.py (geometries 64->40, 24->20, 8->5, 16->10,
* 16x20->10x13, and both checkpoint tables).
*/
#pragma once
#ifndef RAD_RESAMPLE_H
#define RAD_RESAMPLE_H
#include <cmath>
#include <cstdint>
#include <cstring>
#include <vector>
namespace rad {
namespace arch {
namespace resample_detail {
/* aa_filter, the Keys cubic with a = -0.5 that torch's antialias path uses (the -0.75
* OpenCV-compatible kernel belongs to the non-antialias path), in float. */
inline float cubic_aa(float x) {
const float ax = std::fabs(x);
if (ax < 1.0f) return ((1.5f * ax - 2.5f) * ax) * ax + 1.0f;
if (ax < 2.0f) return (((-0.5f * ax + 2.5f) * ax - 4.0f) * ax) + 2.0f;
return 0.0f;
}
struct Axis {
int n = 0; /* tap slots per output pixel (max_interp_size) */
std::vector<int32_t> size; /* [out] taps this output pixel reads */
std::vector<int32_t> idx; /* [out*n] input index per tap (xmin + j) */
std::vector<float> w; /* [out*n] weights, normalized by the tap sum */
};
/* One axis of _compute_indices_min_size_weights_aa, float32 expression for expression. */
inline Axis make_axis(int in, int out) {
Axis a;
const float scale = (float)((double)in / (double)out);
const float support = scale >= 1.0f ? (float)(2.0 * (double)scale) : 2.0f;
const float invscale = scale >= 1.0f ? (float)(1.0 / (double)scale) : 1.0f;
a.n = (int)std::ceil((double)support) * 2 + 1; /* max_interp_size */
a.size.resize((size_t)out, 0);
a.idx.assign((size_t)out * (size_t)a.n, 0);
a.w.assign((size_t)out * (size_t)a.n, 0.0f);
for (int i = 0; i < out; ++i) {
const float c = ((float)i + 0.5f) * scale;
int xmin = (int)(c - support + 0.5f);
if (xmin < 0) xmin = 0;
int xsize = (int)(c + support + 0.5f);
if (xsize > in) xsize = in;
xsize -= xmin;
if (xsize < 0) xsize = 0;
if (xsize > a.n) xsize = a.n;
int* idx = &a.idx[(size_t)i * (size_t)a.n];
float* w = &a.w[(size_t)i * (size_t)a.n];
float total = 0.0f;
for (int j = 0; j < xsize; ++j) {
w[j] = cubic_aa(((float)(xmin + j) - c + 0.5f) * invscale);
idx[j] = xmin + j;
total = (float)(total + w[j]);
}
a.size[i] = xsize;
if (total != 0.0f)
for (int j = 0; j < xsize; ++j) w[j] = (float)(w[j] / total);
}
return a;
}
/* One 1D resize pass. `rows` scans travel `src_row_stride` floats apart, taps step
* `tap_stride` floats along the resized axis, and outputs land at
* dst + r * dst_row_stride + i * out_stride + channel; tap order and float accumulation
* follow ATen's separable 1D resize. */
inline void resize_axis(const float* src, int64_t src_row_stride, int64_t tap_stride,
float* dst, int64_t dst_row_stride, int64_t out_stride, int rows,
const Axis& ax, int out_n, int channels) {
for (int r = 0; r < rows; ++r) {
const float* srow = src + (size_t)r * (size_t)src_row_stride;
float* drow = dst + (size_t)r * (size_t)dst_row_stride;
for (int i = 0; i < out_n; ++i) {
const int n = ax.size[i];
const int32_t* idx = &ax.idx[(size_t)i * (size_t)ax.n];
const float* w = &ax.w[(size_t)i * (size_t)ax.n];
for (int c = 0; c < channels; ++c) {
if (n == 0) { drow[(size_t)i * (size_t)out_stride + (size_t)c] = 0.0f; continue; }
float acc = (float)(srow[(size_t)idx[0] * (size_t)tap_stride + (size_t)c] * w[0]);
for (int j = 1; j < n; ++j)
acc = (float)(acc +
srow[(size_t)idx[j] * (size_t)tap_stride + (size_t)c] * w[j]);
drow[(size_t)i * (size_t)out_stride + (size_t)c] = acc;
}
}
}
}
} // namespace resample_detail
/* Resample an [in_h, in_w, channels] fp32 table (channels innermost) to
* [out_h, out_w, channels] with torch's bicubic + antialias interpolation: the width pass
* over every input row, then the height pass. Runs once at load. */
inline void resample_bicubic_aa(const float* src, int in_h, int in_w, int out_h, int out_w,
int channels, float* dst) {
if (!src || !dst || in_h <= 0 || in_w <= 0 || out_h <= 0 || out_w <= 0 || channels <= 0)
return;
if (in_h == out_h && in_w == out_w) {
std::memcpy(dst, src, (size_t)in_h * (size_t)in_w * (size_t)channels * sizeof(float));
return;
}
const resample_detail::Axis ay = resample_detail::make_axis(in_h, out_h);
const resample_detail::Axis ax = resample_detail::make_axis(in_w, out_w);
const float* work = src;
int work_w = in_w;
std::vector<float> wide;
if (in_w != out_w) { /* width pass first, the order upsample_separable_Nd walks the dims */
wide.assign((size_t)in_h * (size_t)out_w * (size_t)channels, 0.0f);
resample_detail::resize_axis(src, (int64_t)in_w * channels, channels, wide.data(),
(int64_t)out_w * channels, channels, in_h, ax, out_w,
channels);
work = wide.data();
work_w = out_w;
}
if (in_h == out_h) {
if (work != dst)
std::memcpy(dst, work, (size_t)out_h * (size_t)out_w * (size_t)channels * sizeof(float));
return;
}
/* height pass over the widened rows: one scan per output-width column */
resample_detail::resize_axis(work, channels, (int64_t)work_w * channels, dst, channels,
(int64_t)out_w * channels, work_w, ay, out_h, channels);
}
} // namespace arch
} // namespace rad
#endif // RAD_RESAMPLE_H
+8 -4
View File
@@ -2,10 +2,14 @@
* activations.
*
* Scope (aijuus/plans/UNLIMITED-OCR-PLUGIN.md): the text trunk (P1) plus the DeepEncoder vision
* tower (P2, arch/common/rad_block_sam.h: SAM ViT-B/16 at 1024 -> 16x16x1024 map -> CLIP ViT-L/14
* -> the projector -> the 273-row layout, declared with rad_declare_encoder(RAD_MM_IMAGE),
* patch_dim 768 = 3*16*16, merge 16, n_embd 1280). The tower's weights are mapped always; its ops
* and the encoder pass are declared only when SAM's `sam_attn` op resolves, because no existing op
* tower (P2, arch/common/rad_block_sam.h: SAM ViT-B/16 -> map -> CLIP ViT-L/14 -> the projector
* -> the 273-row layout of a 1024 view / 110 rows of a 640 tile, declared with
* rad_declare_encoder(RAD_MM_IMAGE), patch_dim 768 = 3*16*16, merge 16, n_embd 1280). The tower
* serves both view geometries the processor stages -- the gundam mode's 640 tiles and global
* view, and the base mode's pages -- as two op sets over the same weights, the 40 grid's absolute
* position tables bicubic+antialias resamples of the checkpoint's (arch/common/rad_resample.h).
* The tower's weights are mapped always; its ops and the encoder pass are declared only when
* SAM's `sam_attn` op resolves, because no existing op
* can carry the decomposed rel_pos_h/rel_pos_w attention bias (rad_block_sam.h's header states the
* op and why). Without it this plugin is the P1 text-only trunk and refuses images by name. The
* decoder's KV is one RAD_KV_RING group with the checkpoint's `sliding_window_size` (128), the
+14 -1
View File
@@ -119,6 +119,8 @@ int Engine::run_encodes() {
size_t i = 0;
int32_t seg = 0;
int32_t seg_grid = 0; /* the pass's view grid; a pass is one geometry (a tower refuses
a mixed one: its position tables and grids are per geometry) */
while (i < mine.size()) {
std::vector<BatchBuilder::EncoderPart> parts;
int64_t np = 0;
@@ -126,16 +128,27 @@ int Engine::run_encodes() {
mm::Item& it = *mine[i];
const int32_t first = seg;
for (; seg < it.n_seg; ++seg) {
const int32_t g = it.seg_h(seg);
/* The one-output-row view separator (core/mm marks it explicitly) belongs to
* the pass of the view before it, so it neither breaks at a "grid change" nor
* sets the pass's grid. A square segment that is a real view (a chunked line
* of one tile) keeps the ordinary geometry rule below. */
const bool sep = it.seg_is_sep(seg);
const int64_t seg_p = it.patch_at(seg + 1) - it.patch_at(seg);
if (seg_p > max_p) {
RAD_ERR("encoder: a segment of %lld patches does not fit a pass of %lld",
(long long)seg_p, (long long)max_p);
return RAD_E_STATE;
}
if (!sep && np > 0 && seg_grid != 0 && g != seg_grid) break;
if (np + seg_p > max_p) break;
np += seg_p;
if (!sep) seg_grid = g;
}
if (seg == first) {
if (seg_grid == 0) seg_grid = it.seg_h(seg); /* a lone oversized segment */
break;
}
if (seg == first) break;
parts.push_back({ &it, first, seg - first });
if (seg == it.n_seg) { ++i; seg = 0; }
}
+38 -1
View File
@@ -38,6 +38,7 @@ SamplingParams GenSampling::onto(SamplingParams base) const {
if (top_k >= 0) base.top_k = top_k;
if (ngram_ban_n >= 0) base.ngram_ban_n = ngram_ban_n;
if (ngram_window >= 0) base.ngram_window = ngram_window;
if (!ngram_whitelist.empty()) base.ngram_whitelist = ngram_whitelist;
return base;
}
@@ -57,6 +58,8 @@ std::string GenSampling::describe(const SamplingParams& sp) {
std::snprintf(ban, sizeof ban, ", ngram ban n %d over the whole sequence",
sp.ngram_ban_n);
s += ban;
if (!sp.ngram_whitelist.empty())
s += ", whitelist " + std::to_string(sp.ngram_whitelist.size()) + " ids";
}
return s;
}
@@ -124,6 +127,28 @@ bool gen_sampling_parse(const std::string& json_text, const char* src, GenSampli
const int64_t v = it->get<int64_t>();
take_i("no_repeat_ngram_window_size", src, v < 0 ? 0 : v, 0, 131072, &out->ngram_window);
}
/* The ban's whitelist, a JSON array of token ids (the reference's whitelist_token_ids).
* 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())
RAD_WARN("%s states a no_repeat_ngram_whitelist that is not an array; ignoring it",
src);
it = j.find("ngram_whitelist");
}
if (it != j.end() && it->is_array()) {
for (const auto& v : *it) {
const int64_t id = v.is_number_integer() ? v.get<int64_t>() : -1;
if (id < 0 || id > INT32_MAX) {
RAD_WARN("%s states a no_repeat_ngram_whitelist entry outside [0, %d]; ignoring it",
src, INT32_MAX);
continue;
}
out->ngram_whitelist.push_back((int)id);
}
}
return out->any();
}
@@ -142,7 +167,8 @@ bool gen_sampling_from_kv(const std::function<const char*(const char*)>& get, Ge
* file share one set of range checks and one reading of `do_sample`. */
nlohmann::json j = nlohmann::json::object();
static const char* const kFields[] = { "do_sample", "temperature", "top_p", "min_p", "top_k",
"no_repeat_ngram_size", "no_repeat_ngram_window_size" };
"no_repeat_ngram_size", "no_repeat_ngram_window_size",
"no_repeat_ngram_whitelist" };
for (const char* k : kFields) {
const char* v = get(k);
if (!v || !*v) continue;
@@ -151,6 +177,17 @@ bool gen_sampling_from_kv(const std::function<const char*(const char*)>& get, Ge
j[k] = (std::strcmp(v, "0") != 0);
continue;
}
if (std::strcmp(k, "no_repeat_ngram_whitelist") == 0) {
/* Not a number: the container's metadata is string-valued, and the whitelist is a
* JSON array spelled as JSON text. */
try {
j[k] = nlohmann::json::parse(v);
} catch (const std::exception& e) {
RAD_WARN("the container states generation.%s as \"%s\", which is not a JSON "
"array of ids (%s); ignoring it", k, v, e.what());
}
continue;
}
char* end = nullptr;
const double d = std::strtod(v, &end);
if (end == v) {
+6 -1
View File
@@ -28,10 +28,15 @@ struct GenSampling {
* no_repeat_ngram_window_size; Unlimited-OCR ships 35 over the last 128). `ngram_window` is
* normalized to 0, this sampler's "the whole sequence", when the config states it negative. */
int ngram_ban_n = -1, ngram_window = -1;
/* The ban's whitelist: token ids the ban must never ban (the reference processor's
* `whitelist_token_ids`, removed from the banned set before the -inf writes). Transformers
* has no field for it; a container states it as `generation.no_repeat_ngram_whitelist`, a
* JSON array of ids. Empty means not stated. */
std::vector<int32_t> ngram_whitelist;
bool any() const {
return temp >= 0.0f || top_p >= 0.0f || min_p >= 0.0f || top_k >= 0 ||
ngram_ban_n >= 0 || ngram_window >= 0;
ngram_ban_n >= 0 || ngram_window >= 0 || !ngram_whitelist.empty();
}
/* Overlay onto `base` field by field; unstated fields keep base's, so sources stack. */
+7 -1
View File
@@ -970,6 +970,9 @@ int uocr_mode(const VisionConfig& c, const ImageMode& mode, bool* crop, int32_t*
"patches (" + std::to_string(F) + ")");
if (bs < 4 * F)
return no("base_size " + std::to_string(bs) + " is under two output rows");
if (bs / c.patch != 64 && bs / c.patch != 40)
return no("the DeepEncoder serves base grids 64 and 40 (base_size 1024 or 640); "
"base_size " + std::to_string(bs) + " is neither");
if (mode.image_size > 0 && mode.image_size != c.tile)
return no("crop mode cuts pictures into " + std::to_string(c.tile) + "-pixel tiles; "
"image_size " + std::to_string(mode.image_size) + " is not one");
@@ -980,6 +983,9 @@ int uocr_mode(const VisionConfig& c, const ImageMode& mode, bool* crop, int32_t*
return no("image_size " + std::to_string(is) + " is not a whole number of merged patches "
"(" + std::to_string(F) + ")");
if (is < 4 * F) return no("image_size " + std::to_string(is) + " is under two output rows");
if (is / c.patch != 64 && is / c.patch != 40)
return no("the DeepEncoder serves base grids 64 and 40 (image_size 1024 or 640); "
"image_size " + std::to_string(is) + " is neither");
if (mode.base_size > 0 && mode.base_size != bs)
return no("the base mode pads a page to image_size, not base_size");
*crop = false; *base_size = bs; *image_size = is;
@@ -1101,7 +1107,7 @@ int Processor::image_unlimitedocr(const Frame& f, const ImageMode& mode,
* 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 });
it->segments.push_back({ gh, gw, it->n_patch, real_w == 0 });
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);
+4 -1
View File
@@ -229,7 +229,7 @@ struct Item {
* thumbnail): each is `h` x `w` patches starting at patch `patch0`. Empty means every segment
* is grid_h x grid_w. The rest of the engine reads segments only through the accessors below,
* so both forms look alike. */
struct Segment { int32_t h = 0, w = 0; int64_t patch0 = 0; };
struct Segment { int32_t h = 0, w = 0; int64_t patch0 = 0; bool sep = false; };
std::vector<Segment> segments;
/* The model rotates this item's tokens at their token positions (LFM2-VL's 1-D rotary), not
* on the grid the Qwen-VL family's M-RoPE lays out (RopeLayout). */
@@ -240,6 +240,9 @@ struct Item {
int32_t seg_h(int32_t s) const { return segments.empty() ? grid_h : segments[(size_t)s].h; }
int32_t seg_w(int32_t s) const { return segments.empty() ? grid_w : segments[(size_t)s].w; }
/* The one-output-row view separator (Unlimited-OCR stages it as a merge-grid cell of zeros).
* A square segment is not enough: a chunked line of one tile is q x q too. */
bool seg_is_sep(int32_t s) const { return !segments.empty() && segments[(size_t)s].sep; }
/* Segment s's first patch and first output row; s == n_seg is the end of the item. */
int64_t patch_at(int32_t s) const {
if (segments.empty()) return (int64_t)s * grid_h * grid_w;
+6
View File
@@ -596,6 +596,12 @@ struct SamplingParams {
* asks for 35 and 128 (the model card's document mode uses 1024). */
int ngram_ban_n = 0;
int ngram_window = 0;
/* The ids exempt from that ban: the reference processor's whitelist
* (SlidingWindowNoRepeatNgramProcessor's `whitelist_token_ids`, whose set is removed from
* the banned set after it is built -- modeling_unlimitedocr.py:359,379). Global token ids,
* duplicates ignored. Empty (the default) is off: the ban is then bit-identical to the
* no-whitelist form. */
std::vector<int32_t> ngram_whitelist;
};
/* Raw logits at chosen vocabulary ids at the prompt's last position, for a caller that answers
+1 -1
View File
@@ -908,7 +908,7 @@ int Ctx::lane_join(int from, int to) {
* field added to RadBatch changes its size: decide whether the key must read it, then update the
* size here. `agen_b` and `vgen_b` are set only on generator passes, which are never recorded
* (below). */
static_assert(sizeof(void*) != 8 || sizeof(RadBatch) == 336,
static_assert(sizeof(void*) != 8 || sizeof(RadBatch) == 352,
"RadBatch changed: check that Ctx::pass_key reads every new field a pass depends on");
static_assert(sizeof(void*) != 8 || sizeof(RadKVGroupBatch) == 72,
"RadKVGroupBatch changed: check that Ctx::pass_key reads every new field");
+18 -2
View File
@@ -528,7 +528,7 @@ int32_t host_argmax(const float* logits, int64_t n_vocab) {
}
void host_ngram_ban(CandidateSet& s, const int32_t* history, int64_t n_history, int32_t n,
int32_t window) {
int32_t window, const uint32_t* whitelist, int64_t wl_words) {
if (n <= 0 || !history || n_history < (int64_t)n) return;
const int64_t len = n_history;
const int64_t win = (window > 0 && window < len) ? window : len;
@@ -547,6 +547,21 @@ void host_ngram_ban(CandidateSet& s, const int32_t* history, int64_t n_history,
}
if (match) banned.insert(history[idx + plen]);
}
/* The reference's `banned.difference_update(self.whitelist)`, before any -inf: a token whose
* whitelist bit is set is never banned. A bit past the plane is not set, so a token outside
* it stays banned, as an id the reference's set does not contain. */
if (whitelist && wl_words > 0) {
for (auto it = banned.begin(); it != banned.end();) {
const int64_t id = *it;
if (id >= 0 && (id >> 5) < wl_words &&
(whitelist[(size_t)(id >> 5)] >> ((uint32_t)id & 31u)) & 1u)
it = banned.erase(it);
else
++it;
}
}
if (banned.empty()) return;
s.sorted = false; /* a -infinity candidate belongs after every finite one */
for (Candidate& c : s.c)
@@ -575,7 +590,8 @@ int32_t host_sample_into(CandidateSet& s, const SamplingParams& sp, const HostRe
/* The n-gram ban, after the penalties and before the greedy split: the device chain issues it
* there, so a greedy request sees the same masked distribution. Off at ngram_ban_n 0. */
host_ngram_ban(s, in.history, in.n_history, sp.ngram_ban_n, sp.ngram_window);
host_ngram_ban(s, in.history, in.n_history, sp.ngram_ban_n, sp.ngram_window,
in.ngram_whitelist, in.ngram_whitelist_words);
/* Greedy skips the chain: penalties -> mask -> argmax. Temperature 0 collapses every other
* logit to -inf, so a mask applied after it could leave nothing. */
+11 -2
View File
@@ -181,9 +181,14 @@ void host_xtc(CandidateSet& s, float probability, float threshold, size_t min_ke
* SlidingWindowNoRepeatNgramProcessor): a candidate whose token would complete an `n`-gram the
* last `window` tokens of `history` already contain gets -infinity. `n` <= 0 is off, `window` <= 0
* is the whole history. It runs after the penalties and DRY and before every cut, so the greedy
* path sees it too. */
* path sees it too.
*
* `whitelist` is the reference's whitelist (a SET bit means exempt from the ban, the same plane
* form as host_mask's, word w bit b covering token 32w + b): ids removed from the banned set
* before anything is written, as `banned.difference_update(self.whitelist)` does. Null or zero
* words is off -- the reference's empty whitelist, the default serving form. */
void host_ngram_ban(CandidateSet& s, const int32_t* history, int64_t n_history, int32_t n,
int32_t window);
int32_t window, const uint32_t* whitelist = nullptr, int64_t wl_words = 0);
/* The grammar mask. One bit per token, set means admissible; a cleared bit sets the logit to -inf
* instead of removing the candidate, so nothing downstream is renumbered. `n_words` is
@@ -224,6 +229,10 @@ struct HostRefInput {
int64_t total_context = 0; /* DRY's clamp; 0 means use n_history */
const uint32_t* bitmask = nullptr; /* grammar mask, or null */
int64_t n_words = 0;
/* The n-gram ban's whitelist bitmask (a SET bit exempts a token, host_ngram_ban), null =
* no exemptions. */
const uint32_t* ngram_whitelist = nullptr;
int64_t ngram_whitelist_words = 0;
uint64_t pos = 0; /* output position: the RNG's second coordinate */
const DryBreakers* dry_breakers = nullptr; /* null runs DRY with no breakers */
/* The chain's candidate width (SamplerConfig::max_candidates): top-k narrows every row to
+43 -7
View File
@@ -181,6 +181,9 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) {
/* The n-gram ban's per-row {n-gram length, window}. Its own tiny plane because the params row
* is the fixed RadSampleParams wire format every sampler op shares. */
buf_ngram_ = decl("sampler.ngram", RAD_I32, rows, 2, RAD_BUF_PERSIST);
/* The ban's whitelist bitmask, this rank's shard, shaped like the mask plane: a SET bit
* exempts that column. The ban op indexes it by the sampled row, not by mask_row. */
buf_ngram_wl_ = decl("sampler.ngram_wl", RAD_U32, rows, mask_words_, RAD_BUF_PERSIST);
buf_mask_ = decl("sampler.mask", RAD_U32, rows, mask_words_, RAD_BUF_PERSIST);
buf_cand_i_ = decl("sampler.cand_idx", RAD_I32, rows, ncand, RAD_BUF_TRANSIENT);
buf_cand_v_ = decl("sampler.cand_val", RAD_F32, rows, ncand, RAD_BUF_TRANSIENT);
@@ -200,7 +203,8 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) {
buf_lp_g_ = decl("sampler.logprobs_gathered", RAD_F32, rows,
lp_width() * cfg_.world_size, RAD_BUF_PERSIST);
if (!buf_params_ || !buf_params_late_ || !buf_hist_ || !buf_brk_ || !buf_ngram_ || !buf_mask_ ||
if (!buf_params_ || !buf_params_late_ || !buf_hist_ || !buf_brk_ || !buf_ngram_ ||
!buf_ngram_wl_ || !buf_mask_ ||
!buf_cand_i_ || !buf_cand_v_ || !buf_lp_ ||
(vocab_parallel() && (!buf_pairs_ || !buf_gather_ || !buf_lp_g_))) {
RAD_ERR("sampler: a staging buffer failed to declare");
@@ -325,6 +329,7 @@ int Sampler::stage_alloc() {
hist_stage_ = (int32_t*)rad_dev_alloc(rows * cfg_.max_hist * 4, RAD_MEM_HOST_PINNED);
brk_stage_ = (uint8_t*)rad_dev_alloc(rows * cfg_.max_hist, RAD_MEM_HOST_PINNED);
ngram_stage_ = (int32_t*)rad_dev_alloc(rows * 2 * 4, RAD_MEM_HOST_PINNED);
ngram_wl_stage_ = (uint32_t*)rad_dev_alloc(rows * mask_words_ * 4, RAD_MEM_HOST_PINNED);
mask_stage_ = (uint32_t*)rad_dev_alloc(rows * mask_words_ * 4, RAD_MEM_HOST_PINNED);
/* Logprobs readback; only rank 0 reads it. */
@@ -342,10 +347,10 @@ int Sampler::stage_alloc() {
}
if (!params_stage_ || !greedy_stage_ || !late_stage_ || !hist_stage_ || !brk_stage_ ||
!ngram_stage_ || !mask_stage_) {
!ngram_stage_ || !ngram_wl_stage_ || !mask_stage_) {
RAD_ERR("sampler: could not pin %s of staging",
humanb(rows * (3 * (int64_t)sizeof(DeviceSampleParams) + cfg_.max_hist * 5 +
mask_words_ * 4 + 8)).c_str());
mask_words_ * 8 + 8)).c_str());
stage_free();
return RAD_E_NOMEM;
}
@@ -358,7 +363,8 @@ void Sampler::stage_free() {
if (late_stage_) rad_dev_free(late_stage_, RAD_MEM_HOST_PINNED);
if (hist_stage_) rad_dev_free(hist_stage_, RAD_MEM_HOST_PINNED);
if (brk_stage_) rad_dev_free(brk_stage_, RAD_MEM_HOST_PINNED);
if (ngram_stage_) rad_dev_free(ngram_stage_, RAD_MEM_HOST_PINNED);
if (ngram_stage_) rad_dev_free(ngram_stage_, RAD_MEM_HOST_PINNED);
if (ngram_wl_stage_) rad_dev_free(ngram_wl_stage_, RAD_MEM_HOST_PINNED);
if (mask_stage_) rad_dev_free(mask_stage_, RAD_MEM_HOST_PINNED);
if (lp_host_) rad_dev_free(lp_host_, RAD_MEM_HOST_PINNED);
if (lp_ci_host_) rad_dev_free(lp_ci_host_, RAD_MEM_HOST_PINNED);
@@ -372,7 +378,8 @@ void Sampler::stage_free() {
cur_stage_ = nullptr;
hist_stage_ = nullptr;
brk_stage_ = nullptr;
ngram_stage_ = nullptr;
ngram_stage_ = nullptr;
ngram_wl_stage_ = nullptr;
mask_stage_ = nullptr;
}
@@ -604,6 +611,7 @@ int Sampler::build_step(const std::vector<Request*>& reqs) {
any_brk_ = false;
any_late_ = false;
any_ngram_ = false;
any_ngram_wl_ = false;
cur_stage_ = params_stage_;
lp_rows_.clear();
@@ -724,6 +732,21 @@ int Sampler::build_step(const std::vector<Request*>& reqs) {
ngram_stage_[2 * row] = (int32_t)sp.ngram_ban_n;
ngram_stage_[2 * row + 1] = (int32_t)sp.ngram_window;
/* The ban's whitelist, cut to this rank's shard like the grammar mask (shard_mask):
* global ids outside it exempt nothing here. Every row that runs the ban gets its
* words freshly written -- the plane is uploaded whole with the ban, so a row must
* never read another request's stale exemptions. */
if (ngram) {
uint32_t* w = ngram_wl_stage_ + row * mask_words_;
std::memset(w, 0, (size_t)mask_words_ * 4);
for (int32_t id : sp.ngram_whitelist) {
const int64_t at = (int64_t)id - cfg_.vocab_off;
if (at < 0 || at >= cfg_.n_vocab_local) continue;
w[at >> 5] |= 1u << (uint32_t)(at & 31);
any_ngram_wl_ = true;
}
}
/* Greedy over a split vocabulary is a top-1 chain row, not an argmax: sample_argmax
* writes a column of this rank's shard, not a token id. Top-k plus the merge produce
* global ids, and the pick over one candidate is deterministic. A greedy row asking
@@ -916,11 +939,14 @@ int Sampler::build_greedy(int64_t n) {
any_brk_ = false;
any_late_ = false;
any_ngram_ = false;
any_ngram_wl_ = false;
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. */
* 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. */
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];
@@ -986,9 +1012,14 @@ int Sampler::run(RadCtx* c, rad_buf logits, rad_buf out_tokens) {
if (pass_brk)
RAD_TRY(rad_memcpy_async(rad_buf_ptr(c, buf_brk_), brk_stage_,
n_seq_ * cfg_.max_hist, s));
/* The ban's whitelist rides with the ban, and only a row that runs the ban reads it. */
const bool pass_wl = any_ngram && any_ngram_wl_;
if (any_ngram)
RAD_TRY(rad_memcpy_async(rad_buf_ptr(c, buf_ngram_), ngram_stage_,
n_seq_ * 2 * (int64_t)sizeof(int32_t), s));
if (pass_wl)
RAD_TRY(rad_memcpy_async(rad_buf_ptr(c, buf_ngram_wl_), ngram_wl_stage_,
n_seq_ * mask_words_ * 4, s));
if (any_mask)
RAD_TRY(rad_memcpy_async(rad_buf_ptr(c, buf_mask_), mask_stage_,
n_seq_ * mask_words_ * 4, s));
@@ -998,6 +1029,7 @@ int Sampler::run(RadCtx* c, rad_buf logits, rad_buf out_tokens) {
const RadOperand o_hist = opd_rows(buf_hist_, n_seq_);
const RadOperand o_brk = opd_rows(buf_brk_, n_seq_);
const RadOperand o_ngram = opd_rows(buf_ngram_, n_seq_);
const RadOperand o_ngram_wl = opd_rows(buf_ngram_wl_, n_seq_);
const RadOperand o_mask = opd_rows(buf_mask_, n_seq_);
const RadOperand o_ci = opd_rows(buf_cand_i_, n_seq_);
const RadOperand o_cv = opd_rows(buf_cand_v_, n_seq_);
@@ -1030,7 +1062,11 @@ int Sampler::run(RadCtx* c, rad_buf logits, rad_buf out_tokens) {
* below as well as for the chain, which is the reference processor's effect on the
* distribution. Off (the default) the op is not issued at all, so a request without it
* samples exactly as before. */
if (any_ngram) RAD_TRY(issue(op_ngram_ban_, { o_logits, o_params, o_hist, o_ngram }));
/* The whitelist operand is passed only when some staged row carries exemptions; absent
* means nothing is exempt, the reference's empty whitelist and the bit-identical default. */
if (any_ngram)
RAD_TRY(issue(op_ngram_ban_, { o_logits, o_params, o_hist, o_ngram,
pass_wl ? o_ngram_wl : opd_none() }));
/* Greedy rows take the argmax after penalties and the mask. In a mixed batch both the argmax
* and the chain run over the whole batch: the argmax writes every row, then the candidate
+12 -2
View File
@@ -48,7 +48,8 @@
* sample_penalties M(range) n_vocab vocab_off? logits, params, history -> logits (inout)
* sample_dry M(range) n_vocab vocab_off? logits, params, history, breakers?
* -> logits (inout)
* sample_ngram_ban M(range) n_vocab vocab_off? logits, params, history, ngram
* sample_ngram_ban M(range) n_vocab vocab_off? logits, params, history, ngram,
* whitelist?
* -> logits (inout)
* sample_temp M(range) n_vocab logits, params -> logits (inout)
* sample_mask M(range) n_vocab logits, params, bitmask -> logits (inout)
@@ -67,7 +68,9 @@
* a verify. `params` is [M] DeviceSampleParams rows. `history` is [M, max_hist] int32 global
* token ids, row m addressed by its hist_off/hist_len. `breakers` is [M, max_hist] uint8 beside
* it, nonzero where that token is a whole DRY sequence breaker. `bitmask` is [M, mask_words]
* uint32, addressed by the row's mask_row. `vocab_off` is this rank's first vocabulary row,
* uint32, addressed by the row's mask_row. The ban's `whitelist` is a [M, mask_words] uint32
* bitmask (a SET bit exempts that column from the ban) addressed by the row itself, absent when
* no staged row carries one. `vocab_off` is this rank's first vocabulary row,
* declared only when the vocabulary is split; the three ops that map between token ids and this
* rank's logit columns use it. Every op has a libref implementation, which is both its fallback
* and its oracle (spec §17).
@@ -259,6 +262,9 @@ private:
rad_buf buf_hist_ = RAD_NULL_HANDLE;
rad_buf buf_brk_ = RAD_NULL_HANDLE; /* DRY's single-token breaker marks, beside history */
rad_buf buf_ngram_ = RAD_NULL_HANDLE; /* the n-gram ban's {n, window} pair a row */
/* The ban's whitelist bitmask, [rows, mask_words] like the grammar mask plane: a SET bit
* exempts that column from the ban. Uploaded with the ban, only when a staged row has one. */
rad_buf buf_ngram_wl_ = RAD_NULL_HANDLE;
rad_buf buf_mask_ = RAD_NULL_HANDLE;
rad_buf buf_cand_i_ = RAD_NULL_HANDLE;
rad_buf buf_cand_v_ = RAD_NULL_HANDLE;
@@ -283,6 +289,7 @@ private:
int32_t* hist_stage_ = nullptr;
uint8_t* brk_stage_ = nullptr;
int32_t* ngram_stage_ = nullptr; /* [rows][2]: n-gram length, window */
uint32_t* ngram_wl_stage_ = nullptr; /* [rows][mask_words] exemption bitmask */
uint32_t* mask_stage_ = nullptr;
int64_t mask_words_ = 0; /* words for this rank's shard; what the mask op indexes */
@@ -293,6 +300,9 @@ private:
/* Whether any row this step runs the n-gram ban. Its history is the plane the penalties use,
* so this only decides whether that plane is uploaded and the op issued. */
bool any_ngram_ = false;
/* Whether any banned row this step whitelists a column of this rank's shard; only then is
* the exemption plane uploaded and passed to sample_ngram_ban. */
bool any_ngram_wl_ = false;
/* The whole-vocabulary mask the grammar fills, from which this rank's shard is cut. Used
* only when the head is sharded; see declare(). */
+8
View File
@@ -1164,6 +1164,8 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
B.enc_n_seg = 0;
B.enc_cu = nullptr;
B.enc_max_seg = 0;
B.enc_seg_h = nullptr;
B.enc_seg_w = nullptr;
B.n_checkpoints = n_ck;
B.checkpoint_tok = n_ck ? on_rank(base, b0, s.d_cktok) : nullptr;
B.checkpoint_slot = n_ck ? on_rank(base, b0, s.d_ckslot) : nullptr;
@@ -1232,6 +1234,8 @@ const RadBatch* BatchBuilder::build_encoder(const std::vector<EncoderPart>& part
const int64_t max_segs = enc.max_patches / (enc.merge > 0 ? enc.merge : 1) + 1;
int64_t n_patch = 0, n_seg = 0, max_seg = 0;
enc_cu_host_[0] = 0;
enc_seg_h_host_.clear();
enc_seg_w_host_.clear();
for (const EncoderPart& p : parts) {
const mm::Item& it = *p.item;
if (p.seg0 < 0 || p.n_seg <= 0 || p.seg0 + p.n_seg > it.n_seg) {
@@ -1254,6 +1258,8 @@ const RadBatch* BatchBuilder::build_encoder(const std::vector<EncoderPart>& part
for (int32_t q = p.seg0; q < p.seg0 + p.n_seg; ++q) {
const int64_t seg_p = it.patch_at(q + 1) - it.patch_at(q);
enc_cu_host_[n_seg + 1] = enc_cu_host_[n_seg] + (int32_t)seg_p;
enc_seg_h_host_.push_back(it.seg_h(q));
enc_seg_w_host_.push_back(it.seg_w(q));
++n_seg;
if (seg_p > max_seg) max_seg = seg_p;
}
@@ -1300,6 +1306,8 @@ const RadBatch* BatchBuilder::build_encoder(const std::vector<EncoderPart>& part
B.enc_n_seg = n_seg;
B.enc_cu = static_cast<const int32_t*>(enc_cu_dev_[r]);
B.enc_max_seg = (int32_t)max_seg;
B.enc_seg_h = enc_seg_h_host_.data();
B.enc_seg_w = enc_seg_w_host_.data();
}
out_last_ = out_next_;
out_next_ = (out_next_ + 1) % kOut;
+3
View File
@@ -333,6 +333,9 @@ private:
int32_t* enc_coord_host_ = nullptr;
int32_t* enc_cu_host_ = nullptr;
std::vector<int32_t> enc_coord_tmp_; /* one item's coordinates; kept for its capacity */
/* The pass's per-segment grid, host side (RadBatch::enc_seg_h/w). Filled by build_encoder and
* valid until the next build, like the staged coordinates. */
std::vector<int32_t> enc_seg_h_host_, enc_seg_w_host_;
int64_t last_n_tok_ = 0;
struct MediaBytes { int64_t mm = 0, pix = 0, crd = 0, cu = 0; };
MediaBytes media_bytes(); /* the four per-rank device regions alloc_media reserves */
+29 -1
View File
@@ -240,7 +240,7 @@ const char* kAcceptedCommon[] = {
"dry_sequence_breakers", "samplers",
"grammar", "json_schema", "priority", "logprobs", "ignore_eos",
"timings_per_token", "return_progress", "session_id", "n_probs",
"ngram_ban_n", "ngram_window",
"ngram_ban_n", "ngram_window", "ngram_whitelist", "no_repeat_ngram_whitelist",
};
const char* kAcceptedChat[] = {
@@ -916,6 +916,34 @@ static int parse_sampling(const json& b, const OaiLimits& lim, OaiRequest* r, Ap
}
r->sp.ngram_window = (int)i64;
/* The ban's whitelist (the reference's `whitelist_token_ids`, which is removed from the
* banned set before the -inf writes): token ids the ban must never touch. An array of
* non-negative integers; absent, empty or null is off, the reference's empty whitelist and
* the form the model's generation_config ships. */
auto nwl = b.find("ngram_whitelist");
if (nwl == b.end()) nwl = b.find("no_repeat_ngram_whitelist");
if (nwl != b.end() && !nwl->is_null()) {
if (!nwl->is_array()) {
*err = err_bad("ngram_whitelist", "expected an array of integer token ids");
return RAD_E_INVAL;
}
std::vector<int32_t> wl;
for (const auto& v : *nwl) {
int32_t id = 0;
if (!token_id(v, &id)) {
*err = err_bad("ngram_whitelist",
"expected token ids in [0, " + std::to_string(INT32_MAX) + "]");
return RAD_E_INVAL;
}
if (wl.size() >= (size_t)1 << 20) {
*err = err_bad("ngram_whitelist", "at most 1048576 ids");
return RAD_E_INVAL;
}
wl.push_back(id);
}
r->sp.ngram_whitelist = std::move(wl);
}
/* `images_config`: Unlimited-OCR's two picture modes. A string names one ("gundam" for a
* single picture -- the global view plus crops --, "base" for a page of a multi-page
* document); an object carries the reference runner's own dict. */
+11
View File
@@ -1228,6 +1228,17 @@ so that is what a request sending neither field gets:
{"messages": [...], "ngram_ban_n": 35, "ngram_window": 128}
```
**The ban's whitelist** (`ngram_whitelist` in a request, alias `no_repeat_ngram_whitelist`;
`generation.no_repeat_ngram_whitelist` in the container and in a `generation_config.json`, a JSON
array of ids) names token ids the ban must never ban: the reference processor removes them from
the banned set before it blocks anything (`banned.difference_update(whitelist)`). Absent, null and
empty all mean off -- the reference's empty whitelist, the form this checkpoint ships -- and off is
bit-identical to a ban without the feature. There is no command-line flag.
```json
{"messages": [...], "ngram_ban_n": 35, "ngram_window": 128, "ngram_whitelist": [151645, 151644]}
```
**The rest of the sampler** has a flag per field, spelled like the request field:
`--presence-penalty`, `--frequency-penalty`, `--repetition-penalty`, `--repeat-last-n`,
`--typical-p`, `--dry-multiplier`, `--dry-base`, `--dry-allowed-length`, `--dry-penalty-last-n`,
+1 -1
View File
@@ -2382,7 +2382,7 @@ the usual rescale, pairs by value).
| op | params | operands |
|---|---|---|
| `sample_dry` | `M` `n_vocab` `vocab_off`/opt | `logits`:inout, `params`, `history`, `breakers`? |
| `sample_ngram_ban` | `M` `n_vocab` `vocab_off`/opt | `logits`:inout, `params`, `history`, `ngram` |
| `sample_ngram_ban` | `M` `n_vocab` `vocab_off`/opt | `logits`:inout, `params`, `history`, `ngram`, `whitelist`? |
| `sample_typical` | `M` `n_cand` | `cand_idx`:inout, `cand_val`:inout, `params` |
| `sample_xtc` | `M` `n_cand` | `cand_idx`:inout, `cand_val`:inout, `params` |
| `sample_chain` | `M` `n_vocab` `temp`:f64/opt `p`:f64/opt `min_p`:f64/opt `k`/opt | `logits`, `query`?, `u` → `draw` |
+5 -2
View File
@@ -783,8 +783,10 @@ static const RadParamSpec pPenal[] = { P_INT("M"), P_INT("n_vocab"), P_INTO("vo
static const RadOperandSpec oPenalties[] = { INOUT("logits"), OPD("params"), OPD("history") };
static const RadOperandSpec oDry[] = { INOUT("logits"), OPD("params"), OPD("history"),
OPD_O("breakers") };
/* `whitelist` is optional, libref's: a bitmask plane a row, a SET bit exempting a token from
* the ban. Absent, nothing is exempt. */
static const RadOperandSpec oNgramBan[] = { INOUT("logits"), OPD("params"), OPD("history"),
OPD("ngram") };
OPD("ngram"), OPD_O("whitelist") };
static const RadOperandSpec oTemp[] = { INOUT("logits"), OPD("params") };
static const RadOperandSpec oMask[] = { INOUT("logits"), OPD("params"), OPD("bitmask") };
static const RadParamSpec pTopk[] = { P_INT("M"), P_INT("n_vocab"), P_INTO("vocab_off") };
@@ -1225,7 +1227,8 @@ static const RadOpSchema kSchemas[] = {
{ "sample_ngram_ban", ARR(pPenal), ARR(oNgramBan),
"the windowed no-repeat-ngram ban: every token completing an n-gram the last `window` tokens of "
"the row's history contain is set to -infinity. `ngram` is an i32 {n, window} pair a row; n 0 "
"is off." },
"is off. The optional `whitelist` bitmask exempts a token whose column bit is set; absent, "
"nothing is exempt." },
{ "sample_temp", ARR(pMVocab), ARR(oTemp), "per-request temperature." },
{ "sample_topk", ARR(pTopk), ARR(oTopk), "exact top-k candidate set, descending, ties to the "
"lower id." },
+16 -1
View File
@@ -237,10 +237,15 @@ AVX_KERNEL(sample_dry) {
*
* The work is integer comparisons over at most a window of history, so the rows are parallel and
* the scan inside a row stays scalar: libref's own loop, bit for bit. A row with n 0 (the
* default) is skipped before it reads anything. */
* default) is skipped before it reads anything.
*
* The optional `whitelist` bitmask (a SET bit, the row's own plane row) exempts a token from
* the ban, the reference's `banned.difference_update(self.whitelist)`; absent, nothing is
* exempt, and the result is bit-for-bit the ban without it. */
AVX_KERNEL(sample_ngram_ban) {
if (!rad_args_have(a, 4)) return RAD_E_INVAL;
const RadTensor *lg = &a->t[0], *pr = &a->t[1], *hist = &a->t[2], *ng = &a->t[3];
const RadTensor* wl = rad_arg_in(a, 4);
const int64_t n_vocab = p_int(a, "n_vocab", lg->rank >= 2 ? lg->shape[lg->rank - 1] : 0);
if (n_vocab <= 0) return RAD_E_SHAPE;
const int64_t M = numel(lg) / n_vocab;
@@ -251,6 +256,9 @@ AVX_KERNEL(sample_ngram_ban) {
if (hmax <= 0) return RAD_E_SHAPE;
if (numel(ng) < 2 * M) return RAD_E_SHAPE;
const int64_t voff = p_int(a, "vocab_off", 0);
const int64_t wwords = (n_vocab + 31) / 32;
if (wl && wl->dtype != RAD_I32 && wl->dtype != RAD_U32) return RAD_E_DTYPE;
if (wl && numel(wl) < M * wwords) return RAD_E_SHAPE;
AVX_PARALLEL_FOR_IF(M >= 2)
for (int64_t m = 0; m < M; ++m) {
@@ -271,7 +279,13 @@ AVX_KERNEL(sample_ngram_ban) {
const int64_t hb = rowoff(hist, m, hmax) + ho * laststride(hist);
const int64_t hs = laststride(hist);
const int64_t lb = rowoff(lg, m, n_vocab), ls = laststride(lg);
const int64_t wb = wl ? rowoff(wl, m, wwords) : 0, ws = wl ? laststride(wl) : 0;
auto tok_at = [&](int64_t i) { return (int64_t)(int32_t)ldi(hist, hb + i * hs); };
auto exempt = [&](int64_t col) {
if (!wl) return false;
const uint32_t word = (uint32_t)ldi(wl, wb + (col / 32) * ws);
return ((word >> (uint32_t)(col % 32)) & 1u) != 0u;
};
const int64_t plen = n - 1, p0 = hl - plen;
for (int64_t idx = search_start; idx < search_end; ++idx) {
@@ -283,6 +297,7 @@ AVX_KERNEL(sample_ngram_ban) {
const int64_t tok = tok_at(idx + plen);
const int64_t col = tok - voff;
if (tok < 0 || col < 0 || col >= n_vocab) continue;
if (exempt(col)) continue;
stt(lg, lb + col * ls, -INFINITY);
}
}
+19 -13
View File
@@ -2114,11 +2114,15 @@ static const RadOperandSpec oDry[] = {
/* The n-gram ban's own plane: one i32 {n-gram length, window} pair a row (n 0 = off, window <= 0
* = the whole staged history). A plane beside `params` rather than fields in it, because the
* params row is the fixed 24-word RadSampleParams every sampler op shares. */
/* `whitelist` is optional: a bitmask plane a row (a SET bit exempts that column from the ban,
* the reference's whitelist), [M, ceil(n_vocab/32)] i32/u32, contiguous. Absent, nothing is
* exempt. */
static const RadOperandSpec oNgramBan[] = {
{ "logits", RAD_OPD_INOUT, 0 },
{ "params", RAD_OPD_IN, 0 },
{ "history", RAD_OPD_IN, 0 },
{ "ngram", RAD_OPD_IN, 0 },
{ "logits", RAD_OPD_INOUT, 0 },
{ "params", RAD_OPD_IN, 0 },
{ "history", RAD_OPD_IN, 0 },
{ "ngram", RAD_OPD_IN, 0 },
{ "whitelist", RAD_OPD_IN, 1 },
};
static const RadOperandSpec oTemp[] = {
{ "logits", RAD_OPD_INOUT, 0 },
@@ -2838,10 +2842,12 @@ static const RadOpSchema kSchemas[] = {
"occurred before, by its longest such repeat -- what stops a model looping on a phrase "
"rather than on a token. Tokens the breaker plane marks are exempt."),
SCHEMA("sample_ngram_ban", pPenal, oNgramBan,
"the windowed no-repeat-ngram ban: every token completing an n-gram the last `window` "
"tokens of the row's history contain is set to -infinity. `ngram` is one i32 "
"{n, window} pair a row; the window bounds the n-gram's START index, as in the "
"reference, window <= 0 searches the whole span and n 0 is off."),
"the windowed no-repeat-ngram ban: every token completing an n-gram the last `window` "
"tokens of the row's history contain is set to -infinity. `ngram` is one i32 "
"{n, window} pair a row; the window bounds the n-gram's START index, as in the "
"reference, window <= 0 searches the whole span and n 0 is off. The optional "
"`whitelist` bitmask exempts a token whose column bit is set; absent, nothing is "
"exempt."),
SCHEMA("sample_temp", pMVocab, oTemp,
"per-request temperature. temp <= 0 leaves the row untouched; greedy is sample_argmax."),
SCHEMA("sample_mask", pMVocab, oMask,
@@ -3860,9 +3866,9 @@ static const RadConstraint cAttnDenseH64[] = {
C_EQ("head_dim", 64), C_EQ("gqa", 1), C_IN("dtype", "bf16"),
};
/* Unlimited-OCR's SAM tower (r4d_sam_attn_bf16.hip): one block per (segment, tile, head), a thread
* a query row, q and the output accumulator in registers; only head_dim 64 is instantiated and the
* tables must be exactly 2*tile-1 rows (a geometry needing get_rel_pos's resampling is libref's
* and libavx's). */
* a query row, q and the output accumulator in registers; only head_dim 64 is instantiated and a
* rel_pos table that is not 2*tile-1 rows is linear-resampled on read (get_rel_pos), so the 127-row
* global tables serve a 40-grid block as 79 rows. */
static const RadConstraint cSamAttn[] = {
C_EQ("head_dim", 64), C_IN("dtype", "bf16"),
};
@@ -6361,8 +6367,8 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
{ "sam_attn_bf16", "sam_attn", "attn",
"Unlimited-OCR's SAM tower attention: windowed tiles with a decomposed relative-position term",
"head_dim 64; any grid, window and segment count (a segment is one grid_h*grid_w); q/k/v/out at "
"their own row pitch (column slices of one fused projection); rel_pos tables exactly 2*tile-1 "
"rows (a geometry needing get_rel_pos's resampling is libref's and libavx's)",
"their own row pitch (column slices of one fused projection); rel_pos tables of any row count "
">= 1 (a table that is not 2*tile-1 rows is linear-resampled on read)",
"bf16 query / key / value / out and rel_pos tables, i32 cu_seqlens, fp32 accumulate",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cSamAttn), NOTUNE,
+44 -18
View File
@@ -17,9 +17,10 @@
// row is computed once per (query row, tile row) rather than once per key.
//
// Head widths. HD is a template parameter and only 64 is instantiated (SAM ViT-B's 12 x 64); the
// shim refuses any other width rather than reading past the registers. The tables must be exactly
// 2*tile-1 rows, which every geometry the tower declares is; the shim declines a table that would
// need get_rel_pos's resampling (libref and libavx serve that).
// shim refuses any other width rather than reading past the registers. A table whose row count is
// not 2*tile-1 is resampled on read (get_rel_pos's F.interpolate(size=want, mode="linear",
// align_corners=False) in f32): the 127-row global tables give 79 rows at a 40 grid, and every
// other geometry the tower declares already has exactly the rows it wants.
//
// Exactness. f32 throughout, one bf16 rounding of the output, exp2 (the hardware transcendental)
// with the log2(e) factor; the selftest holds it to the house tolerance against a host port of the
@@ -35,12 +36,41 @@ namespace {
constexpr uint32_t kThreads = 128;
constexpr float kLog2e = 1.4426950408889634f;
/* q . row(d) of a rel_pos table as the reference resized it to `want` rows: linear interpolation
* between the two source rows at align_corners=False's coordinate, clamped at the edges. With
* rows == want the source is row d itself (f == 0), so the direct read is unchanged bit for bit. */
template <int HD>
__device__ inline float tab_dot(const uint16_t* __restrict__ tab, int rows, int want, int d,
const float* qf) {
if (rows == want) {
const uint16_t* rp = tab + (size_t)d * HD;
float s = 0.0f;
#pragma unroll
for (int c = 0; c < HD; ++c) s += qf[c] * bf16_to_f32(rp[c]);
return s;
}
double src = ((double)d + 0.5) * (double)rows / (double)want - 0.5;
if (src < 0.0) src = 0.0;
if (src > (double)(rows - 1)) src = (double)(rows - 1);
const int i0 = (int)src, i1 = i0 + 1 < rows ? i0 + 1 : i0;
const float f = (float)(src - (double)i0);
const uint16_t* a = tab + (size_t)i0 * HD;
const uint16_t* b = tab + (size_t)i1 * HD;
float s = 0.0f;
#pragma unroll
for (int c = 0; c < HD; ++c) {
const float av = bf16_to_f32(a[c]);
s += qf[c] * (av + (bf16_to_f32(b[c]) - av) * f);
}
return s;
}
template <int HD>
__global__ __launch_bounds__(kThreads) void sam_attn_kernel(
const uint16_t* __restrict__ gq, const uint16_t* __restrict__ gk,
const uint16_t* __restrict__ gv, uint16_t* __restrict__ go,
const int* __restrict__ cu, const uint16_t* __restrict__ rh,
const uint16_t* __restrict__ rw,
const uint16_t* __restrict__ rw, int rh_rows, int rw_rows,
int q_ld, int k_ld, int v_ld, int o_ld, int nhead, int gh, int gw, int th, int tw,
int nth, int ntw, float scale) {
// blockIdx.x = ((seq * nth + ty) * ntw + tx) * nhead + head: heads adjacent, so the tile's k/v
@@ -72,18 +102,12 @@ __global__ __launch_bounds__(kThreads) void sam_attn_kernel(
float m = -INFINITY, l = 0.0f;
for (int jh = 0; jh < th; ++jh) {
const uint16_t* hrp = rh + (size_t)(lh - jh + th - 1) * HD;
float hr = 0.0f;
#pragma unroll
for (int c = 0; c < HD; ++c) hr += qf[c] * bf16_to_f32(hrp[c]);
const float hr = tab_dot<HD>(rh, rh_rows, 2 * th - 1, lh - jh + th - 1, qf);
const int kh = ty * th + jh;
const bool hreal = kh < gh;
for (int jw = 0; jw < tw; ++jw) {
const uint16_t* wrp = rw + (size_t)(lw - jw + tw - 1) * HD;
float s = hr;
#pragma unroll
for (int c = 0; c < HD; ++c) s += qf[c] * bf16_to_f32(wrp[c]);
float s = hr + tab_dot<HD>(rw, rw_rows, 2 * tw - 1, lw - jw + tw - 1, qf);
const int kw = tx * tw + jw;
const bool real = hreal && kw < gw;
@@ -124,6 +148,7 @@ __global__ __launch_bounds__(kThreads) void sam_attn_kernel(
int launch_sam_attn(const uint16_t* q, const uint16_t* k, const uint16_t* v, uint16_t* o,
const int* cu, const uint16_t* rh, const uint16_t* rw,
int rh_rows, int rw_rows,
int q_ld, int k_ld, int v_ld, int o_ld, int nseq, int nhead, int gh, int gw,
int win, float scale, long stream) {
const int th = win > 0 ? win : gh, tw = win > 0 ? win : gw;
@@ -131,8 +156,8 @@ int launch_sam_attn(const uint16_t* q, const uint16_t* k, const uint16_t* v, uin
const size_t blocks = (size_t)nseq * nth * ntw * nhead;
if (blocks == 0 || blocks > 0x7fffffff) return R4D_NO(RAD_E_SHAPE);
hipLaunchKernelGGL((sam_attn_kernel<64>), dim3((uint32_t)blocks), dim3(kThreads), 0,
(hipStream_t)stream, q, k, v, o, cu, rh, rw, q_ld, k_ld, v_ld, o_ld, nhead,
gh, gw, th, tw, nth, ntw, scale);
(hipStream_t)stream, q, k, v, o, cu, rh, rw, rh_rows, rw_rows,
q_ld, k_ld, v_ld, o_ld, nhead, gh, gw, th, tw, nth, ntw, scale);
return hipGetLastError() == hipSuccess ? RAD_OK : R4D_NO(RAD_E_DEVICE);
}
@@ -188,19 +213,20 @@ extern "C" int r4d_rad_sam_attn(const RadArgs* a, RadStream s) {
const long long nseq = r4d_numel(cu) - 1;
if (nseq < 1) return R4D_NO(RAD_E_SHAPE);
// The tables: [2*tile-1, head_dim] each, the tile being the window or the whole grid.
const long long th = win > 0 ? win : gh, tw = win > 0 ? win : gw;
// The tables: [2*tile-1, head_dim] when the geometry has its own, else the checkpoint's rows
// (the 127-row global table at a 40 grid), resampled on read.
int64_t rhrows = 0, rhld = 0, rwrows = 0, rwld = 0;
R4D_NEED(bf16_rows(rh, hd, &rhrows, &rhld));
R4D_NEED(bf16_rows(rw, hd, &rwrows, &rwld));
if (rhrows != 2 * th - 1 || rwrows != 2 * tw - 1) return R4D_NO(RAD_E_UNSUPPORTED);
if (rhrows < 1 || rwrows < 1) return R4D_NO(RAD_E_UNSUPPORTED);
const float scale = (float)r4d_getf(a, "scale", 1.0 / std::sqrt((double)hd));
return launch_sam_attn((const uint16_t*)r4d_addr(q), (const uint16_t*)r4d_addr(k),
(const uint16_t*)r4d_addr(v), (uint16_t*)r4d_addr(o),
(const int*)r4d_addr(cu), (const uint16_t*)r4d_addr(rh),
(const uint16_t*)r4d_addr(rw), (int)qld, (int)kld, (int)vld, (int)old,
(const uint16_t*)r4d_addr(rw), (int)rhrows, (int)rwrows,
(int)qld, (int)kld, (int)vld, (int)old,
(int)nseq, (int)nh, (int)gh, (int)gw, (int)win, scale,
(long)(uintptr_t)s);
}
+28 -4
View File
@@ -28,6 +28,11 @@
// less `vocab_off`, and a token outside the shard is another rank's to mask (it is not a column
// here at all).
//
// The optional `whitelist` plane is the reference's whitelist (modeling_unlimitedocr.py:359,379):
// word w bit b of the row's own plane row covers column 32w + b, and a SET bit removes that token
// from the banned set -- it is never written. Absent, nothing is exempt, and the kernel's answer
// is the one before the whitelist existed.
//
// The scan is O(w * n) a row over a history of at most max_hist tokens, so one block a row with
// the positions dealt out across the block's threads; the n-1-token prefix is staged in LDS once
// when it fits (n <= 256), which is every request the model card asks for (35).
@@ -53,7 +58,8 @@ using SP = RadSampleParams;
__global__ __launch_bounds__(kThreads) void ngram_ban_kernel(
float* __restrict__ lg, const SP* __restrict__ sp, const int32_t* __restrict__ hist,
const int32_t* __restrict__ ng, uint32_t n_vocab, uint32_t lg_ld, uint32_t hmax, int32_t voff) {
const int32_t* __restrict__ ng, const uint32_t* __restrict__ wl, uint32_t wl_words,
uint32_t n_vocab, uint32_t lg_ld, uint32_t hmax, int32_t voff) {
__shared__ int32_t pf[kMaxPrefix];
__shared__ int64_t s_start, s_end, s_plen, s_p0;
@@ -96,6 +102,9 @@ __global__ __launch_bounds__(kThreads) void ngram_ban_kernel(
const int32_t* __restrict__ h = hist + (size_t)m * hmax + ho;
float* __restrict__ row = lg + (size_t)m * lg_ld;
// The row's own whitelist words (a SET bit exempts the column, the reference's
// `banned.difference_update(self.whitelist)`), read at the position loop below.
const uint32_t* __restrict__ w = wl ? wl + (size_t)m * wl_words : nullptr;
// The prefix: LDS when it fits, otherwise each position reads it from the plane.
const bool in_lds = plen <= (int64_t)kMaxPrefix;
@@ -116,18 +125,21 @@ __global__ __launch_bounds__(kThreads) void ngram_ban_kernel(
const int32_t tok = h[idx + plen];
const int64_t col = (int64_t)tok - voff;
if (tok < 0 || col < 0 || col >= (int64_t)n_vocab) continue;
if (wl && ((w[col >> 5] >> (uint32_t)(col & 31)) & 1u) != 0u) continue;
// Two positions may ban one token; the store is idempotent and the value is constant.
row[col] = -INFINITY;
}
}
int r4d_sample_ngram_ban_f32(long lg, long params, long hist, long ng, int M, int n_vocab,
int hmax, int lg_ld, int vocab_off, long stream) {
int r4d_sample_ngram_ban_f32(long lg, long params, long hist, long ng, long wl, int wl_words,
int M, int n_vocab, int hmax, int lg_ld, int vocab_off, long stream) {
if (!lg || !params || !hist || !ng) return R4D_NO(RAD_E_INVAL);
if (M <= 0 || n_vocab <= 0 || hmax <= 0) return R4D_NO(RAD_E_SHAPE);
if (wl && wl_words <= 0) return R4D_NO(RAD_E_SHAPE);
if (!lg_ld) lg_ld = n_vocab;
hipLaunchKernelGGL(ngram_ban_kernel, dim3((uint32_t)M), dim3(kThreads), 0, (hipStream_t)stream,
(float*)lg, (const SP*)params, (const int32_t*)hist, (const int32_t*)ng,
(const uint32_t*)wl, (uint32_t)(wl ? wl_words : 0),
(uint32_t)n_vocab, (uint32_t)lg_ld, (uint32_t)hmax, (int32_t)vocab_off);
return hipGetLastError() == hipSuccess ? RAD_OK : R4D_NO(RAD_E_DEVICE);
}
@@ -159,7 +171,7 @@ static int params_ok(const RadTensor* t, long long M) {
}
extern "C" int r4d_rad_sample_ngram_ban(const RadArgs* a, RadStream s) {
enum { V_LOGITS = 0, V_PARAMS, V_HIST, V_NGRAM };
enum { V_LOGITS = 0, V_PARAMS, V_HIST, V_NGRAM, V_WL };
const RadTensor* lg = r4d_opt(a, V_LOGITS);
if (!lg) return R4D_NO(RAD_E_INVAL);
R4D_NEED(dt_f32(lg));
@@ -183,8 +195,20 @@ extern "C" int r4d_rad_sample_ngram_ban(const RadArgs* a, RadStream s) {
/* One {n, window} pair a row, at least M of them. */
if (r4d_numel(ng) < 2 * M) return R4D_NO(RAD_E_SHAPE);
/* The optional whitelist bitmask: contiguous words of 32 columns, M rows of them. */
const RadTensor* wl = r4d_opt(a, V_WL);
const long long wwords = (nv + 31) / 32;
long long wl_addr = 0;
if (wl) {
R4D_NEED(dt_i32(wl));
if (!r4d_contig(wl)) return R4D_NO(RAD_E_STRIDE);
if (r4d_numel(wl) < M * wwords) return R4D_NO(RAD_E_SHAPE);
wl_addr = r4d_addr(wl);
}
const long long voff = r4d_geti_or(a, "vocab_off", 0);
return r4d_sample_ngram_ban_f32(r4d_addr(lg), r4d_addr(pr), r4d_addr(h), r4d_addr(ng),
wl_addr, (int)wwords,
(int)M, (int)nv, (int)hmax, (int)ld, (int)voff,
(long)(uintptr_t)s);
}
+57 -11
View File
@@ -18868,8 +18868,10 @@ static void sample_ngram_ban_case(const Plugin& pl) {
}
/* Two shard configurations: the whole vocabulary, and this rank holding ids [16, 64). */
struct Shard { int64_t voff, nv; };
const Shard shards[2] = { { 0, V }, { 16, V - 16 } };
struct Shard { int64_t voff, nv; bool wl; };
const Shard shards[4] = { { 0, V, false }, { 16, V - 16, false }, { 0, V, true },
{ 16, V - 16, true } };
/* The whitelist pass un-bans ids 7 and 21 (the reference bans.difference_update(whitelist)). */
int64_t n_cases = 0, banned_total = 0, mismatches = 0;
std::string first;
@@ -18904,10 +18906,23 @@ static void sample_ngram_ban_case(const Plugin& pl) {
st_memcpy(d_h, hist.data(), (size_t)(M * H) * 4, hipMemcpyHostToDevice);
st_memcpy(d_ng, ng.data(), (size_t)(M * 2) * 4, hipMemcpyHostToDevice);
const int64_t wwords = (nv + 31) / 32;
std::vector<uint32_t> wl((size_t)(M * wwords), 0u);
for (int64_t m = 0; m < M && sh.wl; ++m)
for (int32_t id : { 7, 21 }) {
const int64_t col = (int64_t)id - sh.voff;
if (col >= 0 && col < nv) wl[(size_t)(m * wwords + col / 32)] |= 1u << (col % 32);
}
void* d_wl = nullptr;
if (sh.wl) {
d_wl = dalloc((size_t)(M * wwords) * 4);
st_memcpy(d_wl, wl.data(), (size_t)(M * wwords) * 4, hipMemcpyHostToDevice);
}
std::vector<RadTensor> ts = { T(d_lg, RAD_F32, { M, nv }),
T(d_pr, RAD_F32, { M, (int64_t)(sizeof(RadSampleParams) / 4) }),
T(d_h, RAD_I32, { M, H }),
T(d_ng, RAD_I32, { M, 2 }) };
if (sh.wl) ts.push_back(T(d_wl, RAD_U32, { M, wwords }));
std::vector<RadParam> ps = { PI("M", M), PI("n_vocab", nv), PI("vocab_off", sh.voff) };
RadArgs a;
std::memset(&a, 0, sizeof(a));
@@ -18927,7 +18942,11 @@ static void sample_ngram_ban_case(const Plugin& pl) {
const int64_t g = sh.voff + i;
const size_t k = (size_t)(m * nv + i);
++n_cases;
const bool want = (size_t)g < banned.size() && banned[(size_t)g] != 0;
const int64_t wcol = g - sh.voff;
const bool wled = sh.wl && wcol >= 0 && wcol < nv &&
((wl[(size_t)(m * wwords + wcol / 32)] >>
(wcol % 32)) & 1u);
const bool want = !wled && (size_t)g < banned.size() && banned[(size_t)g] != 0;
if (want) ++banned_total;
const float gv = got[k];
const bool is_inf = std::isinf(gv) && gv < 0.0f;
@@ -18945,7 +18964,7 @@ static void sample_ngram_ban_case(const Plugin& pl) {
* [16, 64). dalloc's buffers are released by the case's dfree_all. */
}
std::printf(" ngram_ban: %lld columns over %lld rows x 2 shards, %lld banned, "
std::printf(" ngram_ban: %lld columns over %lld rows x 4 configs (2 shards + 2 whitelist), %lld banned, "
"%lld mismatches\n", (long long)n_cases, (long long)M, (long long)banned_total,
(long long)mismatches);
ok(what, mismatches == 0 && banned_total > 0,
@@ -18964,14 +18983,18 @@ static void sam_attn_case(const Plugin& pl) {
const RadKernelInfo* r = find(pl, "sam_attn_bf16");
if (!r) { ok(what, false, "row absent"); return; }
struct Geo { int64_t gh, gw, win, nh, hd, nseq; };
const Geo geos[2] = { { 16, 16, 14, 2, 64, 2 }, { 16, 16, 0, 2, 64, 1 } };
/* tab_rows 0 means "2*tile-1, no resize". The third geometry is the production 40-grid global
* block: the checkpoint's 127-row tables serve the 79 rows that block wants. */
struct Geo { int64_t gh, gw, win, nh, hd, nseq, tab_rows; };
const Geo geos[3] = { { 16, 16, 14, 2, 64, 2, 0 }, { 16, 16, 0, 2, 64, 1, 0 },
{ 40, 40, 0, 2, 64, 1, 127 } };
int64_t checked = 0, bad_total = 0;
float worst = 0.0f;
for (const Geo& g : geos) {
const int64_t W = g.nh * g.hd, R = g.gh * g.gw, M = g.nseq * R;
const int64_t tab = 2 * (g.win > 0 ? g.win : (g.gh > g.gw ? g.gh : g.gw)) - 1;
const int64_t want = 2 * (g.win > 0 ? g.win : (g.gh > g.gw ? g.gh : g.gw)) - 1;
const int64_t tab = g.tab_rows > 0 ? g.tab_rows : want;
/* One filler column, so the row pitch is W + 1: q/k/v/out are all slices. */
const int64_t ld = W + 1;
const float scale = 1.0f / std::sqrt((float)g.hd);
@@ -18987,6 +19010,29 @@ static void sam_attn_case(const Plugin& pl) {
rh[i] = h_to_bf16(0.1f * h_bf16(st_rand_bf16((uint32_t)i + 0x1234567u)));
rw[i] = h_to_bf16(0.1f * h_bf16(st_rand_bf16((uint32_t)i + 0x7654321u)));
}
/* The oracle's tables, resampled exactly as libref's get_rel_pos does (f32, align_corners
* False, clamp at the edges); the kernel gets the raw rows. */
auto resized = [&](const std::vector<uint16_t>& raw) {
std::vector<float> out((size_t)(want * g.hd));
if (tab == want) {
for (size_t i = 0; i < out.size(); ++i) out[i] = h_bf16(raw[i]);
return out;
}
for (int64_t d = 0; d < want; ++d) {
double src = ((double)d + 0.5) * (double)tab / (double)want - 0.5;
if (src < 0.0) src = 0.0;
if (src > (double)(tab - 1)) src = (double)(tab - 1);
const int64_t i0 = (int64_t)src, i1 = i0 + 1 < tab ? i0 + 1 : i0;
const float f = (float)(src - (double)i0);
for (int64_t c = 0; c < g.hd; ++c) {
const float a = h_bf16(raw[(size_t)(i0 * g.hd + c)]);
out[(size_t)(d * g.hd + c)] =
a + (h_bf16(raw[(size_t)(i1 * g.hd + c)]) - a) * f;
}
}
return out;
};
const std::vector<float> rhf = resized(rh), rwf = resized(rw);
std::vector<int32_t> cu((size_t)g.nseq + 1);
for (int64_t s = 0; s <= g.nseq; ++s) cu[(size_t)s] = (int32_t)(s * R);
@@ -19036,13 +19082,13 @@ static void sam_attn_case(const Plugin& pl) {
for (int64_t c = 0; c < g.hd; ++c)
qf[c] = h_bf16(q[(size_t)(row * ld + h * g.hd + c)]);
for (int64_t jh = 0; jh < th; ++jh) {
const uint16_t* hrp = &rh[(size_t)((lh - jh + th - 1) * g.hd)];
const float* hrp = &rhf[(size_t)((lh - jh + th - 1) * g.hd)];
double hr = 0.0;
for (int64_t c = 0; c < g.hd; ++c) hr += qf[c] * h_bf16(hrp[c]);
for (int64_t c = 0; c < g.hd; ++c) hr += qf[c] * hrp[c];
for (int64_t jw = 0; jw < tw; ++jw) {
const uint16_t* wrp = &rw[(size_t)((lw - jw + tw - 1) * g.hd)];
const float* wrp = &rwf[(size_t)((lw - jw + tw - 1) * g.hd)];
double sc = hr;
for (int64_t c = 0; c < g.hd; ++c) sc += qf[c] * h_bf16(wrp[c]);
for (int64_t c = 0; c < g.hd; ++c) sc += qf[c] * wrp[c];
const int64_t kh = ty * th + jh, kw = tx * tw + jw;
if (kh < g.gh && kw < g.gw) {
const int64_t krow = cu[(size_t)s] + kh * g.gw + kw;
+10 -3
View File
@@ -704,9 +704,13 @@ static const RadOperandSpec oPenalties[] = { INOUT("logits"), OPD("params"), OPD
* is a whole DRY sequence breaker and never penalised. Absent, no token is exempt. */
static const RadOperandSpec oDry[] = { INOUT("logits"), OPD("params"), OPD("history"),
OPD_O("breakers") };
/* The windowed n-gram ban: penalties' operands plus a {n, window} pair a row. */
/* The windowed n-gram ban: penalties' operands plus a {n, window} pair a row.
* `whitelist` is optional: a bitmask plane [M, ceil(n_vocab/32)] like sample_mask's, a SET bit
* marking a token exempt from the ban (the reference's whitelist, removed from the banned set
* before the -inf writes). Absent, nothing is exempt. Rows are indexed by the sampled position,
* not by mask_row: every row the op bans reads its own words. */
static const RadOperandSpec oNgramBan[] = { INOUT("logits"), OPD("params"), OPD("history"),
OPD("ngram") };
OPD("ngram"), OPD_O("whitelist") };
static const RadOperandSpec oTemp[] = { INOUT("logits"), OPD("params") };
/* `bitmask` is [rows, ceil(n_vocab/32)] uint32, addressed by the row's mask_row -- which is -1 for
* an unconstrained sequence, so the plane is shared and shorter than M. */
@@ -1541,7 +1545,10 @@ static const RadOpSchema kSchemas[] = {
"by setting -infinity, every token that would complete an n-gram the last `window` tokens of "
"the row's history already contain. `ngram` is one i32 {n, window} pair a row; the window "
"bounds the n-gram's START index, as in the reference, window <= 0 searches the whole span and "
"n 0 is off. Columns are ids less vocab_off." },
"n 0 is off. The optional `whitelist` bitmask (a SET bit, word w bit b covering column 32w + b, "
"the row's own plane row) exempts a token from the ban, as the reference's "
"`banned.difference_update(whitelist)` does; absent, nothing is exempt. Columns are ids less "
"vocab_off." },
{ "sample_temp", ARR(pMVocab), ARR(oTemp),
"logits /= temp, per row. temp <= 0 leaves the row untouched -- greedy decoding is "
"sample_argmax, and a temperature of zero silently meaning something else is how a sampler "
+20 -1
View File
@@ -256,10 +256,17 @@ int ref_sample_dry(const RadArgs* a, RadStream) {
* Ids are global and columns are global less `vocab_off`; a banned token on another rank's shard
* is that rank's to mask. Rows whose n is 0 (the default) are untouched, so a request without the
* ban leaves the logits bit for bit as they were. The scan is O(w * n) a row and compares
* integers, so every implementation (this one, libavx, libr4d) agrees by construction. */
* integers, so every implementation (this one, libavx, libr4d) agrees by construction.
*
* The optional `whitelist` bitmask is the reference's whitelist: a token whose column bit is set
* in the row's own plane row is removed from the banned set before the -inf writes
* (`banned.difference_update(self.whitelist)`, modeling_unlimitedocr.py:379), so it is never
* banned. Absent, nothing is exempt -- the default serving form, bit-identical to the ban
* without the operand. */
int ref_sample_ngram_ban(const RadArgs* a, RadStream) {
if (!have(a, 4)) return RAD_E_INVAL;
const RadTensor *lg = &a->t[0], *pr = &a->t[1], *hist = &a->t[2], *ng = &a->t[3];
const RadTensor* wl = a->n_t > 4 && a->t[4].data ? &a->t[4] : nullptr;
const int64_t n_vocab = p_int(a, "n_vocab", lg->rank >= 2 ? lg->shape[lg->rank - 1] : 0);
if (n_vocab <= 0) return RAD_E_SHAPE;
const int64_t M = numel(lg) / n_vocab;
@@ -272,6 +279,9 @@ int ref_sample_ngram_ban(const RadArgs* a, RadStream) {
* read past its end. */
if (numel(ng) < 2 * M) return RAD_E_SHAPE;
const int64_t voff = p_int(a, "vocab_off", 0);
const int64_t wwords = (n_vocab + 31) / 32;
if (wl && wl->dtype != RAD_I32 && wl->dtype != RAD_U32) return RAD_E_DTYPE;
if (wl && numel(wl) < M * wwords) return RAD_E_SHAPE;
REF_PAR_FOR(M * hmax)
for (int64_t m = 0; m < M; ++m) {
@@ -294,9 +304,17 @@ int ref_sample_ngram_ban(const RadArgs* a, RadStream) {
const int64_t hb = rowoff(hist, m, hmax) + ho * laststride(hist);
const int64_t hs = laststride(hist);
const int64_t lb = rowoff(lg, m, n_vocab), ls = laststride(lg);
const int64_t wb = wl ? rowoff(wl, m, wwords) : 0, ws = wl ? laststride(wl) : 0;
auto tok_at = [&](int64_t i) {
return ld_int(hist->dtype, hist->data, hb + i * hs);
};
/* The reference removes the whitelist from the banned set before it writes; a column
* whose bit is set in the row's whitelist words is therefore never written. */
auto exempt = [&](int64_t col) {
if (!wl) return false;
const uint32_t word = (uint32_t)ld_int(wl->dtype, wl->data, wb + (col / 32) * ws);
return ((word >> (uint32_t)(col % 32)) & 1u) != 0u;
};
/* n == 1 bans every token in the window: the prefix is empty, as in the reference. */
const int64_t plen = n - 1, p0 = hl - plen;
@@ -309,6 +327,7 @@ int ref_sample_ngram_ban(const RadArgs* a, RadStream) {
const int64_t tok = tok_at(idx + plen);
const int64_t col = tok - voff;
if (tok < 0 || col < 0 || col >= n_vocab) continue;
if (exempt(col)) continue;
stt(lg, lb + col * ls, -INFINITY);
}
}
+6 -1
View File
@@ -2387,7 +2387,11 @@ int ref_sample_dry_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* ou
* and adds one small plane beside them: `ngram`, an i32 {n-gram length, window} pair a row. It is
* a plane of its own rather than fields in `params` because the params row is a fixed 24-word wire
* format shared by every sampler op (and recorded in the kbench fixtures). Drawn in 0..63 so both
* a length inside the 64-token history and the 0 (= off) and whole-window forms occur. */
* a length inside the 64-token history and the 0 (= off) and whole-window forms occur.
*
* The optional `whitelist` bitmask is sample_mask's plane shape (word w bit b covers column
* 32w + b, a SET bit marking an exempt token), addressed by the sampled row itself; a random draw
* fills it with random bits, so a sweep exercises exemptions as often as plain bans. */
int ref_sample_ngram_ban_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
int64_t M = 0, nv = 0;
if (sample_vocab(p, n_p, &M, &nv) < 0) return RAD_E_UNSUPPORTED;
@@ -2397,6 +2401,7 @@ int ref_sample_ngram_ban_shape(const RadParam* p, int n_p, int operand, RadOpdDe
o.t_idx({ M, (int64_t)REF_SAMPLE_HIST }, nv, -1,
(uint32_t)RAD_OPD_F_IDX_HISTORY); /* history */
o.t_idx({ M, 2 }, 64, -1, 0); /* ngram: {n, window} */
o.t((uint32_t)RAD_I32, { M, (nv + 31) / 32 }); /* whitelist, optional */
return o.finish("sample_ngram_ban", operand, out);
}
+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