radiance 1.11.0

New models:
- GLM-5.3-Flash reads pictures: its vision tower and processor (--image-tokens sets the budget),
  with decode kernels for a few rows and the DSA indexer split over the ranks
- Sage-A1.5 (fp8 and MXFP4) with its vision tower and a DFlash2 drafter
- Unlimited-OCR (bf16)
- Gemma 4 31B with z-lab's DFlash and RedHatAI's DFlash2 drafters; at four cards its all-reduces
  are fused with the junctions, overlapped with the compute and sent compressed
- Ornith-1.5-35B-A3B w4a8 compose files

Speed:
- Block drafters (DFlash, DFlash2) accept their drafts on the card, and the next step is issued
  ahead
- The four-rank all-reduce is faster for every --tp 4 model
- qwen35_w8a8: the norms and SiLU write the int8 linears' operands directly
- --attn-prefill-fp8 off|qk|pv|both: fp8 QK and PV legs for the h256 prefill attention (about +20%
  prefill on a 221K-token prompt for the 27B MXFP4 at TP2); lossy, off by default

Features:
- Control vectors: --control-vector off|on|disabled (disabled by default), a per-request switch,
  and the published Qwen3.8-Flash-Next refusal-direction vector (its license is in NOTICE)
- Krea 2: the `rebalance` request field, as ComfyUI's ConditioningKrea2Rebalance
- Cards with a small PCI BAR run, with kernel arguments kept in host memory
- Dashboard: live acceptance figures; statsdump rotates its file at a size cap
- KV caches every rank holds whole (GLM-5.3's latent and index caches) take one host-tier slot

Fixes:
- Long conversations taking turns no longer fall back to an early snapshot: a host-tier restore
  makes room as memory pressure does and waits a step for the previous turn's release (two
  conversations of 142K and 147K tokens sent back to back: 31.3 s per turn before, 2.8 s now)
- Kernels before Linux 6.16 (amdgpu below 3.64) no longer hang at startup: virtual memory
  management is turned off there, with a warning
- Gemma 4 dense scales its token embeddings as Hugging Face does (bf16), which changes its output
- The four-rank all-reduce fences prefill-sized messages, for a rare divergence after a fresh start
- GLM-5.3: every refusal names the setting and the reason; its template keeps string content
- Several pictures in one request no longer refuse processors that take one image at a time

Changes: Plugin ABI 26: out-of-tree plugins must be rebuilt. The environment switches the PRs
added are fixed rules or flags now (R4D_ATTN_FP8 is --attn-prefill-fp8).
This commit is contained in:
Deadcode committed 2026-10-23 11:57:52 +02:00
210 files changed
+14363 -2138

No files matched your search

