libxe2: strided cast and libref's sigmoid -- MiniCPM5-2B serves on the B65, greedy-identical

Serving MiniCPM5-2B bf16 on the Arc Pro B65 found two things rad-kbench's dense operands did not:

- cast is handed the q slice of the fused qkv row (2048 of every 2560 elements) and refused it,
  stopping the first step by name. It now walks any strides in libref's offlin order.
- gated_quant_fp8 took sigmoid with an f32 exp, within rad-kbench's tolerance but not libref's
  double exp: now and then an ulp in silu moved the bf16 narrowing and one E4M3 code, in some of
  the 42 layers, enough to flip a greedy near-tie tokens later. The engine's own op oracle
  (RADIANCE_OP_ORACLE='*', which runs libref on the operands the device kernel was handed) found
  it: 9 of 600 issues before, 600 of 600 bit-identical after, over a 26-token prefill.

With both, a greedy run on the B65 matches a libref-only host server token for token on all eight
prompts of scripts/sycl/greedy_compare.py (64 tokens each), and the top-5 logprobs agree exactly
over 96 decode steps. /v1/chat/completions answers coherently, reasoning split out.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018EpFgqQidSnH8zo7boVZC1
This commit is contained in:
claudeandClaude Opus 5.5 committed 2026-10-23 16:49:14 +02:00
1 parent d0e797844e
commit 8db5b6efff
5 files changed
+120 -11

No files matched your search

