clef: the joint schema head on the card, served on /v1/systemone

This commit is contained in:
Brandon Bertelsen committed 2026-10-28 00:33:55 -04:00
1 parent 555fbf62f5
commit a96bfe821f
17 files changed
+1786 -27

No files matched your search

+98
View File
@@ -0,0 +1,98 @@
/* rad_clef.h -- the words a clef request hands its head (RadBatch::plugin_words).
*
* clef's joint schema head (arch/common/rad_block_clef.h) reads more of a request than its
* tokens: which prompt positions hold each question's instructions and each option's text, each
* option's token ids (the lm_head rows it averages), and each question's type. The server lays
* them out with the functions below, in the forms the head's kernels read (a cu_seqlens here, a
* gather index there), and the engine carries them to the plugin as one range of int32 words.
* Both sides include this header, so the layout is stated once.
*
* Plain C, like every abi/ header: the plugin is built apart from the engine.
*/
#ifndef RAD_CLEF_H
#define RAD_CLEF_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
/* The bounds the head's buffers are declared at. A request past one is refused by the server. */
enum {
RAD_CLEF_MAX_QUESTIONS = 64,
RAD_CLEF_MAX_OPTIONS = 512, /* every question's options together */
RAD_CLEF_MAX_LEX = 8192 /* every option's tokens together */
};
/* The header: word 0 is the engine's (RadBatch::plugin_words), the rest the counts the layout is
* computed from. */
enum {
RAD_CLEF_W_ROW = 0, /* the sequence's logits row this step, written by the engine */
RAD_CLEF_W_N = 1, /* prompt tokens */
RAD_CLEF_W_Q = 2, /* questions */
RAD_CLEF_W_O = 3, /* options, every question together, in head order */
RAD_CLEF_W_L = 4, /* option tokens, every option together */
RAD_CLEF_W_S = 5, /* segments the prompt is cut into at every span's edges */
RAD_CLEF_HDR = 8
};
/* Where each array starts, in words from the range's start. Every array is int32. */
typedef struct RadClefWords {
int32_t n, q, o, l, s;
int32_t seg_cu; /* [s + 1]: a partition of [0, n) with a boundary at every span's edges */
int32_t q_seg; /* [q]: the segment holding each question's instructions */
int32_t o_seg; /* [o]: the segment holding each option's text */
int32_t o_q; /* [o]: each option's question */
int32_t opt_cu; /* [q + 1]: each question's options, consecutive */
int32_t type; /* [q]: 0 noul, 1 choice, 2 score */
int32_t lex_cu; /* [o + 1]: each option's tokens in lex_ids, consecutive */
int32_t lex_ids; /* [l]: the option tokens, as the prompt holds them */
int32_t last; /* [1]: n - 1, the prompt's last position */
int32_t cu_q; /* [2]: {0, q} */
int32_t cu_o; /* [2]: {0, o} */
int32_t cu_k; /* [2]: {0, n} */
int32_t total; /* words in all */
} RadClefWords;
static inline RadClefWords rad_clef_words_layout(int32_t n, int32_t q, int32_t o, int32_t l,
int32_t s) {
RadClefWords w;
int32_t at = RAD_CLEF_HDR;
w.n = n; w.q = q; w.o = o; w.l = l; w.s = s;
w.seg_cu = at; at += s + 1;
w.q_seg = at; at += q;
w.o_seg = at; at += o;
w.o_q = at; at += o;
w.opt_cu = at; at += q + 1;
w.type = at; at += q;
w.lex_cu = at; at += o + 1;
w.lex_ids = at; at += l;
w.last = at; at += 1;
w.cu_q = at; at += 2;
w.cu_o = at; at += 2;
w.cu_k = at; at += 2;
w.total = at;
return w;
}
/* The layout a range of words carries, read off its header. */
static inline RadClefWords rad_clef_words_read(const int32_t* words) {
return rad_clef_words_layout(words[RAD_CLEF_W_N], words[RAD_CLEF_W_Q], words[RAD_CLEF_W_O],
words[RAD_CLEF_W_L], words[RAD_CLEF_W_S]);
}
/* The most words a request can carry within the bounds: what the head declares
* (rad_declare_plugin_words). A span's two edges each cut the prompt, so the segments are at most
* two a span plus one. */
static inline int32_t rad_clef_max_words(void) {
const int32_t spans = RAD_CLEF_MAX_QUESTIONS + RAD_CLEF_MAX_OPTIONS;
return rad_clef_words_layout(0, RAD_CLEF_MAX_QUESTIONS, RAD_CLEF_MAX_OPTIONS,
RAD_CLEF_MAX_LEX, 2 * spans + 1).total;
}
#ifdef __cplusplus
}
#endif
#endif /* RAD_CLEF_H */
+652
View File
@@ -0,0 +1,652 @@
/* rad_block_clef.h -- clef's joint schema head, inside the backbone's plugin.
*
* Cloudflare's clef and clef-flash decide every question of a request jointly from the backbone's
* final hidden state at EVERY prompt position (joint_schema_model.py, JointSchemaHead). This block
* runs that head on the card, after the trunk, so /v1/systemone needs no second process:
*
* per token, every step hn = layernorm(h); hn is stored in a paged KV group of its own,
* so a prefix hit keeps the rows the trunk did not recompute
* per request, once every row of hn is gathered back out of the group's blocks, the
* memory projection and the six cross-attention layers run over all
* of them, the question and option spans are averaged, and the
* routing, decoder layers and scorer give three numbers an option
* (its lexical prior, its cosine and its residual) into the request's
* logits row, where the server reads them (core/server/clef.cpp)
*
* The spans, the option tokens and the question types come as the request's words
* (abi/rad_clef.h, RadBatch::plugin_words), laid out as the kernels read them. The head's own
* tensors are the release's joint_head.safetensors, added to the container at convert, under their
* own names. Every op here has a device kernel and a host reference, so the same block serves
* the tiny CPU test and the card.
*
* Differences from the reference, all within bf16: the cosine and the prior are means of
* products of RMS-normalised rows (an identity, with eps 1e-12 against torch's max(norm, 1e-12));
* the routing softmax is formed in f32 (seg_softmax_pool). The learned scalars (prior_logit_scale,
* joint_logit_scale, residual_gate) are applied by the server from the container header.
*/
#pragma once
#include <arch/rad_arch.h>
#include <rad_clef.h>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <vector>
namespace rad {
namespace arch {
struct ClefHead {
bool on = false;
int64_t E = 0; /* the backbone's hidden size: the head's input width */
int64_t W = 0; /* the head's width */
int64_t H = 0; /* heads */
int64_t HD = 0; /* W / H */
int64_t F = 0; /* feedforward */
int64_t bs = 0; /* the cache's block size */
int64_t nblk = 0; /* blocks a context holds at most */
int64_t NM = 0; /* nblk * bs: rows a request holds at most */
int64_t n_vocab = 0; /* this rank's logits width */
int layer = 0; /* the group's bound layer index */
double eps = 1e-5; /* torch.nn.LayerNorm's default */
rad_kvgroup kv = 0;
/* ---- weights */
rad_weight hn_w = 0, hn_b = 0, w_mem = 0, w_q = 0, w_oq = 0, w_glob = 0, w_octx = 0,
w_olex = 0, w_type = 0, osn_w = 0, osn_b = 0, fn_w = 0, fn_b = 0, on_w = 0,
on_b = 0, rs1_w = 0, rs1_b = 0, rs2_w = 0, rs2_b = 0;
struct Ev {
rad_weight qn_w = 0, qn_b = 0, mn_w = 0, mn_b = 0, wq = 0, bq = 0, wk = 0, bk = 0, wv = 0,
bv = 0, wo = 0, bo = 0, fn_w = 0, fn_b = 0, w1 = 0, b1 = 0, w2 = 0, b2 = 0;
rad_op ln_q = 0, ln_m = 0, pq = 0, pk = 0, pv = 0, attn = 0, po = 0, ln_f = 0, f1 = 0,
f2 = 0;
};
struct Dec {
rad_weight n1w = 0, n1b = 0, n2w = 0, n2b = 0, n3w = 0, n3b = 0, sa_w = 0, sa_b = 0,
so_w = 0, so_b = 0, cq_w = 0, cq_b = 0, ck_w = 0, ck_b = 0, cv_w = 0, cv_b = 0,
co_w = 0, co_b = 0, w1 = 0, b1 = 0, w2 = 0, b2 = 0;
rad_op ln1 = 0, qkv = 0, sattn = 0, so = 0, ln2 = 0, pq = 0, pk = 0, pv = 0, cattn = 0,
co = 0, ln3 = 0, f1 = 0, f2 = 0;
};
std::vector<Ev> ev;
std::vector<Dec> dec;
/* ---- buffers */
rad_buf b_hn = 0, b_all = 0, b_mem = 0, b_mn = 0, b_k = 0, b_v = 0, b_seg = 0, b_qv = 0,
b_oc = 0, b_g = 0, b_lx = 0, b_lex = 0, b_x = 0, b_t1 = 0, b_t2 = 0, b_ff = 0,
b_qq = 0, b_bf = 0, b_fr = 0, b_sc = 0, b_sum = 0, b_f = 0, b_fq = 0, b_f1 = 0,
b_f2 = 0, b_gw = 0, b_fn = 0, b_on = 0, b_na = 0, b_nb = 0, b_an = 0, b_ln = 0,
b_p = 0, b_neg1 = 0, b_d = 0, b_nd = 0, b_abs = 0, b_prod = 0, b_feat = 0, b_r = 0,
b_out3 = 0;
/* ---- ops, one a use site: the arena plans from each op's read and write sets */
rad_op op_hn = 0, op_store = 0, op_gather = 0, op_mem = 0, op_seg = 0, op_g_q = 0, op_g_o = 0,
op_g_last = 0, op_lex = 0, op_lexmean = 0, op_octx = 0, op_olex = 0, op_add_x1 = 0,
op_oq = 0, op_g_oq = 0, op_add_x2 = 0, op_qproj = 0, op_g_fr = 0, op_mul_sc = 0,
op_score = 0, op_route = 0, op_ln_osn = 0, op_add_f1 = 0, op_glob = 0, op_add_fg = 0,
op_type = 0, op_add_f2 = 0, op_ln_fn = 0, op_g_fr2 = 0, op_ln_on = 0, op_rms_a = 0,
op_rms_b = 0, op_mul_cos = 0, op_mean_cos = 0, op_g_an = 0, op_add_an = 0,
op_rms_an = 0, op_rms_lex = 0, op_mul_pri = 0, op_mean_pri = 0, op_neg1 = 0,
op_nd = 0, op_d = 0, op_relu_d = 0, op_nd2 = 0, op_relu_nd = 0, op_abs = 0,
op_prod = 0, op_cp_fr = 0, op_cp_on = 0, op_cp_prod = 0, op_cp_abs = 0, op_rs1 = 0,
op_rs2 = 0, op_cast = 0;
static bool present(const RadModelMeta* meta) {
const char* t = rad_meta_gets(meta, "decision.type", "");
return t && !std::strcmp(t, "clef");
}
/* Declared after the trunk's layers and lm_head: the trunk's cache block size is known then,
* and the head's rows read the final norm's output `b_h` and write `b_logits`. */
int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx, Names& nm,
const Geom& g, rad_buf b_h, rad_buf b_logits, rad_weight w_lm_head,
rad_kvgroup kv_trunk, int bind_layer);
/* Every trunk step: the final norm's rows into the head's cache. */
void step_tokens(RadCtx* c, const RadBatch* batch, rad_buf b_h);
/* After the lm_head: the head over every sequence that carries words. */
void step_heads(RadCtx* c, const RadBatch* batch, rad_buf b_logits, rad_weight w_lm_head);
private:
const RadKVGroupBatch* group_of(const RadBatch* batch) const {
for (int i = 0; i < batch->n_kv_groups; ++i)
if (batch->kv[i].group == kv) return &batch->kv[i];
return nullptr;
}
};
inline int ClefHead::declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx,
Names& nm, const Geom& g, rad_buf b_h, rad_buf b_logits,
rad_weight w_lm_head, rad_kvgroup kv_trunk, int bind_layer) {
(void)ctx;
E = g.n_embd;
W = rad_meta_geti(meta, "decision.clef.width", 0);
H = rad_meta_geti(meta, "decision.clef.heads", 0);
F = rad_meta_geti(meta, "decision.clef.feedforward", 0);
const long long R = rad_meta_geti(meta, "decision.clef.routing_layers", 0);
const long long D = rad_meta_geti(meta, "decision.clef.layers", 0);
const long long hidden = rad_meta_geti(meta, "decision.clef.hidden_size", 0);
if (W <= 0 || H <= 0 || F <= 0 || R <= 0 || D <= 0 || W % H || hidden != E) {
std::fprintf(stderr, "radiance: clef: the container's decision.clef.* keys do not describe "
"the head (hidden_size %lld against the backbone's %lld, width %lld, "
"heads %lld, feedforward %lld, routing_layers %lld, layers %lld); "
"rad-convert sets them from joint_head_config.json\n",
hidden, (long long)E, (long long)W, (long long)H, (long long)F, R, D);
return RAD_E_INVAL;
}
HD = W / H;
if (g.world != 1) {
std::fprintf(stderr, "radiance: clef's head runs on one rank: its rows are replicated and "
"the option tokens read the whole lm_head\n");
return RAD_E_UNSUPPORTED;
}
if (weight_codes_dtype(b, nm.f("output.weight"), RAD_BF16) != RAD_BF16) {
std::fprintf(stderr, "radiance: clef's head averages lm_head rows as bf16; this container's "
"lm_head is quantised. Keep output.weight bf16 in the recipe\n");
return RAD_E_UNSUPPORTED;
}
if (E % 2) return RAD_E_INVAL;
bs = rad_kv_block_size(b, kv_trunk);
if (bs <= 0) return RAD_E_STATE;
nblk = (g.max_ctx + bs - 1) / bs;
NM = nblk * bs;
n_vocab = g.n_vocab;
layer = bind_layer;
const int64_t QM = RAD_CLEF_MAX_QUESTIONS, OM = RAD_CLEF_MAX_OPTIONS, LM = RAD_CLEF_MAX_LEX;
const int64_t SM = 2 * (QM + OM) + 1;
if (n_vocab < 3 * OM) {
std::fprintf(stderr, "radiance: clef's head writes %lld values into a logits row of %lld\n",
(long long)(3 * OM), (long long)n_vocab);
return RAD_E_UNSUPPORTED;
}
/* ---- the cache: one FULL group, hn's two halves as a slot's K and V, so a block holds
* bs rows of E in position order and a gather of a sequence's blocks is its rows. Bound past
* the trunk, so the scheduler counts it as the head's; cached with the trunk's groups because
* its block size is theirs (core/mem/prefix.cpp). */
RadKVGroupDecl kd{};
kd.kind = RAD_KV_FULL;
kd.dtype = RAD_BF16;
kd.n_head_kv = 1;
kd.head_dim = E / 2;
kv = rad_decl_kv_group(b, nm.f("clef.kv"), &kd);
if (!kv) return RAD_E_INVAL;
RAD_ARCH_TRY(rad_bind_layer_kv(b, layer, kv));
RAD_ARCH_TRY(rad_declare_plugin_words(b, rad_clef_max_words()));
/* ---- weights: the release's names, bf16, read once a request. */
const int ACC = RAD_ACCESS_PER_REQUEST;
auto bw = [&](const char* dn, const char* src, std::initializer_list<int64_t> shp) -> rad_weight {
if (map_copy(b, dn, src) < 0) return 0;
return decl_w(b, dn, RAD_BF16, shp, ACC, RAD_SHARD_NONE, grp_model());
};
/* A packed in_proj's third: rows [k W, (k+1) W) of the weight, and of the bias. */
auto bw_rows = [&](const char* dn, const char* src, int k, int64_t cols) -> rad_weight {
if (map_rows(b, dn, { { src, (int)(k * W), W } }) < 0) return 0;
return cols ? decl_w(b, dn, RAD_BF16, { W, cols }, ACC, RAD_SHARD_NONE, grp_model())
: decl_w(b, dn, RAD_BF16, { W }, ACC, RAD_SHARD_NONE, grp_model());
};
hn_w = bw(nm.f("clef.hidden_norm.weight"), nm.ckpt("hidden_norm.weight"), { E });
hn_b = bw(nm.f("clef.hidden_norm.bias"), nm.ckpt("hidden_norm.bias"), { E });
w_mem = bw(nm.f("clef.memory_projection.weight"), nm.ckpt("memory_projection.weight"), { W, E });
w_q = bw(nm.f("clef.question_projection.weight"), nm.ckpt("question_projection.weight"), { W, E });
w_oq = bw(nm.f("clef.option_question_projection.weight"), nm.ckpt("option_question_projection.weight"), { W, E });
w_glob = bw(nm.f("clef.global_projection.weight"), nm.ckpt("global_projection.weight"), { W, E });
w_octx = bw(nm.f("clef.option_context_projection.weight"), nm.ckpt("option_context_projection.weight"), { W, E });
w_olex = bw(nm.f("clef.option_lexical_projection.weight"), nm.ckpt("option_lexical_projection.weight"), { W, E });
w_type = bw(nm.f("clef.type_embedding.weight"), nm.ckpt("type_embedding.weight"), { 3, W });
osn_w = bw(nm.f("clef.option_summary_norm.weight"), nm.ckpt("option_summary_norm.weight"), { W });
osn_b = bw(nm.f("clef.option_summary_norm.bias"), nm.ckpt("option_summary_norm.bias"), { W });
fn_w = bw(nm.f("clef.field_norm.weight"), nm.ckpt("field_norm.weight"), { W });
fn_b = bw(nm.f("clef.field_norm.bias"), nm.ckpt("field_norm.bias"), { W });
on_w = bw(nm.f("clef.option_norm.weight"), nm.ckpt("option_norm.weight"), { W });
on_b = bw(nm.f("clef.option_norm.bias"), nm.ckpt("option_norm.bias"), { W });
/* The scorer's first linear reads [field | option | field*option | |field-option|], one row
* of 4 W an option, which the blocks below assemble in `feat`. */
rs1_w = bw(nm.f("clef.residual_scorer.0.weight"), nm.ckpt("residual_scorer.0.weight"), { W, 4 * W });
rs1_b = bw(nm.f("clef.residual_scorer.0.bias"), nm.ckpt("residual_scorer.0.bias"), { W });
rs2_w = bw(nm.f("clef.residual_scorer.3.weight"), nm.ckpt("residual_scorer.3.weight"), { 1, W });
rs2_b = bw(nm.f("clef.residual_scorer.3.bias"), nm.ckpt("residual_scorer.3.bias"), { 1 });
if (!hn_w || !hn_b || !w_mem || !w_q || !w_oq || !w_glob || !w_octx || !w_olex || !w_type ||
!osn_w || !osn_b || !fn_w || !fn_b || !on_w || !on_b || !rs1_w || !rs1_b || !rs2_w || !rs2_b)
return RAD_E_INVAL;
ev.assign((size_t)R, Ev{});
for (int i = 0; i < (int)R; ++i) {
Ev& e = ev[(size_t)i];
const char* p = "evidence_layers";
e.qn_w = bw(nm.f("clef.ev.%d.query_norm.weight", i), nm.ckpt("%s.%d.query_norm.weight", p, i), { W });
e.qn_b = bw(nm.f("clef.ev.%d.query_norm.bias", i), nm.ckpt("%s.%d.query_norm.bias", p, i), { W });
e.mn_w = bw(nm.f("clef.ev.%d.memory_norm.weight", i), nm.ckpt("%s.%d.memory_norm.weight", p, i), { W });
e.mn_b = bw(nm.f("clef.ev.%d.memory_norm.bias", i), nm.ckpt("%s.%d.memory_norm.bias", p, i), { W });
e.wq = bw_rows(nm.f("clef.ev.%d.q.weight", i), nm.ckpt("%s.%d.attention.in_proj_weight", p, i), 0, W);
e.wk = bw_rows(nm.f("clef.ev.%d.k.weight", i), nm.ckpt("%s.%d.attention.in_proj_weight", p, i), 1, W);
e.wv = bw_rows(nm.f("clef.ev.%d.v.weight", i), nm.ckpt("%s.%d.attention.in_proj_weight", p, i), 2, W);
e.bq = bw_rows(nm.f("clef.ev.%d.q.bias", i), nm.ckpt("%s.%d.attention.in_proj_bias", p, i), 0, 0);
e.bk = bw_rows(nm.f("clef.ev.%d.k.bias", i), nm.ckpt("%s.%d.attention.in_proj_bias", p, i), 1, 0);
e.bv = bw_rows(nm.f("clef.ev.%d.v.bias", i), nm.ckpt("%s.%d.attention.in_proj_bias", p, i), 2, 0);
e.wo = bw(nm.f("clef.ev.%d.o.weight", i), nm.ckpt("%s.%d.attention.out_proj.weight", p, i), { W, W });
e.bo = bw(nm.f("clef.ev.%d.o.bias", i), nm.ckpt("%s.%d.attention.out_proj.bias", p, i), { W });
e.fn_w = bw(nm.f("clef.ev.%d.ff_norm.weight", i), nm.ckpt("%s.%d.feedforward_norm.weight", p, i), { W });
e.fn_b = bw(nm.f("clef.ev.%d.ff_norm.bias", i), nm.ckpt("%s.%d.feedforward_norm.bias", p, i), { W });
e.w1 = bw(nm.f("clef.ev.%d.ff1.weight", i), nm.ckpt("%s.%d.feedforward.0.weight", p, i), { F, W });
e.b1 = bw(nm.f("clef.ev.%d.ff1.bias", i), nm.ckpt("%s.%d.feedforward.0.bias", p, i), { F });
e.w2 = bw(nm.f("clef.ev.%d.ff2.weight", i), nm.ckpt("%s.%d.feedforward.3.weight", p, i), { W, F });
e.b2 = bw(nm.f("clef.ev.%d.ff2.bias", i), nm.ckpt("%s.%d.feedforward.3.bias", p, i), { W });
if (!e.qn_w || !e.qn_b || !e.mn_w || !e.mn_b || !e.wq || !e.wk || !e.wv || !e.bq || !e.bk ||
!e.bv || !e.wo || !e.bo || !e.fn_w || !e.fn_b || !e.w1 || !e.b1 || !e.w2 || !e.b2)
return RAD_E_INVAL;
}
dec.assign((size_t)D, Dec{});
for (int i = 0; i < (int)D; ++i) {
Dec& d = dec[(size_t)i];
const char* p = "layers";
d.n1w = bw(nm.f("clef.dec.%d.norm1.weight", i), nm.ckpt("%s.%d.norm1.weight", p, i), { W });
d.n1b = bw(nm.f("clef.dec.%d.norm1.bias", i), nm.ckpt("%s.%d.norm1.bias", p, i), { W });
d.n2w = bw(nm.f("clef.dec.%d.norm2.weight", i), nm.ckpt("%s.%d.norm2.weight", p, i), { W });
d.n2b = bw(nm.f("clef.dec.%d.norm2.bias", i), nm.ckpt("%s.%d.norm2.bias", p, i), { W });
d.n3w = bw(nm.f("clef.dec.%d.norm3.weight", i), nm.ckpt("%s.%d.norm3.weight", p, i), { W });
d.n3b = bw(nm.f("clef.dec.%d.norm3.bias", i), nm.ckpt("%s.%d.norm3.bias", p, i), { W });
/* Self-attention keeps its packed in_proj: one GEMM, then column slices. */
d.sa_w = bw(nm.f("clef.dec.%d.sa.in.weight", i), nm.ckpt("%s.%d.self_attn.in_proj_weight", p, i), { 3 * W, W });
d.sa_b = bw(nm.f("clef.dec.%d.sa.in.bias", i), nm.ckpt("%s.%d.self_attn.in_proj_bias", p, i), { 3 * W });
d.so_w = bw(nm.f("clef.dec.%d.sa.o.weight", i), nm.ckpt("%s.%d.self_attn.out_proj.weight", p, i), { W, W });
d.so_b = bw(nm.f("clef.dec.%d.sa.o.bias", i), nm.ckpt("%s.%d.self_attn.out_proj.bias", p, i), { W });
d.cq_w = bw_rows(nm.f("clef.dec.%d.ca.q.weight", i), nm.ckpt("%s.%d.multihead_attn.in_proj_weight", p, i), 0, W);
d.ck_w = bw_rows(nm.f("clef.dec.%d.ca.k.weight", i), nm.ckpt("%s.%d.multihead_attn.in_proj_weight", p, i), 1, W);
d.cv_w = bw_rows(nm.f("clef.dec.%d.ca.v.weight", i), nm.ckpt("%s.%d.multihead_attn.in_proj_weight", p, i), 2, W);
d.cq_b = bw_rows(nm.f("clef.dec.%d.ca.q.bias", i), nm.ckpt("%s.%d.multihead_attn.in_proj_bias", p, i), 0, 0);
d.ck_b = bw_rows(nm.f("clef.dec.%d.ca.k.bias", i), nm.ckpt("%s.%d.multihead_attn.in_proj_bias", p, i), 1, 0);
d.cv_b = bw_rows(nm.f("clef.dec.%d.ca.v.bias", i), nm.ckpt("%s.%d.multihead_attn.in_proj_bias", p, i), 2, 0);
d.co_w = bw(nm.f("clef.dec.%d.ca.o.weight", i), nm.ckpt("%s.%d.multihead_attn.out_proj.weight", p, i), { W, W });
d.co_b = bw(nm.f("clef.dec.%d.ca.o.bias", i), nm.ckpt("%s.%d.multihead_attn.out_proj.bias", p, i), { W });
d.w1 = bw(nm.f("clef.dec.%d.ff1.weight", i), nm.ckpt("%s.%d.linear1.weight", p, i), { F, W });
d.b1 = bw(nm.f("clef.dec.%d.ff1.bias", i), nm.ckpt("%s.%d.linear1.bias", p, i), { F });
d.w2 = bw(nm.f("clef.dec.%d.ff2.weight", i), nm.ckpt("%s.%d.linear2.weight", p, i), { W, F });
d.b2 = bw(nm.f("clef.dec.%d.ff2.bias", i), nm.ckpt("%s.%d.linear2.bias", p, i), { W });
if (!d.n1w || !d.n1b || !d.n2w || !d.n2b || !d.n3w || !d.n3b || !d.sa_w || !d.sa_b ||
!d.so_w || !d.so_b || !d.cq_w || !d.ck_w || !d.cv_w || !d.cq_b || !d.ck_b || !d.cv_b ||
!d.co_w || !d.co_b || !d.w1 || !d.b1 || !d.w2 || !d.b2)
return RAD_E_INVAL;
}
/* ---- buffers, bf16, at the bounds the words are refused past. */
b_hn = decl_b(b, nm.f("clef.hn"), RAD_BF16, { g.max_tok, E });
b_all = decl_b(b, nm.f("clef.all"), RAD_BF16, { NM, E });
b_mem = decl_b(b, nm.f("clef.mem"), RAD_BF16, { NM, W });
b_mn = decl_b(b, nm.f("clef.mn"), RAD_BF16, { NM, W });
b_k = decl_b(b, nm.f("clef.k"), RAD_BF16, { NM, W });
b_v = decl_b(b, nm.f("clef.v"), RAD_BF16, { NM, W });
b_seg = decl_b(b, nm.f("clef.seg"), RAD_BF16, { SM, E });
b_qv = decl_b(b, nm.f("clef.qv"), RAD_BF16, { QM, E });
b_oc = decl_b(b, nm.f("clef.oc"), RAD_BF16, { OM, E });
b_g = decl_b(b, nm.f("clef.g"), RAD_BF16, { 1, E });
b_lx = decl_b(b, nm.f("clef.lx"), RAD_BF16, { LM, E });
b_lex = decl_b(b, nm.f("clef.lex"), RAD_BF16, { OM, E });
b_x = decl_b(b, nm.f("clef.x"), RAD_BF16, { OM, W });
b_t1 = decl_b(b, nm.f("clef.t1"), RAD_BF16, { OM, W });
b_t2 = decl_b(b, nm.f("clef.t2"), RAD_BF16, { OM, W });
b_ff = decl_b(b, nm.f("clef.ff"), RAD_BF16, { OM, F });
b_qq = decl_b(b, nm.f("clef.qq"), RAD_BF16, { QM, W });
b_bf = decl_b(b, nm.f("clef.bf"), RAD_BF16, { QM, W });
b_fr = decl_b(b, nm.f("clef.fr"), RAD_BF16, { OM, W });
b_sc = decl_b(b, nm.f("clef.sc"), RAD_BF16, { OM, 1 });
b_sum = decl_b(b, nm.f("clef.sum"), RAD_BF16, { QM, W });
b_f = decl_b(b, nm.f("clef.f"), RAD_BF16, { QM, W });
b_fq = decl_b(b, nm.f("clef.fq"), RAD_BF16, { QM, 3 * W });
b_f1 = decl_b(b, nm.f("clef.f1"), RAD_BF16, { QM, W });
b_f2 = decl_b(b, nm.f("clef.f2"), RAD_BF16, { QM, W });
b_gw = decl_b(b, nm.f("clef.gw"), RAD_BF16, { 1, W });
b_fn = decl_b(b, nm.f("clef.fn"), RAD_BF16, { QM, W });
b_on = decl_b(b, nm.f("clef.on"), RAD_BF16, { OM, W });
b_na = decl_b(b, nm.f("clef.na"), RAD_BF16, { OM, W });
b_nb = decl_b(b, nm.f("clef.nb"), RAD_BF16, { OM, W });
b_an = decl_b(b, nm.f("clef.an"), RAD_BF16, { OM, E });
b_ln = decl_b(b, nm.f("clef.ln"), RAD_BF16, { OM, E });
b_p = decl_b(b, nm.f("clef.p"), RAD_BF16, { OM, E });
b_neg1 = decl_b(b, nm.f("clef.neg1"), RAD_BF16, { 1, W });
b_d = decl_b(b, nm.f("clef.d"), RAD_BF16, { OM, W });
b_nd = decl_b(b, nm.f("clef.nd"), RAD_BF16, { OM, W });
b_abs = decl_b(b, nm.f("clef.abs"), RAD_BF16, { OM, W });
b_prod = decl_b(b, nm.f("clef.prod"), RAD_BF16, { OM, W });
b_feat = decl_b(b, nm.f("clef.feat"), RAD_BF16, { OM, 4 * W });
b_r = decl_b(b, nm.f("clef.r"), RAD_BF16, { OM, W });
b_out3 = decl_b(b, nm.f("clef.out3"), RAD_BF16, { 3 * OM, 1 });
if (!b_hn || !b_all || !b_mem || !b_mn || !b_k || !b_v || !b_seg || !b_qv || !b_oc || !b_g ||
!b_lx || !b_lex || !b_x || !b_t1 || !b_t2 || !b_ff || !b_qq || !b_bf || !b_fr || !b_sc ||
!b_sum || !b_f || !b_fq || !b_f1 || !b_f2 || !b_gw || !b_fn || !b_on || !b_na || !b_nb ||
!b_an || !b_ln || !b_p || !b_neg1 || !b_d || !b_nd || !b_abs || !b_prod || !b_feat || !b_r ||
!b_out3)
return RAD_E_INVAL;
/* ---- ops. The lambdas state each kind once; the row bound is the op's band. */
auto lnorm = [&](int64_t rows, int64_t n, rad_weight w, rad_weight bias) {
return RAD_OP(b, "layernorm",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("eps", eps),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w, bias));
};
auto gemm = [&](int64_t rows, int64_t N, int64_t K, rad_weight w) {
return RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", K),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w));
};
auto gemmb = [&](int64_t rows, int64_t N, int64_t K, const char* act, rad_weight w,
rad_weight bias) {
return RAD_OP(b, "gemm_nt_bias",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", K),
RAD_STR("dtype", "bf16"), RAD_STR("act", act)),
RAD_WEIGHTS(w, bias));
};
auto unary = [&](const char* op, int64_t rows, int64_t n) {
return RAD_OP(b, op,
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS);
};
auto gather = [&](int64_t rows, int64_t n) { return unary("gather_rows", rows, n); };
auto cross = [&](int64_t rows) {
return RAD_OP(b, "attn_cross",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("head_dim", HD), RAD_INT("gqa", 1),
RAD_INT("causal", 0), RAD_STR("dtype", "bf16"),
RAD_F64("scale", 1.0 / std::sqrt((double)HD))),
RAD_NOWEIGHTS);
};
auto rmsp = [&](int64_t rows, int64_t n) {
return RAD_OP(b, "rmsnorm_p",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("eps", 1e-12),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS);
};
/* The mean of a row: a cosine from two RMS-normed rows, or with `mult` the dot product
* scaled (mult = n / sqrt(W) gives options . field / sqrt(W)). */
auto rowmean = [&](int64_t rows, int64_t n, double mult) {
return RAD_OP(b, "pool_cols",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_INT("k", n),
RAD_F64("mult", mult), RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS);
};
/* Every step: the final norm's rows into the cache. kv_store carries the block size and so is
* the group's consumer (core/build/rad_builder.cpp, find_kv_consumer); its write is the pool. */
op_hn = rw(b, lnorm(g.max_tok, E, hn_w, hn_b), { b_h }, { b_hn });
op_store = rw(b, RAD_OP(b, "kv_store",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", E / 2),
RAD_INT("n_head_kv", 1), RAD_INT("block_size", bs),
RAD_STR("kv_dtype", "bf16")),
RAD_NOWEIGHTS),
{ b_hn }, {});
if (rad_kv_block_size(b, kv) != bs) {
std::fprintf(stderr, "radiance: clef's cache took block size %lld, the trunk's is %lld\n",
(long long)rad_kv_block_size(b, kv), (long long)bs);
return RAD_E_STATE;
}
/* Per request. A sequence's blocks are rows of bs * E: the gather reads the pool as
* [n_blocks, bs * E] and writes `all` as [nblk, bs * E], which the ops below read as rows of E
* (a contiguous buffer at another width, core/runtime and libr4d's r4d_rows_pitch). */
op_gather = rw(b, gather(nblk, bs * E), {}, { b_all });
op_mem = rw(b, gemm(NM, W, E, w_mem), { b_all }, { b_mem });
op_seg = rw(b, unary("seg_mean", NM, E), { b_all }, { b_seg });
op_g_q = rw(b, gather(QM, E), { b_seg }, { b_qv });
op_g_o = rw(b, gather(OM, E), { b_seg }, { b_oc });
op_g_last = rw(b, gather(1, E), { b_all }, { b_g });
op_lex = rw(b, RAD_OP(b, "embed_lookup",
RAD_PARAMS(RAD_RANGE("M", 1, LM), RAD_INT("n_embd", E),
RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", "bf16"),
RAD_INT("vocab_offset", g.vocab_off)),
RAD_WEIGHTS(w_lm_head)),
{}, { b_lx });
op_lexmean = rw(b, unary("seg_mean", LM, E), { b_lx }, { b_lex });
op_octx = rw(b, gemm(OM, W, E, w_octx), { b_oc }, { b_x });
op_olex = rw(b, gemm(OM, W, E, w_olex), { b_lex }, { b_t1 });
op_add_x1 = rw(b, unary("add", OM, W), { b_x, b_t1 }, { b_x });
op_oq = rw(b, gemm(QM, W, E, w_oq), { b_qv }, { b_qq });
op_g_oq = rw(b, gather(OM, W), { b_qq }, { b_t1 });
op_add_x2 = rw(b, unary("add", OM, W), { b_x, b_t1 }, { b_x });
for (Ev& e : ev) {
e.ln_q = rw(b, lnorm(OM, W, e.qn_w, e.qn_b), { b_x }, { b_t1 });
e.ln_m = rw(b, lnorm(NM, W, e.mn_w, e.mn_b), { b_mem }, { b_mn });
e.pq = rw(b, gemmb(OM, W, W, "none", e.wq, e.bq), { b_t1 }, { b_t2 });
e.pk = rw(b, gemmb(NM, W, W, "none", e.wk, e.bk), { b_mn }, { b_k });
e.pv = rw(b, gemmb(NM, W, W, "none", e.wv, e.bv), { b_mn }, { b_v });
e.attn = rw(b, cross(OM), { b_t2, b_k, b_v }, { b_t1 });
e.po = rw(b, gemmb(OM, W, W, "none", e.wo, e.bo), { b_t1, b_x }, { b_x });
e.ln_f = rw(b, lnorm(OM, W, e.fn_w, e.fn_b), { b_x }, { b_t1 });
e.f1 = rw(b, gemmb(OM, F, W, "gelu", e.w1, e.b1), { b_t1 }, { b_ff });
e.f2 = rw(b, gemmb(OM, W, F, "none", e.w2, e.b2), { b_ff, b_x }, { b_x });
}
op_qproj = rw(b, gemm(QM, W, E, w_q), { b_qv }, { b_bf });
op_g_fr = rw(b, gather(OM, W), { b_bf }, { b_fr });
op_mul_sc = rw(b, unary("mul", OM, W), { b_x, b_fr }, { b_t1 });
op_score = rw(b, rowmean(OM, W, (double)W / std::sqrt((double)W)), { b_t1 }, { b_sc });
op_route = rw(b, unary("seg_softmax_pool", OM, W), { b_sc, b_x }, { b_sum });
op_ln_osn = rw(b, lnorm(QM, W, osn_w, osn_b), { b_sum }, { b_f1 });
op_add_f1 = rw(b, unary("add", QM, W), { b_bf, b_f1 }, { b_f });
op_glob = rw(b, gemm(1, W, E, w_glob), { b_g }, { b_gw });
op_add_fg = rw(b, unary("add", QM, W), { b_f, b_gw }, { b_f });
op_type = rw(b, RAD_OP(b, "embed_lookup",
RAD_PARAMS(RAD_RANGE("M", 1, QM), RAD_INT("n_embd", W),
RAD_INT("n_vocab", 3), RAD_STR("dtype", "bf16"),
RAD_INT("vocab_offset", 0)),
RAD_WEIGHTS(w_type)),
{}, { b_f1 });
op_add_f2 = rw(b, unary("add", QM, W), { b_f, b_f1 }, { b_f });
for (Dec& d : dec) {
d.ln1 = rw(b, lnorm(QM, W, d.n1w, d.n1b), { b_f }, { b_f1 });
d.qkv = rw(b, gemmb(QM, 3 * W, W, "none", d.sa_w, d.sa_b), { b_f1 }, { b_fq });
d.sattn = rw(b, RAD_OP(b, "attn_dense",
RAD_PARAMS(RAD_RANGE("M", 1, QM), RAD_INT("head_dim", HD),
RAD_INT("gqa", 1), RAD_INT("causal", 0),
RAD_STR("dtype", "bf16"),
RAD_F64("scale", 1.0 / std::sqrt((double)HD)),
RAD_INT("max_seqlen", QM)),
RAD_NOWEIGHTS),
{ b_fq }, { b_f1 });
d.so = rw(b, gemmb(QM, W, W, "none", d.so_w, d.so_b), { b_f1, b_f }, { b_f });
d.ln2 = rw(b, lnorm(QM, W, d.n2w, d.n2b), { b_f }, { b_f1 });
d.pq = rw(b, gemmb(QM, W, W, "none", d.cq_w, d.cq_b), { b_f1 }, { b_f2 });
d.pk = rw(b, gemmb(NM, W, W, "none", d.ck_w, d.ck_b), { b_mem }, { b_k });
d.pv = rw(b, gemmb(NM, W, W, "none", d.cv_w, d.cv_b), { b_mem }, { b_v });
d.cattn = rw(b, cross(QM), { b_f2, b_k, b_v }, { b_f1 });
d.co = rw(b, gemmb(QM, W, W, "none", d.co_w, d.co_b), { b_f1, b_f }, { b_f });
d.ln3 = rw(b, lnorm(QM, W, d.n3w, d.n3b), { b_f }, { b_f1 });
d.f1 = rw(b, gemmb(QM, F, W, "gelu", d.w1, d.b1), { b_f1 }, { b_ff });
d.f2 = rw(b, gemmb(QM, W, F, "none", d.w2, d.b2), { b_ff, b_f }, { b_f });
}
op_ln_fn = rw(b, lnorm(QM, W, fn_w, fn_b), { b_f }, { b_fn });
/* The scorer, an option at a time against its question's field. */
op_g_fr2 = rw(b, gather(OM, W), { b_fn }, { b_fr });
op_ln_on = rw(b, lnorm(OM, W, on_w, on_b), { b_x }, { b_on });
op_rms_a = rw(b, rmsp(OM, W), { b_fr }, { b_na });
op_rms_b = rw(b, rmsp(OM, W), { b_on }, { b_nb });
op_mul_cos = rw(b, unary("mul", OM, W), { b_na, b_nb }, { b_t1 });
op_mean_cos = rw(b, rowmean(OM, W, 1.0), { b_t1 }, { b_out3 });
op_g_an = rw(b, gather(OM, E), { b_qv }, { b_an });
op_add_an = rw(b, unary("add", OM, E), { b_an, b_g }, { b_an });
op_rms_an = rw(b, rmsp(OM, E), { b_an }, { b_p });
op_rms_lex = rw(b, rmsp(OM, E), { b_lex }, { b_ln });
op_mul_pri = rw(b, unary("mul", OM, E), { b_p, b_ln }, { b_an });
op_mean_pri = rw(b, rowmean(OM, E, 1.0), { b_an }, { b_out3 });
op_neg1 = rw(b, RAD_OP(b, "fill",
RAD_PARAMS(RAD_RANGE("M", 1, 1), RAD_INT("n", W),
RAD_STR("dtype", "bf16"), RAD_F64("value", -1.0)),
RAD_NOWEIGHTS),
{}, { b_neg1 });
op_nd = rw(b, unary("mul", OM, W), { b_on, b_neg1 }, { b_nd });
op_d = rw(b, unary("add", OM, W), { b_fr, b_nd }, { b_d });
op_relu_d = rw(b, unary("relu", OM, W), { b_d }, { b_abs });
op_nd2 = rw(b, unary("mul", OM, W), { b_d, b_neg1 }, { b_nd });
op_relu_nd = rw(b, unary("relu", OM, W), { b_nd }, { b_nd });
op_abs = rw(b, unary("add", OM, W), { b_abs, b_nd }, { b_abs });
op_prod = rw(b, unary("mul", OM, W), { b_fr, b_on }, { b_prod });
/* The four feature blocks side by side in `feat`: the field rows are gathered straight into
* the first, the other three copied in (cast at one dtype is the copy op), so the scorer's
* first linear is one GEMM over 4 W, rounded once as the reference rounds it. */
auto copy = [&]() {
return RAD_OP(b, "cast",
RAD_PARAMS(RAD_RANGE("M", 1, OM), RAD_INT("n", W), RAD_STR("from", "bf16"),
RAD_STR("to", "bf16")),
RAD_NOWEIGHTS);
};
op_cp_fr = rw(b, copy(), { b_fr }, { b_feat });
op_cp_on = rw(b, copy(), { b_on }, { b_feat });
op_cp_prod = rw(b, copy(), { b_prod }, { b_feat });
op_cp_abs = rw(b, copy(), { b_abs }, { b_feat });
op_rs1 = rw(b, gemmb(OM, W, 4 * W, "gelu", rs1_w, rs1_b), { b_feat }, { b_r });
op_rs2 = rw(b, gemmb(OM, 1, W, "none", rs2_w, rs2_b), { b_r }, { b_out3 });
op_cast = rw(b, RAD_OP(b, "cast",
RAD_PARAMS(RAD_RANGE("M", 1, 1), RAD_INT("n", 3 * OM),
RAD_STR("from", "bf16"), RAD_STR("to", "f32")),
RAD_NOWEIGHTS),
{ b_out3 }, { b_logits });
rad_note(b, "clef's joint schema head on the card: width %lld, %lld heads of %lld, "
"feedforward %lld, %lld routing + %lld decoder layers; hn cached as a FULL group "
"of block %lld (%lld rows a context); at most %d questions, %d options, %d option "
"tokens a request; three values an option into the logits row",
(long long)W, (long long)H, (long long)HD, (long long)F, R, D, (long long)bs,
(long long)NM, (int)QM, (int)OM, (int)LM);
on = true;
return RAD_OK;
}
inline void ClefHead::step_tokens(RadCtx* c, const RadBatch* batch, rad_buf b_h) {
if (!on || batch->n_tok <= 0) return;
const RadKVGroupBatch* kb = group_of(batch);
if (!kb) { rad_step_fail(c, "clef: the head's cache group is not in the step batch"); return; }
const int64_t T = batch->n_tok;
RAD_ISSUE_N(c, op_hn, T, brows(b_h, T), RAD_W(hn_w), RAD_W(hn_b), brows(b_hn, T));
RAD_ISSUE_N(c, op_store, T, bcol(b_hn, 0, E / 2, T), bcol(b_hn, E / 2, E / 2, T),
praw(kb->slot_mapping, RAD_I32, T), kv_cache(kv, layer));
}
inline void ClefHead::step_heads(RadCtx* c, const RadBatch* batch, rad_buf b_logits,
rad_weight w_lm_head) {
if (!on || !batch->plugin_cu_h || !batch->plugin_words_h) return;
const RadKVGroupBatch* kb = group_of(batch);
if (!kb) { rad_step_fail(c, "clef: the head's cache group is not in the step batch"); return; }
const int64_t QM = RAD_CLEF_MAX_QUESTIONS, OM = RAD_CLEF_MAX_OPTIONS, LM = RAD_CLEF_MAX_LEX;
const int64_t SM = 2 * (QM + OM) + 1;
for (int64_t s = 0; s < batch->n_seq; ++s) {
const int32_t w0 = batch->plugin_cu_h[s], w1 = batch->plugin_cu_h[s + 1];
if (w1 <= w0) continue;
if (w1 - w0 < RAD_CLEF_HDR) { rad_step_fail(c, "clef: a request's words have no header"); return; }
const int32_t* hw = batch->plugin_words_h + w0;
const int32_t* dw = batch->plugin_words + w0;
const RadClefWords L = rad_clef_words_read(hw);
const int64_t N = L.n, Q = L.q, O = L.o, Lx = L.l, S = L.s;
const int32_t row = hw[RAD_CLEF_W_ROW];
const int64_t nb = (N + bs - 1) / bs;
if (w1 - w0 < L.total || N < 1 || N > NM || Q < 1 || Q > QM || O < 1 || O > OM ||
Lx < 1 || Lx > LM || S < 1 || S > SM || row < 0 || row >= batch->n_out ||
nb > kb->max_blocks) {
rad_step_fail(c, "clef: a request's words are out of the head's bounds");
return;
}
auto dev = [&](int32_t off, int64_t n) { return praw(dw + off, RAD_I32, n); };
auto out3 = [&](int64_t at, int64_t rows) { return bcol_at(b_out3, at, 1, 0, 1, rows); };
const int32_t* bt = kb->block_table + s * kb->block_table_pitch;
/* Every row of hn, from the sequence's blocks. */
RAD_ISSUE_N(c, op_gather, nb, kv_cache(kv, layer), praw(bt, RAD_I32, nb),
brows(b_all, nb * bs));
RAD_ISSUE_N(c, op_mem, N, brows(b_all, N), RAD_W(w_mem), brows(b_mem, N));
/* The question, option and global vectors. */
RAD_ISSUE_N(c, op_seg, N, brows(b_all, N), dev(L.seg_cu, S + 1), brows(b_seg, S));
RAD_ISSUE_N(c, op_g_q, Q, brows(b_seg, S), dev(L.q_seg, Q), brows(b_qv, Q));
RAD_ISSUE_N(c, op_g_o, O, brows(b_seg, S), dev(L.o_seg, O), brows(b_oc, O));
RAD_ISSUE_N(c, op_g_last, 1, brows(b_all, N), dev(L.last, 1), brows(b_g, 1));
RAD_ISSUE_N(c, op_lex, Lx, dev(L.lex_ids, Lx), RAD_W(w_lm_head), brows(b_lx, Lx));
RAD_ISSUE_N(c, op_lexmean, Lx, brows(b_lx, Lx), dev(L.lex_cu, O + 1), brows(b_lex, O));
/* Option queries, then the evidence layers over the memory. */
RAD_ISSUE_N(c, op_octx, O, brows(b_oc, O), RAD_W(w_octx), brows(b_x, O));
RAD_ISSUE_N(c, op_olex, O, brows(b_lex, O), RAD_W(w_olex), brows(b_t1, O));
RAD_ISSUE_N(c, op_add_x1, O, brows(b_x, O), brows(b_t1, O), brows(b_x, O));
RAD_ISSUE_N(c, op_oq, Q, brows(b_qv, Q), RAD_W(w_oq), brows(b_qq, Q));
RAD_ISSUE_N(c, op_g_oq, O, brows(b_qq, Q), dev(L.o_q, O), brows(b_t1, O));
RAD_ISSUE_N(c, op_add_x2, O, brows(b_x, O), brows(b_t1, O), brows(b_x, O));
for (const Ev& e : ev) {
RAD_ISSUE_N(c, e.ln_q, O, brows(b_x, O), RAD_W(e.qn_w), RAD_W(e.qn_b), brows(b_t1, O));
RAD_ISSUE_N(c, e.ln_m, N, brows(b_mem, N), RAD_W(e.mn_w), RAD_W(e.mn_b), brows(b_mn, N));
RAD_ISSUE_N(c, e.pq, O, brows(b_t1, O), RAD_W(e.wq), RAD_W(e.bq), RAD_NONE, brows(b_t2, O));
RAD_ISSUE_N(c, e.pk, N, brows(b_mn, N), RAD_W(e.wk), RAD_W(e.bk), RAD_NONE, brows(b_k, N));
RAD_ISSUE_N(c, e.pv, N, brows(b_mn, N), RAD_W(e.wv), RAD_W(e.bv), RAD_NONE, brows(b_v, N));
RAD_ISSUE_N(c, e.attn, O, brows(b_t2, O), brows(b_k, N), brows(b_v, N),
dev(L.cu_o, 2), dev(L.cu_k, 2), brows(b_t1, O));
RAD_ISSUE_N(c, e.po, O, brows(b_t1, O), RAD_W(e.wo), RAD_W(e.bo), brows(b_x, O), brows(b_x, O));
RAD_ISSUE_N(c, e.ln_f, O, brows(b_x, O), RAD_W(e.fn_w), RAD_W(e.fn_b), brows(b_t1, O));
RAD_ISSUE_N(c, e.f1, O, brows(b_t1, O), RAD_W(e.w1), RAD_W(e.b1), RAD_NONE, brows(b_ff, O));
RAD_ISSUE_N(c, e.f2, O, brows(b_ff, O), RAD_W(e.w2), RAD_W(e.b2), brows(b_x, O), brows(b_x, O));
}
/* Base fields, each question's routing over its options, and the field vectors. */
RAD_ISSUE_N(c, op_qproj, Q, brows(b_qv, Q), RAD_W(w_q), brows(b_bf, Q));
RAD_ISSUE_N(c, op_g_fr, O, brows(b_bf, Q), dev(L.o_q, O), brows(b_fr, O));
RAD_ISSUE_N(c, op_mul_sc, O, brows(b_x, O), brows(b_fr, O), brows(b_t1, O));
RAD_ISSUE_N(c, op_score, O, brows(b_t1, O), brows(b_sc, O));
RAD_ISSUE_N(c, op_route, O, brows(b_sc, O), brows(b_x, O), dev(L.opt_cu, Q + 1), brows(b_sum, Q));
RAD_ISSUE_N(c, op_ln_osn, Q, brows(b_sum, Q), RAD_W(osn_w), RAD_W(osn_b), brows(b_f1, Q));
RAD_ISSUE_N(c, op_add_f1, Q, brows(b_bf, Q), brows(b_f1, Q), brows(b_f, Q));
RAD_ISSUE_N(c, op_glob, 1, brows(b_g, 1), RAD_W(w_glob), brows(b_gw, 1));
RAD_ISSUE_N(c, op_add_fg, Q, brows(b_f, Q), brows(b_gw, 1), brows(b_f, Q));
RAD_ISSUE_N(c, op_type, Q, dev(L.type, Q), RAD_W(w_type), brows(b_f1, Q));
RAD_ISSUE_N(c, op_add_f2, Q, brows(b_f, Q), brows(b_f1, Q), brows(b_f, Q));
for (const Dec& d : dec) {
RAD_ISSUE_N(c, d.ln1, Q, brows(b_f, Q), RAD_W(d.n1w), RAD_W(d.n1b), brows(b_f1, Q));
RAD_ISSUE_N(c, d.qkv, Q, brows(b_f1, Q), RAD_W(d.sa_w), RAD_W(d.sa_b), RAD_NONE, brows(b_fq, Q));
RAD_ISSUE_N(c, d.sattn, Q, bcol(b_fq, 0, W, Q), bcol(b_fq, W, W, Q),
bcol(b_fq, 2 * W, W, Q), dev(L.cu_q, 2), brows(b_f1, Q));
RAD_ISSUE_N(c, d.so, Q, brows(b_f1, Q), RAD_W(d.so_w), RAD_W(d.so_b), brows(b_f, Q), brows(b_f, Q));
RAD_ISSUE_N(c, d.ln2, Q, brows(b_f, Q), RAD_W(d.n2w), RAD_W(d.n2b), brows(b_f1, Q));
RAD_ISSUE_N(c, d.pq, Q, brows(b_f1, Q), RAD_W(d.cq_w), RAD_W(d.cq_b), RAD_NONE, brows(b_f2, Q));
RAD_ISSUE_N(c, d.pk, N, brows(b_mem, N), RAD_W(d.ck_w), RAD_W(d.ck_b), RAD_NONE, brows(b_k, N));
RAD_ISSUE_N(c, d.pv, N, brows(b_mem, N), RAD_W(d.cv_w), RAD_W(d.cv_b), RAD_NONE, brows(b_v, N));
RAD_ISSUE_N(c, d.cattn, Q, brows(b_f2, Q), brows(b_k, N), brows(b_v, N),
dev(L.cu_q, 2), dev(L.cu_k, 2), brows(b_f1, Q));
RAD_ISSUE_N(c, d.co, Q, brows(b_f1, Q), RAD_W(d.co_w), RAD_W(d.co_b), brows(b_f, Q), brows(b_f, Q));
RAD_ISSUE_N(c, d.ln3, Q, brows(b_f, Q), RAD_W(d.n3w), RAD_W(d.n3b), brows(b_f1, Q));
RAD_ISSUE_N(c, d.f1, Q, brows(b_f1, Q), RAD_W(d.w1), RAD_W(d.b1), RAD_NONE, brows(b_ff, Q));
RAD_ISSUE_N(c, d.f2, Q, brows(b_ff, Q), RAD_W(d.w2), RAD_W(d.b2), brows(b_f, Q), brows(b_f, Q));
}
RAD_ISSUE_N(c, op_ln_fn, Q, brows(b_f, Q), RAD_W(fn_w), RAD_W(fn_b), brows(b_fn, Q));
/* The scorer: the cosine, the lexical prior and the residual, one value an option, into
* out3's three stretches (prior | cosine | residual). */
RAD_ISSUE_N(c, op_g_fr2, O, brows(b_fn, Q), dev(L.o_q, O), brows(b_fr, O));
RAD_ISSUE_N(c, op_ln_on, O, brows(b_x, O), RAD_W(on_w), RAD_W(on_b), brows(b_on, O));
RAD_ISSUE_N(c, op_rms_a, O, brows(b_fr, O), brows(b_na, O));
RAD_ISSUE_N(c, op_rms_b, O, brows(b_on, O), brows(b_nb, O));
RAD_ISSUE_N(c, op_mul_cos, O, brows(b_na, O), brows(b_nb, O), brows(b_t1, O));
RAD_ISSUE_N(c, op_mean_cos, O, brows(b_t1, O), out3(OM, O));
RAD_ISSUE_N(c, op_g_an, O, brows(b_qv, Q), dev(L.o_q, O), brows(b_an, O));
RAD_ISSUE_N(c, op_add_an, O, brows(b_an, O), brows(b_g, 1), brows(b_an, O));
RAD_ISSUE_N(c, op_rms_an, O, brows(b_an, O), brows(b_p, O));
RAD_ISSUE_N(c, op_rms_lex, O, brows(b_lex, O), brows(b_ln, O));
RAD_ISSUE_N(c, op_mul_pri, O, brows(b_p, O), brows(b_ln, O), brows(b_an, O));
RAD_ISSUE_N(c, op_mean_pri, O, brows(b_an, O), out3(0, O));
RAD_ISSUE_N(c, op_neg1, 1, brows(b_neg1, 1));
RAD_ISSUE_N(c, op_nd, O, brows(b_on, O), brows(b_neg1, 1), brows(b_nd, O));
RAD_ISSUE_N(c, op_d, O, brows(b_fr, O), brows(b_nd, O), brows(b_d, O));
RAD_ISSUE_N(c, op_relu_d, O, brows(b_d, O), brows(b_abs, O));
RAD_ISSUE_N(c, op_nd2, O, brows(b_d, O), brows(b_neg1, 1), brows(b_nd, O));
RAD_ISSUE_N(c, op_relu_nd, O, brows(b_nd, O), brows(b_nd, O));
RAD_ISSUE_N(c, op_abs, O, brows(b_abs, O), brows(b_nd, O), brows(b_abs, O));
RAD_ISSUE_N(c, op_prod, O, brows(b_fr, O), brows(b_on, O), brows(b_prod, O));
/* [field | option | field*option | |field-option|], then the scorer. The field rows go
* in again (a copy into the first block) so every block arrives the same way. */
RAD_ISSUE_N(c, op_cp_fr, O, brows(b_fr, O), bcol(b_feat, 0, W, O));
RAD_ISSUE_N(c, op_cp_on, O, brows(b_on, O), bcol(b_feat, W, W, O));
RAD_ISSUE_N(c, op_cp_prod, O, brows(b_prod, O), bcol(b_feat, 2 * W, W, O));
RAD_ISSUE_N(c, op_cp_abs, O, brows(b_abs, O), bcol(b_feat, 3 * W, W, O));
RAD_ISSUE_N(c, op_rs1, O, brows(b_feat, O), RAD_W(rs1_w), RAD_W(rs1_b), RAD_NONE, brows(b_r, O));
RAD_ISSUE_N(c, op_rs2, O, brows(b_r, O), RAD_W(rs2_w), RAD_W(rs2_b), RAD_NONE, out3(2 * OM, O));
/* The three stretches, as f32, into the request's logits row (one row of 3 OM). */
RAD_ISSUE_N(c, op_cast, 1, brows(b_out3, 3 * OM),
bcol_at(b_logits, row, n_vocab, 0, 3 * OM, 1));
}
}
} /* namespace arch */
} /* namespace rad */
+17
View File
@@ -38,6 +38,7 @@
*/
#include <arch/rad_arch.h>
#include <arch/rad_block_attn_gated.h>
#include <arch/rad_block_clef.h>
#include <arch/rad_block_gdn.h>
#include <arch/rad_block_mlp.h>
#include <arch/rad_block_vit.h>
@@ -85,6 +86,11 @@ struct Model {
VisionTower vit{};
MediaRows mrows{};
/* ---- clef's joint schema head (arch/common/rad_block_clef.h), declared only when the
* container says `decision.type=clef`; `clef.on` is false otherwise and every step below is
* the one it was. */
ClefHead clef{};
std::vector<Layer> layers;
};
@@ -424,6 +430,12 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
rad_note(b, "the %lld MTP/NextN layer(s) under `mtp.` are not declared: this plugin "
"serves the trunk only", (long long)nextn);
/* clef's head reads the final norm's rows and the lm_head, and keeps its own cache group,
* bound well past the trunk's layers. */
if (ClefHead::present(meta))
RAD_ARCH_TRY(m.clef.declare(b, meta, ctx, nm, g, m.b_h, m.b_logits, m.w_lm_head,
m.kv_full, (int)g.n_layer + 256));
/* The vision tower, last, so its activations share the arena with every buffer above. */
if (m.media) RAD_ARCH_TRY(m.vit.declare(b, meta, ctx, nm, g.n_embd, (int)g.n_layer + 64));
return RAD_OK;
@@ -455,6 +467,8 @@ static void step(RadCtx* c, const RadBatch* batch) {
RAD_ISSUE(c, m.op_final_norm,
brows(m.b_x, batch->n_tok), RAD_W(m.w_out_norm), brows(m.b_h, batch->n_tok));
/* clef: every token's final hidden state into the head's cache (a no-op without the head). */
m.clef.step_tokens(c, batch, m.b_h);
/* The lm_head runs only on the rows the sampler asked for; a mid-prompt prefill chunk has
* n_out zero and skips it. */
@@ -466,6 +480,9 @@ static void step(RadCtx* c, const RadBatch* batch) {
RAD_ISSUE_N(c, m.op_logits, batch->n_out,
brows(m.b_hout, batch->n_out), RAD_W(m.w_lm_head),
brows(m.b_logits, batch->n_out));
/* clef: the head over each sequence that carries a request's words, after the lm_head
* has written the row it adds to. */
m.clef.step_heads(c, batch, m.b_logits, m.w_lm_head);
}
}
+17
View File
@@ -86,6 +86,7 @@
#endif
#include <arch/rad_block_mtp_fp8.h>
#include <arch/rad_block_dflash2.h>
#include <arch/rad_block_clef.h>
#include <arch/rad_block_vit.h>
#include <cstring>
@@ -205,6 +206,10 @@ struct Model {
VisionTower vit{};
MediaRows mrows{};
/* ---- clef's joint schema head (arch/common/rad_block_clef.h), declared only when the
* container says `decision.type=clef`; off, every step below is the one it was. */
ClefHead clef{};
std::vector<Layer> layers;
/* The pipelined prefill (step_pipelined): on where declare allowed it; the bounds buffer it
@@ -1269,6 +1274,12 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
rad_note(b, "the %lld MTP/NextN layer(s) under `mtp.` are not loaded: this deployment "
"does not speculate", (long long)nextn);
/* clef's head (arch/common/rad_block_clef.h) reads the final norm's rows and the lm_head,
* and keeps its own cache group, bound well past the trunk's and a drafter's layers. */
if (ClefHead::present(meta))
RAD_ARCH_TRY(m.clef.declare(b, meta, ctx, nm, g, m.a_h.x, m.b_logits, m.w_lm_head,
m.kv_full, (int)g.n_layer + 256));
/* The vision tower, last: an encoder pass issues nothing else, so its activations share the
* arena with every buffer above. Its weight groups start past every text layer, the MTP head
* and a drafter's. */
@@ -1493,6 +1504,8 @@ static void step_pipelined(RadCtx* c, const RadBatch* batch, Model& m, const int
}
pipe_wait1(c);
if (L > 0) pipe_taps(c, m, L - 1, R, T - R);
/* clef: both pieces' final norm is done by here; the head's cache takes every row. */
m.clef.step_tokens(c, batch, m.a_h.x);
if (batch->n_out > 0) {
RAD_ISSUE_N(c, m.op_gather, batch->n_out,
@@ -1501,6 +1514,7 @@ static void step_pipelined(RadCtx* c, const RadBatch* batch, Model& m, const int
RAD_ISSUE_N(c, m.op_logits, batch->n_out,
brows(m.b_hout, batch->n_out), RAD_W(m.w_lm_head),
brows(m.b_logits, batch->n_out));
m.clef.step_heads(c, batch, m.b_logits, m.w_lm_head);
}
}
#endif
@@ -1596,6 +1610,8 @@ static void step(RadCtx* c, const RadBatch* batch) {
RAD_ISSUE(c, m.op_final_norm,
brows(m.b_x, batch->n_tok), RAD_W(m.w_out_norm), brows(m.a_h.x, batch->n_tok));
/* clef: every token's final hidden state into the head's cache (a no-op without the head). */
m.clef.step_tokens(c, batch, m.a_h.x);
if (batch->n_out > 0) {
RAD_ISSUE_N(c, m.op_gather, batch->n_out,
@@ -1605,6 +1621,7 @@ static void step(RadCtx* c, const RadBatch* batch) {
RAD_ISSUE_N(c, m.op_logits, batch->n_out,
brows(m.b_hout, batch->n_out), RAD_W(m.w_lm_head),
brows(m.b_logits, batch->n_out));
m.clef.step_heads(c, batch, m.b_logits, m.w_lm_head);
}
}
+13
View File
@@ -2431,6 +2431,19 @@ int Engine::run_server() {
o.audio_model = aud_gen_ != nullptr;
o.video_model = vid_gen_ != nullptr;
o.decision_type = rad_meta_gets(&meta_, "decision.type", "");
/* clef's learned scalars, which the server applies to what the head returns (server/clef.h);
* rad-convert writes them beside decision.type. */
if (o.decision_type == "clef") {
const char* const keys[3] = { "decision.clef.prior_logit_scale",
"decision.clef.joint_logit_scale",
"decision.clef.residual_gate" };
o.clef_scalars = true;
for (const char* k : keys) o.clef_scalars = o.clef_scalars && rad_meta_gets(&meta_, k, nullptr);
o.clef_prior_logit_scale = rad_meta_getf(&meta_, keys[0], 0.0);
o.clef_joint_logit_scale = rad_meta_getf(&meta_, keys[1], 0.0);
o.clef_residual_gate = rad_meta_getf(&meta_, keys[2], 0.0);
}
o.plugin_words = ranks_.empty() ? 0 : ranks_[0]->program.plugin_words;
o.model_id = !cfg_.served_model_name.empty() ? cfg_.served_model_name
: meta_.name && *meta_.name ? meta_.name : "radiance";
o.host = cfg_.host;
+104
View File
@@ -7,6 +7,8 @@
*/
#include "clef.h"
#include "rad_clef.h"
#include <nlohmann/json.hpp>
#include <algorithm>
@@ -202,6 +204,108 @@ int parse_clef_request(const std::string& body, const OaiDeps& d, const OaiLimit
return RAD_OK;
}
int64_t clef_option_count(const ClefRequest& r) {
int64_t o = 0;
for (const ClefQuestion& q : r.questions) o += (int64_t)q.options.size();
return o;
}
int clef_words(const ClefRequest& r, std::vector<int32_t>* out, ApiError* err) {
const int64_t N = (int64_t)r.tokens.size(), Q = (int64_t)r.questions.size();
const int64_t O = clef_option_count(r);
int64_t L = 0;
for (const ClefQuestion& q : r.questions)
for (const TokenSpan& s : q.option_spans) L += s.second - s.first;
if (Q > RAD_CLEF_MAX_QUESTIONS) {
*err = err_bad("questions", "at most " + std::to_string(RAD_CLEF_MAX_QUESTIONS) +
" questions a request");
return RAD_E_INVAL;
}
if (O > RAD_CLEF_MAX_OPTIONS) {
*err = err_bad("questions", "at most " + std::to_string(RAD_CLEF_MAX_OPTIONS) +
" options a request, every question together");
return RAD_E_INVAL;
}
if (L > RAD_CLEF_MAX_LEX) {
*err = err_bad("questions", "the options render to " + std::to_string(L) +
" tokens; at most " + std::to_string(RAD_CLEF_MAX_LEX) +
" a request");
return RAD_E_INVAL;
}
/* The prompt cut at every span's edges. Spans are disjoint, so each is one whole segment. */
std::vector<int32_t> cuts = { 0, (int32_t)N };
for (const ClefQuestion& q : r.questions) {
cuts.push_back((int32_t)q.question.first);
cuts.push_back((int32_t)q.question.second);
for (const TokenSpan& s : q.option_spans) {
cuts.push_back((int32_t)s.first);
cuts.push_back((int32_t)s.second);
}
}
std::sort(cuts.begin(), cuts.end());
cuts.erase(std::unique(cuts.begin(), cuts.end()), cuts.end());
const int64_t S = (int64_t)cuts.size() - 1;
auto seg_at = [&](int64_t start) {
return (int32_t)(std::lower_bound(cuts.begin(), cuts.end(), (int32_t)start) - cuts.begin());
};
const RadClefWords w = rad_clef_words_layout((int32_t)N, (int32_t)Q, (int32_t)O, (int32_t)L,
(int32_t)S);
std::vector<int32_t>& v = *out;
v.assign((size_t)w.total, 0);
v[RAD_CLEF_W_N] = (int32_t)N;
v[RAD_CLEF_W_Q] = (int32_t)Q;
v[RAD_CLEF_W_O] = (int32_t)O;
v[RAD_CLEF_W_L] = (int32_t)L;
v[RAD_CLEF_W_S] = (int32_t)S;
std::copy(cuts.begin(), cuts.end(), v.begin() + w.seg_cu);
int64_t o = 0, l = 0;
for (int64_t qi = 0; qi < Q; ++qi) {
const ClefQuestion& q = r.questions[(size_t)qi];
v[(size_t)(w.q_seg + qi)] = seg_at(q.question.first);
v[(size_t)(w.type + qi)] = q.type_id;
v[(size_t)(w.opt_cu + qi)] = (int32_t)o;
for (const TokenSpan& s : q.option_spans) {
v[(size_t)(w.o_seg + o)] = seg_at(s.first);
v[(size_t)(w.o_q + o)] = (int32_t)qi;
v[(size_t)(w.lex_cu + o)] = (int32_t)l;
for (int64_t t = s.first; t < s.second; ++t) v[(size_t)(w.lex_ids + l++)] = r.tokens[(size_t)t];
++o;
}
}
v[(size_t)(w.opt_cu + Q)] = (int32_t)O;
v[(size_t)(w.lex_cu + O)] = (int32_t)L;
v[(size_t)w.last] = (int32_t)(N - 1);
v[(size_t)w.cu_q] = 0; v[(size_t)w.cu_q + 1] = (int32_t)Q;
v[(size_t)w.cu_o] = 0; v[(size_t)w.cu_o + 1] = (int32_t)O;
v[(size_t)w.cu_k] = 0; v[(size_t)w.cu_k + 1] = (int32_t)N;
return RAD_OK;
}
std::vector<int32_t> clef_score_ids(int64_t n_options) {
std::vector<int32_t> ids;
ids.reserve((size_t)(3 * n_options));
for (int k = 0; k < 3; ++k)
for (int64_t o = 0; o < n_options; ++o) ids.push_back((int32_t)(k * RAD_CLEF_MAX_OPTIONS + o));
return ids;
}
std::vector<float> clef_logits(const std::vector<float>& scores, int64_t n_options,
const ClefScalars& s) {
const double cap = std::log(100.0);
const double ps = std::exp(std::min(s.prior_logit_scale, cap));
const double js = std::exp(std::min(s.joint_logit_scale, cap));
const double gate = 1.0 / (1.0 + std::exp(-s.residual_gate));
std::vector<float> out((size_t)n_options, 0.0f);
if ((int64_t)scores.size() < 3 * n_options) return out;
for (int64_t o = 0; o < n_options; ++o) {
const double prior = scores[(size_t)o], cosine = scores[(size_t)(n_options + o)];
const double residual = scores[(size_t)(2 * n_options + o)];
out[(size_t)o] = (float)(ps * prior + gate * (js * cosine + residual));
}
return out;
}
int clef_answer(const ClefQuestion& q, const std::vector<float>& logits, json* out, ApiError* err) {
if (logits.size() != q.options.size()) {
*err = err_internal("the head returned no logits for question " + q.name);
+24
View File
@@ -59,5 +59,29 @@ int clef_answer(const ClefQuestion& q, const std::vector<float>& logits, json* o
* sorted and non-ASCII kept. Exposed for the tests. */
std::string clef_render(const json& v);
/* The request's words for the head on the card (abi/rad_clef.h, Request::plugin_words): the
* prompt cut into segments at every span's edges, which segment each question and option is,
* each option's question and tokens, each question's type. 400 past the head's bounds. */
int clef_words(const ClefRequest& r, std::vector<int32_t>* out, ApiError* err);
/* The options a request has in all, in head order: the head returns three values for each. */
int64_t clef_option_count(const ClefRequest& r);
/* The logits-row positions the head's three values an option land at (prior, cosine, residual;
* each stretch RAD_CLEF_MAX_OPTIONS wide), as TokenScores asks for them. */
std::vector<int32_t> clef_score_ids(int64_t n_options);
/* The head's learned scalars, from the container header (rad-convert writes them from
* joint_head.safetensors; the engine copies them to ServerOptions). */
struct ClefScalars {
double prior_logit_scale = 0.0, joint_logit_scale = 0.0, residual_gate = 0.0;
};
/* One logit an option from the head's three values (`scores` in clef_score_ids' order):
* exp(prior_logit_scale) * prior + sigmoid(residual_gate) * (exp(joint_logit_scale) * cosine +
* residual), the scales clamped at 100 as the release clamps them. */
std::vector<float> clef_logits(const std::vector<float>& scores, int64_t n_options,
const ClefScalars& s);
} /* namespace server */
} /* namespace rad */
+91 -1
View File
@@ -2,6 +2,7 @@
#include "server_priv.h"
#include <cstdio>
#include "clef.h"
#include "json_partial.h"
#include "systemone.h"
#include "rad_internal.h"
@@ -1744,10 +1745,12 @@ HttpResponse Server::handle_embeddings(const HttpRequest& req) {
HttpResponse Server::handle_systemone(const HttpRequest& req) {
if (!deps_.sched || !deps_.tok)
return error_response(err_not_implemented("the server has no engine attached"), req.peer);
if (opt_.decision_type == "clef") return handle_clef(req);
if (opt_.decision_type != "d1")
return error_response(err_not_implemented(
"/v1/systemone serves a decision model; this container does not declare one "
"(convert d1 with --set decision.type=d1)"), req.peer);
"(convert d1 with --set decision.type=d1, clef with --set decision.type=clef)"),
req.peer);
DecisionRequest r;
ApiError err;
@@ -1862,6 +1865,93 @@ HttpResponse Server::handle_systemone(const HttpRequest& req) {
{ "usage", { { "input_tokens", r.input_tokens }, { "output_tokens", 0 } } } }));
}
/* clef (clef.h): one request is the whole prompt, every question decided jointly by the head on
* the card (arch/common/rad_block_clef.h). The request's spans and option tokens go down as its
* words, and the head's three values an option come back through Request::token_scores, off the
* logits row; the learned scalars combine them here and each question's softmax is its answer. */
HttpResponse Server::handle_clef(const HttpRequest& req) {
if (!opt_.clef_scalars)
return error_response(err_internal("this container declares clef but carries no "
"decision.clef.* scalars; convert it again with "
"rad-convert --set decision.type=clef"), req.peer);
ClefRequest r;
ApiError err;
if (parse_clef_request(req.body, odeps_, lim_, opt_.model_id, &r, &err) < 0)
return error_response(err, req.peer);
std::vector<int32_t> words;
if (clef_words(r, &words, &err) < 0) return error_response(err, req.peer);
if ((int64_t)words.size() > opt_.plugin_words)
return error_response(err_internal("the loaded plugin takes fewer words a request than "
"this one needs"), req.peer);
const int64_t n_opt = clef_option_count(r);
if (auto no = admit(1, req.peer, ApiShape::OpenAI, "questions")) return *no;
RAD_INFO("systemone (clef) admitted%s questions=%zu options=%lld prompt=%zu tok",
from_peer(req.peer).c_str(), r.questions.size(), (long long)n_opt, r.tokens.size());
std::vector<Generation> gens(1);
Generation& g = gens[0];
g.index = 0;
g.sink = std::make_shared<Sink>(16);
auto ts = std::make_shared<TokenScores>();
ts->tokens = clef_score_ids(n_opt);
Request rq;
rq.prompt = r.tokens;
rq.token_scores = ts;
rq.plugin_words = std::move(words);
rq.max_tokens = 1;
rq.sp.temp = 0.0f;
rq.sink = g.sink.get();
std::vector<Request> part;
part.push_back(std::move(rq));
std::vector<uint64_t> ids;
deps_.sched->submit_all(part, &ids);
g.id = ids.empty() ? 0 : ids[0];
g.sink->id = g.id;
if (!g.id) {
retire(gens);
release(1);
return error_response(err_internal("the scheduler refused the request"), req.peer);
}
for (;;) {
if (g.sink->done()) { g.closed = true; g.finish = g.sink->finish_reason(); break; }
if (req.peer_gone() || stopping_.load()) return *abandoned(req, gens, 1);
g.sink->wait();
}
if (g.finish == Finish::Error || g.finish == Finish::Cancelled) {
const std::string why = g.finish == Finish::Error ? engine_failure(*g.sink)
: "the engine cancelled the request";
retire(gens);
release(1);
return error_response(err_internal(why), req.peer);
}
ClefScalars sc;
sc.prior_logit_scale = opt_.clef_prior_logit_scale;
sc.joint_logit_scale = opt_.clef_joint_logit_scale;
sc.residual_gate = opt_.clef_residual_gate;
const std::vector<float> logits = clef_logits(ts->logits, n_opt, sc);
json answers = json::object();
size_t at = 0;
for (const ClefQuestion& q : r.questions) {
std::vector<float> ql(logits.begin() + (std::ptrdiff_t)at,
logits.begin() + (std::ptrdiff_t)(at + q.options.size()));
at += q.options.size();
json a;
if (clef_answer(q, ql, &a, &err) < 0) {
retire(gens);
release(1);
return error_response(err, req.peer);
}
answers[q.name] = std::move(a);
}
retire(gens);
release(1);
metrics_.observe_http(200);
return HttpResponse::json_body(200, json_dump(json{
{ "answers", std::move(answers) },
{ "usage", { { "input_tokens", (int64_t)r.tokens.size() }, { "output_tokens", 0 } } } }));
}
HttpResponse Server::handle_models(const HttpRequest& req) {
const std::string id = req.param("id");
/* Runtime LoRA: each loaded adapter is a model of its own, whose parent is the served one. */
+9 -1
View File
@@ -82,8 +82,15 @@ struct ServerOptions {
int64_t video_ttl_s = 3600;
int64_t max_videos = 32;
/* The decision protocol from the container's `decision.type`: "d1" serves /v1/systemone
* (systemone.h); empty answers it 501. Never inferred from a name. */
* (systemone.h), "clef" serves it through the head on the card (clef.h); empty answers it
* 501. Never inferred from a name. */
std::string decision_type;
/* clef: the head's learned scalars from the container header (decision.clef.*, written by
* rad-convert from joint_head.safetensors), and whether the header carried them. */
double clef_prior_logit_scale = 0.0, clef_joint_logit_scale = 0.0, clef_residual_gate = 0.0;
bool clef_scalars = false;
/* The most words one request may hand the plugin (Program::plugin_words). */
int64_t plugin_words = 0;
/* What --model named, reported as the model entry's `root` as vLLM reports its loaded path
* (the served name says nothing about the file behind it). Empty omits the field. */
std::string model_path;
@@ -243,6 +250,7 @@ private:
HttpResponse handle_infill(const HttpRequest& req);
HttpResponse handle_embeddings(const HttpRequest& req);
HttpResponse handle_systemone(const HttpRequest& req);
HttpResponse handle_clef(const HttpRequest& req);
HttpResponse handle_apply_template(const HttpRequest& req);
using ToChat = int (*)(const std::string& body, const OaiLimits& lim, std::string* chat,
std::string* extra, ApiError* err);
+33 -1
View File
@@ -2039,7 +2039,7 @@ flags are refused on it, and so are the pixel bands.
| `POST /v1/completions` | raw text completion |
| `POST /v1/embeddings` | needs a model with an embedding head, else 501 |
| `POST /v1/images/generations`, `POST /v1/images/edits` | OpenAI's images API; needs an image model (Qwen-Image 2.1), else 501 (§5.6) |
| `POST /v1/systemone` | LiquidAI d1's decisions over a state: named yes/no, choice and score questions answered as probabilities, nothing generated; needs a container converted as d1, else 501 (§5.13) |
| `POST /v1/systemone` | Decisions over a state: named yes/no, choice and score questions answered as probabilities, nothing generated; LiquidAI's d1, or Cloudflare's clef and clef-flash with their joint head on the card; needs a container converted as one, else 501 (§5.13). `POST /v1/decisions` is the same endpoint under LiteLLM's name |
| `POST /v1/audio/transcriptions` | OpenAI's speech to text, for a model whose plugin transcribes (Qwen3-ASR), else 501 (§5.14) |
| `GET /v1/realtime` (WebSocket) | OpenAI's realtime transcription session: audio streamed in, the words back as they are spoken (§5.14) |
| `POST /v1/audio/speech` | OpenAI's speech API, whole or streamed: speech from a speech model (Breeze-TTS-2, `instructions` describing the voice; drama-3, speakers and direction in the input); songs from a music model (MiniMax-Music3), `input` the lyrics and `instructions` the song; else 501 (§5.15) |
@@ -2754,6 +2754,38 @@ together. A single question is one pass of the whole prompt, tokenised as one te
Against d1's own runner in float32, on eight text cases (one and several questions, JSON and long log
states): every choice and every `input_tokens` equal, worst probability difference 0.0044.
#### clef and clef-flash
Cloudflare's clef (27B) and clef-flash (9B) are decision models on Qwen3.5 that answer the same
request, every question of it jointly: a joint schema head reads the backbone's final hidden state
at every prompt position, the mean over each question's instructions and each option's text, and
the lm_head rows of each option's tokens, and gives one logit an option. radiance runs that head
on the card, after the trunk, inside the `qwen35_bf16` and `qwen35_fp8` plugins
(`arch/common/rad_block_clef.h`): there is no second process. The head's own tensors ship as
`joint_head.safetensors` beside the checkpoint and are added at convert; `joint_head_config.json`
beside them gives the head's geometry.
```sh
rad-convert /srv/models/clef-flash -o clef-flash.rad \
--add /srv/models/clef-flash/joint_head.safetensors --set decision.type=clef
radiance --model clef-flash.rad --port 8000
```
The request and the response are the same as d1's above; `/v1/decisions` is the same endpoint
under LiteLLM's name. What differs:
- One request is one prompt, the state and every question together, so questions are not shared
through the prefix cache; a state many requests share (the rules in front of each respondent)
is, with the head's own per-token rows beside the trunk's cache.
- `state` must be a non-empty string or JSON value; pictures answer 501 for now.
- A prompt longer than the context answers 400 with `context_length_exceeded` (clef's own code
cuts it silently). A request has at most 64 questions, 512 options and 8192 option tokens.
- The head runs on one rank, and the lm_head stays bf16 (a recipe that quantises it is refused).
- `GET /v1/models` reports `"decision": "clef"` in the model's capabilities.
Against clef's own head on the CPU reference, on a tiny model with random weights
(`tests/clef_decision_test.cpp`): worst probability difference 0.0004.
### 5.14 Speech to text
A model whose architecture plugin says how it transcribes -- Qwen3-ASR, served as its checkpoint
+24 -22
View File
@@ -1,42 +1,44 @@
<!-- Machine-drafted by Claude (Opus 5.5) on 2026-10-27. Decision by the user. -->
<!-- Machine-drafted by Claude (Opus 5.5, then Fable 5.1) on 2026-10-27 and 2026-10-28. Decision by the user. -->
# ADR 0001: clef's joint head runs on the GPU, inside the qwen35 plugins
Status: accepted, 2026-10-27.
Status: accepted 2026-10-27, built 2026-10-28.
## Context
Issue #166 asks radiance to serve clef and clef-flash on `/v1/systemone` with no Python sidecar. clef's head reads the final hidden state of every prompt token, not one position as d1 does. Two places fit: the GPU, inside `qwen35_bf16` and `qwen35_fp8`, or the CPU, in the server.
On threadripper, fp8 clef-flash serves 1.43 respondents/s on 13k-token guidance prompts and 9.16 on 676-token prompts. The PyTorch head takes 8.6 ms of the 95 ms short-prompt time (`bench/timings.md`). The CPU head is estimated at 60-120 ms on a short prompt and 0.4-0.9 s on a 13k-token cache miss. That figure is inferred, not measured.
On threadripper, fp8 clef-flash with the head in a PyTorch sidecar served 1.43 respondents/s on 13k-token guidance prompts and 9.16 on 676-token prompts. The PyTorch head took 8.6 ms of the 95 ms short-prompt time (`bench/timings.md`). A CPU head was estimated at 60-120 ms on a short prompt and 0.4-0.9 s on a 13k-token cache miss (inferred, not measured).
## Decision
The head runs on the GPU, in the plugin step. The per-token part (LayerNorm, memory projection, and K and V for the 6 cross-attention layers) is written into a paged FULL KV group during the trunk step, so the prefix cache keeps it. A per-request tail pass runs the query side over those planes.
The head runs on the GPU, in the plugin step (`arch/common/rad_block_clef.h`), with these parts:
## Reuse, before any new code
1. Every step, the final norm's rows go through the head's `hidden_norm` and into a paged FULL KV group of the head's own (`clef.kv`, one layer bound past the trunk's). Its block size is the trunk's, so the prefix cache keeps those rows with the trunk's cache. 8 KB a token on clef-flash.
2. On the step that samples a prompt's first token, the head gathers every row of its group back out (`gather_rows` over the sequence's block table, the way the KV tier packs blocks), runs the memory projection and the six cross-attention layers over all of them, averages the question and option spans, routes, runs the decoder layers and the scorer, and writes three values an option (lexical prior, cosine, residual) into the request's logits row.
3. The request's spans, option tokens and question types reach the plugin as integer words (`Request::plugin_words`, `RadBatch::plugin_words`, laid out by `abi/rad_clef.h`). This is the one ABI change: version 32, five trailing fields on `RadBatch`, and `rad_declare_plugin_words`. A pass carrying words is never recorded for replay.
4. The server reads the three values through `Request::token_scores`, as d1 does, and applies the head's three learned scalars from the container header (`decision.clef.*`, written by `rad-convert` from `joint_head.safetensors` and `joint_head_config.json`).
## What was reused, and the one new kernel
| Head piece | Existing code |
| --- | --- |
| LayerNorm with bias | `layernorm` op, as in `arch/common/rad_block_vit.h` |
| Linear, with or without bias, fused exact GELU | `gemm_nt_bias` (`act "gelu"`), `gemm_nt` |
| Self-attention over the field rows | `attn_dense`, `causal 0`, head_dim 64 |
| Cross-attention over the memory rows | `attn_cross` or a paged read of the clef KV group |
| Span means, lm_head row means | `seg_mean`, `gather_rows`, `embed_lookup` / `embed_lookup_q` |
| Per-token K/V kept in the prefix cache | a FULL KV group, bound past `n_layers` as `drafter_kv_group` does |
| LayerNorm with bias, linear with bias and fused exact GELU | `layernorm`, `gemm_nt_bias`, as the vision tower uses them |
| Self-attention over the field rows | `attn_dense`, `causal 0` |
| Field and option rows over every prompt token | `attn_cross`, as sdxl uses it |
| Span means, lm_head rows of the option tokens | `seg_mean`, `gather_rows`, `embed_lookup` |
| Per-token rows kept across requests | a FULL KV group, `kv_store`, the prefix cache |
| Rows back out of the group | `gather_rows` over the pool, one block a row |
| Cosine and prior | `rmsnorm_p` on both rows, then the row mean of their product (an identity) |
| Head weights in the container | `rad-convert --add joint_head.safetensors --set decision.type=clef` |
| Weights optional, gated on metadata | `RadWeightDecl::optional`, gated like the vision tower |
| Result back to the server | the `token_scores` path: stage, issue, collect in `core/engine.cpp` |
| Prompt, spans, answer | `core/server/clef.cpp` (commit 82c114e) |
| The answer back to the server | the `token_scores` path, unchanged |
## New code this needs
1. A per-request payload on `Request` and `RadBatch`: question and option spans, type ids, option token ids.
2. A per-request head tail in the plugin step, and a small logits buffer the engine copies out.
3. A GPU `softmax` kernel for the option routing weights. Only CPU kernels exist.
4. The three learned scalars (`prior_logit_scale`, `joint_logit_scale`, `residual_gate`) go through `exp` and `sigmoid`. The plugin returns prior, cosine and residual per option, and the server combines them, so no `exp` kernel is needed.
5. Span rows must be fresh: prefix reuse stops at the start of the schema, so the span hidden states are always computed in the request's own step.
One kernel did not exist: a softmax-weighted sum over each question's options (`seg_softmax_pool`), added to libref, libavx and libr4d with its schema, shape, self-test case and `docs/OPS.md` entry. `softmax` had only host kernels, and a weightless op with no device kernel is a hole the engine refuses.
## Consequences
The clef KV group needs an attention consumer at block size 16, or the prefix cache silently drops it. The startup report names such a group "not cached". Cosine and dot products run in bf16, so answers can differ from PyTorch in the third decimal place. The golden test measures that difference.
- The head runs on one rank: `world > 1` is refused at declare. clef 27B in bf16 needs two cards and so is not served with the head yet.
- The lm_head must stay bf16 (the head averages its rows); a recipe that quantises it is refused at declare.
- A request has at most 64 questions, 512 options and 8192 option tokens (`abi/rad_clef.h`); past that the server answers 400.
- `tests/clef_decision_test.cpp` serves a tiny clef on the CPU and compares every probability with the release's own head in float32 (`tests/mkclefgolden.py`): largest difference 0.0004 on 2026-10-28.
- bf16 through the head moves a probability by up to a few hundredths against PyTorch on the real model; the 100-respondent runs in `bench/timings.md` measure it.
+12 -2
View File
@@ -301,12 +301,19 @@ set(RAD_E2E_DEPS radiance rad-convert libref libquant qwen35_bf16 lfm2_bf16 gemm
if(TARGET libavx)
list(APPEND RAD_E2E_DEPS libavx)
endif()
foreach(t engine_e2e_test convert_test)
foreach(t engine_e2e_test convert_test clef_decision_test)
if(TARGET ${t})
target_compile_definitions(${t} PRIVATE
RAD_E2E_SERVER="$<TARGET_FILE:radiance>" RAD_E2E_CONVERT="$<TARGET_FILE:rad-convert>"
RAD_E2E_HOME="${RAD_PLUGIN_OUT}" RAD_E2E_RECIPES="${CMAKE_SOURCE_DIR}/data/recipes")
add_dependencies(${t} ${RAD_E2E_DEPS})
if(t STREQUAL "clef_decision_test")
# The tiny clef's golden (tests/mkclefgolden.py) and the one plugin a clef container selects.
target_compile_definitions(${t} PRIVATE
RAD_CLEF_GOLDEN="${CMAKE_CURRENT_SOURCE_DIR}/data/golden/clef_tiny.json")
add_dependencies(${t} radiance rad-convert libref libquant qwen35_bf16)
else()
add_dependencies(${t} ${RAD_E2E_DEPS})
endif()
endif()
endforeach()
# 6 to 17 s by build type and load, mostly libref's GEMMs and decode steps and the engine's own
@@ -314,6 +321,9 @@ endforeach()
if(TARGET engine_e2e_test)
set_tests_properties(engine_e2e_test PROPERTIES LABELS "e2e" TIMEOUT 300)
endif()
if(TARGET clef_decision_test)
set_tests_properties(clef_decision_test PROPERTIES LABELS "e2e" TIMEOUT 300)
endif()
# abi_layout_test compares the ABI's struct layouts with a C translation unit's: abi_c_test.c
# includes every abi/ header as strict C11, so a header only C++ accepts fails the build.
+397
View File
@@ -0,0 +1,397 @@
/* clef_decision_test.cpp -- /v1/systemone on a clef container, end to end on the CPU.
*
* A tiny qwen35 (tests/tiny_model.h) with a tiny joint schema head of its own, converted with the
* head added and `decision.type=clef`, served by the radiance binary on the host backend. The
* answers are checked against tests/data/golden/clef_tiny.json, the release's own head
* (joint_schema_model.py) over transformers' forward pass in float32, made by
* tests/mkclefgolden.py from the checkpoint this test writes (RAD_E2E_KEEP=1 keeps it). The
* golden carries the weights' hashes, so a golden for other weights is refused by name.
*
* What one run covers: the prompt and spans from the request, the words to the plugin, the
* head's cache group filled over two prefill chunks, the gather of every row back out of it, the
* head's own ops on libref, the three values an option through the logits row, the scalars from
* the container header; then the same request again, a whole prefix hit, so the head reads every
* row from the cache alone; and the bounds and the image refusal.
*/
#include "rad_test.h"
#include "tiny_model.h"
#include "rad_clef.h"
#include <nlohmann/json.hpp>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <cerrno>
#include <cmath>
#include <condition_variable>
#include <cstring>
#include <fstream>
#include <mutex>
#include <thread>
using json = nlohmann::json;
namespace {
std::vector<std::string> engine_env() {
return { "ROCR_VISIBLE_DEVICES=99", "RADIANCE_HOST_VRAM_MIB=1024", "OMP_WAIT_POLICY=passive",
"OMP_NUM_THREADS=2", std::string("RADIANCE_HOME=") + RAD_E2E_HOME };
}
std::vector<std::string> engine_argv(const std::string& model,
const std::vector<std::string>& args) {
std::vector<std::string> a = { RAD_E2E_SERVER, "--model", model, "--kernels", "libref",
"--debug-accept-reference-kernels" };
a.insert(a.end(), args.begin(), args.end());
return a;
}
std::string tail(const std::string& log, int n = 14) {
size_t at = log.size();
for (int i = 0; i <= n && at != std::string::npos && at > 0; ++i) at = log.rfind('\n', at - 1);
return at == std::string::npos || at >= log.size() ? log : log.substr(at + 1);
}
/* A server on a free loopback port (as engine_e2e_test.cpp runs one). */
struct Server {
tiny::Child child;
std::thread drain;
std::mutex mu;
std::condition_variable cv;
std::string log;
bool eof = false;
int port = 0;
bool start(const std::string& model, const std::vector<std::string>& args) {
std::vector<std::string> a = { "--host", "127.0.0.1", "--port", "0" };
a.insert(a.end(), args.begin(), args.end());
if (!child.start(engine_argv(model, a), engine_env())) return false;
drain = std::thread([this] {
char buf[4096];
for (;;) {
const ssize_t n = ::read(child.fd, buf, sizeof buf);
if (n < 0 && errno == EINTR) continue;
std::lock_guard<std::mutex> lk(mu);
if (n <= 0) { eof = true; cv.notify_all(); return; }
log.append(buf, (size_t)n);
cv.notify_all();
}
});
static const std::string kTag = "listening on http://127.0.0.1:";
std::unique_lock<std::mutex> lk(mu);
cv.wait(lk, [&] { return eof || log.find(kTag) != std::string::npos; });
const size_t at = log.find(kTag);
if (at != std::string::npos) port = std::atoi(log.c_str() + at + kTag.size());
if (port <= 0) fprintf(stderr, " the server did not start:\n%s\n", tail(log).c_str());
return port > 0;
}
int stop() {
if (child.pid <= 0) return -1;
kill(child.pid, SIGTERM);
if (drain.joinable()) drain.join();
close(child.fd);
child.fd = -1;
std::string rest;
return child.wait(&rest);
}
std::string output() {
std::lock_guard<std::mutex> lk(mu);
return log;
}
~Server() {
if (child.pid > 0) kill(child.pid, SIGKILL);
if (drain.joinable()) drain.join();
}
};
/* One request on its own loopback connection. */
struct Call {
int fd = -1;
std::string why;
bool fail(const char* what) {
why = std::string(what) + ": " + std::strerror(errno);
return false;
}
bool send(int port, const char* method, const std::string& path, const std::string& body) {
fd = socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
if (fd < 0) return fail("socket");
sockaddr_in a{};
a.sin_family = AF_INET;
a.sin_port = htons((uint16_t)port);
a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
if (connect(fd, (sockaddr*)&a, sizeof a) != 0) return fail("connect");
std::string req = std::string(method) + " " + path + " HTTP/1.1\r\nHost: 127.0.0.1\r\n" +
"Connection: close\r\nContent-Type: application/json\r\n" +
"Content-Length: " + std::to_string(body.size()) + "\r\n\r\n" + body;
for (size_t off = 0; off < req.size();) {
const ssize_t n = ::send(fd, req.data() + off, req.size() - off, MSG_NOSIGNAL);
if (n <= 0) return fail("send");
off += (size_t)n;
}
return true;
}
int read(std::string* body) {
std::string raw;
char buf[16384];
for (;;) {
const ssize_t n = ::recv(fd, buf, sizeof buf, 0);
if (n < 0 && errno == EINTR) continue;
if (n <= 0) break;
raw.append(buf, (size_t)n);
}
close(fd);
fd = -1;
const size_t h = raw.find("\r\n\r\n");
if (raw.compare(0, 9, "HTTP/1.1 ") != 0 || h == std::string::npos) {
why = "no response (" + std::to_string(raw.size()) + " bytes)";
return -1;
}
std::string head = raw.substr(0, h), rest = raw.substr(h + 4);
for (char& c : head) c = (char)std::tolower((unsigned char)c);
if (head.find("transfer-encoding: chunked") != std::string::npos) {
std::string out;
for (size_t at = 0;;) {
const size_t eol = rest.find("\r\n", at);
if (eol == std::string::npos) break;
const size_t n = std::strtoul(rest.c_str() + at, nullptr, 16);
if (n == 0) break;
out += rest.substr(eol + 2, n);
at = eol + 2 + n + 2;
}
rest = out;
}
*body = rest;
return std::atoi(raw.c_str() + 9);
}
~Call() { if (fd >= 0) close(fd); }
};
json call(int port, const char* method, const std::string& path, const json& body, int* status) {
Call c;
std::string out;
const int st = c.send(port, method, path, body.is_null() ? "" : body.dump()) ? c.read(&out) : -1;
*status = st;
if (st < 0) fprintf(stderr, " %s %s: %s\n", method, path.c_str(), c.why.c_str());
return json::parse(out, nullptr, false);
}
uint64_t fnv1a(const std::string& path) {
std::ifstream f(path, std::ios::binary);
std::string bytes((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());
uint64_t h = 0xcbf29ce484222325ull;
for (unsigned char c : bytes) h = (h ^ c) * 0x100000001b3ull;
return h;
}
std::string hex16(uint64_t v) {
char s[24];
std::snprintf(s, sizeof s, "%016llx", (unsigned long long)v);
return s;
}
/* The tiny clef: tiny_model.h's qwen35 (hidden 64) and a head of width 64 with one head of 64
* (libr4d's attention width, so the same declaration serves the card), feedforward 128, one
* routing and one decoder layer; LayerNorm gains near one, every linear at unit gain, the three
* scalars fixed. The release's tensor names, so rad-convert and the plugin read them as they
* read clef-flash's. */
bool write_tiny_clef(const std::string& dir, uint64_t seed) {
tiny::Qwen35 s;
s.seed = seed;
/* The head writes three stretches of RAD_CLEF_MAX_OPTIONS into a logits row, so the
* vocabulary must hold them; the byte tokenizer uses the first 259 ids. */
s.vocab = 2048;
if (!tiny::write_qwen35(dir, s)) return false;
const int64_t E = s.hidden, W = 64, F = 128;
tiny::Rng r(seed + 500);
std::vector<tiny::Tensor> ts;
auto ln = [&](const std::string& p, int64_t n) {
ts.push_back(tiny::noise(p + ".weight", { n }, r, 0.1f, 1.0f));
ts.push_back(tiny::noise(p + ".bias", { n }, r, 0.1f));
};
auto lin = [&](const std::string& p, int64_t n_out, int64_t n_in, bool bias) {
ts.push_back(tiny::linear(p + ".weight", n_out, n_in, r));
if (bias) ts.push_back(tiny::noise(p + ".bias", { n_out }, r, 0.1f));
};
/* torch.nn.MultiheadAttention packs q, k and v as in_proj_weight and in_proj_bias. */
auto in_proj = [&](const std::string& p) {
ts.push_back(tiny::linear(p + ".in_proj_weight", 3 * W, W, r));
ts.push_back(tiny::noise(p + ".in_proj_bias", { 3 * W }, r, 0.1f));
};
ln("hidden_norm", E);
for (const char* p : { "memory_projection", "question_projection", "option_question_projection",
"global_projection", "option_context_projection",
"option_lexical_projection" })
lin(p, W, E, false);
ts.push_back(tiny::noise("type_embedding.weight", { 3, W }, r, 0.5f));
for (int i = 0; i < 1; ++i) {
const std::string p = "evidence_layers." + std::to_string(i) + ".";
ln(p + "query_norm", W);
ln(p + "memory_norm", W);
in_proj(p + "attention");
lin(p + "attention.out_proj", W, W, true);
ln(p + "feedforward_norm", W);
lin(p + "feedforward.0", F, W, true);
lin(p + "feedforward.3", W, F, true);
}
ln("option_summary_norm", W);
for (int i = 0; i < 1; ++i) {
const std::string p = "layers." + std::to_string(i) + ".";
in_proj(p + "self_attn");
lin(p + "self_attn.out_proj", W, W, true);
in_proj(p + "multihead_attn");
lin(p + "multihead_attn.out_proj", W, W, true);
lin(p + "linear1", F, W, true);
lin(p + "linear2", W, F, true);
ln(p + "norm1", W);
ln(p + "norm2", W);
ln(p + "norm3", W);
}
ln("field_norm", W);
ln("option_norm", W);
lin("residual_scorer.0", W, 4 * W, true);
lin("residual_scorer.3", 1, W, true);
ts.push_back(tiny::noise("prior_logit_scale", {}, r, 0.0f, 0.5f));
ts.push_back(tiny::noise("joint_logit_scale", {}, r, 0.0f, 0.5f));
ts.push_back(tiny::noise("residual_gate", {}, r, 0.0f, -1.0f));
if (!tiny::write_safetensors(dir + "/joint_head.safetensors", ts)) return false;
nlohmann::ordered_json c;
c["hidden_size"] = E;
c["width"] = W;
c["routing_layers"] = 1;
c["layers"] = 1;
c["heads"] = 1;
c["feedforward"] = F;
return tiny::write_text(dir + "/joint_head_config.json", c.dump(2));
}
double prob(const json& answers, const char* q, const char* field, const char* option) {
const json& a = answers.at(q);
if (option) return a.at("probabilities").at(option).get<double>();
return a.at(field).get<double>();
}
} /* namespace */
TEST(a_clef_container_decides_every_question_on_the_card_and_matches_the_release) {
const bool keep = std::getenv("RAD_E2E_KEEP") != nullptr;
tiny::TempDir dir{ "clef", keep };
REQUIRE(dir.ok());
const std::string ck = dir / "clef-tiny";
REQUIRE_EQ(mkdir(ck.c_str(), 0755), 0);
REQUIRE(write_tiny_clef(ck, 7));
if (keep) fprintf(stderr, " the tiny clef is kept at %s (tests/mkclefgolden.py)\n", ck.c_str());
/* Converted with the head added; the head's geometry and scalars land in the header. */
const std::string rad = dir / "clef-tiny.rad";
std::string log;
const int st = tiny::run({ RAD_E2E_CONVERT, ck, "-o", rad, "--add",
ck + "/joint_head.safetensors", "--set", "decision.type=clef" },
engine_env(), &log, 300);
if (st != 0) fprintf(stderr, " rad-convert exited %d:\n%s\n", st, tail(log).c_str());
REQUIRE_EQ(st, 0);
CHECK(log.find("clef head 64 x 1") != std::string::npos);
std::ifstream gf(RAD_CLEF_GOLDEN);
if (!gf.is_open())
fprintf(stderr, " no golden at %s: run this test with RAD_E2E_KEEP=1, then "
"tests/mkclefgolden.py on the kept directory\n", RAD_CLEF_GOLDEN);
REQUIRE(gf.is_open());
const json gold = json::parse(gf);
const std::string wf = hex16(fnv1a(ck + "/model.safetensors"));
const std::string hf = hex16(fnv1a(ck + "/joint_head.safetensors"));
if (gold["weights_fnv"] != wf || gold["head_fnv"] != hf)
fprintf(stderr, " the golden was made from other weights (%s / %s here): regenerate "
"it with tests/mkclefgolden.py\n", wf.c_str(), hf.c_str());
REQUIRE(gold["weights_fnv"] == wf && gold["head_fnv"] == hf);
/* A small step, so the prompt prefills in more than one chunk and the head's cache is
* filled across them. */
Server s;
REQUIRE(s.start(rad, { "--max-num-seqs", "2", "--max-model-len", "2048",
"--max-num-batched-tokens", "512" }));
int status = 0;
const json models = call(s.port, "GET", "/v1/models", json(), &status);
CHECK_EQ(status, 200);
CHECK(models["data"][0]["capabilities"]["decision"] == "clef");
const json a = call(s.port, "POST", "/v1/systemone", gold["request"], &status);
if (status != 200) fprintf(stderr, " %s\n%s\n", a.dump().c_str(), tail(s.output()).c_str());
REQUIRE_EQ(status, 200);
CHECK_EQ(a["usage"]["input_tokens"].get<int64_t>(), gold["n_prompt_tokens"].get<int64_t>());
const json& ans = a["answers"];
REQUIRE(ans.contains("refund") && ans.contains("team") && ans.contains("tone"));
CHECK(ans["refund"]["type"] == "noul");
CHECK(ans["team"]["type"] == "choice");
CHECK(ans["tone"]["type"] == "score");
double sum = 0.0;
for (const auto& kv : ans["team"]["probabilities"].items()) sum += kv.value().get<double>();
CHECK(std::fabs(sum - 1.0) < 2e-3);
/* Against the release's head in float32 over the same tiny weights. bf16 through the trunk
* and the head moves a probability by a few hundredths at most. */
const json& g = gold["answers"];
double worst = 0.0;
auto diff = [&](double got, double want) { worst = std::max(worst, std::fabs(got - want)); };
diff(prob(ans, "refund", "noul", nullptr), g["refund"]["true"].get<double>());
for (const char* o : { "billing", "product", "shipping" })
diff(prob(ans, "team", nullptr, o), g["team"][o].get<double>());
for (const char* l : { "0", "1", "2" })
diff(prob(ans, "tone", nullptr, l), g["tone"][l].get<double>());
fprintf(stderr, " largest probability difference from the release's head: %.4f\n", worst);
CHECK(worst < 0.03);
CHECK(ans["team"]["choice"] == [&] {
std::string best;
double bp = -1.0;
for (const auto& kv : g["team"].items())
if (kv.value().get<double>() > bp) { bp = kv.value().get<double>(); best = kv.key(); }
return best;
}());
/* The same request again: the whole prompt is a prefix hit, so the trunk recomputes one
* token and the head reads every row from its cache. The answer must not move. Then the
* LiteLLM spelling of the endpoint. */
const json b = call(s.port, "POST", "/v1/systemone", gold["request"], &status);
CHECK_EQ(status, 200);
CHECK(b["answers"] == ans);
const json d = call(s.port, "POST", "/v1/decisions", gold["request"], &status);
CHECK_EQ(status, 200);
CHECK(d["answers"] == ans);
/* The bounds and the refusals. */
json many = gold["request"];
many["questions"] = json::object();
for (int i = 0; i <= RAD_CLEF_MAX_QUESTIONS; ++i)
many["questions"]["q" + std::to_string(i)] = { { "type", "noul" } };
call(s.port, "POST", "/v1/systemone", many, &status);
CHECK_EQ(status, 400);
json img = gold["request"];
img["images"] = json::array({ "data:image/png;base64,AAAA" });
call(s.port, "POST", "/v1/systemone", img, &status);
CHECK_EQ(status, 501);
json wrong = gold["request"];
wrong["model"] = "other";
call(s.port, "POST", "/v1/systemone", wrong, &status);
CHECK_EQ(status, 400);
CHECK_EQ(s.stop(), 0);
}
/* A container converted without the head's metadata is refused at convert, not served half. */
TEST(a_clef_convert_without_the_head_is_refused) {
tiny::TempDir dir{ "clef" };
REQUIRE(dir.ok());
const std::string ck = dir / "clef-tiny";
REQUIRE_EQ(mkdir(ck.c_str(), 0755), 0);
REQUIRE(write_tiny_clef(ck, 7));
std::string log;
const int st = tiny::run({ RAD_E2E_CONVERT, ck, "-o", dir / "no-head.rad", "--set",
"decision.type=clef" }, engine_env(), &log, 300);
CHECK(st != 0);
CHECK(log.find("joint_head.safetensors") != std::string::npos);
}
RAD_TEST_MAIN()
+84
View File
@@ -10,6 +10,7 @@
#include "server/adapters.h"
#include "server/clef.h"
#include "text/tokenizer.h"
#include "rad_clef.h"
#include <nlohmann/json.hpp>
@@ -157,6 +158,89 @@ TEST(answers_are_softmaxes_in_the_releases_shape) {
CHECK(clef_answer(r.questions[2], { 0.0f }, &a, &e) < 0);
}
/* The request's words for the head: the prompt cut into segments at every span's edges, each
* span one whole segment, every option's tokens as the prompt holds them. */
TEST(the_words_cut_the_prompt_at_every_span_and_carry_the_option_tokens) {
ByteTokenizer tok;
ClefRequest r;
ApiError e;
CHECK_OK(parse(tok, kBody, &r, &e));
std::vector<int32_t> w;
CHECK_OK(clef_words(r, &w, &e));
const RadClefWords L = rad_clef_words_read(w.data());
CHECK_EQ((size_t)L.total, w.size());
CHECK_EQ(L.n, (int32_t)r.tokens.size());
CHECK_EQ(L.q, 3);
CHECK_EQ(L.o, 6);
CHECK_EQ(clef_option_count(r), (int64_t)6);
/* 9 spans, none adjacent: 18 cuts plus the ends, so 19 segments. */
CHECK_EQ(L.s, 19);
CHECK_EQ(w[(size_t)L.seg_cu], 0);
CHECK_EQ(w[(size_t)(L.seg_cu + L.s)], L.n);
for (int32_t i = 0; i < L.s; ++i) CHECK(w[(size_t)(L.seg_cu + i)] < w[(size_t)(L.seg_cu + i + 1)]);
/* Each question's segment is exactly its instruction span. */
for (size_t qi = 0; qi < r.questions.size(); ++qi) {
const int32_t s = w[(size_t)(L.q_seg + (int32_t)qi)];
CHECK_EQ((int64_t)w[(size_t)(L.seg_cu + s)], r.questions[qi].question.first);
CHECK_EQ((int64_t)w[(size_t)(L.seg_cu + s + 1)], r.questions[qi].question.second);
CHECK_EQ(w[(size_t)(L.type + (int32_t)qi)], r.questions[qi].type_id);
}
CHECK_EQ(w[(size_t)L.opt_cu], 0);
CHECK_EQ(w[(size_t)(L.opt_cu + 1)], 2);
CHECK_EQ(w[(size_t)(L.opt_cu + 3)], 6);
/* Option 2 is the choice's first option, "billing": its segment is its span and its tokens
* are the prompt's there. */
const TokenSpan sp = r.questions[1].option_spans[0];
const int32_t os = w[(size_t)(L.o_seg + 2)];
CHECK_EQ((int64_t)w[(size_t)(L.seg_cu + os)], sp.first);
CHECK_EQ(w[(size_t)(L.o_q + 2)], 1);
const int32_t l0 = w[(size_t)(L.lex_cu + 2)], l1 = w[(size_t)(L.lex_cu + 3)];
CHECK_EQ((int64_t)(l1 - l0), sp.second - sp.first);
std::vector<int32_t> lex(w.begin() + L.lex_ids + l0, w.begin() + L.lex_ids + l1);
CHECK_EQ(tok.decode(lex), "{\"description\":\"Charges\",\"option_id\":\"billing\"}");
CHECK_EQ(w[(size_t)(L.lex_cu + L.o)], L.l);
CHECK_EQ(w[(size_t)L.last], L.n - 1);
CHECK_EQ(w[(size_t)L.cu_k + 1], L.n);
CHECK_EQ(w[(size_t)L.cu_o + 1], L.o);
CHECK((int32_t)w.size() <= rad_clef_max_words());
/* The head's three values an option land in three stretches of the logits row. */
const std::vector<int32_t> ids = clef_score_ids(6);
CHECK_EQ(ids.size(), (size_t)18);
CHECK_EQ(ids[6], (int32_t)RAD_CLEF_MAX_OPTIONS);
CHECK_EQ(ids[17], (int32_t)(2 * RAD_CLEF_MAX_OPTIONS + 5));
}
TEST(too_many_questions_are_a_400) {
ByteTokenizer tok;
std::string body = R"({"state": "s", "questions": {)";
for (int i = 0; i <= RAD_CLEF_MAX_QUESTIONS; ++i)
body += (i ? "," : "") + std::string("\"q") + std::to_string(i) + R"(": {"type": "noul"})";
body += "}}";
ClefRequest r;
ApiError e;
CHECK_OK(parse(tok, body, &r, &e));
std::vector<int32_t> w;
CHECK(clef_words(r, &w, &e) < 0);
CHECK_EQ(e.param, "questions");
}
/* exp(prior_scale) * prior + sigmoid(gate) * (exp(joint_scale) * cosine + residual), the scales
* clamped at 100. The release's clef-flash values: both scales 2.296875, the gate -2. */
TEST(the_scalars_combine_the_heads_three_values) {
ClefScalars s;
s.prior_logit_scale = std::log(2.0);
s.joint_logit_scale = std::log(4.0);
s.residual_gate = 0.0; /* sigmoid 0.5 */
const std::vector<float> v = { 1.0f, 2.0f, /* prior */
0.5f, 0.25f, /* cosine */
3.0f, -1.0f }; /* residual */
const std::vector<float> l = clef_logits(v, 2, s);
CHECK(std::fabs(l[0] - (2.0 * 1.0 + 0.5 * (4.0 * 0.5 + 3.0))) < 1e-5);
CHECK(std::fabs(l[1] - (2.0 * 2.0 + 0.5 * (4.0 * 0.25 - 1.0))) < 1e-5);
s.prior_logit_scale = 10.0; /* past the clamp: 100 */
CHECK(std::fabs(clef_logits(v, 2, s)[0] - (100.0 + 0.5 * 5.0)) < 1e-3);
}
TEST(ids_and_spans_match_the_releases_encode_record) {
const char* dir = std::getenv("RAD_CLEF_DIR");
if (!dir) SKIP("RAD_CLEF_DIR names no clef release with a tokenizer.json");
+51
View File
@@ -0,0 +1,51 @@
{
"weights_fnv": "c05967c756955d1d",
"head_fnv": "a8ffa91b55b639d8",
"n_prompt_tokens": 1274,
"request": {
"state": {
"text": "The parcel arrived two weeks late and the box was crushed, but the vase inside was intact. I would like a partial refund for the delay.",
"channel": "email"
},
"questions": {
"refund": {
"type": "noul",
"instructions": "Does the customer ask for money back?"
},
"team": {
"type": "choice",
"instructions": "Which team should take this?",
"criteria": {
"shipping": "Delivery delays and damage in transit",
"billing": "Charges and refunds",
"product": "Faults in the item itself"
}
},
"tone": {
"type": "score",
"instructions": "How upset is the customer?",
"criteria": [
"Calm",
"Mildly annoyed",
"Angry"
]
}
}
},
"answers": {
"refund": {
"true": 0.47794339060783386,
"false": 0.5220565795898438
},
"team": {
"billing": 0.3436005115509033,
"product": 0.3282530605792999,
"shipping": 0.328146368265152
},
"tone": {
"0": 0.3329094648361206,
"1": 0.3263286054134369,
"2": 0.34076187014579773
}
}
}
+92
View File
@@ -0,0 +1,92 @@
"""mkclefgolden.py CKPTDIR OUT.json -- the golden for tests/clef_decision_test.cpp: the release's own
head (joint_schema_model.py, beside the clef-flash weights, CLEF_DIR) over transformers' forward pass
of the tiny qwen35 the test writes, in float32, on the request in this file.
CKPTDIR is the tiny clef's directory as the test keeps it: run `RAD_E2E_KEEP=1
build/tests/clef_decision_test` and pass the directory it prints. The golden records the FNV-1a
hashes of model.safetensors and joint_head.safetensors (the test refuses a golden made from other
weights), the request, and each question's probabilities."""
import json, os, re, sys
from types import SimpleNamespace
import torch
from safetensors.torch import load_file
ckpt_dir, out = sys.argv[1], sys.argv[2]
# transformers routes Qwen3.5's delta-net and causal convolution to fla's Triton kernels wherever
# those packages import, which needs a card. The golden is the reference PyTorch path on the CPU,
# so the two packages are made unimportable before transformers looks for them.
sys.modules["fla"] = None
sys.modules["causal_conv1d"] = None
DEV = "cpu"
sys.path.insert(0, os.environ["CLEF_DIR"])
import joint_schema_model as jsm # noqa: E402
REQUEST = {
"state": {"text": "The parcel arrived two weeks late and the box was crushed, but the vase "
"inside was intact. I would like a partial refund for the delay.",
"channel": "email"},
"questions": {
"refund": {"type": "noul", "instructions": "Does the customer ask for money back?"},
"team": {"type": "choice", "instructions": "Which team should take this?",
"criteria": {"shipping": "Delivery delays and damage in transit",
"billing": "Charges and refunds",
"product": "Faults in the item itself"}},
"tone": {"type": "score", "instructions": "How upset is the customer?",
"criteria": ["Calm", "Mildly annoyed", "Angry"]},
},
}
SPECIAL = {"<|endoftext|>": 256, "<|im_start|>": 257, "<|im_end|>": 258}
class ByteTokenizer:
"""The tiny tokenizer: one byte one id, the three specials as added tokens."""
def __call__(self, text, add_special_tokens=False):
ids = []
for piece in re.split(r"(<\|endoftext\|>|<\|im_start\|>|<\|im_end\|>)", text):
if piece in SPECIAL:
ids.append(SPECIAL[piece])
else:
ids.extend(piece.encode("utf-8"))
return SimpleNamespace(input_ids=ids) # encode_record reads .input_ids
def fnv(path):
h = 0xcbf29ce484222325
for b in open(path, "rb").read():
h = ((h ^ b) * 0x100000001b3) & (2**64 - 1)
return h
cfg = json.load(open(os.path.join(ckpt_dir, "config.json")))
from transformers import Qwen3_5ForCausalLM, Qwen3_5TextConfig # noqa: E402
c = {k: v for k, v in cfg.items() if k not in ("architectures", "model_type")}
model = Qwen3_5ForCausalLM(Qwen3_5TextConfig(**c))
sd = {k.replace("model.language_model.", "model."): v.float()
for k, v in load_file(os.path.join(ckpt_dir, "model.safetensors")).items()}
missing, unexpected = model.load_state_dict(sd, strict=False)
missing = [k for k in missing if k != "lm_head.weight"]
if missing or unexpected:
raise SystemExit(f"backbone: missing {missing}, unexpected {unexpected}")
model = model.float().eval().to(DEV)
head_cfg = json.load(open(os.path.join(ckpt_dir, "joint_head_config.json")))
head = jsm.JointSchemaHead(**head_cfg)
head.load_state_dict({k: v.float() for k, v in
load_file(os.path.join(ckpt_dir, "joint_head.safetensors")).items()},
strict=True)
head = head.float().eval().to(DEV)
rec = jsm.encode_record(ByteTokenizer(), REQUEST)
ids = torch.tensor([rec.input_ids], device=DEV)
with torch.no_grad():
hidden = model.model(input_ids=ids, use_cache=False, return_dict=True).last_hidden_state
logits = head(hidden, ids, torch.ones_like(ids), [rec], model.lm_head.weight)[0]
answers = {q.question_id: dict(zip(q.option_ids, ql.float().softmax(-1).cpu().tolist()))
for q, ql in zip(rec.questions, logits)}
json.dump({"weights_fnv": "%016x" % fnv(os.path.join(ckpt_dir, "model.safetensors")),
"head_fnv": "%016x" % fnv(os.path.join(ckpt_dir, "joint_head.safetensors")),
"n_prompt_tokens": len(rec.input_ids),
"request": REQUEST, "answers": answers},
open(out, "w"), indent=1)
print(f"{out}: {len(rec.input_ids)} prompt tokens, {len(answers)} questions")
+68
View File
@@ -25,6 +25,8 @@
#include "rad_plugin.h"
#include "rad_quant.h"
#include <nlohmann/json.hpp>
#include <sys/stat.h>
#ifdef _OPENMP
@@ -50,6 +52,69 @@ namespace {
bool file_exists(const std::string& p) { std::ifstream f(p); return (bool)f; }
/* clef (decision.type=clef): the head's geometry from joint_head_config.json beside the
* checkpoint, and its three learned scalars from the head's own tensors (joint_head.safetensors,
* merged with --add), into the header. The plugin declares the head from the geometry
* (arch/common/rad_block_clef.h) and the server applies the scalars (core/server/clef.h). */
int clef_metadata(const std::string& in, const std::string& config_dir, const Checkpoint& ck,
MetaOwn& meta) {
std::string dir = config_dir;
if (dir.empty()) {
struct stat st{};
if (stat(in.c_str(), &st) == 0 && S_ISDIR(st.st_mode)) dir = in;
else {
const size_t slash = in.find_last_of('/');
dir = slash == std::string::npos ? "." : in.substr(0, slash);
}
}
const std::string path = dir + "/joint_head_config.json";
std::ifstream f(path);
if (!f) {
RAD_ERR("%s: decision.type=clef needs the head's joint_head_config.json beside the "
"checkpoint (or under --config)", path.c_str());
return -1;
}
nlohmann::json c;
try { f >> c; } catch (const std::exception& e) {
RAD_ERR("%s: %s", path.c_str(), e.what());
return -1;
}
for (const char* k : { "hidden_size", "width", "routing_layers", "layers", "heads", "feedforward" }) {
if (!c.contains(k) || !c[k].is_number_integer() || c[k].get<long long>() <= 0) {
RAD_ERR("%s: `%s` is missing or not a positive integer", path.c_str(), k);
return -1;
}
meta.set(std::string("decision.clef.") + k, std::to_string(c[k].get<long long>()));
}
for (const char* k : { "prior_logit_scale", "joint_logit_scale", "residual_gate" }) {
const SrcTensor* t = ck.find(k);
if (!t || !t->data || t->bytes < 2) {
RAD_ERR("the head's `%s` is not in the checkpoint: add joint_head.safetensors with "
"--add", k);
return -1;
}
float v = 0.0f;
if (t->rad_dtype == RAD_BF16) {
uint16_t h = 0;
std::memcpy(&h, t->data, 2);
const uint32_t u = (uint32_t)h << 16;
std::memcpy(&v, &u, 4);
} else if (t->rad_dtype == RAD_F32 && t->bytes >= 4) {
std::memcpy(&v, t->data, 4);
} else {
RAD_ERR("the head's `%s` is %s; bf16 or f32 is read", k, rad_dtype_name(t->rad_dtype));
return -1;
}
char s[32];
std::snprintf(s, sizeof s, "%.9g", (double)v);
meta.set(std::string("decision.clef.") + k, s);
}
RAD_INFO("clef head %s x %s, %s routing + %s decoder layers; scalars from the checkpoint",
meta.get("decision.clef.width"), meta.get("decision.clef.heads"),
meta.get("decision.clef.routing_layers"), meta.get("decision.clef.layers"));
return 0;
}
/* `blk.12.attn_q.weight` -> 12; -1 for a model-level name (GGUF naming, as in an imatrix). */
int32_t layer_from_name(const std::string& n) {
if (n.rfind("blk.", 0) != 0) return -1;
@@ -402,6 +467,9 @@ int main(int argc, char** argv) {
* and in the engine both read RadModelMeta from the container header, so the value holds for
* both. */
for (const auto& kv : set_kv) meta.set(kv.first, kv.second);
if (const char* dt = meta.get("decision.type"); dt && !std::strcmp(dt, "clef") &&
clef_metadata(in, config_dir, ck, meta) < 0)
return 1;
/* The quantisation descriptor (which selects the plugin pair) is derived from
* quantization_config, so a --set of it re-derives the descriptor. E.g. a bf16 checkpoint
* whose recipe writes Qwen's block fp8 targets qwen35_fp8 by setting what that release