+26 -23
View File
@@ -596,22 +596,17 @@ inline rad_op rw(RadBuilder* b, rad_op h,
* (core/runtime/ctx.h): it is no collective, keeps no counter and touches no arena byte.
*
* Only at decode and verify heights, up to kPrefetchRows rows: a DFlash2 verify's 8 a sequence, a
* z-lab DFlash verify's 16, a plain decode's one. With the ceiling at 64, a prompt's prefill steps
* (40 rows on the 31B's test prompt) took the reads too, and a freshly started 31B server's first
* greedy reply then differed on 4 of 6 starts (4x R9700, the cards' memory scribbled before each
* start); at 16, and with no reads at all, 0 of 6. Per-op output hashes later located that
* divergence at the prefill all-reduce's first reuse of a double-buffered slot: a race in the
* all-reduce, which its full fence on prefill-sized messages (libr4d) cures, not in anything the
* reads touch. The reads stay off prompt steps all the same. */
* z-lab DFlash verify's 16, a plain decode's one. Prompt steps never take the reads: beside the
* prefill all-reduces they made a fresh server's first greedy reply differ, the slot-reuse race
* that libr4d's full fence on prefill-sized four-rank messages (kArFenceFromElems) also cures. */
constexpr int64_t kPrefetchRows = 16;
/* The read goes on lane 0 itself, right after the GEMM, where its chained form (libr4d
* r4dchain_prefetch) waits for that GEMM and then reads beside the collective after it without
* holding the collective: no join between the lanes, so no record on the GEMM and no barrier bit
* on it, and the read starts as the GEMM's last block ends rather than ~10 us later on lane 1. On
* 4x R9700 (31B DFlash2, three rounds, every reply identical): code 385-386 tok/s against 363-365,
* prose 284-286 against 269-270, decode after a 6.4k prompt 580-583 against 538-541. Only where
* launches chain (rad_chain_on, the core's decision), since a plain launch would read in series
* there; elsewhere the read goes on lane 1, behind a join from lane 0. */
/* Where launches chain (rad_chain_on, the core's decision) the read goes on lane 0 itself, right
* after the GEMM: its chained form (libr4d r4dchain_prefetch) waits for that GEMM and then reads
* beside the collective after it without holding the collective, so there is no join between the
* lanes and the read starts as the GEMM's last block ends rather than ~10 us later on lane 1 (on
* 4x R9700, the 31B with DFlash2 decoded 6-8% faster than with the read on lane 1). A plain launch
* would read in series on lane 0, so elsewhere the read goes on lane 1, behind a join from lane
* 0. */
inline bool prefetch_lane0() { return rad_chain_on() != 0; }
inline void prefetch_beside(RadCtx* c, rad_op op, rad_weight w, int64_t T) {
if (!op || T > kPrefetchRows) return;
@@ -622,15 +617,9 @@ inline void prefetch_beside(RadCtx* c, rad_op op, rad_weight w, int64_t T) {
if (rad_lane_join(c, 0, 1) == RAD_OK && rad_lane(c, 1) == RAD_OK) RAD_ISSUE(c, op, RAD_W(w));
rad_lane(c, 0);
}
/* RADIANCE_PREFETCH=0 declares no reads at all (docs/GUIDE.md); read at declare. */
inline bool prefetch_enabled() {
const char* e = std::getenv("RADIANCE_PREFETCH");
return !(e && !std::strcmp(e, "0"));
}
/* The `prefetch` of `w`'s first `bytes`, where a library serves it and the reads are on; 0
* otherwise. */
/* The `prefetch` of `w`'s first `bytes` where a library serves it; 0 otherwise. */
inline rad_op decl_prefetch(RadBuilder* b, rad_weight w, int64_t bytes) {
if (!w || bytes <= 0 || !prefetch_enabled() || !rad_op_declared(b, "prefetch")) return 0;
if (!w || bytes <= 0 || !rad_op_declared(b, "prefetch")) return 0;
return RAD_OP(b, "prefetch", RAD_PARAMS(RAD_INT("bytes", bytes)), RAD_WEIGHTS(w));
}
@@ -687,6 +676,9 @@ struct Geom {
/* Messages below this many bytes use the exact all-reduce even with a lossy wire. Passed as
* `all_reduce`'s `min_bytes`; 0 leaves the default to the kernel plugin. */
int64_t wire_min_bytes = 0;
/* RAD_ATTN_FP8_* bits: the attention products accepted in e4m3 (RadBuildCtx describes it).
* decl_attn passes it on as `attn_paged`'s `prefill_fp8`. */
int attn_prefill_fp8 = 0;
float eps = 1e-6f;
/* GemmaRMSNorm's `1 +`. Qwen3.5, Qwen3-Next and Gemma normalise with `x_hat * (1 + w)` and
* store `w` near 0.1, so reading it as a plain gain shrinks every normed activation 5-10x. An
@@ -957,6 +949,7 @@ inline int geom_from(Geom& g, const RadModelMeta* m, const RadBuildCtx* c,
g.world = c->world_size ? c->world_size : 1;
g.wire_exact= c->tp_wire_lossy ? 0 : 1;
g.wire_min_bytes = c->tp_wire_min_bytes;
g.attn_prefill_fp8 = c->attn_prefill_fp8;
g.eps = m->rms_eps;
g.theta = m->rope_theta;
g.rope_scale= 1.0f; /* yarn_from reads the model's rotary scaling */
@@ -1163,6 +1156,16 @@ inline rad_op decl_rotary(RadBuilder* b, const Geom& g, const char* name,
return rad_decl_op(b, name, p.data(), (int)p.size(), weights, nw);
}
/* An `attn_paged` op with the deployment's `prefill_fp8` appended (docs/OPS.md). At 0 the
* parameters are passed unchanged, so op identities and tune keys do not change. */
inline rad_op decl_attn(RadBuilder* b, const Geom& g, const char* name,
const RadParam* params, int n, const rad_weight* weights, int nw) {
if (g.attn_prefill_fp8 == 0) return rad_decl_op(b, name, params, n, weights, nw);
std::vector<RadParam> p(params, params + n);
p.push_back(RAD_INT("prefill_fp8", g.attn_prefill_fp8));
return rad_decl_op(b, name, p.data(), (int)p.size(), weights, nw);
}
/* Reads a model's rotary scaling into `g.rope_scale` and `g.yarn`. Every architecture calls it
* after geom_from, for the target ("") and for a drafter with its own config ("draft."). Only the
* free-form keys are read; RadModelMeta::rope_scale is not, since a factor without its type would
+1 -1
View File
@@ -139,7 +139,7 @@ inline int AttnBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
/* attn_paged before kv_store: block_size is RAD_DERIVED, read off the resolved attention
* kernel and back into kv_store with rad_kv_block_size() (rad_block_attn_gated.h says why). */
op_attn = rw(b, RAD_OP(b, "attn_paged",
op_attn = rw(b, decl_attn(b, g, "attn_paged",
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1),
RAD_INT("window", 0), RAD_INT("n_head", g.n_head),
+1 -1
View File
@@ -124,7 +124,7 @@ inline int AttnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, r
/* Declared before kv_store, which reads back the resolved `block_size` (rad_block_attn_gated.h
* explains declare vs issue order). */
op_attn = rw(b, RAD_OP(b, "attn_paged",
op_attn = rw(b, decl_attn(b, g, "attn_paged",
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1),
RAD_INT("window", 0), RAD_INT("n_head", g.n_head),
+1 -1
View File
@@ -195,7 +195,7 @@ inline int AttnGatedBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, in
*
* The ranged parameter is q_len, not M: 1 at decode, up to n_spec+1 at a verify, thousands in
* a prefill chunk, with a libr4d kernel per band. `scale` defaults to 1/sqrt(head_dim). */
op_attn = rw(b, RAD_OP(b, "attn_paged",
op_attn = rw(b, decl_attn(b, g, "attn_paged",
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1),
RAD_INT("window", 0),
+1 -1
View File
@@ -293,7 +293,7 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
/* Declared before kv_store, which reads back the resolved `block_size`
* (rad_block_attn_gated.h). */
op_attn = RAD_OP(b, "attn_paged",
op_attn = decl_attn(b, g, "attn_paged",
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1),
RAD_INT("window", 0),
+2 -4
View File
@@ -151,7 +151,8 @@ struct GlmKda {
!w.input || !w.forget_low || !w.gate_low || !w.out || w.input == w.out ||
w.forget_low == w.gate_low)
return RAD_E_INVAL;
// All seven projections are plain BF16 in the pinned checkpoint.
// All seven projections are plain bf16 in the pinned checkpoint; under w_bf16,
// LinearFP8::declare refuses a quantised one by name.
Geom bg = g;
bg.w_bf16 = true;
const int64_t width = GlmTp::kda_width(g.world), heads = GlmTp::heads(g.world);
@@ -193,9 +194,6 @@ struct GlmKda {
RAD_ARCH_TRY(output.declare(b, nm, bg, nm.f("blk.%d.attn_output", layer), 4096, width,
RAD_SHARD_COL, group, { nm.ckpt("%s.o_proj.weight", prefix) },
act(w.core.out), w.out));
if (!qkv.bf16 || !beta.bf16 || !forget_a.bf16 || !forget_b.bf16 || !gate_a.bf16 ||
!gate_b.bf16 || !output.bf16)
return RAD_E_UNSUPPORTED;
if (reduce) op_ar = GlmTp::reduce(b, g, w.out);
return reduce && g.world > 1 && !op_ar ? RAD_E_INVAL : RAD_OK;
}
+1 -1
View File
@@ -1,7 +1,7 @@
/* rad_block_glm_vision.h -- GLM-5.3's vision tower (transformers' Glm5NextVisionModel), served by
* glm5next.
*
* WHAT IT COMPUTES, per encoder pass (RadBatch::enc):
* What it computes, per encoder pass (RadBatch::enc):
*
* x = patches @ Wp^T + bp the Conv3d patch embedding as a linear layer; a
* patch row is (channel, frame, y, x), no position
+20 -27
View File
@@ -365,36 +365,25 @@ inline void HyperConn::read(RadCtx* c_, int64_t T, int64_t r0, int64_t rows) con
c.rotate ? brow_slice(w.rs, r0, rows, fp8_blocks(g.n_embd)) : RAD_NONE);
}
/* The block's output `y` is read from `w.x.x`, the buffer the read wrote the block's input to:
* every block leaves its delta in the activation its norm produced, and the input is dead by
* then. */
/* ================================================================== the control-vector projection
*
* A control vector is one unit direction per layer (a `controlvector` GGUF, core/cvec.h). Turned on
* for a request, a steered layer's wide stream is projected off that layer's direction right after
* the feed-forward's write:
* A control vector is one unit direction per layer (a `controlvector` GGUF, core/cvec.h). For a
* request that takes it, a steered layer's wide stream loses its component along that layer's
* direction right after the feed-forward's write:
*
* h[s] -= scale * (h[s] . v) * v for each of the hc streams s
* h[s] -= scale * (h[s] . v) * v for each of the hc streams s
*
* which is llama.cpp's `--cvec-mode project` and the operation the Qwen3.8-Flash-Next package
* documents. The dot is per stream, not on the stream mean: the patch applies it to the
* [n_embd, hc, tokens] view where `mul_mat(v, cur)` reduces over dim 0 alone.
* This is llama.cpp's `--cvec-mode project`. The dot is per stream, not on the stream mean, as
* llama.cpp's `mul_mat(v, cur)` over the [n_embd, hc, tokens] view reduces dim 0 alone.
*
* Two properties the architecture plugin does not have to think about, both here:
* The switch is per request: `on` is a derived buffer of one int32 per row
* (core/sched/derive.cpp, `projection_on_rows`), so a step that mixes a projected conversation
* with a stock one projects only the rows that asked. The kernel neither reads nor writes a zero
* row, and a pass with no row on issues nothing (RadBatch::control_vector). `scale` is the norm
* the file stored for the layer times the package's own scale.
*
* - **the switch is per request.** `on` is a derived buffer of one int32 per token row
* (core/sched/derive.cpp's `projection_on_rows`), so a step that mixes a projected
* conversation with a stock one projects exactly the rows that asked for it. All zeros is the
* stock model: the kernel skips a zero row without reading or writing it, so an unprojected
* request's stream is the one the stock model computes. (The *deployment* is not bit-identical
* to one with no vector: the direction table's VRAM can move an expert or a KV block, which is
* the tie-level variance radiance documents elsewhere. Measured, docs/GUIDE.md 4.10.)
* - **the parameters travel with the file.** `scale` is the norm the file stored for that layer
* (times the package's own `scale`, read from its JSON), and the direction row is sliced from
* the table at issue, so nothing is configured per deployment or scanned per layer.
*
* One instance per layer: `declare` emits an op only when the vector steers that layer, so a
* deployment without a vector declares no op, no buffer and no branch in the step. */
* One instance per layer; `declare` emits an op only where the vector steers, so a deployment
* without a vector declares no op and no buffer. */
struct HcProject {
rad_op op = 0; /* 0: this layer is not steered (or there is no vector) */
const float* dir = nullptr; /* this layer's row of the device direction table */
@@ -456,9 +445,10 @@ struct HcProject {
}
/* Rows [r0, r0 + rows) of the stream. The whole step is r0 = 0; the pipelined step issues one
* call per piece, in the same place in the graph. */
void step(RadCtx* c_, int64_t r0, int64_t rows) const {
if (!op) return;
* call per piece, in the same place in the graph. Nothing is issued on a pass where no row
* takes the vector (RadBatch::control_vector): every row would be skipped. */
void step(RadCtx* c_, const RadBatch* batch, int64_t r0, int64_t rows) const {
if (!op || !batch || !batch->control_vector) return;
RAD_ISSUE_N(c_, op, rows,
brow_slice(h, r0, rows, hc * n),
praw(dir, RAD_F32, n),
@@ -466,6 +456,9 @@ struct HcProject {
}
};
/* The block's output `y` is read from `w.x.x`, the buffer the read wrote the block's input to:
* every block leaves its delta in the activation its norm produced, and the input is dead by
* then. */
inline void HyperConn::write(RadCtx* c_, int64_t T, int64_t r0, int64_t rows) const {
if (!op_write) return;
if (takes_gather(T)) {
File diff suppressed because it is too large. Load diff
+3 -2
View File
@@ -1052,8 +1052,9 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
if (known && !plain) {
char en[256];
rad_enc_format(&enc, en, sizeof en);
fprintf(stderr, "radiance: '%s' is %s and this model's linears are plain bf16; a "
"bf16 container is served bf16 throughout\n", wn, en);
fprintf(stderr, "radiance: '%s' is %s, but this linear runs as a plain bf16 GEMM "
"(a bf16 model, or a block that keeps its linears bf16); the "
"container must store it bf16\n", wn, en);
return RAD_E_DTYPE;
}
/* A bf16 weight needs the input's bf16 plane, which a quantised model's producer may not
+22 -16
View File
@@ -115,18 +115,15 @@ inline double embed_scale(int64_t hidden) {
/* prefetch where a library serves it: the 31B trunk reading the next GEMM's leading weight bytes
* into the on-die cache beside the all-reduce in front of that GEMM, at decode heights (on lane 0
* as a chained read, or on the second lane: rad_arch.h prefetch_lane0), and the DFlash2 drafter's
* reads likewise. It writes nothing the model reads. Each read takes a weight's first 20 MB. With
* the reads on lane 0 (two rounds on 4x R9700): 20 MB 391 / 391 code tok/s, 289 / 288 prose;
* 16 MB 386 / 384, 285 / 283; 24 MB 388 / 387; 12 MB 368 / 369. */
* reads likewise. It writes nothing the model reads. Each read takes a weight's first 20 MB: on 4x
* R9700 with the reads on lane 0, 16 and 24 MB decoded 1-2% slower and 12 MB about 6%. */
constexpr int64_t kPrefetchBytes = (int64_t)20 << 20;
/* down_proj's read, the trunk GEMM no other read covers: its first 9 MB, beside the attention. It
* took the place of o_proj's read there: the 31B at tp 4 on 4x R9700, two rounds, every reply
* identical, 380 / 281 / 203 tok/s against 367 / 271 / 196 with o_proj's 16 MB; 10, 11, 12, 14
* and 20 MB of down_proj 379, 377, 373, 373 and 362; down_proj beside o_proj's read, or beside the
* feed-forward reduction, slower than either alone. The reads beside a reduction are one queue,
* and a longer one beside the attention pushes gate_up's read past the reduction it should hide
* in. */
/* down_proj's read, the trunk GEMM no other read covers: its first 9 MB, beside the attention, in
* place of a read of o_proj there (about 3.5% faster on the 31B at tp 4 on 4x R9700; 10-20 MB of
* down_proj were slower, as were two reads beside one reduction). The reads beside a reduction
* are one queue, and a longer one beside the attention pushes gate_up's read past the reduction
* it should hide in. */
constexpr int64_t kPrefetchDownBytes = (int64_t)9 << 20;
/* Block fp8 as libr4d's fp8a8 GEMMs read it: fp8_e4m3 codes, a bf16 scale per 128x128 block, no
@@ -166,8 +163,8 @@ inline long long dflash_block(const RadModelMeta* meta) {
/* DFlash proposes its whole block in one pass, so its depth is the block it was trained at less
* the anchor, and nothing else: 15 for z-lab's Gemma 4 drafters (block_size 16). True when the
* container carries one and `out` now names its depth. Chained launches measured a gain with it
* (the 26B-A4B's speculative step, +1% on 4x R9700), so the probe asks for them
* container carries one and `out` names its depth. Chained launches pay with it (the 26B-A4B's
* speculative step is 1% faster on 4x R9700), so the probe asks for them
* (RadArchProbe::chain_pays). */
inline bool dflash_probe(const RadModelMeta* meta, RadArchProbe* out) {
if (dflash_kind(meta) != 1) return false;
@@ -181,8 +178,8 @@ inline bool dflash_probe(const RadModelMeta* meta, RadArchProbe* out) {
/* The same for a DFlash2 drafter, for a plugin that serves rad_block_dflash2.h (the 31B's): its
* anchor predicts nothing either, so the depth is the trained block less one, 7 for RedHatAI's
* gemma-4-31B-it-speculator.dflash2 (block_size 8). Chained launches measured a gain with it (the
* 31B's speculative step, +13% on 4x R9700), so the probe asks for them. */
* gemma-4-31B-it-speculator.dflash2 (block_size 8). Chained launches pay with it (the 31B's
* speculative step is 13% faster on 4x R9700), so the probe asks for them. */
inline bool dflash2_probe(const RadModelMeta* meta, RadArchProbe* out) {
if (dflash_kind(meta) != 2) return false;
const long long bs = dflash_block(meta);
@@ -519,7 +516,12 @@ inline int Dflash1::Lin::declare(RadBuilder* b, Names& nm, const char* base, int
int64_t p[RAD_MAX_ROW_PARTS] = {0};
int np = 0;
for (int64_t q : row_parts) {
if (np >= RAD_MAX_ROW_PARTS || q % 16) return RAD_E_INVAL;
if (np >= RAD_MAX_ROW_PARTS || q % 16) {
fprintf(stderr, "radiance: '%s' has a %lld-row part per rank; an int8 weight takes at "
"most %d parts, each a multiple of 16 rows.\n", base, (long long)q,
(int)RAD_MAX_ROW_PARTS);
return RAD_E_INVAL;
}
p[np++] = q;
}
w = decl_view(b, wn, nullptr, "codes", RAD_I8, { N, K }, access, shard, grp, p, np);
@@ -582,7 +584,11 @@ inline int Dflash1::declare_drafter(RadBuilder* b, const RadModelMeta* meta,
return RAD_E_UNSUPPORTED;
}
dc.block = trained;
if (dg.n_layer > MAX_LAYERS) return RAD_E_UNSUPPORTED;
if (dg.n_layer > MAX_LAYERS) {
fprintf(stderr, "radiance: gemma4: the DFlash drafter has %lld layers; this block carries "
"at most %d\n", (long long)dg.n_layer, MAX_LAYERS);
return RAD_E_UNSUPPORTED;
}
{
std::vector<int> full;
const char* lt = rad_meta_gets(meta, "draft.layer_types", nullptr);
+167
View File
@@ -0,0 +1,167 @@
/* 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):
* 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;
/* ATen's own `xsize = min(xsize, n)`, kept for parity. It cannot bind here: with
* xmin > 0 the window spans 2*support + 1 taps, at most a.n = 2*ceil(support) + 1
* (the bound ATen sized the slots from), and with xmin == 0 it spans fewer. So the
* clamp is a no-op safety net, never a silent tap truncation. */
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