+38
View File
@@ -57,6 +57,44 @@ int submit(F&& f) {
return RAD_OK;
}
/* A tensor's element addressing for kernels that walk it in logical (row-major) order: libref's
* offlin, copied by value into the kernel. Contiguous costs nothing; a strided view (the q slice of
* a fused qkv row, which `cast` copies out) decomposes the index over its axes. */
struct Lin {
char* base = nullptr;
uint32_t dtype = 0;
uint32_t rank = 0;
bool contig = true;
int64_t shape[RAD_MAX_RANK] = {};
int64_t stride[RAD_MAX_RANK] = {};
static Lin of(const RadTensor* t) {
Lin l;
l.base = (char*)t->data;
l.dtype = t->dtype;
l.rank = t->rank;
int64_t acc = 1;
for (int i = (int)t->rank - 1; i >= 0; --i) {
l.shape[i] = t->shape[i];
l.stride[i] = t->stride[i];
if (t->shape[i] != 1 && t->stride[i] != acc) l.contig = false;
acc *= t->shape[i];
}
return l;
}
int64_t off(int64_t lin) const {
if (contig || rank == 0) return lin;
int64_t o = 0;
for (int i = (int)rank - 1; i >= 0; --i) {
const int64_t s = shape[i];
if (s <= 0) return 0;
o += (lin % s) * stride[i];
lin /= s;
}
return o;
}
};
/* An index or position element as libref's ld_int reads it. */
inline int64_t ld_index(uint32_t dt, const void* p, int64_t i) {
switch (dt) {
+6 -7
View File
@@ -102,12 +102,10 @@ int cast(const RadArgs* a, RadStream st) {
const RadTensor *X = &a->t[0], *Y = &a->t[1];
const int64_t nel = rad_tensor_numel(Y);
if (nel <= 0 || rad_tensor_numel(X) < nel) return RAD_E_SHAPE;
if (!rad_tensor_is_contiguous(X) || !rad_tensor_is_contiguous(Y))
return refuse("cast: strided operands are not served");
const bool int_pair = is_int(X->dtype) && is_int(Y->dtype);
const char* xb = (const char*)X->data;
char* yb = (char*)Y->data;
const uint32_t xdt = X->dtype, ydt = Y->dtype;
/* Either side may be a strided view: the graph casts q out of the fused qkv row, 2048 of
* every 2560 elements. Elements are walked in logical order through libref's offlin. */
const Lin x = Lin::of(X), y = Lin::of(Y);
sycl::queue* q = queue_of(st);
if (!q) return RAD_E_DEVICE;
const size_t groups = (size_t)((nel + (int64_t)kWg - 1) / (int64_t)kWg);
@@ -115,8 +113,9 @@ int cast(const RadArgs* a, RadStream st) {
syclex::nd_launch(*q, sycl::nd_range<1>{groups * kWg, kWg}, [=](sycl::nd_item<1> it) {
const int64_t i = (int64_t)it.get_global_id(0);
if (i >= nel) return;
if (int_pair) st_index(ydt, yb, i, ld_index(xdt, xb, i));
else rad_store_f32(yb, ydt, i, rad_load_f32(xb, xdt, i));
const int64_t xo = x.off(i), yo = y.off(i);
if (int_pair) st_index(y.dtype, y.base, yo, ld_index(x.dtype, x.base, xo));
else rad_store_f32(y.base, y.dtype, yo, rad_load_f32(x.base, x.dtype, xo));
});
});
}
+5 -3
View File
@@ -29,9 +29,11 @@ namespace {
constexpr size_t kWg = 256; /* work-items a row */
/* sigmoid as libref's act_sigmoid, in f32 (libref computes exp in double and rounds once; the
* device's f32 exp is within an ulp, inside the tolerance). */
inline float sigmoidf(float x) { return 1.0f / (1.0f + sycl::exp(-x)); }
/* sigmoid exactly as libref's act_sigmoid: exp in double, rounded once to f32 (ref_exp). An f32
* exp is within an ulp, inside rad-kbench's tolerance, but an ulp in silu now and then moves the
* bf16 narrowing and then an E4M3 code; the engine-level oracle (RADIANCE_OP_ORACLE) caught one
* such code in some of MiniCPM5-2B's 42 layers, enough to flip a greedy near-tie later. */
inline float sigmoidf(float x) { return 1.0f / (1.0f + (float)sycl::exp((double)-x)); }
/* The sum of src(i)^2 over i < n in ascending order, f32, as libref sums it, computed by work-item
* 0 and returned to every work-item of the group. */
+1 -1
View File
@@ -67,7 +67,7 @@ const RadKernelInfo kKernels[] = {
.domain = RAD_DOMAIN_DEVICE, .launch = xe2::gather_rows },
{ .name = "xe2_cast", .op = "cast", .family = "elem",
.computes = "dtype conversion; integer to integer exact",
.shape = "contiguous operands",
.shape = "any strides (libref's offlin order)",
.dtypes = "any float or integer pair",
.domain = RAD_DOMAIN_DEVICE, .launch = xe2::cast },
+70
View File
@@ -0,0 +1,70 @@
"""greedy_compare.py URL_A URL_B [--max-tokens N] -- greedy decoding on two radiance servers,
token for token.
Milestone A's check (docs/SYCL_PROGRESS.md): the Intel (SYCL) backend and the host backend serve the
same container; at temperature 0 their outputs must agree. Each prompt goes to both servers through
/v1/completions with logprobs, so the comparison is on token ids as the servers report them (the
`tokens` field) and their text, and the first divergence is reported with both sides' top
candidates at that step: a near-tie that flips is told apart from a broken kernel by the logit gap.
Exit status 0 when every prompt agrees, 1 otherwise. Standard library only.
"""
import argparse
import json
import sys
import urllib.request
PROMPTS = [
"The capital of France is",
"def fibonacci(n):\n ",
"Q: What is 17 times 23?\nA:",
"Once upon a time, in a village by the sea,",
"The three primary colors are",
"Translate to German: 'The weather is nice today.'\nGerman:",
"<|im_start|>user\nWrite one sentence about the ocean.<|im_end|>\n<|im_start|>assistant\n",
"List the planets of the solar system in order from the sun:",
]
def complete(url, prompt, max_tokens):
body = json.dumps({"prompt": prompt, "max_tokens": max_tokens, "temperature": 0,
"logprobs": 5}).encode()
req = urllib.request.Request(url.rstrip("/") + "/v1/completions", data=body,
headers={"Content-Type": "application/json"})
with urllib.request.urlopen(req, timeout=3600) as r:
out = json.load(r)
ch = out["choices"][0]
lp = ch.get("logprobs") or {}
return ch.get("text", ""), lp.get("tokens") or [], lp.get("top_logprobs") or []
def main():
ap = argparse.ArgumentParser()
ap.add_argument("a")
ap.add_argument("b")
ap.add_argument("--max-tokens", type=int, default=64)
args = ap.parse_args()
bad = 0
for p in PROMPTS:
ta, toks_a, top_a = complete(args.a, p, args.max_tokens)
tb, toks_b, top_b = complete(args.b, p, args.max_tokens)
same = ta == tb and toks_a == toks_b
n = min(len(toks_a), len(toks_b))
first = next((i for i in range(n) if toks_a[i] != toks_b[i]), None)
if first is None and len(toks_a) != len(toks_b):
first = n
print(f"{'SAME' if same else 'DIFF'} {len(toks_a):3d} tok {p[:48]!r}")
print(f" A: {ta[:160]!r}")
if not same:
bad += 1
print(f" B: {tb[:160]!r}")
print(f" first divergence at token {first}")
if first is not None and first < len(top_a) and first < len(top_b):
print(f" A top: {json.dumps(top_a[first])}")
print(f" B top: {json.dumps(top_b[first])}")
print(f"{len(PROMPTS) - bad}/{len(PROMPTS)} prompts identical")
return 0 if bad == 0 else 1
if __name__ == "__main__":
sys.exit(main())