Skip to content

Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦

C

qwen36: Clef's joint schema head answers DECIDE next to SUBMIT

JustVugg9b86fc98ab25
diff --git a/c/clef_head.h b/c/clef_head.h
new file mode 100644
index 00000000..002b43ba
--- /dev/null
+++ b/c/clef_head.h
@@ -0,0 +1,677 @@
+/* clef_head.h -- Clef (Cloudflare, Apache-2.0): a joint schema head over a
+ * decoder's final hidden states, and the rendering of a DECIDE record into
+ * that decoder's input. docs/clef.md.
+ *
+ * Clef is Qwen3.8-27B, post-trained, plus a small transformer that reads the
+ * backbone's last hidden states and scores every option of every question in
+ * one pass. The specification is the checkpoint's own joint_schema_model.py;
+ * each step below names the function it follows:
+ *
+ * rendering encode_record clef_render(): the chat-shaped prompt,
+ * the state, then one FIELD per question
+ * with its options as JSON; every piece
+ * tokenized on its own, the state cut from
+ * the end to fit max_length
+ * head JointSchemaHead clef_head_forward(): LayerNorm over the
+ * hidden states, span means for questions
+ * and options, lexical option vectors from
+ * the LM head's rows, two evidence routing
+ * layers, four decoder layers over the
+ * fields, the prior + gated joint score
+ * answer systemone a softmax per question, nothing fitted
+ * on top (Clef ships no temperature)
+ *
+ * The engine owns the backbone: it renders with clef_render() through its own
+ * tokenizer, runs the prompt, hands the final-normed hidden state of every
+ * position to clef_head_forward(), and reads the logits back in the record's
+ * option order. Everything here is f32; the reference runs in bf16.
+ *
+ * Needs decide_serve.h (the record) and matmul_f32.h (the one GEMM). */
+#ifndef COLI_CLEF_HEAD_H
+#define COLI_CLEF_HEAD_H
+
+#include <math.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "decide_serve.h"
+#include "matmul_f32.h"
+
+/* encode_record(max_length=16384), the default systemone() calls it with */
+#define CLEF_MAX_LENGTH 16384
+
+/* joint_schema_model.SYSTEM_PROMPT and the fixed pieces of encode_record */
+#define CLEF_SYSTEM_PROMPT "Read the complete state and schema. Decide every field jointly. " \
+ "Each answer must be exactly one of that field's allowed options."
+#define CLEF_PREFIX "<|im_start|>system\n" CLEF_SYSTEM_PROMPT "<|im_end|>\n<|im_start|>user\nSTATE:\n"
+#define CLEF_SUFFIX "\n<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\nJOINT SCHEMA DECISIONS:"
+#define CLEF_NOUL_TRUE "The proposition is true or the answer is yes."
+#define CLEF_NOUL_FALSE "The proposition is false or the answer is no."
+
+/* joint_schema_model.QUESTION_TYPES */
+enum { CLEF_NOUL = 0, CLEF_CHOICE = 1, CLEF_SCORE = 2 };
+
+/* ------------------------------------------------------------ rendering */
+
+/* text -> token ids, the engine's tokenizer (added tokens matched, as
+ * tokenizer(text, add_special_tokens=False) does). Returns 0 on failure. */
+typedef int (*ClefEncodeFn)(void *ctx, const char *text, int **ids, int *count);
+
+typedef struct {
+ int type; /* CLEF_NOUL | CLEF_CHOICE | CLEF_SCORE */
+ int qs, qe; /* the instruction's tokens, [qs, qe) */
+ int n; /* options */
+ int *os, *oe; /* each option's JSON, [os, oe), in the reference's order */
+ int *record_index; /* reference option k is the record's option record_index[k] */
+} ClefQuestion;
+
+typedef struct {
+ int *ids, n; /* the model input */
+ ClefQuestion *q; int n_q; /* in the record's (= the request's) order */
+ int state_tokens, state_used; /* the state's tokens before and after the cut */
+} ClefInput;
+
+static void clef_input_free(ClefInput *in)
+{
+ if (!in) return;
+ for (int i = 0; i < in->n_q; i++) {
+ free(in->q[i].os); free(in->q[i].oe); free(in->q[i].record_index);
+ }
+ free(in->q); free(in->ids);
+ memset(in, 0, sizeof(*in));
+}
+
+typedef struct { int *v; int n, cap, failed; } ClefIds;
+
+static void clef_ids_push(ClefIds *a, const int *v, int n)
+{
+ if (a->failed || n <= 0) return;
+ if (a->n + n > a->cap) {
+ int cap = a->cap ? a->cap : 256;
+ while (cap < a->n + n) cap *= 2;
+ int *grown = (int *)realloc(a->v, (size_t)cap * sizeof(int));
+ if (!grown) { a->failed = 1; return; }
+ a->v = grown; a->cap = cap;
+ }
+ memcpy(a->v + a->n, v, (size_t)n * sizeof(int));
+ a->n += n;
+}
+
+/* _tokens(tokenizer, text): one piece, tokenized on its own and appended */
+static int clef_tokens(ClefIds *out, ClefEncodeFn encode, void *ctx, const char *text)
+{
+ int *ids = NULL, n = 0;
+ if (!encode(ctx, text, &ids, &n)) return 0;
+ clef_ids_push(out, ids, n);
+ free(ids);
+ return !out->failed;
+}
+
+/* json.dumps(text, ensure_ascii=False) of a string: Python's escapes (\" \\ \b
+ * \f \n \r \t, \u00XX for the other control characters, lowercase hex),
+ * everything else as it is. */
+static void clef_json_string(DecideBuf *b, const char *text)
+{
+ decide_buf_put(b, "\"", 1);
+ for (const unsigned char *p = (const unsigned char *)text; *p; p++) {
+ const char *esc = NULL;
+ switch (*p) {
+ case '"': esc = "\\\""; break;
+ case '\\': esc = "\\\\"; break;
+ case '\b': esc = "\\b"; break;
+ case '\f': esc = "\\f"; break;
+ case '\n': esc = "\\n"; break;
+ case '\r': esc = "\\r"; break;
+ case '\t': esc = "\\t"; break;
+ default: break;
+ }
+ if (esc) decide_buf_put(b, esc, 2);
+ else if (*p < 0x20) decide_buf_printf(b, "\\u%04x", *p);
+ else decide_buf_put(b, (const char *)p, 1);
+ }
+ decide_buf_put(b, "\"", 1);
+}
+
+/* render({"option_id": id, "description": description}): sort_keys puts the
+ * description first; a description of None is left out. */
+static char *clef_option_json(const DecideQuestion *q, const DecideOption *o)
+{
+ DecideBuf b = {0};
+ const char *text = o->text;
+ int is_json = o->text_json;
+ if (q->type == DECIDE_NOUL && !o->has_text) {
+ /* question_options(): the defaults, updated by what the caller gave */
+ text = !strcmp(o->label, "true") ? CLEF_NOUL_TRUE : CLEF_NOUL_FALSE;
+ is_json = 0;
+ }
+ decide_buf_put(&b, "{", 1);
+ if (text) {
+ decide_buf_put(&b, "\"description\":", 14);
+ if (is_json) decide_buf_put(&b, text, strlen(text));
+ else clef_json_string(&b, text);
+ decide_buf_put(&b, ",", 1);
+ }
+ decide_buf_put(&b, "\"option_id\":", 12);
+ clef_json_string(&b, o->label);
+ decide_buf_put(&b, "}", 1);
+ if (b.failed) { free(b.data); return NULL; }
+ return b.data;
+}
+
+static int clef_cmp_labels(const void *a, const void *b, void *labels)
+{
+ const DecideOption *o = (const DecideOption *)labels;
+ return strcmp(o[*(const int *)a].label, o[*(const int *)b].label);
+}
+
+/* A small insertion sort with a context: qsort_r is not portable, and a
+ * question has at most 255 options. sorted() on str compares code points,
+ * which strcmp on UTF-8 does too. */
+static void clef_sort_options(int *order, int n, const DecideOption *options)
+{
+ for (int i = 1; i < n; i++) {
+ int v = order[i], j = i - 1;
+ while (j >= 0 && clef_cmp_labels(&order[j], &v, (void *)options) > 0) { order[j + 1] = order[j]; j--; }
+ order[j + 1] = v;
+ }
+}
+
+/* encode_record(tokenizer, record, max_length): the record must be in the raw
+ * form (the caller's own values; decide_serve.h). Returns 1, or 0 with `err`
+ * starting with the field ("questions: ...") when the record does not fit. */
+static int clef_render(const DecideRecord *rec, ClefEncodeFn encode, void *ctx, int max_length,
+ ClefInput *out, char *err, size_t cap)
+{
+ memset(out, 0, sizeof(*out));
+ if (!rec->raw)
+ return decide_fail(err, cap, "record: Clef reads the raw form (CAPS decide_record=raw), "
+ "this one is the default form");
+ ClefIds schema = {0}, prefix = {0}, state = {0}, suffix = {0};
+ out->q = (ClefQuestion *)calloc((size_t)rec->n_questions, sizeof(ClefQuestion));
+ if (!out->q) return decide_fail(err, cap, "out of memory");
+ out->n_q = rec->n_questions;
+ int ok = clef_tokens(&schema, encode, ctx, "\n\nSCHEMA FIELDS:\n");
+ char line[64];
+ for (int i = 0; ok && i < rec->n_questions; i++) {
+ const DecideQuestion *q = &rec->questions[i];
+ ClefQuestion *cq = &out->q[i];
+ cq->type = q->type == DECIDE_NOUL ? CLEF_NOUL : q->type == DECIDE_CHOICE ? CLEF_CHOICE : CLEF_SCORE;
+ DecideBuf head = {0};
+ decide_buf_printf(&head, "\nFIELD %d\nID: ", i + 1);
+ decide_buf_put(&head, q->id, strlen(q->id));
+ decide_buf_printf(&head, "\nTYPE: %s\nINSTRUCTION: ", decide_type_name(q->type));
+ ok = !head.failed && clef_tokens(&schema, encode, ctx, head.data);
+ free(head.data);
+ if (!ok) break;
+ cq->qs = schema.n;
+ /* instructions None or "": the question id */
+ ok = clef_tokens(&schema, encode, ctx,
+ q->has_instructions && q->instructions[0] ? q->instructions : q->id);
+ cq->qe = schema.n;
+ ok = ok && clef_tokens(&schema, encode, ctx, "\nALLOWED OPTIONS:\n");
+ if (!ok) break;
+ cq->n = q->n_options;
+ cq->os = (int *)calloc((size_t)cq->n, sizeof(int));
+ cq->oe = (int *)calloc((size_t)cq->n, sizeof(int));
+ cq->record_index = (int *)calloc((size_t)cq->n, sizeof(int));
+ if (!cq->os || !cq->oe || !cq->record_index) { ok = 0; break; }
+ /* question_options(): noul true then false (the record has false, true),
+ * choice sorted by label, score in level order */
+ for (int k = 0; k < cq->n; k++) cq->record_index[k] = k;
+ if (q->type == DECIDE_NOUL) { cq->record_index[0] = 1; cq->record_index[1] = 0; }
+ else if (q->type == DECIDE_CHOICE) clef_sort_options(cq->record_index, cq->n, q->options);
+ for (int k = 0; ok && k < cq->n; k++) {
+ snprintf(line, sizeof(line), "OPTION %d: ", k + 1);
+ ok = clef_tokens(&schema, encode, ctx, line);
+ char *json = ok ? clef_option_json(q, &q->options[cq->record_index[k]]) : NULL;
+ cq->os[k] = schema.n;
+ ok = json && clef_tokens(&schema, encode, ctx, json);
+ cq->oe[k] = schema.n;
+ free(json);
+ ok = ok && clef_tokens(&schema, encode, ctx, "\n");
+ if (ok && cq->oe[k] <= cq->os[k]) ok = 0;
+ }
+ ok = ok && clef_tokens(&schema, encode, ctx, "END FIELD\n");
+ if (ok && cq->qe <= cq->qs) ok = 0;
+ }
+ ok = ok && clef_tokens(&prefix, encode, ctx, CLEF_PREFIX) &&
+ clef_tokens(&suffix, encode, ctx, CLEF_SUFFIX) &&
+ clef_tokens(&state, encode, ctx, rec->state);
+ if (!ok) {
+ free(schema.v); free(prefix.v); free(state.v); free(suffix.v);
+ clef_input_free(out);
+ return decide_fail(err, cap, "the record could not be tokenized");
+ }
+ int fixed = prefix.n + schema.n + suffix.n;
+ if (fixed > max_length) {
+ free(schema.v); free(prefix.v); free(state.v); free(suffix.v);
+ clef_input_free(out);
+ return decide_fail(err, cap, "questions: the schema requires %d tokens before the state; "
+ "the maximum is %d", fixed, max_length);
+ }
+ out->state_tokens = state.n;
+ out->state_used = state.n < max_length - fixed ? state.n : max_length - fixed;
+ int offset = prefix.n + out->state_used;
+ ClefIds all = {0};
+ clef_ids_push(&all, prefix.v, prefix.n);
+ clef_ids_push(&all, state.v, out->state_used);
+ clef_ids_push(&all, schema.v, schema.n);
+ clef_ids_push(&all, suffix.v, suffix.n);
+ free(schema.v); free(prefix.v); free(state.v); free(suffix.v);
+ if (all.failed) { free(all.v); clef_input_free(out); return decide_fail(err, cap, "out of memory"); }
+ for (int i = 0; i < out->n_q; i++) {
+ ClefQuestion *cq = &out->q[i];
+ cq->qs += offset; cq->qe += offset;
+ for (int k = 0; k < cq->n; k++) { cq->os[k] += offset; cq->oe[k] += offset; }
+ }
+ out->ids = all.v;
+ out->n = all.n;
+ return 1;
+}
+
+/* ---------------------------------------------------------------- the head */
+
+typedef struct { float *w, *b; } ClefNorm; /* nn.LayerNorm, eps 1e-5 */
+typedef struct { float *in_w, *in_b, *out_w, *out_b; } ClefAttn; /* nn.MultiheadAttention */
+
+typedef struct { /* EvidenceRoutingLayer */
+ ClefNorm query_norm, memory_norm, ff_norm;
+ ClefAttn attn;
+ float *ff1_w, *ff1_b, *ff2_w, *ff2_b;
+} ClefRoute;
+
+typedef struct { /* nn.TransformerDecoderLayer(norm_first=True, gelu) */
+ ClefAttn self_attn, cross_attn;
+ ClefNorm norm1, norm2, norm3;
+ float *ff1_w, *ff1_b, *ff2_w, *ff2_b;
+} ClefDecoder;
+
+typedef struct {
+ int hidden, width, routing_layers, layers, heads, feedforward;
+ ClefNorm hidden_norm;
+ float *memory_proj, *question_proj, *option_question_proj, *global_proj;
+ float *option_context_proj, *option_lexical_proj; /* [width, hidden] */
+ float *type_embedding; /* [3, width] */
+ ClefRoute *route;
+ ClefNorm option_summary_norm, field_norm, option_norm;
+ ClefDecoder *dec;
+ float *score1_w, *score1_b, *score2_w, *score2_b; /* [width, 4 width], [1, width] */
+ float prior_logit_scale, joint_logit_scale, residual_gate;
+} ClefHead;
+
+/* A tensor of the head as f32, `numel` elements, or NULL when it is missing or
+ * the wrong size (the caller refuses the checkpoint). */
+typedef float *(*ClefLoadFn)(void *ctx, const char *name, int64_t numel);
+
+typedef struct { void *ctx; ClefLoadFn load; int missing; char first[160]; } ClefLoader;
+
+static float *clef_take(ClefLoader *l, const char *name, int64_t numel)
+{
+ float *p = l->load(l->ctx, name, numel);
+ if (!p && !l->missing++) snprintf(l->first, sizeof(l->first), "%s", name);
+ return p;
+}
+
+static void clef_take_norm(ClefLoader *l, ClefNorm *n, const char *stem, int d)
+{
+ char name[160];
+ snprintf(name, sizeof(name), "%s.weight", stem); n->w = clef_take(l, name, d);
+ snprintf(name, sizeof(name), "%s.bias", stem); n->b = clef_take(l, name, d);
+}
+
+static void clef_take_attn(ClefLoader *l, ClefAttn *a, const char *stem, int d)
+{
+ char name[160];
+ snprintf(name, sizeof(name), "%s.in_proj_weight", stem); a->in_w = clef_take(l, name, (int64_t)3 * d * d);
+ snprintf(name, sizeof(name), "%s.in_proj_bias", stem); a->in_b = clef_take(l, name, (int64_t)3 * d);
+ snprintf(name, sizeof(name), "%s.out_proj.weight", stem); a->out_w = clef_take(l, name, (int64_t)d * d);
+ snprintf(name, sizeof(name), "%s.out_proj.bias", stem); a->out_b = clef_take(l, name, d);
+}
+
+/* Every tensor of JointSchemaHead's state dict, sized from joint_head_config.json.
+ * Returns 1, or 0 with the first missing or misshapen tensor in `err`. */
+static int clef_head_load(ClefHead *h, void *ctx, ClefLoadFn load, char *err, size_t cap)
+{
+ ClefLoader l = {ctx, load, 0, ""};
+ const int H = h->hidden, W = h->width, F = h->feedforward;
+ char stem[96];
+ clef_take_norm(&l, &h->hidden_norm, "hidden_norm", H);
+ h->memory_proj = clef_take(&l, "memory_projection.weight", (int64_t)W * H);
+ h->question_proj = clef_take(&l, "question_projection.weight", (int64_t)W * H);
+ h->option_question_proj = clef_take(&l, "option_question_projection.weight", (int64_t)W * H);
+ h->global_proj = clef_take(&l, "global_projection.weight", (int64_t)W * H);
+ h->option_context_proj = clef_take(&l, "option_context_projection.weight", (int64_t)W * H);
+ h->option_lexical_proj = clef_take(&l, "option_lexical_projection.weight", (int64_t)W * H);
+ h->type_embedding = clef_take(&l, "type_embedding.weight", (int64_t)3 * W);
+ h->route = (ClefRoute *)calloc((size_t)h->routing_layers, sizeof(ClefRoute));
+ h->dec = (ClefDecoder *)calloc((size_t)h->layers, sizeof(ClefDecoder));
+ if (!h->route || !h->dec) { snprintf(err, cap, "out of memory"); return 0; }
+ for (int i = 0; i < h->routing_layers; i++) {
+ ClefRoute *r = &h->route[i];
+ char name[160];
+ snprintf(stem, sizeof(stem), "evidence_layers.%d.query_norm", i); clef_take_norm(&l, &r->query_norm, stem, W);
+ snprintf(stem, sizeof(stem), "evidence_layers.%d.memory_norm", i); clef_take_norm(&l, &r->memory_norm, stem, W);
+ snprintf(stem, sizeof(stem), "evidence_layers.%d.feedforward_norm", i); clef_take_norm(&l, &r->ff_norm, stem, W);
+ snprintf(stem, sizeof(stem), "evidence_layers.%d.attention", i); clef_take_attn(&l, &r->attn, stem, W);
+ snprintf(name, sizeof(name), "evidence_layers.%d.feedforward.0.weight", i); r->ff1_w = clef_take(&l, name, (int64_t)F * W);
+ snprintf(name, sizeof(name), "evidence_layers.%d.feedforward.0.bias", i); r->ff1_b = clef_take(&l, name, F);
+ snprintf(name, sizeof(name), "evidence_layers.%d.feedforward.3.weight", i); r->ff2_w = clef_take(&l, name, (int64_t)W * F);
+ snprintf(name, sizeof(name), "evidence_layers.%d.feedforward.3.bias", i); r->ff2_b = clef_take(&l, name, W);
+ }
+ clef_take_norm(&l, &h->option_summary_norm, "option_summary_norm", W);
+ for (int i = 0; i < h->layers; i++) {
+ ClefDecoder *d = &h->dec[i];
+ char name[160];
+ snprintf(stem, sizeof(stem), "layers.%d.self_attn", i); clef_take_attn(&l, &d->self_attn, stem, W);
+ snprintf(stem, sizeof(stem), "layers.%d.multihead_attn", i); clef_take_attn(&l, &d->cross_attn, stem, W);
+ snprintf(stem, sizeof(stem), "layers.%d.norm1", i); clef_take_norm(&l, &d->norm1, stem, W);
+ snprintf(stem, sizeof(stem), "layers.%d.norm2", i); clef_take_norm(&l, &d->norm2, stem, W);
+ snprintf(stem, sizeof(stem), "layers.%d.norm3", i); clef_take_norm(&l, &d->norm3, stem, W);
+ snprintf(name, sizeof(name), "layers.%d.linear1.weight", i); d->ff1_w = clef_take(&l, name, (int64_t)F * W);
+ snprintf(name, sizeof(name), "layers.%d.linear1.bias", i); d->ff1_b = clef_take(&l, name, F);
+ snprintf(name, sizeof(name), "layers.%d.linear2.weight", i); d->ff2_w = clef_take(&l, name, (int64_t)W * F);
+ snprintf(name, sizeof(name), "layers.%d.linear2.bias", i); d->ff2_b = clef_take(&l, name, W);
+ }
+ clef_take_norm(&l, &h->field_norm, "field_norm", W);
+ clef_take_norm(&l, &h->option_norm, "option_norm", W);
+ h->score1_w = clef_take(&l, "residual_scorer.0.weight", (int64_t)W * 4 * W);
+ h->score1_b = clef_take(&l, "residual_scorer.0.bias", W);
+ h->score2_w = clef_take(&l, "residual_scorer.3.weight", W);
+ h->score2_b = clef_take(&l, "residual_scorer.3.bias", 1);
+ float *scalar;
+ if ((scalar = clef_take(&l, "prior_logit_scale", 1))) { h->prior_logit_scale = *scalar; free(scalar); }
+ if ((scalar = clef_take(&l, "joint_logit_scale", 1))) { h->joint_logit_scale = *scalar; free(scalar); }
+ if ((scalar = clef_take(&l, "residual_gate", 1))) { h->residual_gate = *scalar; free(scalar); }
+ if (l.missing) {
+ snprintf(err, cap, "%d head tensor(s) missing or of the wrong size, the first %s", l.missing, l.first);
+ return 0;
+ }
+ return 1;
+}
+
+/* ---- the pieces of the forward ---- */
+
+static void clef_layernorm(float *out, const float *x, const ClefNorm *n, int rows, int d)
+{
+ #pragma omp parallel for schedule(static)
+ for (int r = 0; r < rows; r++) {
+ const float *v = x + (int64_t)r * d;
+ float *o = out + (int64_t)r * d;
+ double mean = 0, var = 0;
+ for (int i = 0; i < d; i++) mean += v[i];
+ mean /= d;
+ for (int i = 0; i < d; i++) { double c = v[i] - mean; var += c * c; }
+ var /= d;
+ float inv = (float)(1.0 / sqrt(var + 1e-5));
+ for (int i = 0; i < d; i++) o[i] = (float)((v[i] - mean) * inv) * n->w[i] + n->b[i];
+ }
+}
+
+static void clef_add_bias(float *y, const float *b, int rows, int d)
+{
+ for (int r = 0; r < rows; r++) for (int i = 0; i < d; i++) y[(int64_t)r * d + i] += b[i];
+}
+
+/* nn.GELU() and activation="gelu": the exact erf form */
+static float clef_gelu(float x) { return 0.5f * x * (1.0f + erff(x * 0.70710678118654752f)); }
+
+/* y[rows, out] = x @ W^T + b */
+static void clef_linear(float *y, const float *x, const float *w, const float *b, int rows, int in, int out)
+{
+ matmul(y, x, w, rows, in, out);
+ if (b) clef_add_bias(y, b, rows, out);
+}
+
+/* nn.MultiheadAttention(batch_first) without a mask: out[nq, d] */
+static int clef_attention(const ClefAttn *a, const float *q_in, int nq, const float *kv_in, int nk,
+ int d, int heads, float *out)
+{
+ float *Q = (float *)malloc((size_t)nq * d * sizeof(float));
+ float *K = (float *)malloc((size_t)nk * d * sizeof(float));
+ float *V = (float *)malloc((size_t)nk * d * sizeof(float));
+ float *C = (float *)malloc((size_t)nq * d * sizeof(float));
+ int hd = d / heads, ok = Q && K && V && C;
+ if (ok) {
+ clef_linear(Q, q_in, a->in_w, a->in_b, nq, d, d);
+ clef_linear(K, kv_in, a->in_w + (int64_t)d * d, a->in_b + d, nk, d, d);
+ clef_linear(V, kv_in, a->in_w + (int64_t)2 * d * d, a->in_b + 2 * d, nk, d, d);
+ const float scale = 1.0f / sqrtf((float)hd);
+ #pragma omp parallel
+ {
+ float *p = (float *)malloc((size_t)nk * sizeof(float));
+ #pragma omp for schedule(dynamic, 1)
+ for (int t = 0; t < nq * heads; t++) {
+ int i = t / heads, h = t % heads;
+ float *c = C + (int64_t)i * d + h * hd;
+ if (!p) { for (int j = 0; j < hd; j++) c[j] = NAN; continue; }
+ const float *qv = Q + (int64_t)i * d + h * hd;
+ float mx = -INFINITY;
+ for (int k = 0; k < nk; k++) {
+ p[k] = dot_f32_lanes(qv, K + (int64_t)k * d + h * hd, hd) * scale;
+ if (p[k] > mx) mx = p[k];
+ }
+ double sum = 0;
+ for (int k = 0; k < nk; k++) { p[k] = expf(p[k] - mx); sum += p[k]; }
+ float inv = (float)(1.0 / sum);
+ for (int j = 0; j < hd; j++) c[j] = 0.f;
+ for (int k = 0; k < nk; k++) {
+ float w = p[k] * inv;
+ const float *vv = V + (int64_t)k * d + h * hd;
+ for (int j = 0; j < hd; j++) c[j] += w * vv[j];
+ }
+ }
+ free(p);
+ }
+ clef_linear(out, C, a->out_w, a->out_b, nq, d, d);
+ }
+ free(Q); free(K); free(V); free(C);
+ return ok;
+}
+
+/* x += linear2(gelu(linear1(norm(x)))) */
+static int clef_feedforward(float *x, const ClefNorm *norm, const float *w1, const float *b1,
+ const float *w2, const float *b2, int rows, int d, int f)
+{
+ float *n = (float *)malloc((size_t)rows * d * sizeof(float));
+ float *u = (float *)malloc((size_t)rows * f * sizeof(float));
+ float *y = (float *)malloc((size_t)rows * d * sizeof(float));
+ int ok = n && u && y;
+ if (ok) {
+ clef_layernorm(n, x, norm, rows, d);
+ clef_linear(u, n, w1, b1, rows, d, f);
+ for (int64_t i = 0; i < (int64_t)rows * f; i++) u[i] = clef_gelu(u[i]);
+ clef_linear(y, u, w2, b2, rows, f, d);
+ for (int64_t i = 0; i < (int64_t)rows * d; i++) x[i] += y[i];
+ }
+ free(n); free(u); free(y);
+ return ok;
+}
+
+static double clef_norm2(const float *v, int n)
+{
+ double s = 0;
+ for (int i = 0; i < n; i++) s += (double)v[i] * v[i];
+ return sqrt(s);
+}
+
+/* The LM head's row for a token id (the lexical option vectors read the output
+ * embedding, not the input one), f32, `hidden` wide. Returns 0 on failure. */
+typedef int (*ClefRowFn)(void *ctx, int id, float *out);
+
+/* JointSchemaHead.forward for one record. `hidden` holds the final-normed
+ * hidden state of every position, [n, H]; it is overwritten (hidden_norm runs
+ * in place). `logits[q]` receives in->q[q].n values in the REFERENCE's option
+ * order. Returns 1, or 0 with `err` set. */
+static int clef_head_forward(const ClefHead *h, float *hidden, const ClefInput *in,
+ ClefRowFn lm_row, void *row_ctx, double **logits, char *err, size_t cap)
+{
+ const int H = h->hidden, W = h->width, F = h->feedforward, L = in->n, Q = in->n_q;
+ int N = 0;
+ for (int q = 0; q < Q; q++) N += in->q[q].n;
+ float *memory = (float *)malloc((size_t)L * W * sizeof(float));
+ float *qv = (float *)calloc((size_t)Q * H, sizeof(float)); /* question_vectors */
+ float *ctxv = (float *)calloc((size_t)N * H, sizeof(float)); /* option context means */
+ float *lex = (float *)calloc((size_t)N * H, sizeof(float)); /* lexical option means */
+ float *row = (float *)malloc((size_t)H * sizeof(float));
+ float *routed = (float *)malloc((size_t)N * W * sizeof(float));
+ float *tmp = (float *)malloc((size_t)(N > Q ? N : Q) * W * sizeof(float));
+ float *tmp2 = (float *)malloc((size_t)(N > Q ? N : Q) * W * sizeof(float));
+ float *mnorm = (float *)malloc((size_t)L * W * sizeof(float));
+ float *fields = (float *)malloc((size_t)Q * W * sizeof(float));
+ float *base = (float *)malloc((size_t)Q * W * sizeof(float));
+ float *summary = (float *)calloc((size_t)Q * W, sizeof(float));
+ float *feat = (float *)malloc((size_t)4 * W * sizeof(float));
+ float *hid = (float *)malloc((size_t)W * sizeof(float));
+ int ok = memory && qv && ctxv && lex && row && routed && tmp && tmp2 && mnorm && fields &&
+ base && summary && feat && hid;
+ if (!ok) { snprintf(err, cap, "out of memory in the decision head"); goto done; }
+
+ /* normalized_hidden = hidden_norm(hidden_states); memory = memory_projection(...) */
+ clef_layernorm(hidden, hidden, &h->hidden_norm, L, H);
+ matmul(memory, hidden, h->memory_proj, L, H, W);
+ const float *global = hidden + (int64_t)(L - 1) * H;
+
+ /* _mean_span for the questions and the options; the lexical vectors are the
+ * mean of the LM head's rows at the option's tokens */
+ for (int q = 0, o = 0; q < Q; q++) {
+ const ClefQuestion *cq = &in->q[q];
+ for (int t = cq->qs; t < cq->qe; t++)
+ for (int i = 0; i < H; i++) qv[(int64_t)q * H + i] += hidden[(int64_t)t * H + i];
+ for (int i = 0; i < H; i++) qv[(int64_t)q * H + i] /= (float)(cq->qe - cq->qs);
+ for (int k = 0; k < cq->n; k++, o++) {
+ float *c = ctxv + (int64_t)o * H, *x = lex + (int64_t)o * H;
+ for (int t = cq->os[k]; t < cq->oe[k]; t++) {
+ for (int i = 0; i < H; i++) c[i] += hidden[(int64_t)t * H + i];
+ if (!lm_row(row_ctx, in->ids[t], row)) {
+ ok = 0; snprintf(err, cap, "cannot read the LM head's row %d", in->ids[t]); goto done;
+ }
+ for (int i = 0; i < H; i++) x[i] += row[i];
+ }
+ float count = (float)(cq->oe[k] - cq->os[k]);
+ for (int i = 0; i < H; i++) { c[i] /= count; x[i] /= count; }
+ }
+ }
+
+ /* option queries: context + lexical + the question's own vector */
+ matmul(routed, ctxv, h->option_context_proj, N, H, W);
+ matmul(tmp, lex, h->option_lexical_proj, N, H, W);
+ for (int64_t i = 0; i < (int64_t)N * W; i++) routed[i] += tmp[i];
+ matmul(base, qv, h->option_question_proj, Q, H, W);
+ for (int q = 0, o = 0; q < Q; q++)
+ for (int k = 0; k < in->q[q].n; k++, o++)
+ for (int i = 0; i < W; i++) routed[(int64_t)o * W + i] += base[(int64_t)q * W + i];
+
+ /* EvidenceRoutingLayer x routing_layers: the options read the whole sequence */
+ for (int r = 0; r < h->routing_layers && ok; r++) {
+ const ClefRoute *rl = &h->route[r];
+ clef_layernorm(tmp, routed, &rl->query_norm, N, W);
+ clef_layernorm(mnorm, memory, &rl->memory_norm, L, W);
+ ok = clef_attention(&rl->attn, tmp, N, mnorm, L, W, h->heads, tmp2);
+ for (int64_t i = 0; ok && i < (int64_t)N * W; i++) routed[i] += tmp2[i];
+ ok = ok && clef_feedforward(routed, &rl->ff_norm, rl->ff1_w, rl->ff1_b, rl->ff2_w, rl->ff2_b, N, W, F);
+ }
+ if (!ok) { snprintf(err, cap, "out of memory in the decision head"); goto done; }
+
+ /* fields: the question, a softmax-weighted summary of its options, the last
+ * position, the question type */
+ matmul(base, qv, h->question_proj, Q, H, W);
+ for (int q = 0, o = 0; q < Q; q++) {
+ const ClefQuestion *cq = &in->q[q];
+ const float *field = base + (int64_t)q * W;
+ double mx = -INFINITY, sum = 0;
+ double *w = (double *)malloc((size_t)cq->n * sizeof(double));
+ if (!w) { ok = 0; snprintf(err, cap, "out of memory in the decision head"); goto done; }
+ for (int k = 0; k < cq->n; k++) {
+ w[k] = dot_f32_lanes(routed + (int64_t)(o + k) * W, field, W) / sqrt((double)W);
+ if (w[k] > mx) mx = w[k];
+ }
+ for (int k = 0; k < cq->n; k++) { w[k] = exp(w[k] - mx); sum += w[k]; }
+ for (int k = 0; k < cq->n; k++) {
+ float wk = (float)(w[k] / sum);
+ for (int i = 0; i < W; i++) summary[(int64_t)q * W + i] += wk * routed[(int64_t)(o + k) * W + i];
+ }
+ free(w);
+ o += cq->n;
+ }
+ clef_layernorm(fields, summary, &h->option_summary_norm, Q, W);
+ matmul(hid, global, h->global_proj, 1, H, W);
+ for (int q = 0; q < Q; q++)
+ for (int i = 0; i < W; i++)
+ fields[(int64_t)q * W + i] += base[(int64_t)q * W + i] + hid[i] +
+ h->type_embedding[(int64_t)in->q[q].type * W + i];
+
+ /* TransformerDecoderLayer x layers (norm_first): self-attention over the
+ * fields, cross-attention into the (unnormalized) memory, feed-forward */
+ for (int l = 0; l < h->layers && ok; l++) {
+ const ClefDecoder *d = &h->dec[l];
+ clef_layernorm(tmp, fields, &d->norm1, Q, W);
+ ok = clef_attention(&d->self_attn, tmp, Q, tmp, Q, W, h->heads, tmp2);
+ for (int64_t i = 0; ok && i < (int64_t)Q * W; i++) fields[i] += tmp2[i];
+ if (ok) clef_layernorm(tmp, fields, &d->norm2, Q, W);
+ ok = ok && clef_attention(&d->cross_attn, tmp, Q, memory, L, W, h->heads, tmp2);
+ for (int64_t i = 0; ok && i < (int64_t)Q * W; i++) fields[i] += tmp2[i];
+ ok = ok && clef_feedforward(fields, &d->norm3, d->ff1_w, d->ff1_b, d->ff2_w, d->ff2_b, Q, W, F);
+ }
+ if (!ok) { snprintf(err, cap, "out of memory in the decision head"); goto done; }
+ clef_layernorm(fields, fields, &h->field_norm, Q, W);
+ clef_layernorm(routed, routed, &h->option_norm, N, W); /* options = option_norm(routed) */
+
+ /* the score: prior (lexical vs question + last position) + gated joint
+ * (scaled cosine + the residual scorer) */
+ const double prior_scale = exp(fmin((double)h->prior_logit_scale, log(100.0)));
+ const double joint_scale = exp(fmin((double)h->joint_logit_scale, log(100.0)));
+ const double gate = 1.0 / (1.0 + exp(-(double)h->residual_gate));
+ for (int q = 0, o = 0; q < Q; q++) {
+ const ClefQuestion *cq = &in->q[q];
+ const float *field = fields + (int64_t)q * W;
+ for (int i = 0; i < H; i++) row[i] = qv[(int64_t)q * H + i] + global[i];
+ double anchor_norm = fmax(clef_norm2(row, H), 1e-12);
+ double field_norm = fmax(clef_norm2(field, W), 1e-8);
+ for (int k = 0; k < cq->n; k++, o++) {
+ const float *x = lex + (int64_t)o * H, *opt = routed + (int64_t)o * W;
+ double lex_norm = fmax(clef_norm2(x, H), 1e-12), dot = 0;
+ for (int i = 0; i < H; i++) dot += (double)x[i] * row[i];
+ double prior = prior_scale * dot / (lex_norm * anchor_norm);
+ double opt_norm = fmax(clef_norm2(opt, W), 1e-8), fo = 0;
+ for (int i = 0; i < W; i++) fo += (double)field[i] * opt[i];
+ double cosine = fo / (field_norm * opt_norm);
+ for (int i = 0; i < W; i++) {
+ feat[i] = field[i];
+ feat[W + i] = opt[i];
+ feat[2 * W + i] = field[i] * opt[i];
+ feat[3 * W + i] = fabsf(field[i] - opt[i]);
+ }
+ clef_linear(hid, feat, h->score1_w, h->score1_b, 1, 4 * W, W);
+ double residual = h->score2_b[0];
+ for (int i = 0; i < W; i++) residual += (double)clef_gelu(hid[i]) * h->score2_w[i];
+ logits[q][k] = prior + gate * (joint_scale * cosine + residual);
+ }
+ }
+done:
+ free(memory); free(qv); free(ctxv); free(lex); free(row); free(routed); free(tmp); free(tmp2);
+ free(mnorm); free(fields); free(base); free(summary); free(feat); free(hid);
+ return ok;
+}
+
+/* A question's answer from its logits (reference order): softmax, then both
+ * back in the record's option order. */
+static int clef_answer(const ClefQuestion *cq, const double *logits, DecideAnswer *a)
+{
+ a->n = cq->n;
+ a->logits = (double *)calloc((size_t)cq->n, sizeof(double));
+ a->probs = (double *)calloc((size_t)cq->n, sizeof(double));
+ if (!a->logits || !a->probs) return 0;
+ double mx = -INFINITY, sum = 0;
+ for (int k = 0; k < cq->n; k++) if (logits[k] > mx) mx = logits[k];
+ for (int k = 0; k < cq->n; k++) sum += exp(logits[k] - mx);
+ for (int k = 0; k < cq->n; k++) {
+ a->logits[cq->record_index[k]] = logits[k];
+ a->probs[cq->record_index[k]] = exp(logits[k] - mx) / sum;
+ }
+ a->temperature = NAN; /* the head's logits are the answer: no calibration */
+ return 1;
+}
+
+#endif
diff --git a/c/decide_serve.h b/c/decide_serve.h
index a49f4937..f1617cc9 100644
--- a/c/decide_serve.h
+++ b/c/decide_serve.h
@@ -27,6 +27,16 @@
* differently from a document. A noul question always has two options, false
* then true; a score question has one option per level, level 0 first.
*
+ * The raw form ("record": "raw"), sent to an engine whose CAPS line says
+ * decide_record=raw, carries the caller's values instead of the gateway's
+ * readings of them, for a model whose reference renders the request itself
+ * (Clef): instructions null when none were sent, a noul side the caller did
+ * not describe without a "text" key (null when it was described as null), an
+ * empty description kept, and JSON values written compactly with sorted keys
+ * (json.dumps(value, ensure_ascii=False, separators=(",", ":"),
+ * sort_keys=True)) and marked "json": true on an option. The shape and the
+ * option order are the default form's.
+ *
* The answer (engine -> gateway), the DECISION payload:
*
* {"answers": [{"id": "q", "logits": [...], "probs": [...],
@@ -63,12 +73,16 @@ enum { DECIDE_STATE_STRING = 0, DECIDE_STATE_OBJECT, DECIDE_STATE_ARRAY, DECIDE_
typedef struct {
char *label;
char *text; /* NULL when the option has no description */
+ int has_text; /* the option carried a "text" key: in the raw form a noul
+ * side the caller did not describe has none */
+ int text_json; /* raw form: the text is a JSON value, not a string */
} DecideOption;
typedef struct {
char *id;
int type; /* DECIDE_CHOICE | DECIDE_SCORE | DECIDE_NOUL */
- char *instructions;
+ char *instructions; /* "" when a raw record says null */
+ int has_instructions;/* 0: a raw record's caller sent none */
int n_options;
DecideOption *options;
} DecideQuestion;
@@ -76,6 +90,7 @@ typedef struct {
typedef struct {
char *state;
int state_type;
+ int raw; /* "record": "raw", the caller's own values (see above) */
int n_questions;
DecideQuestion *questions;
jval *root; /* owns every string above */
@@ -134,8 +149,13 @@ static int decide_record_parse(const char *json, DecideRecord *record, char *err
}
record->root = root;
jval *state = json_get(root, "state"), *kind = json_get(root, "state_type");
- jval *questions = json_get(root, "questions");
+ jval *questions = json_get(root, "questions"), *form = json_get(root, "record");
if (!state || state->t != J_STR) { decide_record_free(record); return decide_fail(err, cap, "state: must be a string"); }
+ if (form && (form->t != J_STR || strcmp(form->str, "raw"))) {
+ decide_record_free(record);
+ return decide_fail(err, cap, "record: unknown form (the one other than the default is \"raw\")");
+ }
+ record->raw = form != NULL;
record->state = state->str;
record->state_type = DECIDE_STATE_STRING;
if (kind && kind->t == J_STR) {
@@ -169,11 +189,16 @@ static int decide_record_parse(const char *json, DecideRecord *record, char *err
}
out->type = !strcmp(type->str, "choice") ? DECIDE_CHOICE
: !strcmp(type->str, "score") ? DECIDE_SCORE : DECIDE_NOUL;
- if (!ins || ins->t != J_STR) {
+ if (record->raw && ins && ins->t == J_NULL) {
+ out->instructions = (char *)"";
+ } else if (!ins || ins->t != J_STR) {
decide_record_free(record);
- return decide_fail(err, cap, "questions.%s.instructions: must be a string", out->id);
+ return decide_fail(err, cap, "questions.%s.instructions: must be a string%s", out->id,
+ record->raw ? " or null" : "");
+ } else {
+ out->instructions = ins->str;
+ out->has_instructions = 1;
}
- out->instructions = ins->str;
if (!opts || opts->t != J_ARR || opts->len < 1 || opts->len > DECIDE_MAX_OPTIONS ||
(out->type == DECIDE_NOUL && opts->len != 2)) {
decide_record_free(record);
@@ -187,14 +212,22 @@ static int decide_record_parse(const char *json, DecideRecord *record, char *err
for (int o = 0; o < opts->len; o++) {
jval *option = opts->kids[o];
jval *label = json_get(option, "label"), *text = json_get(option, "text");
+ jval *is_json = json_get(option, "json");
if (!option || option->t != J_OBJ || !label || label->t != J_STR ||
(text && text->t != J_STR && text->t != J_NULL)) {
decide_record_free(record);
return decide_fail(err, cap, "questions.%s.options[%d]: needs a string label "
"and a string or null text", out->id, o);
}
+ if (is_json && (is_json->t != J_BOOL || (is_json->boolean && (!text || text->t != J_STR)))) {
+ decide_record_free(record);
+ return decide_fail(err, cap, "questions.%s.options[%d]: \"json\" marks a string text "
+ "as a JSON value", out->id, o);
+ }
out->options[o].label = label->str;
out->options[o].text = text && text->t == J_STR ? text->str : NULL;
+ out->options[o].has_text = text != NULL;
+ out->options[o].text_json = is_json && is_json->boolean;
}
}
return 1;
diff --git a/c/openai_server.py b/c/openai_server.py
index 2838036f..a4c6c4d0 100644
--- a/c/openai_server.py
+++ b/c/openai_server.py
@@ -4941,13 +4941,65 @@ def decision_state_type(value):
return "number"
-def systemone_decision_record(body):
+def decision_json_sorted(value):
+ """A JSON value the way a raw-form engine's reference writes it (Clef's
+ render(): compact separators, keys sorted)."""
+ return json.dumps(value, ensure_ascii=False, separators=(",", ":"), sort_keys=True)
+
+
+def _raw_decision_record(body):
+ """The raw form (docs/systemone.md, "Decision engines"): the caller's own
+ values, for an engine that renders the request the way its reference does.
+ Nothing is substituted: instructions are null when none were sent, an empty
+ text stays empty, a noul side the caller did not describe has no "text" key
+ (and null when it was described as null), and JSON values are written with
+ sorted keys and marked "json"."""
+ def option(label, value, given=True):
+ out = {"label": label}
+ if not given:
+ return out
+ if value is None or isinstance(value, str):
+ out["text"] = value
+ else:
+ out["text"] = decision_json_sorted(value)
+ out["json"] = True
+ return out
+
+ questions = []
+ for qid, question in body["questions"].items():
+ kind = question["type"]
+ criteria = question.get("criteria")
+ instructions = question.get("instructions")
+ if kind == "choice":
+ options = [option(str(label), text) for label, text in criteria.items()]
+ elif kind == "score":
+ options = [option(str(i), text) for i, text in enumerate(criteria)]
+ else:
+ given = criteria if isinstance(criteria, dict) else {}
+ options = [option(side, given.get(side), side in given) for side in ("false", "true")]
+ questions.append({"id": qid, "type": kind,
+ "instructions": (instructions if instructions is None or
+ isinstance(instructions, str)
+ else decision_json_sorted(instructions)),
+ "options": options})
+ state = body["state"]
+ return {"record": "raw",
+ "state": state if isinstance(state, str) else decision_json_sorted(state),
+ "state_type": decision_state_type(state), "questions": questions}
+
+
+def systemone_decision_record(body, form=None):
"""The DECIDE record for a /v1/systemone request that passed validation.
Each question keeps its options in the caller's order: a choice's labels with
their descriptions, a score's levels (level 0 first), a noul's false then true
with the optional criteria. Instructions left out get the same default text the
- LLM path asks with."""
+ LLM path asks with. form="raw" is the form an engine asks for with
+ `CAPS decide_record=raw` (_raw_decision_record)."""
+ if form == "raw":
+ return _raw_decision_record(body)
+ if form is not None:
+ raise ValueError(f"unknown DECIDE record form: {form!r}")
defaults = {"noul": "Is this true?", "choice": "Which of the following applies?",
"score": "Rate this on the scale below."}
questions = []
@@ -4983,7 +5035,7 @@ def _decision_texts(record):
yield question["instructions"]
for option in question["options"]:
yield option["label"]
- yield option["text"]
+ yield option.get("text") # a raw record's undescribed noul side has none
def decision_payload(record):
@@ -5111,6 +5163,10 @@ class Engine:
# means it has nothing else: the generating endpoints answer 400.
self.decides = self.caps.get("decide") == "1"
self.chats = self.caps.get("chat") != "0"
+ # decide_record=raw: the engine renders the request the way its own reference
+ # does (Clef), so the record carries the caller's values, not the gateway's
+ # defaults (systemone_decision_record). None: the default form.
+ self.decide_record = self.caps.get("decide_record")
self.dispatcher = threading.Thread(target=self._dispatch_stdout,
name="colibri-stdout", daemon=True)
self.dispatcher.start()
@@ -6783,7 +6839,11 @@ class APIHandler(BaseHTTPRequestHandler):
"""The native path: the request as one DECIDE record, the engine's
probabilities back, shaped exactly like the LLM path's reply. No prompt is
rendered and no option is scored on its own: one round trip, one forward."""
- record = systemone_decision_record(body)
+ form = getattr(self.server.engine, "decide_record", None)
+ if form not in (None, "raw"):
+ raise APIError(502, f"The decision engine asks for a record form this server does not "
+ f"write ({form!r}).", None, "engine_error", "server_error")
+ record = systemone_decision_record(body, form)
if cache_slot is None:
cache_slot = conversation_cache_slot([{"role": "system", "content": record["state"]}],
self.server.kv_slots)
diff --git a/c/qwen36.c b/c/qwen36.c
index 7bafaa03..258f7e50 100644
--- a/c/qwen36.c
+++ b/c/qwen36.c
@@ -65,6 +65,8 @@ static int qwen36_max_ctx(void) {
#include "pin_pool.h" /* riuso del prefisso tra turni (shared) */
#include "decode_batch.h" /* ColiSubmit + coli_submit_ext: le chiavi key=value di SUBMIT */
#include "json.h" /* tokenizer.json parsing (reuse minimal parser) */
+#include "tok_unicode.h" /* is_S/is_L/is_N: the exact pre-tokenizer classes (Clef) */
+#include "qwen38_nfc.h" /* NFC, the tokenizer.json normalizer (Clef) */
#include "qwen36_tier.h" /* optional CUDA VRAM expert tier */
#include "vk_tier.h" /* optional Vulkan routed-expert tier (COLI_VULKAN=1; stubs without VK=1) */
#include "route_trace.h" /* the tier's expert history (.coli_usage), kept only while the tier is on */
@@ -133,7 +135,23 @@ static const char *jstr(jval *o,const char *k){ jval *v=json_get(o,k); return (v
static double jnum(jval *o,const char *k){ jval *v=json_get(o,k); return (v&&v->t==J_NUM)?v->num:0; }
enum { U_W=0, U_L=1, U_M=2, U_N=3, U_P=4, U_O=5 };
+/* Clef (clef_head.h) renders every request into the prompt its reference
+ * tokenizes, so its token ids must be the reference's to the last one: the full
+ * Unicode classes and the NFC normalizer. The regex is the one its tokenizer.json
+ * and transformers' Qwen2Tokenizer apply, `[^\r\n\p{L}\p{N}]?\p{L}+` and
+ * ` ?[^\s\p{L}\p{N}]+[\r\n]*`: a combining mark is not part of a letter run there
+ * (measured: "x" U+0303 U+0304 "y" is three pieces), so it is classed with
+ * punctuation and U_M never comes out. The ranges below are the original
+ * approximation, kept for every other checkpoint so their ids do not move. */
+static int g_tok_exact = 0;
+static int g_clef = 0; /* a Clef decision head is loaded (DECIDE answered) */
static int uclass(unsigned cp){
+ if (g_tok_exact) {
+ if (is_S(cp)) return U_W;
+ if (is_L(cp)) return U_L;
+ if (is_N(cp)) return U_N;
+ return U_P;
+ }
if (cp==0x20||cp==0x09||cp==0x0A||cp==0x0D||cp==0x0B||cp==0x0C) return U_W;
if (cp==0x00A0||cp==0x2000||cp==0x2001||cp==0x2002||cp==0x2003||cp==0x2004||cp==0x2005||cp==0x2006||cp==0x2007||cp==0x2008||cp==0x2009||cp==0x200A||cp==0x2028||cp==0x2029||cp==0x202F||cp==0x205F||cp==0x3000||cp==0xFEFF) return U_W;
if (cp>=0x30&&cp<=0x39) return U_N;
@@ -320,6 +338,21 @@ static void encode_text(const char *text,int **out_ids,int *out_n){
/* Ordinary text runs to the next added token, and the pre-tokenizer
* sees that boundary as the end of its input, exactly as HF's does. */
int end=next_special(text,i+1,tlen);
+ if(g_tok_exact){
+ /* the added tokens are matched on the original bytes (normalized=false),
+ * the ordinary span is NFC-normalized before the regex (qwen38.c) */
+ char *norm=NULL; size_t nl=0;
+ if(q38_nfc_normalize(text+i,(size_t)(end-i),&norm,&nl)||nl>(size_t)INT_MAX){
+ free(norm); fprintf(stderr,"[enc] NFC normalization failed\n"); exit(1);
+ }
+ for(int k=0;k<(int)nl;){
+ int j=pretok_end(norm,k,(int)nl); if(j<=k) j=k+utf8_adv(norm,k,(int)nl);
+ if(j>(int)nl) j=(int)nl;
+ bpe_piece(norm+k,j-k,&ids,&n,&cap);
+ k=j;
+ }
+ free(norm); i=end; continue;
+ }
while(i<end){
int j=pretok_end(text,i,end); if(j<=i) j=i+utf8_adv(text,i,end);
if(j>end) j=end;
@@ -3573,6 +3606,10 @@ static int g_echo_k = 0; /* 0 = spento */
static const char *g_echo_id = NULL;
static void serve_echo(const char *id, int pos, int token, const float *lo, int V, int k);
#endif
+/* Clef's decision head reads the final-normed hidden state of EVERY position of
+ * the prompt (clef_head.h). When set, step() writes them here, [S, hidden]; the
+ * DECIDE path sets it around its one prefill and nothing else ever does. */
+static float *g_hidden_sink = NULL;
#ifdef COLI_VULKAN
#include "qwen36_chain.h" /* COLI_VK_CHAIN: every layer's dense chain on the device */
@@ -3616,6 +3653,7 @@ static float *step(Model *m, const int *ids, int S, int pos_base) {
#ifndef QWEN36_NO_MAIN
echo = g_echo_k > 0 && g_echo_id && S > 1;
#endif
+ if (g_hidden_sink) echo = 1; /* the head reads every row */
chain_logit = falloc(c->vocab);
if (!q36c_forward(m, x, S, pos_base, lf, echo, chain_logit)) {
free(chain_logit); chain_logit = NULL;
@@ -3625,6 +3663,11 @@ static float *step(Model *m, const int *ids, int S, int pos_base) {
if (!chain_logit)
#endif
layers_forward_range(m, x, S, pos_base, 0, c->n_layers, 1, lf);
+ if (g_hidden_sink) {
+ #pragma omp parallel for schedule(static)
+ for (int s = 0; s < S; s++)
+ rmsnorm_row(g_hidden_sink + (int64_t)s*D, x + (int64_t)s*D, m->final_norm, D, c->eps);
+ }
/* Recorded HERE, where the tokens actually entered the state, rather than
* derived from the caller's bookkeeping: the invariant that fed[0..len-1]
* are the ids the state was built from is the whole safety argument. */
@@ -4112,6 +4155,24 @@ static int serve_read_req(ServeReq *q){
g_pending_image.grid_h = gh; g_pending_image.grid_w = gw; g_pending_image.present = 1;
return 0;
}
+ if(g_clef && !strcmp(cmd,"DECIDE")){
+ /* DECIDE <id> <slot> <bytes>, then the record and a newline (Clef only:
+ * an engine without the head never announced decide=1). As for IMAGE, a
+ * header that does not say how long the payload is ends the session. */
+ int dslot; unsigned long long bytes;
+ if(sscanf(line,"%*s %*s %d %llu",&dslot,&bytes)!=2 || dslot<0 || bytes>(64ull<<20)){
+ printf("ERROR %s BAD_FRAME\n",id); fflush(stdout); return -1;
+ }
+ char *payload=malloc((size_t)bytes+1);
+ if(!payload){ printf("ERROR %s DECIDE_FAILED out of memory\n",id); fflush(stdout); return -1; }
+ if(bytes && fread(payload,1,(size_t)bytes,stdin)!=(size_t)bytes){ free(payload); return -1; }
+ int t = fgetc(stdin); if(t=='\r') t = fgetc(stdin);
+ if(t!='\n'){ free(payload); return -1; }
+ payload[bytes]=0;
+ snprintf(q->id,sizeof(q->id),"%s",id);
+ q->payload=payload; q->plen=(int)bytes;
+ return 3;
+ }
if(!strcmp(cmd,"CANCEL")||!strcmp(cmd,"STOP")) return 0;
if(strcmp(cmd,"SUBMIT")) return 0;
int slot, plen, max_tok; float temp, top_p;
@@ -4467,13 +4528,313 @@ static void serve_one(Model *m, ServeReq *q){
#endif
}
+/* ======================= Clef: DECIDE on the same engine ======================= *
+ * Cloudflare's Clef (docs/clef.md) is Qwen3.8-27B post-trained with a joint schema
+ * head: a container converted from it carries joint_head_config.json and
+ * joint_head.safetensors next to its shards (tools/convert_qwen36.py copies them).
+ * With them the engine still chats, and also answers DECIDE: the record is
+ * rendered the way the reference renders it (clef_head.h), the backbone reads it
+ * in one prefill, and the head scores every option from the final-normed hidden
+ * state of every position. Without the two files none of this runs: g_clef stays
+ * 0, CAPS says what it always said, and a DECIDE frame is not even parsed. */
+#include "clef_head.h"
+
+static ClefHead g_clef_head;
+static int g_clef_max_len = CLEF_MAX_LENGTH;
+
+static int q36_has_clef_head(const char *snap){
+ char a[2048], b[2048];
+ snprintf(a, sizeof a, "%s/joint_head_config.json", snap);
+ snprintf(b, sizeof b, "%s/joint_head.safetensors", snap);
+ FILE *fa = fopen(a, "rb"), *fb = fopen(b, "rb");
+ int both = fa && fb;
+ if (fa) fclose(fa);
+ if (fb) fclose(fb);
+ return both;
+}
+
+/* A tensor of joint_head.safetensors (st_init indexed it with the shards) as f32. */
+static float *q36_clef_tensor(void *ctx, const char *name, int64_t numel){
+ Model *m = (Model *)ctx;
+ st_tensor *t = st_find(&m->S, name);
+ if (!t || t->numel != numel || t->dtype > 2) return NULL; /* BF16, F16, F32 */
+ float *p = (float *)malloc((size_t)numel * sizeof(float));
+ if (!p) return NULL;
+ st_read_f32(&m->S, name, p, 0);
+ return p;
+}
+
+/* The LM head's row for a token, at the precision on disk: the lexical option
+ * vectors average them, and the dense copy the engine multiplies with may be
+ * int8 or int4. */
+static int q36_clef_lm_row(void *ctx, int id, float *out){
+ Model *m = (Model *)ctx;
+ int D = m->c.hidden;
+ if (id < 0 || id >= m->c.vocab) return 0;
+ if (m->lm_head.w) { memcpy(out, m->lm_head.w + (int64_t)id * D, (size_t)D * sizeof(float)); return 1; }
+ char rn[QW_DENSE_NAME_MAX];
+ st_tensor *t = st_find(&m->S, dense_resolve(m, "lm_head.weight", rn, sizeof rn));
+ if (!t || t->numel != (int64_t)m->c.vocab * D || t->dtype > 2) return 0;
+ int esz = st_dtype_esz(t->dtype);
+ uint16_t *raw = (uint16_t *)malloc((size_t)D * esz);
+ if (!raw) return 0;
+ st_read_range_raw_cap(&m->S, t->fd, t->off + (int64_t)id * D * esz, (int64_t)D * esz,
+ raw, (int64_t)D * esz, 0, "clef lm_head row");
+ if (t->dtype == 0) bf16_to_f32_bulk(raw, out, D);
+ else if (t->dtype == 1) f16_to_f32_bulk(raw, out, D);
+ else memcpy(out, raw, (size_t)D * sizeof(float));
+ free(raw);
+ return 1;
+}
+
+static int q36_clef_encode(void *ctx, const char *text, int **ids, int *count){
+ (void)ctx;
+ encode_text(text, ids, count);
+ return 1;
+}
+
+/* joint_head_config.json -> the head's shape, checked against the backbone, then
+ * every tensor. A broken head is a refusal at load, never a chat model that
+ * quietly cannot decide. */
+static void q36_clef_load(Model *m, const char *snap){
+ char path[2048];
+ snprintf(path, sizeof path, "%s/joint_head_config.json", snap);
+ FILE *f = fopen(path, "rb");
+ if (!f) { perror(path); exit(1); }
+ fseek(f, 0, SEEK_END); long n = ftell(f); fseek(f, 0, SEEK_SET);
+ if (n <= 0 || n > (1L << 20)) { fprintf(stderr, "[clef] %s: empty or larger than 1 MB\n", path); exit(1); }
+ char *buf = (char *)malloc((size_t)n + 1);
+ if (!buf || fread(buf, 1, (size_t)n, f) != (size_t)n) { fprintf(stderr, "[clef] cannot read %s\n", path); exit(1); }
+ buf[n] = 0; fclose(f);
+ jval *cfg = json_parse_checked(buf);
+ free(buf);
+ if (!cfg || cfg->t != J_OBJ) { fprintf(stderr, "[clef] %s is not a JSON object\n", path); exit(1); }
+ ClefHead *h = &g_clef_head;
+ memset(h, 0, sizeof(*h));
+ #define CLEF_KEY(key, field, lo, hi) do { jval *v = json_get(cfg, key); \
+ if (!v || v->t != J_NUM || v->num != floor(v->num) || v->num < (lo) || v->num > (hi)) { \
+ fprintf(stderr, "[clef] %s: \"%s\" missing or outside %d..%d -- refusing\n", path, key, lo, hi); exit(1); } \
+ h->field = (int)v->num; } while (0)
+ CLEF_KEY("hidden_size", hidden, 1, 65536);
+ CLEF_KEY("width", width, 1, 16384);
+ CLEF_KEY("routing_layers", routing_layers, 0, 64);
+ CLEF_KEY("layers", layers, 0, 64);
+ CLEF_KEY("heads", heads, 1, 256);
+ CLEF_KEY("feedforward", feedforward, 1, 65536);
+ #undef CLEF_KEY
+ json_free(cfg);
+ if (h->hidden != m->c.hidden || h->width % h->heads) {
+ fprintf(stderr, "[clef] head hidden_size %d / width %d / heads %d do not fit a %d-wide backbone -- refusing\n",
+ h->hidden, h->width, h->heads, m->c.hidden);
+ exit(1);
+ }
+ char err[256];
+ if (!clef_head_load(h, m, q36_clef_tensor, err, sizeof err)) {
+ fprintf(stderr, "[clef] joint_head.safetensors: %s -- refusing\n", err);
+ exit(1);
+ }
+ const char *e = getenv("COLI_CLEF_MAX_LEN");
+ if (e && *e) {
+ g_clef_max_len = atoi(e);
+ if (g_clef_max_len < 1) { fprintf(stderr, "[clef] COLI_CLEF_MAX_LEN must be positive\n"); exit(1); }
+ }
+ g_clef = 1;
+ fprintf(stderr, "[clef] decision head: %d routing + %d decoder layers, width %d, %d heads; "
+ "a record reads up to %d tokens (the engine's context is %d)\n",
+ h->routing_layers, h->layers, h->width, h->heads, g_clef_max_len, qwen36_max_ctx());
+}
+
+/* One record: rendered, one prefill that keeps every position's hidden state,
+ * the head, a softmax per question. `keep` (the --records test mode) leaves the
+ * rendered input in *last for the caller to print. */
+static int q36_clef_decide(Model *m, const DecideRecord *rec, DecideAnswer *answers, int *input_tokens,
+ ClefInput *last, char *err, size_t cap){
+ Cfg *c = &m->c;
+ ClefInput in;
+ if (!clef_render(rec, q36_clef_encode, NULL, g_clef_max_len, &in, err, cap)) return 0;
+ int max_ctx = qwen36_max_ctx();
+ if (in.n > max_ctx) {
+ int n = in.n;
+ clef_input_free(&in);
+ return decide_fail(err, cap, "record: %d tokens do not fit this engine's context of %d "
+ "(Q36_MAXT; Clef itself reads up to %d)", n, max_ctx, g_clef_max_len);
+ }
+ float *hidden = (float *)malloc((size_t)in.n * c->hidden * sizeof(float));
+ double **logits = (double **)calloc((size_t)in.n_q, sizeof(double *));
+ int ok = hidden && logits;
+ for (int q = 0; ok && q < in.n_q; q++) ok = (logits[q] = (double *)calloc((size_t)in.q[q].n, sizeof(double))) != NULL;
+ if (!ok) snprintf(err, cap, "out of memory for %d positions", in.n);
+ if (ok) {
+ /* a decision reads from position 0, with no picture and no reuse: the
+ * attention rows and the recurrence it leaves behind are recorded in kvp
+ * by step(), so the next chat turn or snapshot checks them as usual */
+ q36_vision_detach(m);
+ m->max_t = in.n;
+ ensure_kv(m);
+ reset_recurrent(m);
+ m->kv_len = 0;
+ m->first_step = 1;
+ if (m->seen) memset(m->seen, 0, (size_t)c->n_layers * c->n_experts);
+ if (m->momentum_logits) memset(m->momentum_logits, 0, (size_t)c->n_layers * c->n_experts * sizeof(float));
+ g_hidden_sink = hidden;
+ float *lo = step(m, in.ids, in.n, 0);
+ g_hidden_sink = NULL;
+ free(lo);
+ ok = clef_head_forward(&g_clef_head, hidden, &in, q36_clef_lm_row, m, logits, err, cap);
+ }
+ for (int q = 0; ok && q < in.n_q; q++) {
+ ok = clef_answer(&in.q[q], logits[q], &answers[q]);
+ answers[q].tokens = in.n;
+ answers[q].state_tokens = in.state_tokens;
+ answers[q].state_dropped = in.state_tokens - in.state_used;
+ if (!ok) snprintf(err, cap, "out of memory");
+ }
+ if (logits) for (int q = 0; q < in.n_q; q++) free(logits[q]);
+ free(logits); free(hidden);
+ *input_tokens = in.n;
+ if (ok && last) *last = in;
+ else clef_input_free(&in);
+ return ok;
+}
+
+/* DECIDE <id>: DECISION + DONE, or ERROR <id> DECIDE_INVALID|DECIDE_FAILED. */
+static void clef_serve_one(Model *m, ServeReq *q){
+ char reason[1024] = "";
+ DecideRecord rec;
+ if (!decide_record_parse(q->payload, &rec, reason, sizeof reason)) {
+ decide_write_refusal(stdout, q->id, "DECIDE_INVALID", reason);
+ return;
+ }
+ DecideAnswer *answers = (DecideAnswer *)calloc((size_t)rec.n_questions, sizeof(DecideAnswer));
+ int tokens = 0;
+ double started = decide_now_ms();
+ int ok = answers && q36_clef_decide(m, &rec, answers, &tokens, NULL, reason, sizeof reason);
+ double elapsed = decide_now_ms() - started;
+ if (!ok) {
+ if (!answers) snprintf(reason, sizeof reason, "out of memory");
+ decide_write_refusal(stdout, q->id, decide_is_request_error(reason) ? "DECIDE_INVALID" : "DECIDE_FAILED",
+ reason);
+ } else {
+ size_t length = 0;
+ char *json = decide_answers_json(&rec, answers, tokens, elapsed, &length);
+ if (!json) coli_serve_write_error(stdout, q->id, "DECIDE_FAILED out of memory");
+ else {
+ ColiServeDone done = {0, elapsed > 0 ? tokens / (elapsed / 1e3) : 0.0, 0.0, rss_gb(), tokens, 0};
+ coli_serve_write_decision(stdout, q->id, json, length);
+ coli_serve_write_done(stdout, q->id, &done);
+ free(json);
+ }
+ }
+ fprintf(stderr, "[clef] DECIDE %s: %d question(s), %d tokens, %.1f ms\n", q->id, rec.n_questions, tokens, elapsed);
+ decide_answers_free(answers, answers ? rec.n_questions : 0);
+ free(answers);
+ decide_record_free(&rec);
+}
+
+static char *q36_read_file(const char *path){
+ FILE *f = fopen(path, "rb");
+ if (!f) return NULL;
+ fseek(f, 0, SEEK_END); long n = ftell(f); fseek(f, 0, SEEK_SET);
+ char *buf = n >= 0 ? (char *)malloc((size_t)n + 1) : NULL;
+ if (!buf || fread(buf, 1, (size_t)n, f) != (size_t)n) { free(buf); fclose(f); return NULL; }
+ buf[n] = 0; fclose(f);
+ return buf;
+}
+
+/* Test modes (tests/test_clef_tiny.py), the path the serve loop takes minus the
+ * wire: CLEF_TOKENIZE=<json array of strings> prints their ids; CLEF_RECORDS=
+ * <json array of {"payload": record}> prints one DECISION object per record, and
+ * with CLEF_IDS=1 the rendered input (ids, spans, option order) beside it. */
+static int q36_clef_test_modes(Model *m){
+ const char *tok = getenv("CLEF_TOKENIZE"), *recs = getenv("CLEF_RECORDS");
+ if (tok) {
+ char *text = q36_read_file(tok);
+ jval *root = text ? json_parse_checked(text) : NULL;
+ if (!root || root->t != J_ARR) { fprintf(stderr, "%s: expected a JSON array of strings\n", tok); return 1; }
+ printf("[");
+ for (int i = 0; i < root->len; i++) {
+ if (root->kids[i]->t != J_STR) { fprintf(stderr, "%s: entry %d is not a string\n", tok, i); return 1; }
+ int *ids = NULL, n = 0;
+ encode_text(root->kids[i]->str, &ids, &n);
+ printf("%s[", i ? "," : "");
+ for (int t = 0; t < n; t++) printf("%s%d", t ? "," : "", ids[t]);
+ printf("]");
+ free(ids);
+ }
+ printf("]\n");
+ json_free(root); free(text);
+ return 0;
+ }
+ if (!g_clef) { fprintf(stderr, "CLEF_RECORDS: this checkpoint has no decision head\n"); return 1; }
+ int dump = getenv("CLEF_IDS") && getenv("CLEF_IDS")[0] == '1';
+ char *text = q36_read_file(recs);
+ jval *root = text ? json_parse_checked(text) : NULL;
+ if (!root || root->t != J_ARR) { fprintf(stderr, "%s: expected a JSON array of records\n", recs); return 1; }
+ for (int i = 0; i < root->len; i++) {
+ jval *payload = json_get(root->kids[i], "payload");
+ char reason[1024] = "";
+ DecideRecord rec;
+ DecideBuf out = {0};
+ if (!payload || payload->t != J_STR || !decide_record_parse(payload->str, &rec, reason, sizeof reason)) {
+ if (!payload || payload->t != J_STR) snprintf(reason, sizeof reason, "record %d has no string payload", i);
+ decide_buf_put(&out, "{\"error\":", 9); decide_buf_string(&out, reason); decide_buf_put(&out, "}", 1);
+ printf("%s\n", out.data); fflush(stdout); free(out.data);
+ continue;
+ }
+ DecideAnswer *answers = (DecideAnswer *)calloc((size_t)rec.n_questions, sizeof(DecideAnswer));
+ ClefInput in; memset(&in, 0, sizeof in);
+ int tokens = 0;
+ double t0 = decide_now_ms();
+ int ok = answers && q36_clef_decide(m, &rec, answers, &tokens, &in, reason, sizeof reason);
+ double ms = decide_now_ms() - t0;
+ if (!ok) {
+ decide_buf_put(&out, "{\"error\":", 9); decide_buf_string(&out, reason); decide_buf_put(&out, "}", 1);
+ } else {
+ size_t len = 0;
+ char *json = decide_answers_json(&rec, answers, tokens, ms, &len);
+ if (json && len > 1) {
+ decide_buf_put(&out, json, len - 1); /* reopen the object */
+ if (dump) {
+ decide_buf_put(&out, ",\"input_ids\":[", 14);
+ for (int t = 0; t < in.n; t++) decide_buf_printf(&out, "%s%d", t ? "," : "", in.ids[t]);
+ decide_buf_printf(&out, "],\"state_tokens\":%d,\"state_used\":%d,\"spans\":[",
+ in.state_tokens, in.state_used);
+ for (int q = 0; q < in.n_q; q++) {
+ const ClefQuestion *cq = &in.q[q];
+ decide_buf_printf(&out, "%s{\"type\":%d,\"question\":[%d,%d],\"options\":[",
+ q ? "," : "", cq->type, cq->qs, cq->qe);
+ for (int k = 0; k < cq->n; k++) decide_buf_printf(&out, "%s[%d,%d]", k ? "," : "", cq->os[k], cq->oe[k]);
+ decide_buf_put(&out, "],\"order\":[", 11);
+ for (int k = 0; k < cq->n; k++) decide_buf_printf(&out, "%s%d", k ? "," : "", cq->record_index[k]);
+ decide_buf_put(&out, "]}", 2);
+ }
+ decide_buf_put(&out, "]", 1);
+ }
+ decide_buf_put(&out, "}", 1);
+ }
+ free(json);
+ }
+ printf("%s\n", out.data ? out.data : "{\"error\":\"out of memory\"}");
+ fflush(stdout);
+ free(out.data);
+ clef_input_free(&in);
+ decide_answers_free(answers, answers ? rec.n_questions : 0);
+ free(answers);
+ decide_record_free(&rec);
+ }
+ json_free(root); free(text);
+ return 0;
+}
+
static void serve_loop(Model *m){
coli_serve_binary_mode();
setvbuf(stdin,NULL,_IONBF,0);
fputs("\x01\x01READY\x01\x01\n",stdout);
/* fra READY e STAT: il gateway lo legge nella stretta di mano, quindi sa che
* modalita' serve prima della prima richiesta (docs/serve_protocol.md) */
- printf("CAPS vision=%d\n",m->vis_ready?1:0);
+ /* Clef answers DECIDE too, and still chats: decide=1 without chat=0. Its
+ * records come in the raw form (decide_record=raw, decide_serve.h). */
+ printf("CAPS vision=%d%s\n",m->vis_ready?1:0,g_clef?" decide=1 decide_record=raw":"");
printf("STAT 0 0.00 0.0 %.2f\n",rss_gb());
fflush(stdout);
emap_emit(m); /* dopo READY e STAT: il boot reader legge STAT dopo il sentinel */
@@ -4490,6 +4851,7 @@ static void serve_loop(Model *m){
* inkling.c, kimi_k3.c, qwen38.c, deepseek_v41.c and colibri.c
* already do this. */
if(r==2){ serve_one(m,&q); q36_vision_detach(m); free(q.payload); emap_emit(m); }
+ if(r==3){ clef_serve_one(m,&q); free(q.payload); }
}
}
@@ -4713,6 +5075,7 @@ int main(int argc, char **argv) {
* is ever reached — which is exactly how `coli` launches it (SERVE=1, no
* prompt argument). */
int serve_mode = getenv("SERVE") && getenv("SERVE")[0]=='1';
+ if (getenv("CLEF_RECORDS") || getenv("CLEF_TOKENIZE")) serve_mode = 1; /* Clef's test modes: no prompt */
/* load tokenizer early so text-prompt mode can encode before model_init */
{
@@ -4720,6 +5083,9 @@ int main(int argc, char **argv) {
if (tokpath && *tokpath) load_tokenizer(tokpath);
else if (argc > 4 && argv[4] && *argv[4]) load_tokenizer(argv[4]);
else { char tpb[2048]; snprintf(tpb,sizeof tpb,"%s/tokenizer.json",snap); load_tokenizer(tpb); }
+ /* Clef: its requests are rendered into prompts, and the ids must be the
+ * reference tokenizer's (see g_tok_exact) */
+ if (q36_has_clef_head(snap)) g_tok_exact = 1;
}
if (serve_mode) {
@@ -4754,6 +5120,7 @@ int main(int argc, char **argv) {
* with the run's tokens already correct (#1262). Static storage outlives
* every thread, so the pointer the worker holds stays valid. */
static Model m; model_init(&m, snap, cap, bits);
+ if (g_tok_exact) q36_clef_load(&m, snap);
g_expert_gs = m.c.expert_gs;
if (g_expert_gs) fprintf(stderr, "[qwen36] group-scaled experts: gs=%d\n", g_expert_gs);
fprintf(stderr, "resident weights loaded in %.1fs | RSS after load: %.2f GB\n", m.dense_load_s, rss_gb());
@@ -4964,6 +5331,10 @@ int main(int argc, char **argv) {
/* coli serve mode: speak the gateway wire protocol instead of argv
* generation. AFTER the tier init: serve sessions ride the VRAM experts
* exactly like argv runs, and serve_loop never returns. */
+ if (getenv("CLEF_RECORDS") || getenv("CLEF_TOKENIZE")) {
+ if (!g_tok) { fprintf(stderr, "[clef] tokenizer.json required\n"); return 1; }
+ return q36_clef_test_modes(&m);
+ }
if (getenv("SERVE") && getenv("SERVE")[0] == '1') {
if (!g_tok) { fprintf(stderr, "[serve] tokenizer.json required (put in SNAP or set TOK)\n"); return 1; }
serve_loop(&m);
diff --git a/c/tools/convert_qwen36.py b/c/tools/convert_qwen36.py
index d5d0bc67..4a041817 100644
--- a/c/tools/convert_qwen36.py
+++ b/c/tools/convert_qwen36.py
@@ -347,6 +347,26 @@ def main():
if Path(extra_path).is_file():
shutil.copy2(extra_path, out / extra)
print(f"{extra} -> {out / extra}")
+ # A decision head over the backbone (Cloudflare's Clef: docs/clef.md) is two
+ # files next to the shards, outside the index. They are copied as they are:
+ # the engine reads the head from them, and coli recognises the checkpoint by
+ # them. Both or neither: half a head would load as a chat model that cannot
+ # say why it does not decide.
+ head_files = ("joint_head_config.json", "joint_head.safetensors")
+ if args.repo:
+ listed = set(HfApi(token=token).list_repo_files(args.repo))
+ head_paths = ([hf_hub_download(args.repo, name, token=token) for name in head_files]
+ if all(name in listed for name in head_files) else [])
+ else:
+ head_paths = [str(src_dir / name) for name in head_files]
+ present = [path for path in head_paths if Path(path).is_file()]
+ if len(present) == len(head_files):
+ for name, path in zip(head_files, head_paths):
+ shutil.copy2(path, out / name)
+ print(f"{name} -> {out / name}")
+ elif present:
+ sys.exit(f"ERROR: {Path(present[0]).name} without its sibling: a decision head needs "
+ f"both {' and '.join(head_files)}")
# ---- build weight map (key -> shard file) ----
if idx_path:
@@ -357,6 +377,8 @@ def main():
sys.exit("remote repo without index.json is unsupported; download the repo first")
wm = {}
for sh in sorted(src_dir.glob("*.safetensors")):
+ if sh.name in head_files: # the decision head, copied above
+ continue
with safe_open_np(str(sh), framework="np") as f:
for k in f.keys():
wm[k] = sh.name