laya: Laya decision models on /v1/systemone (arch/laya)

This commit is contained in:
Brandon Bertelsen committed 2026-10-28 23:44:38 -04:00
1 parent d24cf32a13
commit 9c605a103d
18 files changed
+2346 -175

No files matched your search

+44
View File
@@ -0,0 +1,44 @@
/* rad_laya.h -- the words a Laya request hands its plugin (RadBatch::plugin_words), and the pooled
* row the plugin answers in.
*
* Laya (arch/laya) reads one sequence a question, `[CLS] <type> question: <instructions> [SEP]
* [MASK] opt0 [MASK] opt1 ... [SEP] <state> [SEP]`, and scores each option at its [MASK]. The
* server builds the sequence (core/server/laya.cpp) and hands the plugin what the tokens do not
* say: the question's type, which picks the head's type embedding, and where the markers are. The
* plugin answers in the sequence's pooled row: one logit an option, in marker order.
*
* Plain C, like every abi/ header: the plugin is built apart from the engine.
*/
#ifndef RAD_LAYA_H
#define RAD_LAYA_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
enum {
/* Options a question, llama.cpp's bound for laya. The pooled row holds one logit an option. */
RAD_LAYA_MAX_OPTIONS = 255,
RAD_LAYA_POOLED = 256
};
/* The question types in the order of the head's type embedding rows (laya's QTYPES). */
enum { RAD_LAYA_CHOICE = 0, RAD_LAYA_SCORE = 1, RAD_LAYA_NOUL = 2 };
/* A sequence's words. Word 0 is the engine's (RadBatch::plugin_words). */
enum {
RAD_LAYA_W_ROW = 0, /* written by the engine */
RAD_LAYA_W_N = 1, /* the sequence's tokens */
RAD_LAYA_W_TYPE = 2, /* RAD_LAYA_CHOICE, RAD_LAYA_SCORE or RAD_LAYA_NOUL */
RAD_LAYA_W_K = 3, /* options, so markers */
RAD_LAYA_W_MARKERS = 4, /* [k]: each option's [MASK] position in the sequence, in order */
RAD_LAYA_MAX_WORDS = RAD_LAYA_W_MARKERS + RAD_LAYA_MAX_OPTIONS
};
#ifdef __cplusplus
}
#endif
#endif /* RAD_LAYA_H */
+10
View File
@@ -0,0 +1,10 @@
# Built in radiance's tree, or standalone against an installed radiance
# (`cmake -S arch/laya -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(laya LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(laya architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/laya.cpp)
+530
View File
@@ -0,0 +1,530 @@
/* laya -- Convai Innovations' Laya decision models (laya, laya-typed-decisions,
* laya-multilingual), served on /v1/systemone. bf16 weights and activations, f32 norms and biases.
*
* A Laya checkpoint is a ModernBERT encoder and a small decision head (DecisionModel in laya's
* common.py). It reads one sequence a question,
* [CLS] <type> question: <instructions> [SEP] [MASK] opt0 [MASK] opt1 ... [SEP] <state> [SEP]
* which the server builds (core/server/laya.cpp), and scores each option at its [MASK]. Like
* nomicbert it declares a pooled output and no logits, so the engine runs it with no sampler and
* no KV cache, every sequence whole in one step, and returns each sequence's pooled row: here one
* logit an option (abi/rad_laya.h). The request's words carry what the tokens do not: the
* question's type and where its markers sit.
*
* ============================== THE SHAPE ==============================
*
* encoder (ModernBERT): token embedding, then LayerNorm; every norm has no bias, no linear has one
* h += Wo attn(rope(Wqkv LN_a(h))) no LN_a on layer 0
* h += Wo (gelu(Wi_in LN_m(h)) * Wi_gate LN_m(h)) Wi is one [2 ff, E] tensor, [in | gate]
* a final LayerNorm
* attention: a `full_attention` layer (layer_types) attends over the whole sequence with the full
* rotary theta, the others over |i - j| <= local_attention / 2 with the sliding one; NeoX rotary
* over the whole head, scale 1 / sqrt(head_dim)
* head: h + type_emb[type]; head_layers pre-norm transformer layers (torch's
* TransformerEncoderLayer with norm_first: E / 64 heads, a ReLU feed-forward of 4 E, every
* linear and norm with a bias); the rows at the markers; LayerNorm, Linear + gelu, Linear to
* one logit an option
*
* The release's escalation head (act_head) and its stored temperatures are not declared: the
* answer is the option logits, and the server applies the fitted temperatures rad-convert writes
* into the header from rl_agent_config.json.
*/
#include <arch/rad_arch.h>
#include <rad_laya.h>
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <cstring>
#include <string>
#include <vector>
namespace laya {
using namespace rad::arch;
struct Layer {
bool sliding = false;
rad_weight w_attn_norm = 0, w_qkv = 0, w_out = 0, w_mlp_norm = 0, w_wi = 0, w_wo = 0;
rad_op op_attn_norm = 0, op_qkv = 0, op_rope = 0, op_attn = 0, op_out = 0, op_add_attn = 0;
rad_op op_mlp_norm = 0, op_wi = 0, op_act = 0, op_wo = 0, op_add_mlp = 0;
};
struct HeadLayer {
rad_weight n1_w = 0, n1_b = 0, qkv_w = 0, qkv_b = 0, out_w = 0, out_b = 0;
rad_weight n2_w = 0, n2_b = 0, l1_w = 0, l1_b = 0, l2_w = 0, l2_b = 0;
rad_op op_n1 = 0, op_qkv = 0, op_attn = 0, op_out = 0, op_n2 = 0, op_l1 = 0, op_relu = 0,
op_l2 = 0;
};
struct Model {
Names nm{""};
Geom g{};
int64_t F = 0; /* the encoder's feed-forward width */
int64_t head_dim_h = 0; /* the head's attention width, E / max(1, E / 64) */
rad_buf b_o = 0, b_x = 0, b_h = 0, b_t = 0, b_qkv = 0, b_att = 0, b_wi = 0, b_ff = 0,
b_hff = 0, b_trow = 0, b_m = 0, b_m2 = 0, b_sc = 0, b_pooled = 0;
rad_weight w_tok = 0, w_emb_norm = 0, w_final_norm = 0, w_type = 0;
rad_weight w_sn = 0, b_sn = 0, w_s1 = 0, b_s1 = 0, w_s2 = 0, b_s2 = 0;
rad_op op_embed = 0, op_emb_norm = 0, op_final_norm = 0, op_type = 0, op_add_type = 0;
rad_op op_gather = 0, op_sn = 0, op_s1 = 0, op_s2 = 0, op_fill = 0, op_out = 0;
std::vector<Layer> layers;
std::vector<HeadLayer> head;
};
static Model g_model[MAX_RANKS];
static int probe(const RadModelMeta* meta, RadArchProbe* out) {
if (!meta || !out) return RAD_E_INVAL;
out->draft_depth = 0;
const char* dt = rad_meta_gets(meta, "decision.type", nullptr);
if (!dt || std::strcmp(dt, "laya")) {
fprintf(stderr, "radiance: laya: the container declares no Laya decision head "
"(decision.type=laya); convert the checkpoint directory with rad-convert, "
"which reads rl_agent_config.json beside it\n");
return RAD_E_UNSUPPORTED;
}
return RAD_OK;
}
/* Which layers attend over the sliding window: `layer_types` as the config states it, or every
* layer but each global_attn_every_n_layers-th in configs written before transformers 5. */
static int sliding_layers(const RadModelMeta* meta, int64_t n_layer, std::vector<bool>* out) {
out->assign((size_t)n_layer, false);
if (const char* lt = rad_meta_gets(meta, "layer_types", nullptr)) {
int64_t l = 0;
for (const char* p = lt; *p;) {
while (*p == ' ') ++p;
const char* e = p;
while (*e && *e != ' ') ++e;
if (e == p) break;
const std::string t(p, e);
if (l >= n_layer || (t != "full_attention" && t != "sliding_attention")) return RAD_E_INVAL;
(*out)[(size_t)l++] = t == "sliding_attention";
p = e;
}
return l == n_layer ? RAD_OK : RAD_E_INVAL;
}
const int64_t every = rad_meta_geti(meta, "global_attn_every_n_layers", 0);
if (every <= 0) return RAD_E_INVAL;
for (int64_t l = 0; l < n_layer; ++l) (*out)[(size_t)l] = l % every != 0;
return RAD_OK;
}
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
if (!b || !meta || !ctx) return RAD_E_INVAL;
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
if (ctx->world_size > 1) {
fprintf(stderr, "radiance: laya runs on one card (--tp 1); the largest checkpoint is "
"0.4B parameters\n");
return RAD_E_UNSUPPORTED;
}
RadArchProbe pr{};
RAD_ARCH_TRY(probe(meta, &pr));
Model& m = g_model[ctx->rank];
m = Model{};
m.nm = Names(ctx->scope);
RAD_ARCH_TRY(geom_from(m.g, meta, ctx, "bf16", RAD_BF16));
Geom& g = m.g;
Names& nm = m.nm;
const int64_t T = g.max_tok, E = g.n_embd, S = g.max_seqs, P = RAD_LAYA_POOLED;
m.F = g.n_ff;
const int64_t F = m.F;
/* The variant flags this plugin does not serve, refused by name. */
for (const char* k : { "norm_bias", "attention_bias", "mlp_bias" })
if (rad_meta_geti(meta, k, 0) != 0) {
fprintf(stderr, "radiance: laya: the encoder sets %s; ModernBERT as Laya ships it has "
"no bias there\n", k);
return RAD_E_UNSUPPORTED;
}
const char* act = rad_meta_gets(meta, "hidden_activation", "gelu");
if (std::strcmp(act, "gelu")) {
fprintf(stderr, "radiance: laya: hidden_activation '%s'; this plugin serves exact gelu\n", act);
return RAD_E_UNSUPPORTED;
}
if (g.n_head_kv != g.n_head || g.head_dim * g.n_head != E) {
fprintf(stderr, "radiance: laya: %lld heads of %lld (%lld for keys) do not tile hidden %lld\n",
(long long)g.n_head, (long long)g.head_dim, (long long)g.n_head_kv, (long long)E);
return RAD_E_INVAL;
}
std::vector<bool> sliding;
if (sliding_layers(meta, g.n_layer, &sliding) != RAD_OK) {
fprintf(stderr, "radiance: laya: neither layer_types (%lld entries of full_attention or "
"sliding_attention) nor global_attn_every_n_layers says which layers "
"attend locally\n", (long long)g.n_layer);
return RAD_E_INVAL;
}
const int64_t local = rad_meta_geti(meta, "local_attention", 128);
/* transformers masks the local layers to |i - j| <= local_attention / 2; attn_dense's window
* keeps |i - j| < window. */
const int64_t window = local / 2 + 1;
const double theta_full = rad_meta_getf(meta, "rope_parameters.full_attention.rope_theta",
rad_meta_getf(meta, "global_rope_theta", 160000.0));
const double theta_slide = rad_meta_getf(meta, "rope_parameters.sliding_attention.rope_theta",
rad_meta_getf(meta, "local_rope_theta", 10000.0));
const int64_t n_head_layers = rad_meta_geti(meta, "decision.laya.head_layers", -1);
if (local < 2 || !(theta_full > 0.0) || !(theta_slide > 0.0) || n_head_layers < 0) {
fprintf(stderr, "radiance: laya: local_attention %lld, rotary thetas %g and %g, or "
"decision.laya.head_layers %lld is not a Laya model\n", (long long)local,
theta_full, theta_slide, (long long)n_head_layers);
return RAD_E_INVAL;
}
/* torch's MultiheadAttention in the head: E / 64 heads, at least one. */
const int64_t hh = std::max<int64_t>(1, E / 64);
m.head_dim_h = E / hh;
if (m.head_dim_h * hh != E) {
fprintf(stderr, "radiance: laya: hidden %lld does not split into %lld head heads\n",
(long long)E, (long long)hh);
return RAD_E_INVAL;
}
RAD_ARCH_TRY(rad_declare_plugin_words(b, RAD_LAYA_MAX_WORDS));
/* ---- activations. b_sc is P rows longer than any step's markers: the last sequence's pooled
* row is copied from P scores, its own and then filler. */
m.b_o = decl_b(b, nm.f("o"), RAD_BF16, { T, E });
m.b_x = decl_b(b, nm.f("x"), RAD_BF16, { T, E });
m.b_h = decl_b(b, nm.f("h"), RAD_BF16, { T, E });
m.b_t = decl_b(b, nm.f("t"), RAD_BF16, { T, E });
m.b_qkv = decl_b(b, nm.f("qkv"), RAD_BF16, { T, 3 * E });
m.b_att = decl_b(b, nm.f("attn"), RAD_BF16, { T, E });
m.b_wi = decl_b(b, nm.f("wi"), RAD_BF16, { T, 2 * F });
m.b_ff = decl_b(b, nm.f("ff"), RAD_BF16, { T, F });
m.b_hff = decl_b(b, nm.f("hff"), RAD_BF16, { T, 4 * E });
m.b_trow = decl_b(b, nm.f("type"), RAD_BF16, { S, E });
m.b_m = decl_b(b, nm.f("mark"), RAD_BF16, { T, E });
m.b_m2 = decl_b(b, nm.f("mark2"), RAD_BF16, { T, E });
m.b_sc = decl_b(b, nm.f("score"), RAD_BF16, { T + P, 1 });
m.b_pooled = decl_b(b, nm.f("pooled"), RAD_F32, { S, P }, RAD_BUF_PERSIST);
if (!m.b_o || !m.b_x || !m.b_h || !m.b_t || !m.b_qkv || !m.b_att || !m.b_wi || !m.b_ff ||
!m.b_hff || !m.b_trow || !m.b_m || !m.b_m2 || !m.b_sc || !m.b_pooled)
return RAD_E_INVAL;
RAD_ARCH_TRY(rad_declare_pooled(b, m.b_pooled));
/* ---- weights. Linears and tables bf16, norms and biases f32. */
const int A = RAD_ACCESS_PER_TOKEN, N = RAD_SHARD_NONE;
auto w_model = [&](const char* name, const char* src, uint32_t dt,
std::initializer_list<int64_t> shape, int access = RAD_ACCESS_PER_TOKEN) {
if (map_copy(b, nm.f("%s", name), nm.ckpt("%s", src)) != RAD_OK) return (rad_weight)0;
return decl_w(b, nm.f("%s", name), dt, shape, access, N, grp_model());
};
m.w_tok = w_model("token_embd.weight", "encoder.embeddings.tok_embeddings.weight",
RAD_BF16, { g.n_vocab, E }, RAD_ACCESS_VOCAB);
m.w_emb_norm = w_model("emb_norm.weight", "encoder.embeddings.norm.weight", RAD_F32, { E });
m.w_final_norm = w_model("output_norm.weight", "encoder.final_norm.weight", RAD_F32, { E });
m.w_type = w_model("type_emb.weight", "type_emb.weight", RAD_BF16, { 3, E });
m.w_sn = w_model("scorer.norm.weight", "scorer.0.weight", RAD_F32, { E });
m.b_sn = w_model("scorer.norm.bias", "scorer.0.bias", RAD_F32, { E });
m.w_s1 = w_model("scorer.fc1.weight", "scorer.1.weight", RAD_BF16, { E, E });
m.b_s1 = w_model("scorer.fc1.bias", "scorer.1.bias", RAD_F32, { E });
m.w_s2 = w_model("scorer.fc2.weight", "scorer.3.weight", RAD_BF16, { 1, E });
m.b_s2 = w_model("scorer.fc2.bias", "scorer.3.bias", RAD_F32, { 1 });
if (!m.w_tok || !m.w_emb_norm || !m.w_final_norm || !m.w_type || !m.w_sn || !m.b_sn ||
!m.w_s1 || !m.b_s1 || !m.w_s2 || !m.b_s2)
return RAD_E_INVAL;
/* ---- ops, each kind stated once. */
auto lnorm = [&](int64_t rows, bool bias, rad_weight w, rad_weight bw) {
return bias ? RAD_OP(b, "layernorm",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", E),
RAD_F64("eps", g.eps), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w, bw))
: RAD_OP(b, "layernorm",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", E),
RAD_F64("eps", g.eps), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w));
};
auto gemm = [&](int64_t rows, int64_t n_out, int64_t n_in, rad_weight w) {
return RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", n_out), RAD_INT("K", n_in),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w));
};
auto gemmb = [&](int64_t rows, int64_t n_out, int64_t n_in, const char* act_name, rad_weight w,
rad_weight bw) {
return RAD_OP(b, "gemm_nt_bias",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", n_out), RAD_INT("K", n_in),
RAD_STR("dtype", "bf16"), RAD_STR("act", act_name)),
RAD_WEIGHTS(w, bw));
};
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 attn = [&](int64_t head_dim, double scale, int64_t win) {
return win > 0 ? RAD_OP(b, "attn_dense",
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", head_dim),
RAD_INT("gqa", 1), RAD_INT("causal", 0),
RAD_STR("dtype", "bf16"), RAD_F64("scale", scale),
RAD_INT("max_seqlen", T), RAD_INT("window", win)),
RAD_NOWEIGHTS)
: RAD_OP(b, "attn_dense",
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", head_dim),
RAD_INT("gqa", 1), RAD_INT("causal", 0),
RAD_STR("dtype", "bf16"), RAD_F64("scale", scale),
RAD_INT("max_seqlen", T)),
RAD_NOWEIGHTS);
};
auto rope = [&](double theta) {
return RAD_OP(b, "rope",
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", g.head_dim),
RAD_INT("n_head", g.n_head), RAD_INT("n_head_kv", g.n_head_kv),
RAD_F64("theta", theta), RAD_F64("scale", 1.0),
RAD_STR("mode", "neox")),
RAD_NOWEIGHTS);
};
m.op_embed = rw(b, RAD_OP(b, "embed_lookup",
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n_embd", E),
RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", "bf16"),
RAD_INT("vocab_offset", 0), RAD_F64("mult", 1.0)),
RAD_WEIGHTS(m.w_tok)),
{}, { m.b_o });
m.op_emb_norm = rw(b, lnorm(T, false, m.w_emb_norm, 0), { m.b_o }, { m.b_x });
m.layers.resize((size_t)g.n_layer);
for (int64_t l = 0; l < g.n_layer; ++l) {
Layer& y = m.layers[(size_t)l];
y.sliding = sliding[(size_t)l];
const long long ll = (long long)l;
const RadWeightGroup gl = grp_layer((int)l);
auto src = [&](const char* s) { return nm.ckpt("encoder.layers.%lld.%s", ll, s); };
if (l > 0) RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.attn_norm.weight", ll), src("attn_norm.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.attn_qkv.weight", ll), src("attn.Wqkv.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.attn_out.weight", ll), src("attn.Wo.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.ffn_norm.weight", ll), src("mlp_norm.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.ffn_in_gate.weight", ll), src("mlp.Wi.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.ffn_down.weight", ll), src("mlp.Wo.weight")));
if (l > 0)
y.w_attn_norm = decl_w(b, nm.f("blk.%lld.attn_norm.weight", ll), RAD_F32, { E }, A, N, gl);
y.w_qkv = decl_w(b, nm.f("blk.%lld.attn_qkv.weight", ll), RAD_BF16, { 3 * E, E }, A, N, gl);
y.w_out = decl_w(b, nm.f("blk.%lld.attn_out.weight", ll), RAD_BF16, { E, E }, A, N, gl);
y.w_mlp_norm = decl_w(b, nm.f("blk.%lld.ffn_norm.weight", ll), RAD_F32, { E }, A, N, gl);
y.w_wi = decl_w(b, nm.f("blk.%lld.ffn_in_gate.weight", ll), RAD_BF16, { 2 * F, E }, A, N, gl);
y.w_wo = decl_w(b, nm.f("blk.%lld.ffn_down.weight", ll), RAD_BF16, { E, F }, A, N, gl);
if ((l > 0 && !y.w_attn_norm) || !y.w_qkv || !y.w_out || !y.w_mlp_norm || !y.w_wi || !y.w_wo)
return RAD_E_INVAL;
const rad_buf att_in = l > 0 ? m.b_h : m.b_x;
if (l > 0) y.op_attn_norm = rw(b, lnorm(T, false, y.w_attn_norm, 0), { m.b_x }, { m.b_h });
y.op_qkv = rw(b, gemm(T, 3 * E, E, y.w_qkv), { att_in }, { m.b_qkv });
y.op_rope = rw(b, rope(y.sliding ? theta_slide : theta_full), { m.b_qkv }, { m.b_qkv });
y.op_attn = rw(b, attn(g.head_dim, 1.0 / std::sqrt((double)g.head_dim), y.sliding ? window : 0),
{ m.b_qkv }, { m.b_att });
y.op_out = rw(b, gemm(T, E, E, y.w_out), { m.b_att }, { m.b_o });
y.op_add_attn = rw(b, unary("add", T, E), { m.b_x, m.b_o }, { m.b_x });
y.op_mlp_norm = rw(b, lnorm(T, false, y.w_mlp_norm, 0), { m.b_x }, { m.b_h });
y.op_wi = rw(b, gemm(T, 2 * F, E, y.w_wi), { m.b_h }, { m.b_wi });
y.op_act = rw(b, RAD_OP(b, "act_mul",
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", F),
RAD_STR("act", "gelu"), RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ m.b_wi }, { m.b_ff });
y.op_wo = rw(b, gemm(T, E, F, y.w_wo), { m.b_ff }, { m.b_o });
y.op_add_mlp = rw(b, unary("add", T, E), { m.b_x, m.b_o }, { m.b_x });
if ((l > 0 && !y.op_attn_norm) || !y.op_qkv || !y.op_rope || !y.op_attn || !y.op_out ||
!y.op_add_attn || !y.op_mlp_norm || !y.op_wi || !y.op_act || !y.op_wo || !y.op_add_mlp)
return RAD_E_INVAL;
}
m.op_final_norm = rw(b, lnorm(T, false, m.w_final_norm, 0), { m.b_x }, { m.b_h });
/* ---- the head, over the encoder's rows in b_h. */
m.op_type = rw(b, RAD_OP(b, "embed_lookup",
RAD_PARAMS(RAD_RANGE("M", 1, 1), RAD_INT("n_embd", E), RAD_INT("n_vocab", 3),
RAD_STR("dtype", "bf16"), RAD_INT("vocab_offset", 0)),
RAD_WEIGHTS(m.w_type)),
{}, { m.b_trow });
m.op_add_type = rw(b, unary("add", T, E), { m.b_h, m.b_trow }, { m.b_h });
m.head.resize((size_t)n_head_layers);
for (int64_t j = 0; j < n_head_layers; ++j) {
HeadLayer& h = m.head[(size_t)j];
const long long jj = (long long)j;
auto hw = [&](const char* name, const char* src, uint32_t dt,
std::initializer_list<int64_t> shape) {
if (map_copy(b, nm.f("head.%lld.%s", jj, name), nm.ckpt("head.layers.%lld.%s", jj, src)) != RAD_OK)
return (rad_weight)0;
return decl_w(b, nm.f("head.%lld.%s", jj, name), dt, shape, A, N, grp_model());
};
h.n1_w = hw("norm1.weight", "norm1.weight", RAD_F32, { E });
h.n1_b = hw("norm1.bias", "norm1.bias", RAD_F32, { E });
h.qkv_w = hw("attn_qkv.weight", "self_attn.in_proj_weight", RAD_BF16, { 3 * E, E });
h.qkv_b = hw("attn_qkv.bias", "self_attn.in_proj_bias", RAD_F32, { 3 * E });
h.out_w = hw("attn_out.weight", "self_attn.out_proj.weight", RAD_BF16, { E, E });
h.out_b = hw("attn_out.bias", "self_attn.out_proj.bias", RAD_F32, { E });
h.n2_w = hw("norm2.weight", "norm2.weight", RAD_F32, { E });
h.n2_b = hw("norm2.bias", "norm2.bias", RAD_F32, { E });
h.l1_w = hw("ffn_up.weight", "linear1.weight", RAD_BF16, { 4 * E, E });
h.l1_b = hw("ffn_up.bias", "linear1.bias", RAD_F32, { 4 * E });
h.l2_w = hw("ffn_down.weight", "linear2.weight", RAD_BF16, { E, 4 * E });
h.l2_b = hw("ffn_down.bias", "linear2.bias", RAD_F32, { E });
if (!h.n1_w || !h.n1_b || !h.qkv_w || !h.qkv_b || !h.out_w || !h.out_b || !h.n2_w ||
!h.n2_b || !h.l1_w || !h.l1_b || !h.l2_w || !h.l2_b)
return RAD_E_INVAL;
h.op_n1 = rw(b, lnorm(T, true, h.n1_w, h.n1_b), { m.b_h }, { m.b_t });
h.op_qkv = rw(b, gemmb(T, 3 * E, E, "none", h.qkv_w, h.qkv_b), { m.b_t }, { m.b_qkv });
h.op_attn = rw(b, attn(m.head_dim_h, 1.0 / std::sqrt((double)m.head_dim_h), 0),
{ m.b_qkv }, { m.b_att });
h.op_out = rw(b, gemmb(T, E, E, "none", h.out_w, h.out_b), { m.b_att, m.b_h }, { m.b_h });
h.op_n2 = rw(b, lnorm(T, true, h.n2_w, h.n2_b), { m.b_h }, { m.b_t });
h.op_l1 = rw(b, gemmb(T, 4 * E, E, "none", h.l1_w, h.l1_b), { m.b_t }, { m.b_hff });
h.op_relu = rw(b, unary("relu", T, 4 * E), { m.b_hff }, { m.b_hff });
h.op_l2 = rw(b, gemmb(T, E, 4 * E, "none", h.l2_w, h.l2_b), { m.b_hff, m.b_h }, { m.b_h });
if (!h.op_n1 || !h.op_qkv || !h.op_attn || !h.op_out || !h.op_n2 || !h.op_l1 ||
!h.op_relu || !h.op_l2)
return RAD_E_INVAL;
}
/* The rows at the markers, a sequence at a time, then the scorer over all of them. */
m.op_gather = rw(b, unary("gather_rows", RAD_LAYA_MAX_OPTIONS, E), { m.b_h }, { m.b_m });
m.op_sn = rw(b, lnorm(T, true, m.w_sn, m.b_sn), { m.b_m }, { m.b_t });
m.op_s1 = rw(b, gemmb(T, E, E, "gelu", m.w_s1, m.b_s1), { m.b_t }, { m.b_m2 });
m.op_s2 = rw(b, gemmb(T, 1, E, "none", m.w_s2, m.b_s2), { m.b_m2 }, { m.b_sc });
/* Past the last marker's score, P filler rows the last pooled row's copy may read. */
m.op_fill = rw(b, RAD_OP(b, "fill",
RAD_PARAMS(RAD_RANGE("M", 1, 1), RAD_INT("n", P),
RAD_STR("dtype", "bf16"), RAD_F64("value", -1e4)),
RAD_NOWEIGHTS),
{}, { m.b_sc });
m.op_out = rw(b, RAD_OP(b, "cast",
RAD_PARAMS(RAD_RANGE("M", 1, 1), RAD_INT("n", P),
RAD_STR("from", "bf16"), RAD_STR("to", "f32")),
RAD_NOWEIGHTS),
{ m.b_sc }, { m.b_pooled });
if (!m.op_embed || !m.op_emb_norm || !m.op_final_norm || !m.op_type || !m.op_add_type ||
!m.op_gather || !m.op_sn || !m.op_s1 || !m.op_s2 || !m.op_fill || !m.op_out)
return RAD_E_INVAL;
int64_t n_sliding = 0;
for (bool s : sliding) n_sliding += s ? 1 : 0;
rad_note(b, "laya decision model: ModernBERT %lld layers (%lld sliding over %lld, rotary %g "
"and %g), hidden %lld, ffn %lld, %lld heads of %lld; head %lld layers of %lld "
"heads; at most %d options a question, one logit each in the pooled row",
(long long)g.n_layer, (long long)n_sliding, (long long)local, theta_full, theta_slide,
(long long)E, (long long)F, (long long)g.n_head, (long long)g.head_dim,
(long long)n_head_layers, (long long)hh, (int)RAD_LAYA_MAX_OPTIONS);
return RAD_OK;
}
static void step(RadCtx* c, const RadBatch* batch) {
const Model& m = g_model[rad_rank(c)];
const Geom& g = m.g;
const int64_t T = batch->n_tok, S = batch->n_seq, E = g.n_embd, F = m.F;
const int64_t P = RAD_LAYA_POOLED;
if (T <= 0 || S <= 0) return;
if (!batch->plugin_cu_h || !batch->plugin_words_h || !batch->plugin_words) {
rad_step_fail(c, "laya: the step carries no words; every Laya sequence comes from "
"/v1/systemone with its question's type and markers");
return;
}
/* Each sequence's first row from the words: an embedding input runs whole in one step, so
* the sequences' token counts add up to the step's. */
std::vector<int64_t> first((size_t)S + 1, 0);
for (int64_t s = 0; s < S; ++s) {
const int32_t w0 = batch->plugin_cu_h[s], w1 = batch->plugin_cu_h[s + 1];
const int32_t* hw = batch->plugin_words_h + w0;
const int64_t n = w1 - w0 > RAD_LAYA_W_K ? hw[RAD_LAYA_W_N] : -1;
const int64_t k = w1 - w0 > RAD_LAYA_W_K ? hw[RAD_LAYA_W_K] : -1;
const int64_t type = w1 - w0 > RAD_LAYA_W_K ? hw[RAD_LAYA_W_TYPE] : -1;
bool ok = n > 0 && k >= 1 && k <= RAD_LAYA_MAX_OPTIONS && w1 - w0 >= RAD_LAYA_W_MARKERS + k &&
type >= RAD_LAYA_CHOICE && type <= RAD_LAYA_NOUL;
for (int64_t i = 0; ok && i < k; ++i) {
const int32_t at = hw[RAD_LAYA_W_MARKERS + i];
ok = at >= 0 && at < n;
}
if (!ok) {
rad_step_fail(c, "laya: a sequence's words are not a Laya question's (type, markers)");
return;
}
first[(size_t)s + 1] = first[(size_t)s] + n;
}
if (first[(size_t)S] != T) {
rad_step_fail(c, "laya: the words' token counts do not add up to the step's tokens");
return;
}
const RadOperand cu = praw(batch->cu_seqlens, RAD_I32, S + 1);
const RadOperand pos = praw(batch->positions, RAD_I32, T);
/* ---- the encoder over every sequence at once. */
RAD_ISSUE_N(c, m.op_embed, T, praw(batch->token_ids, RAD_I32, T), RAD_W(m.w_tok), brows(m.b_o, T));
RAD_ISSUE_N(c, m.op_emb_norm, T, brows(m.b_o, T), RAD_W(m.w_emb_norm), RAD_NONE, brows(m.b_x, T));
for (size_t l = 0; l < m.layers.size(); ++l) {
const Layer& y = m.layers[l];
rad_buf att_in = m.b_x;
if (l > 0) {
RAD_ISSUE_N(c, y.op_attn_norm, T, brows(m.b_x, T), RAD_W(y.w_attn_norm), RAD_NONE,
brows(m.b_h, T));
att_in = m.b_h;
}
RAD_ISSUE_N(c, y.op_qkv, T, brows(att_in, T), RAD_W(y.w_qkv), brows(m.b_qkv, T));
RAD_ISSUE_N(c, y.op_rope, T, brows(m.b_qkv, T), pos);
RAD_ISSUE_N(c, y.op_attn, T, bcol(m.b_qkv, 0, E, T), bcol(m.b_qkv, E, E, T),
bcol(m.b_qkv, 2 * E, E, T), cu, brows(m.b_att, T));
RAD_ISSUE_N(c, y.op_out, T, brows(m.b_att, T), RAD_W(y.w_out), brows(m.b_o, T));
RAD_ISSUE_N(c, y.op_add_attn, T, brows(m.b_x, T), brows(m.b_o, T), brows(m.b_x, T));
RAD_ISSUE_N(c, y.op_mlp_norm, T, brows(m.b_x, T), RAD_W(y.w_mlp_norm), RAD_NONE,
brows(m.b_h, T));
RAD_ISSUE_N(c, y.op_wi, T, brows(m.b_h, T), RAD_W(y.w_wi), brows(m.b_wi, T));
RAD_ISSUE_N(c, y.op_act, T, bcol(m.b_wi, 0, F, T), bcol(m.b_wi, F, F, T), brows(m.b_ff, T));
RAD_ISSUE_N(c, y.op_wo, T, brows(m.b_ff, T), RAD_W(y.w_wo), brows(m.b_o, T));
RAD_ISSUE_N(c, y.op_add_mlp, T, brows(m.b_x, T), brows(m.b_o, T), brows(m.b_x, T));
}
RAD_ISSUE_N(c, m.op_final_norm, T, brows(m.b_x, T), RAD_W(m.w_final_norm), RAD_NONE,
brows(m.b_h, T));
/* ---- the head: each sequence's type row added over its rows, then the head's layers. */
for (int64_t s = 0; s < S; ++s) {
const int32_t* dw = batch->plugin_words + batch->plugin_cu_h[s];
const int64_t r0 = first[(size_t)s], n = first[(size_t)s + 1] - r0;
RAD_ISSUE_N(c, m.op_type, 1, praw(dw + RAD_LAYA_W_TYPE, RAD_I32, 1), RAD_W(m.w_type),
brow_slice(m.b_trow, s, 1, E));
RAD_ISSUE_N(c, m.op_add_type, n, brow_slice(m.b_h, r0, n, E), brow_slice(m.b_trow, s, 1, E),
brow_slice(m.b_h, r0, n, E));
}
for (const HeadLayer& h : m.head) {
RAD_ISSUE_N(c, h.op_n1, T, brows(m.b_h, T), RAD_W(h.n1_w), RAD_W(h.n1_b), brows(m.b_t, T));
RAD_ISSUE_N(c, h.op_qkv, T, brows(m.b_t, T), RAD_W(h.qkv_w), RAD_W(h.qkv_b), RAD_NONE,
brows(m.b_qkv, T));
RAD_ISSUE_N(c, h.op_attn, T, bcol(m.b_qkv, 0, E, T), bcol(m.b_qkv, E, E, T),
bcol(m.b_qkv, 2 * E, E, T), cu, brows(m.b_att, T));
RAD_ISSUE_N(c, h.op_out, T, brows(m.b_att, T), RAD_W(h.out_w), RAD_W(h.out_b),
brows(m.b_h, T), brows(m.b_h, T));
RAD_ISSUE_N(c, h.op_n2, T, brows(m.b_h, T), RAD_W(h.n2_w), RAD_W(h.n2_b), brows(m.b_t, T));
RAD_ISSUE_N(c, h.op_l1, T, brows(m.b_t, T), RAD_W(h.l1_w), RAD_W(h.l1_b), RAD_NONE,
brows(m.b_hff, T));
RAD_ISSUE_N(c, h.op_relu, T, brows(m.b_hff, T), brows(m.b_hff, T));
RAD_ISSUE_N(c, h.op_l2, T, brows(m.b_hff, T), RAD_W(h.l2_w), RAD_W(h.l2_b),
brows(m.b_h, T), brows(m.b_h, T));
}
/* ---- the markers' rows, consecutive across sequences, and one score each. */
std::vector<int64_t> mark((size_t)S + 1, 0);
for (int64_t s = 0; s < S; ++s) {
const int32_t* dw = batch->plugin_words + batch->plugin_cu_h[s];
const int64_t k = batch->plugin_words_h[batch->plugin_cu_h[s] + RAD_LAYA_W_K];
const int64_t r0 = first[(size_t)s], n = first[(size_t)s + 1] - r0;
RAD_ISSUE_N(c, m.op_gather, k, brow_slice(m.b_h, r0, n, E),
praw(dw + RAD_LAYA_W_MARKERS, RAD_I32, k), brow_slice(m.b_m, mark[(size_t)s], k, E));
mark[(size_t)s + 1] = mark[(size_t)s] + k;
}
const int64_t K = mark[(size_t)S];
RAD_ISSUE_N(c, m.op_sn, K, brows(m.b_m, K), RAD_W(m.w_sn), RAD_W(m.b_sn), brows(m.b_t, K));
RAD_ISSUE_N(c, m.op_s1, K, brows(m.b_t, K), RAD_W(m.w_s1), RAD_W(m.b_s1), RAD_NONE, brows(m.b_m2, K));
RAD_ISSUE_N(c, m.op_s2, K, brows(m.b_m2, K), RAD_W(m.w_s2), RAD_W(m.b_s2), RAD_NONE, brows(m.b_sc, K));
RAD_ISSUE_N(c, m.op_fill, 1, brow_slice(m.b_sc, K, P, 1));
/* Each sequence's pooled row: its k scores and, past them, the next scores or filler, which
* the server does not read. */
for (int64_t s = 0; s < S; ++s)
RAD_ISSUE_N(c, m.op_out, 1, brow_slice(m.b_sc, mark[(size_t)s], P, 1),
bcol_at(m.b_pooled, s, P, 0, P, 1));
}
} /* namespace laya */
RAD_ARCH_PLUGIN(laya, "laya", "", "0.1.0",
"Convai Innovations' Laya (laya, laya-typed-decisions, laya-multilingual): a "
"ModernBERT encoder and a decision head scoring each option at its [MASK], one "
"sequence a question, served on /v1/systemone; bf16")
RAD_ARCH_PROBE(laya)
+19
View File
@@ -28,6 +28,7 @@
#include <atomic>
#include <chrono>
#include <csignal>
#include <cstdio>
#include <cstring>
#include <cstdint>
#include <cstdlib>
@@ -2443,6 +2444,24 @@ int Engine::run_server() {
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);
}
/* Laya's sequence lengths, special tokens and fitted temperatures, which the server builds
* and reads each question with (server/laya.h); rad-convert writes them from the checkpoint's
* rl_agent_config.json and tokenizer/. */
if (o.decision_type == "laya") {
server::LayaSettings& l = o.laya;
l.max_len = rad_meta_geti(&meta_, "decision.laya.max_len", 0);
l.head_max_len = rad_meta_geti(&meta_, "decision.laya.head_max_len", 0);
l.cls = (int32_t)rad_meta_geti(&meta_, "decision.laya.cls", -1);
l.sep = (int32_t)rad_meta_geti(&meta_, "decision.laya.sep", -1);
l.mask = (int32_t)rad_meta_geti(&meta_, "decision.laya.mask", -1);
l.mask_token = rad_meta_gets(&meta_, "decision.laya.mask_token", "");
std::sscanf(rad_meta_gets(&meta_, "decision.laya.temperature", "1 1 1"), "%lf %lf %lf",
&l.temperature[0], &l.temperature[1], &l.temperature[2]);
const std::string tbo = "decision.laya.temperature_by_options.";
for (int i = 0; i < meta_.n_kv; ++i)
if (std::strncmp(meta_.kv_key[i], tbo.c_str(), tbo.size()) == 0)
l.temperature_by_options[meta_.kv_key[i] + tbo.size()] = std::strtod(meta_.kv_val[i], nullptr);
}
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";
+2 -1
View File
@@ -390,7 +390,8 @@ json Server::capabilities() const {
* whatever its conditioning network's processor would take. */
const bool img = opt_.image_model || opt_.video_model;
caps["grammar"] = !img && deps_.grammar != nullptr;
caps["embedding"] = deps_.embed != nullptr;
/* Laya runs on the embedding path, but answers /v1/systemone, not /v1/embeddings. */
caps["embedding"] = deps_.embed != nullptr && opt_.decision_type != "laya";
caps["image"] = deps_.mm && deps_.mm->accepts(MediaKind::Image);
caps["video"] = !img && deps_.mm && deps_.mm->accepts(MediaKind::Video);
caps["audio"] = !img && deps_.mm && deps_.mm->accepts(MediaKind::Audio);
+402
View File
@@ -0,0 +1,402 @@
/* laya.cpp -- Laya's sequences, words and answers (laya.h).
*
* Every string below is laya's own, from laya/common.py: "<type> question: ", the option forms
* ("label: description", "level i: description", "false: ..."/"true: ...") and the noul defaults.
* Each piece is tokenized on its own and the ids concatenated, as build_head does, so a marker
* always sits at its own option's first position.
*/
#include "laya.h"
#include "rad_laya.h"
#include <nlohmann/json.hpp>
#include <algorithm>
#include <cctype>
#include <cmath>
#include <limits>
namespace rad {
namespace server {
namespace {
bool only_keys(const json& o, std::initializer_list<const char*> allowed, const std::string& path,
ApiError* err) {
for (const auto& kv : o.items()) {
bool ok = false;
for (const char* k : allowed) ok = ok || kv.key() == k;
if (!ok) {
*err = err_unsupported(path + kv.key(), "not a field of a System One request");
return false;
}
}
return true;
}
bool blank(const std::string& s) {
return std::all_of(s.begin(), s.end(), [](unsigned char c) { return std::isspace(c) != 0; });
}
std::string replace_all(std::string s, const std::string& from, const std::string& to) {
if (from.empty()) return s;
for (size_t at = s.find(from); at != std::string::npos; at = s.find(from, at + to.size()))
s.replace(at, from.size(), to);
return s;
}
/* render_criterion: a string as it is, anything else as JSON text. */
std::string criterion(const json& v) { return v.is_string() ? v.get<std::string>() : laya_render(v); }
/* A choice label as Python's str() writes it (the option text) and as its json module writes a
* dict key (the response's key): they differ only for a bool. */
std::string label_text(const json& v) {
if (v.is_boolean()) return v.get<bool>() ? "True" : "False";
return v.is_string() ? v.get<std::string>() : laya_render(v);
}
std::string label_key(const json& v) {
return v.is_string() ? v.get<std::string>() : laya_render(v);
}
/* Python compares 1, 1.0 and True as one dict key. */
bool same_label(const json& a, const json& b) {
const bool na = a.is_number() || a.is_boolean(), nb = b.is_number() || b.is_boolean();
if (na && nb) {
auto num = [](const json& v) { return v.is_boolean() ? (v.get<bool>() ? 1.0 : 0.0) : v.get<double>(); };
return num(a) == num(b);
}
return a == b;
}
/* _check_question and _to_internal, then render_options: the option texts in model order. */
int question(const std::string& path, const json& src, LayaQuestion* q, std::string* ins,
std::vector<std::string>* opts, ApiError* err) {
if (!src.is_object()) { *err = err_bad(path, "must be an object"); return RAD_E_INVAL; }
if (!only_keys(src, { "type", "instructions", "criteria" }, path + ".", err)) return RAD_E_INVAL;
const auto ty = src.find("type");
if (ty == src.end() || !ty->is_string() ||
(*ty != "choice" && *ty != "score" && *ty != "noul")) {
*err = err_bad(path + ".type", "must be choice, score or noul");
return RAD_E_INVAL;
}
q->type = ty->get<std::string>();
q->type_id = q->type == "choice" ? RAD_LAYA_CHOICE : q->type == "score" ? RAD_LAYA_SCORE : RAD_LAYA_NOUL;
const auto in = src.find("instructions");
if (in == src.end() || in->is_null() || (in->is_string() && blank(in->get<std::string>())) ||
((in->is_array() || in->is_object()) && in->empty())) {
*err = err_bad(path + ".instructions", "required: the text the model should answer");
return RAD_E_INVAL;
}
*ins = in->is_string() ? in->get<std::string>() : laya_render(*in);
const json crit = src.contains("criteria") ? src.at("criteria") : json();
if (q->type == "choice") {
if (!(crit.is_object() || crit.is_array()) || crit.empty()) {
*err = err_bad(path + ".criteria", "must be a non-empty object of label to description, "
"or a non-empty array of labels");
return RAD_E_INVAL;
}
if (crit.is_object()) {
for (const auto& kv : crit.items()) {
const json& d = kv.value();
q->keys.push_back(kv.key());
q->labels.push_back(kv.key());
opts->push_back(d.is_null() || d == "" ? kv.key() : kv.key() + ": " + criterion(d));
}
} else {
for (size_t i = 0; i < crit.size(); ++i) {
const json& l = crit[i];
if (!(l.is_string() || l.is_number() || l.is_boolean())) {
*err = err_bad(path + ".criteria", "label " + std::to_string(i) + " must be a "
"string, number or bool: a label is the option's text and its "
"answer key");
return RAD_E_INVAL;
}
for (size_t j = 0; j < i; ++j)
if (same_label(crit[j], l)) {
*err = err_bad(path + ".criteria", "label " + std::to_string(i) +
" repeats label " + std::to_string(j) + "; every option "
"needs its own answer key");
return RAD_E_INVAL;
}
q->keys.push_back(label_key(l));
q->labels.push_back(l);
opts->push_back(label_text(l));
}
}
return RAD_OK;
}
if (q->type == "score") {
if (!crit.is_array() || crit.empty()) {
*err = err_bad(path + ".criteria", "must be a non-empty array of level descriptions, "
"level 0 first");
return RAD_E_INVAL;
}
for (size_t i = 0; i < crit.size(); ++i) {
if (crit[i].is_null()) {
*err = err_bad(path + ".criteria", "level " + std::to_string(i) + " is null; give "
"every level a description");
return RAD_E_INVAL;
}
q->keys.push_back(std::to_string(i));
q->legend.push_back(criterion(crit[i]));
opts->push_back("level " + std::to_string(i) + ": " + q->legend.back());
}
return RAD_OK;
}
/* noul: false then true, so the second probability is P(true). */
json t, f;
if (!crit.is_null()) {
if (!crit.is_object()) {
*err = err_bad(path + ".criteria", "must be an object with optional `true` and `false` "
"descriptions, or absent");
return RAD_E_INVAL;
}
for (const auto& kv : crit.items()) {
std::string k = kv.key();
for (char& ch : k) ch = (char)std::tolower((unsigned char)ch);
if (k == "true") t = kv.value();
else if (k == "false") f = kv.value();
else {
*err = err_bad(path + ".criteria", "takes only `true` and `false`, got `" + kv.key() + "`");
return RAD_E_INVAL;
}
}
}
q->keys = { "false", "true" };
opts->push_back("false: " + (f.is_null() || f == "" ? std::string("no, the statement does not hold")
: criterion(f)));
opts->push_back("true: " + (t.is_null() || t == "" ? std::string("yes, the statement holds")
: criterion(t)));
return RAD_OK;
}
double round4(double v) { return std::round(v * 10000.0) / 10000.0; }
/* temp_bucket, and the clamp the package applies to every fitted temperature as it loads. */
double temperature_of(const LayaQuestion& q, size_t k, const LayaSettings& s) {
const char* size = k <= 2 ? "2" : k <= 5 ? "3-5" : k <= 10 ? "6-10" : "11+";
const auto it = s.temperature_by_options.find(q.type + ":" + size);
const double t = it != s.temperature_by_options.end() ? it->second : s.temperature[q.type_id];
return std::isfinite(t) ? std::min(5.0, std::max(0.5, t)) : 1.0;
}
/* confidence_from_probs: 1 - H(p) / log(k), within [0, 1]; 1 below two options. */
double entropy_confidence(const std::vector<float>& p) {
const size_t k = p.size();
if (k < 2) return 1.0;
float ent = 0.0f;
for (float v : p) ent += v * std::log(std::min(1.0f, std::max(1e-12f, v)));
const double c = 1.0 - (double)(-ent) / std::log((double)k);
return c < 0.0 ? 0.0 : c > 1.0 ? 1.0 : c;
}
} /* namespace */
std::string laya_render(const json& v) {
if (v.is_object()) {
std::string s = "{";
bool first = true;
for (const auto& kv : v.items()) {
if (!first) s += ", ";
first = false;
s += json(kv.key()).dump(-1, ' ', false, nlohmann::ordered_json::error_handler_t::replace);
s += ": " + laya_render(kv.value());
}
return s + "}";
}
if (v.is_array()) {
std::string s = "[";
for (size_t i = 0; i < v.size(); ++i) s += (i ? ", " : "") + laya_render(v[i]);
return s + "]";
}
return v.dump(-1, ' ', false, nlohmann::ordered_json::error_handler_t::replace);
}
int parse_laya_request(const std::string& body, const OaiDeps& d, const OaiLimits& lim,
const std::string& model_id, const LayaSettings& s, LayaRequest* out,
ApiError* err) {
*out = LayaRequest{};
json b;
RAD_TRY(parse_request_object(body, lim, &b, err));
if (!only_keys(b, { "model", "state", "questions", "images" }, "", err)) return RAD_E_INVAL;
if (b.contains("model") && (!b["model"].is_string() || b["model"] != model_id)) {
*err = err_bad("model", "must name the loaded model, " + model_id);
return RAD_E_INVAL;
}
if (!b.contains("state") || b["state"].is_null() ||
(b["state"].is_string() && b["state"].get<std::string>().empty())) {
*err = err_bad("state", "required: a non-empty string or any JSON value");
return RAD_E_INVAL;
}
if (b.contains("images") && !(b["images"].is_array() && b["images"].empty())) {
*err = err_not_implemented("images: Laya reads its state as text only");
return RAD_E_UNSUPPORTED;
}
const json& qs = b.contains("questions") ? b["questions"] : json();
if (!qs.is_object() || qs.empty()) {
*err = err_bad("questions", "must be a non-empty object of named questions");
return RAD_E_INVAL;
}
const ITokenizer& tok = *d.tok;
auto ids = [&](const std::string& text) {
return tok.encode(replace_all(text, s.mask_token, " "), false, true);
};
/* The state is tokenized once and cut per question; a list of turns keeps its end. */
const json& st = b["state"];
const bool keep_end = st.is_array();
const std::vector<int32_t> state = ids(st.is_string() ? st.get<std::string>() : laya_render(st));
out->state_tokens = (int64_t)state.size();
for (const auto& kv : qs.items()) {
const std::string path = "questions." + kv.key();
if (blank(kv.key())) {
*err = err_bad("questions", "a question's name must not be empty");
return RAD_E_INVAL;
}
LayaQuestion q;
q.name = kv.key();
std::string ins;
std::vector<std::string> opts;
RAD_TRY(question(path, kv.value(), &q, &ins, &opts, err));
const int64_t n = (int64_t)opts.size();
if (n > RAD_LAYA_MAX_OPTIONS) {
*err = err_bad(path + ".criteria", "at most " + std::to_string(RAD_LAYA_MAX_OPTIONS) +
" options a question");
return RAD_E_INVAL;
}
/* build_head: options capped at 48 tokens, all of them shrunk evenly when they leave the
* instruction fewer than 16 of head_max_len, and the instruction cut to what is left. */
std::vector<std::vector<int32_t>> opt;
int64_t used = 0;
for (const std::string& o : opts) {
std::vector<int32_t> t = ids(" " + o);
if (t.size() > 48) t.resize(48);
t.insert(t.begin(), s.mask);
used += (int64_t)t.size();
opt.push_back(std::move(t));
}
int64_t budget = s.head_max_len - used;
if (budget < 16) {
const int64_t per = std::max<int64_t>(4, (s.head_max_len - 16) / std::max<int64_t>(1, n));
used = 0;
for (auto& t : opt) {
if ((int64_t)t.size() > per) t.resize((size_t)per);
used += (int64_t)t.size();
}
budget = s.head_max_len - used;
}
std::vector<int32_t> head = ids(q.type + " question: " + ins);
head.resize((size_t)std::min<int64_t>((int64_t)head.size(), std::max<int64_t>(8, budget)));
std::vector<int32_t>& seq = q.tokens;
seq.push_back(s.cls);
seq.insert(seq.end(), head.begin(), head.end());
seq.push_back(s.sep);
for (const auto& t : opt) {
q.markers.push_back((int32_t)seq.size());
seq.insert(seq.end(), t.begin(), t.end());
}
seq.push_back(s.sep);
/* build_sequence: the state gets the room left before the closing [SEP]. */
const int64_t room = std::max<int64_t>(0, s.max_len - (int64_t)seq.size() - 1);
const int64_t take = std::min<int64_t>(room, (int64_t)state.size());
if (keep_end) seq.insert(seq.end(), state.end() - take, state.end());
else seq.insert(seq.end(), state.begin(), state.begin() + take);
seq.push_back(s.sep);
q.state_used = take;
if ((int64_t)seq.size() > s.max_len) seq.resize((size_t)s.max_len);
q.markers.erase(std::remove_if(q.markers.begin(), q.markers.end(),
[&](int32_t m) { return m >= s.max_len; }),
q.markers.end());
if ((int64_t)q.markers.size() != n) {
*err = err_bad(path + ".criteria", std::to_string(n) + " options do not fit this "
"model's " + std::to_string(s.max_len) + "-token sequence (head_max_len " +
std::to_string(s.head_max_len) + "); fewer or shorter options fit");
return RAD_E_INVAL;
}
out->questions.push_back(std::move(q));
}
return RAD_OK;
}
std::vector<int32_t> laya_words(const LayaQuestion& q) {
std::vector<int32_t> w((size_t)RAD_LAYA_W_MARKERS, 0);
w[RAD_LAYA_W_N] = (int32_t)q.tokens.size();
w[RAD_LAYA_W_TYPE] = q.type_id;
w[RAD_LAYA_W_K] = (int32_t)q.markers.size();
w.insert(w.end(), q.markers.begin(), q.markers.end());
return w;
}
int laya_answer(const LayaQuestion& q, const std::vector<float>& pooled, const LayaSettings& s,
json* out, ApiError* err) {
const size_t k = q.keys.size();
if (pooled.size() < k) {
*err = err_internal("the plugin returned no logits for question " + q.name);
return RAD_E_STATE;
}
/* _decode_answers, in float32 as the package's numpy rows are. */
const float t = (float)temperature_of(q, k, s);
std::vector<float> p(k);
float peak = -std::numeric_limits<float>::infinity();
for (size_t i = 0; i < k; ++i) {
if (!std::isfinite(pooled[i])) {
*err = err_internal("question " + q.name + " scored a non-finite logit");
return RAD_E_STATE;
}
p[i] = pooled[i] / t;
peak = std::max(peak, p[i]);
}
float total = 0.0f;
for (float& v : p) total += (v = std::exp(v - peak));
for (float& v : p) v /= total;
json a = json::object();
a["type"] = q.type;
if (q.type == "noul") {
a["noul"] = round4(p[1]);
*out = std::move(a);
return RAD_OK;
}
json probs = json::object();
for (size_t i = 0; i < k; ++i) probs[q.keys[i]] = round4(p[i]);
if (q.type == "choice") {
const size_t best = (size_t)(std::max_element(p.begin(), p.end()) - p.begin());
a["choice"] = q.labels[best];
a["confidence"] = round4(entropy_confidence(p));
a["probabilities"] = std::move(probs);
} else {
double expected = 0.0;
json legend = json::object();
for (size_t i = 0; i < k; ++i) {
expected += (double)i * (double)p[i];
legend[q.keys[i]] = q.legend[i];
}
a["score"] = round4(expected);
a["confidence"] = round4(entropy_confidence(p));
a["probabilities"] = std::move(probs);
a["legend"] = std::move(legend);
}
*out = std::move(a);
return RAD_OK;
}
json laya_usage(const LayaRequest& r) {
int64_t input = 0, dropped = 0;
json cut = json::array();
for (const LayaQuestion& q : r.questions) {
input += (int64_t)q.tokens.size();
dropped = std::max(dropped, r.state_tokens - q.state_used);
if (q.state_used < r.state_tokens) cut.push_back(q.name);
}
return json{ { "input_tokens", input }, { "output_tokens", 0 },
{ "state_tokens", r.state_tokens }, { "state_tokens_dropped", dropped },
{ "truncated", dropped > 0 }, { "truncated_questions", std::move(cut) } };
}
} /* namespace server */
} /* namespace rad */
+85
View File
@@ -0,0 +1,85 @@
/* laya.h -- POST /v1/systemone for Convai Innovations' Laya decision models: each question's
* sequence, its words for the plugin, and the answer from the plugin's option logits.
*
* Laya reads one sequence a question, `[CLS] <type> question: <instructions> [SEP] [MASK] opt0
* [MASK] opt1 ... [SEP] <state> [SEP]`, and scores each option at its [MASK] (arch/laya). This
* file is a C++ rewrite of _check_question, _to_internal, render_options, build_head,
* build_sequence and _decode_answers in laya's own package (laya/agent.py, laya/common.py), its
* strings kept as they are: the model was trained on exactly this text.
*
* As the package does, a state longer than the room a question leaves is cut (to its start, or to
* its end when the state is a list of turns), and `usage` says so with the package's own keys:
* state_tokens, state_tokens_dropped, truncated and truncated_questions.
*
* Served only when the container declares laya (`decision.type` = `laya`, which rad-convert sets
* for a Laya checkpoint directory).
*/
#pragma once
#include "oai.h"
#include <map>
#include <string>
#include <vector>
namespace rad {
namespace server {
/* The container's Laya settings (decision.laya.*, which rad-convert writes from
* rl_agent_config.json and tokenizer/; the engine copies them here). */
struct LayaSettings {
int64_t max_len = 0, head_max_len = 0;
int32_t cls = -1, sep = -1, mask = -1;
std::string mask_token;
double temperature[3] = { 1.0, 1.0, 1.0 }; /* choice, score, noul */
std::map<std::string, double> temperature_by_options; /* "choice:3-5" -> t */
bool ok() const {
return max_len > 0 && head_max_len > 0 && cls >= 0 && sep >= 0 && mask >= 0 &&
!mask_token.empty();
}
};
struct LayaQuestion {
std::string name, type; /* type: choice | score | noul */
int type_id = 0; /* RAD_LAYA_CHOICE, _SCORE or _NOUL (abi/rad_laya.h) */
/* One entry an option, in the order the model scores them: a choice's labels as the request
* gives them (`keys` the response's keys, `labels` the values `choice` answers with), a score's
* levels "0".."n-1", noul false then true. */
std::vector<std::string> keys;
std::vector<json> labels;
std::vector<std::string> legend; /* score: each level as the model read it */
std::vector<int32_t> tokens; /* the sequence */
std::vector<int32_t> markers; /* each option's [MASK] position in it */
int64_t state_used = 0; /* state tokens the sequence holds */
};
struct LayaRequest {
std::vector<LayaQuestion> questions;
int64_t state_tokens = 0; /* the state, tokenized whole */
};
/* Parse, validate and build every question's sequence. 400 for what the package refuses, and for
* options that do not fit the head's budget. */
int parse_laya_request(const std::string& body, const OaiDeps& d, const OaiLimits& lim,
const std::string& model_id, const LayaSettings& s, LayaRequest* out,
ApiError* err);
/* The question's words for the plugin (abi/rad_laya.h): its tokens, type and markers. */
std::vector<int32_t> laya_words(const LayaQuestion& q);
/* One question's answer from the plugin's pooled row (its first k values are the option logits):
* the fitted temperature, clamped to [0.5, 5] as the package clamps it, a softmax, and the
* package's rounding and confidence. A non-finite logit is an error. */
int laya_answer(const LayaQuestion& q, const std::vector<float>& pooled, const LayaSettings& s,
json* out, ApiError* err);
/* The request's `usage`: input_tokens (every sequence) and the package's truncation report. */
json laya_usage(const LayaRequest& r);
/* json.dumps(v, ensure_ascii=False) with Python's default separators, keys in the request's
* order: how the package renders a state, an instruction or a criterion that is not a string.
* Exposed for the tests. */
std::string laya_render(const json& v);
} /* namespace server */
} /* namespace rad */
+104 -1
View File
@@ -3,6 +3,8 @@
#include <cstdio>
#include "clef.h"
#include "laya.h"
#include "rad_laya.h"
#include "json_partial.h"
#include "systemone.h"
#include "rad_internal.h"
@@ -1621,6 +1623,11 @@ HttpResponse Server::handle_embeddings(const HttpRequest& req) {
if (!deps_.sched || !deps_.tok)
return error_response(err_not_implemented("the server has no engine attached"),
req.peer);
/* Laya runs on the embedding path, but its pooled row is option logits, not a vector. */
if (opt_.decision_type == "laya")
return error_response(err_not_implemented("/v1/embeddings requires an embedding model; "
"this one is Laya, which answers /v1/systemone"),
req.peer);
if (!deps_.embed)
return error_response(err_not_implemented(
opt_.image_model ? "/v1/embeddings requires an embedding model; this one makes images"
@@ -1746,10 +1753,12 @@ 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 == "laya") return handle_laya(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, clef with --set decision.type=clef)"),
"(convert d1 with --set decision.type=d1, clef with --set decision.type=clef; "
"rad-convert sets laya for a Laya checkpoint directory)"),
req.peer);
DecisionRequest r;
@@ -1952,6 +1961,100 @@ HttpResponse Server::handle_clef(const HttpRequest& req) {
{ "usage", { { "input_tokens", (int64_t)r.tokens.size() }, { "output_tokens", 0 } } } }));
}
/* Laya (laya.h): one engine request a question, each its own sequence with the state in it, as
* Laya reads them, submitted together so the scheduler runs them in one step. Laya's plugin
* (arch/laya) declares a pooled output, so each request runs on the embedding path and comes back
* as its pooled row, whose first k values are the question's option logits. */
HttpResponse Server::handle_laya(const HttpRequest& req) {
if (!opt_.laya.ok() || !deps_.embed || deps_.embed->dim() < RAD_LAYA_POOLED)
return error_response(err_internal("this container declares laya but carries no complete "
"decision.laya.* settings or no Laya plugin; convert the "
"checkpoint directory again with rad-convert"), req.peer);
LayaRequest r;
ApiError err;
if (parse_laya_request(req.body, odeps_, lim_, opt_.model_id, opt_.laya, &r, &err) < 0)
return error_response(err, req.peer);
const int n = (int)r.questions.size();
for (const LayaQuestion& q : r.questions)
if ((int64_t)q.tokens.size() > deps_.embed->max_input())
return error_response(err_bad("questions", "question " + q.name + " is " +
std::to_string(q.tokens.size()) + " tokens; this "
"deployment runs at most " +
std::to_string(deps_.embed->max_input()) +
" a step (--max-num-batched-tokens)"), req.peer);
if (auto no = admit(n, req.peer, ApiShape::OpenAI, "questions")) return *no;
RAD_INFO("systemone (laya) admitted%s questions=%d state=%lld tok",
from_peer(req.peer).c_str(), n, (long long)r.state_tokens);
std::vector<Generation> gens;
std::vector<Request> rqs;
gens.reserve((size_t)n);
rqs.reserve((size_t)n);
for (int i = 0; i < n; ++i) {
Generation g;
g.index = i;
g.prompt_index = i;
g.sink = std::make_shared<Sink>(16);
Request rq;
rq.prompt = r.questions[(size_t)i].tokens;
rq.plugin_words = laya_words(r.questions[(size_t)i]);
rq.embed = true;
rq.max_tokens = 1;
rq.sp.temp = 0.0f;
rq.sink = g.sink.get();
rqs.push_back(std::move(rq));
gens.push_back(std::move(g));
}
std::vector<uint64_t> ids;
deps_.sched->submit_all(rqs, &ids);
for (size_t i = 0; i < ids.size(); ++i) {
gens[i].id = ids[i];
gens[i].sink->id = ids[i];
if (!ids[i]) {
cancel_all(gens, false);
retire(gens);
release(n);
return error_response(err_internal("the scheduler refused question " +
r.questions[i].name), req.peer);
}
}
for (;;) {
bool all = true;
for (auto& g : gens) {
if (!g.closed && g.sink->done()) { g.closed = true; g.finish = g.sink->finish_reason(); }
all = all && g.closed;
}
if (all) break;
if (auto no = abandoned(req, gens, n)) return *no;
for (auto& g : gens) if (!g.closed) { g.sink->wait(); break; }
}
json answers = json::object();
for (int i = 0; i < n; ++i) {
const Generation& g = gens[(size_t)i];
const LayaQuestion& q = r.questions[(size_t)i];
if (g.finish == Finish::Error || g.finish == Finish::Cancelled) {
const std::string why = g.finish == Finish::Error ? engine_failure(*g.sink)
: "the engine cancelled question " + q.name;
retire(gens);
release(n);
return error_response(err_internal(why), req.peer);
}
json a;
if (laya_answer(q, g.sink->embedding(), opt_.laya, &a, &err) < 0) {
retire(gens);
release(n);
return error_response(err, req.peer);
}
answers[q.name] = std::move(a);
}
retire(gens);
release(n);
metrics_.observe_http(200);
return HttpResponse::json_body(200, json_dump(json{ { "answers", std::move(answers) },
{ "usage", laya_usage(r) } }));
}
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. */
+7 -2
View File
@@ -16,6 +16,7 @@
#include <functional>
#include "http.h"
#include "iface.h"
#include "laya.h"
#include "liveview.h"
#include "metrics.h"
#include "oai.h"
@@ -82,13 +83,16 @@ 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), "clef" serves it through the head on the card (clef.h); empty answers it
* 501. Never inferred from a name. */
* (systemone.h), "clef" serves it through the head on the card (clef.h), "laya" through the
* Laya plugin's option logits (laya.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;
/* laya: the sequence lengths, special tokens and fitted temperatures from the container
* header (decision.laya.*, written by rad-convert). */
LayaSettings laya;
/* 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
@@ -251,6 +255,7 @@ private:
HttpResponse handle_embeddings(const HttpRequest& req);
HttpResponse handle_systemone(const HttpRequest& req);
HttpResponse handle_clef(const HttpRequest& req);
HttpResponse handle_laya(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);
+9 -1
View File
@@ -301,7 +301,7 @@ 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 clef_decision_test)
foreach(t engine_e2e_test convert_test clef_decision_test laya_decision_test)
if(TARGET ${t})
target_compile_definitions(${t} PRIVATE
RAD_E2E_SERVER="$<TARGET_FILE:radiance>" RAD_E2E_CONVERT="$<TARGET_FILE:rad-convert>"
@@ -311,6 +311,11 @@ foreach(t engine_e2e_test convert_test clef_decision_test)
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 clef_bf16)
elseif(t STREQUAL "laya_decision_test")
# The tiny Laya's golden (tests/mklayagolden.py) and the plugin a Laya container selects.
target_compile_definitions(${t} PRIVATE
RAD_LAYA_GOLDEN="${CMAKE_CURRENT_SOURCE_DIR}/data/golden/laya_tiny.json")
add_dependencies(${t} radiance rad-convert libref libquant laya)
else()
add_dependencies(${t} ${RAD_E2E_DEPS})
endif()
@@ -324,6 +329,9 @@ endif()
if(TARGET clef_decision_test)
set_tests_properties(clef_decision_test PROPERTIES LABELS "e2e" TIMEOUT 300)
endif()
if(TARGET laya_decision_test)
set_tests_properties(laya_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.
+2 -169
View File
@@ -14,186 +14,19 @@
* 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 "decision_e2e.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;
using namespace decision_e2e;
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
+242
View File
@@ -0,0 +1,242 @@
{
"weights_fnv": "230e9131e87efe05",
"laya_commit": "fe9a6c3502",
"requests": [
{
"state": "Charged twice for one order; refund one please.",
"questions": {
"refund": {
"type": "noul",
"instructions": "Does the customer ask for money back?"
},
"team": {
"type": "choice",
"instructions": "Which team should take this?",
"criteria": {
"billing": "Charges and refunds",
"shipping": "Delivery",
"product": ""
}
},
"tone": {
"type": "score",
"instructions": "How upset is the customer?",
"criteria": [
"Calm",
"Mildly annoyed",
"Angry"
]
}
}
},
{
"state": {
"message": "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, and please tell the courier.",
"channel": "email"
},
"questions": {
"topic": {
"type": "choice",
"instructions": "Topic?",
"criteria": [
"a",
"b",
"c",
"d",
"e",
"f",
"g",
"h",
"i",
"j",
"k",
"l"
]
},
"spam": {
"type": "noul",
"instructions": {
"ask": "Is this unsolicited?"
},
"criteria": {
"true": "unsolicited bulk mail"
}
},
"team": {
"type": "choice",
"instructions": "Route it.",
"criteria": [
"billing",
"technical",
"sales",
"other"
]
}
}
},
{
"state": [
{
"role": "user",
"content": "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, and please tell the courier."
},
{
"role": "agent",
"content": "Sorry, checking."
},
{
"role": "user",
"content": "Any news on the refund?"
}
],
"questions": {
"waiting": {
"type": "noul",
"instructions": "Is the customer still waiting?"
}
}
}
],
"results": [
{
"answers": {
"refund": {
"type": "noul",
"noul": 0.4816,
"confidence": 0.5184,
"answer_confidence": 0.5184,
"action": {
"act_probability": 0.3778
}
},
"team": {
"type": "choice",
"choice": "product",
"probabilities": {
"billing": 0.2738,
"shipping": 0.3475,
"product": 0.3787
},
"confidence": 0.0081,
"answer_confidence": 0.3787,
"action": {
"act_probability": 0.6045
}
},
"tone": {
"type": "score",
"score": 1.3351,
"legend": {
"0": "Calm",
"1": "Mildly annoyed",
"2": "Angry"
},
"probabilities": {
"0": 0.2201,
"1": 0.2247,
"2": 0.5552
},
"confidence": 0.094,
"answer_confidence": 0.5552,
"action": {
"act_probability": 0.8258
}
}
},
"usage": {
"input_tokens": 297,
"output_tokens": 0,
"state_tokens": 47,
"state_tokens_dropped": 0,
"truncated": false,
"truncated_questions": []
}
},
{
"answers": {
"topic": {
"type": "choice",
"choice": "d",
"probabilities": {
"a": 0.0212,
"b": 0.0235,
"c": 0.0906,
"d": 0.2956,
"e": 0.1971,
"f": 0.1235,
"g": 0.0387,
"h": 0.001,
"i": 0.0043,
"j": 0.0429,
"k": 0.1461,
"l": 0.0153
},
"confidence": 0.2101,
"answer_confidence": 0.2956,
"action": {
"act_probability": 0.5545
}
},
"spam": {
"type": "noul",
"noul": 0.4899,
"confidence": 0.5101,
"answer_confidence": 0.5101,
"action": {
"act_probability": 0.4172
}
},
"team": {
"type": "choice",
"choice": "billing",
"probabilities": {
"billing": 0.3187,
"technical": 0.2485,
"sales": 0.2368,
"other": 0.1961
},
"confidence": 0.0111,
"answer_confidence": 0.3187,
"action": {
"act_probability": 0.4443
}
}
},
"usage": {
"input_tokens": 384,
"output_tokens": 0,
"state_tokens": 199,
"state_tokens_dropped": 123,
"truncated": true,
"truncated_questions": [
"topic",
"spam",
"team"
]
}
},
{
"answers": {
"waiting": {
"type": "noul",
"noul": 0.4588,
"confidence": 0.5412,
"answer_confidence": 0.5412,
"action": {
"act_probability": 0.6247
}
}
},
"usage": {
"input_tokens": 128,
"output_tokens": 0,
"state_tokens": 303,
"state_tokens_dropped": 227,
"truncated": true,
"truncated_questions": [
"waiting"
]
}
}
]
}
+185
View File
@@ -0,0 +1,185 @@
/* decision_e2e.h -- the radiance binary on a free loopback port and plain HTTP calls to it, for
* the decision models' end-to-end tests (clef_decision_test.cpp, laya_decision_test.cpp).
*
* The server runs on the host backend with the reference kernels, as engine_e2e_test.cpp runs one.
* RAD_E2E_SERVER and RAD_E2E_HOME come from tests/CMakeLists.txt.
*/
#pragma once
#include "rad_test.h"
#include "tiny_model.h"
#include <nlohmann/json.hpp>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <cerrno>
#include <condition_variable>
#include <cstring>
#include <fstream>
#include <mutex>
#include <thread>
namespace decision_e2e {
using json = nlohmann::ordered_json; /* the request order, which Laya reads */
inline 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 };
}
inline 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;
}
inline 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); }
};
inline 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);
}
inline 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;
}
inline std::string hex16(uint64_t v) {
char s[24];
std::snprintf(s, sizeof s, "%016llx", (unsigned long long)v);
return s;
}
} /* namespace decision_e2e */
+288
View File
@@ -0,0 +1,288 @@
/* laya_decision_test.cpp -- /v1/systemone on a Laya container, end to end on the CPU.
*
* A tiny Laya in the release's own layout (config.json saying model_type laya, encoder/config.json
* a three-layer ModernBERT with one sliding layer pair, rl_agent_config.json, tokenizer/, and
* model.safetensors with the release's tensor names), converted with `--set decision.type=laya`
* and served by the radiance binary on the host backend. The answers and usage are checked against
* tests/data/golden/laya_tiny.json, laya's own Agent.predict on the same checkpoint in float32,
* made by tests/mklayagolden.py from the directory this test writes (RAD_E2E_KEEP=1 keeps it). The
* golden carries the weights' hash, so a golden for other weights is refused by name.
*
* What one run covers: rad-convert reading the release's folders; each question's sequence, the
* state cut and its report; one engine request a question on the embedding path; the plugin's
* encoder (full and sliding layers), head and scorer on libref; the option logits through the
* pooled row; the fitted temperatures (one clamped) and the package's confidence; then the same
* request again, the capability report, and the refusals.
*/
#include "decision_e2e.h"
#include "rad_laya.h"
#include <sys/stat.h>
#include <cmath>
#include <fstream>
using namespace decision_e2e;
namespace {
/* The tiny Laya: hidden 64 in one head of 64 (libr4d's attention width, so the same declaration
* serves the card), feed-forward 96, three encoder layers (full, sliding, sliding over
* local_attention 8), two head layers; LayerNorm gains near one, every linear at unit gain but the
* scorer's last, which spreads the option logits. The byte tokenizer's specials after its own three
* are [CLS] 259, [SEP] 260, [MASK] 261, [PAD] 262, [UNK] 263; the vocabulary pads to 320. */
bool write_tiny_laya(const std::string& dir, uint64_t seed) {
const int64_t E = 64, F = 96, L = 3, V = 320, HL = 2, A = 256;
tiny::Rng r(seed);
std::vector<tiny::Tensor> ts;
auto gain = [&](const std::string& n, int64_t k) { ts.push_back(tiny::noise(n, { k }, r, 0.1f, 1.0f)); };
auto bias = [&](const std::string& n, int64_t k) { ts.push_back(tiny::noise(n, { k }, r, 0.1f)); };
auto lin = [&](const std::string& n, int64_t o, int64_t i, float g = 1.0f) {
ts.push_back(tiny::linear(n, o, i, r, g));
};
ts.push_back(tiny::noise("encoder.embeddings.tok_embeddings.weight", { V, E }, r, 1.0f));
gain("encoder.embeddings.norm.weight", E);
for (int64_t l = 0; l < L; ++l) {
const std::string p = "encoder.layers." + std::to_string(l) + ".";
if (l > 0) gain(p + "attn_norm.weight", E);
lin(p + "attn.Wqkv.weight", 3 * E, E);
lin(p + "attn.Wo.weight", E, E);
gain(p + "mlp_norm.weight", E);
lin(p + "mlp.Wi.weight", 2 * F, E);
lin(p + "mlp.Wo.weight", E, F);
}
gain("encoder.final_norm.weight", E);
for (int64_t j = 0; j < HL; ++j) {
const std::string p = "head.layers." + std::to_string(j) + ".";
lin(p + "self_attn.in_proj_weight", 3 * E, E);
bias(p + "self_attn.in_proj_bias", 3 * E);
lin(p + "self_attn.out_proj.weight", E, E);
bias(p + "self_attn.out_proj.bias", E);
lin(p + "linear1.weight", 4 * E, E);
bias(p + "linear1.bias", 4 * E);
lin(p + "linear2.weight", E, 4 * E);
bias(p + "linear2.bias", E);
gain(p + "norm1.weight", E);
bias(p + "norm1.bias", E);
gain(p + "norm2.weight", E);
bias(p + "norm2.bias", E);
}
ts.push_back(tiny::noise("type_emb.weight", { 3, E }, r, 0.5f));
gain("scorer.0.weight", E);
bias("scorer.0.bias", E);
lin("scorer.1.weight", E, E);
bias("scorer.1.bias", E);
lin("scorer.3.weight", 1, E, 3.0f);
bias("scorer.3.bias", 1);
/* The escalation head and the stored temperatures: in the release's state dict (its loader
* is strict), not declared by the plugin. */
lin("act_head.0.weight", A, E + 4);
bias("act_head.0.bias", A);
lin("act_head.2.weight", 2, A);
bias("act_head.2.bias", 2);
ts.push_back(tiny::noise("temperature", { 3 }, r, 0.0f, 1.0f, "F32"));
if (!tiny::write_safetensors(dir + "/model.safetensors", ts)) return false;
nlohmann::ordered_json root;
root["model_type"] = "laya";
root["architectures"] = { "LayaTypedDecisions" };
nlohmann::ordered_json enc;
enc["architectures"] = { "ModernBertForMaskedLM" };
enc["model_type"] = "modernbert";
enc["hidden_size"] = E;
enc["intermediate_size"] = F;
enc["num_hidden_layers"] = L;
enc["num_attention_heads"] = 1;
enc["layer_types"] = { "full_attention", "sliding_attention", "sliding_attention" };
enc["global_attn_every_n_layers"] = 3;
enc["local_attention"] = 8;
enc["rope_parameters"] = { { "full_attention", { { "rope_theta", 160000.0 }, { "rope_type", "default" } } },
{ "sliding_attention", { { "rope_theta", 10000.0 }, { "rope_type", "default" } } } };
enc["max_position_embeddings"] = 8192;
enc["vocab_size"] = V;
enc["norm_eps"] = 1e-5;
enc["norm_bias"] = false;
enc["attention_bias"] = false;
enc["mlp_bias"] = false;
enc["hidden_activation"] = "gelu";
enc["embedding_dropout"] = 0.0;
enc["attention_dropout"] = 0.0;
enc["mlp_dropout"] = 0.0;
enc["pad_token_id"] = 262;
enc["cls_token_id"] = 259;
enc["sep_token_id"] = 260;
enc["bos_token_id"] = 259;
enc["eos_token_id"] = 260;
enc["tie_word_embeddings"] = true;
nlohmann::ordered_json rl;
rl["encoder"] = "answerdotai/ModernBERT-large";
rl["head_layers"] = HL;
rl["max_len"] = 128;
rl["head_max_len"] = 48;
rl["max_prefixes"] = 6;
rl["act_costs"] = { { "escalate", 0.5 } };
rl["amp_dtype"] = "bf16";
rl["model_name"] = "laya-tiny";
rl["temperature"] = { 1.3, 0.9, 1.7 };
rl["temperature_by_options"] = { { "choice:3-5", 1.6 }, { "noul:2", 2.2 }, { "choice:11+", 0.1 } };
nlohmann::ordered_json tc;
tc["cls_token"] = "[CLS]";
tc["mask_token"] = "[MASK]";
tc["pad_token"] = "[PAD]";
tc["sep_token"] = "[SEP]";
tc["unk_token"] = "[UNK]";
tc["model_max_length"] = 8192;
tc["tokenizer_class"] = "PreTrainedTokenizerFast";
return mkdir((dir + "/encoder").c_str(), 0755) == 0 &&
mkdir((dir + "/tokenizer").c_str(), 0755) == 0 &&
tiny::write_text(dir + "/config.json", root.dump(2)) &&
tiny::write_text(dir + "/encoder/config.json", enc.dump(2)) &&
tiny::write_text(dir + "/rl_agent_config.json", rl.dump(2)) &&
tiny::write_text(dir + "/tokenizer/tokenizer_config.json", tc.dump(2)) &&
tiny::write_text(dir + "/tokenizer/tokenizer.json",
tiny::tokenizer_json({ "[CLS]", "[SEP]", "[MASK]", "[PAD]", "[UNK]" }));
}
/* The largest difference between radiance's answers and the package's: every probability, every
* confidence, every noul and score; and whether each choice agrees where the package's top two are
* apart. */
double compare(const json& got, const json& want, bool* choices_agree) {
double worst = 0.0;
auto d = [&](const json& a, const json& b) {
worst = std::max(worst, std::fabs(a.get<double>() - b.get<double>()));
};
for (const auto& kv : want.items()) {
const json& w = kv.value();
if (!got.contains(kv.key())) { *choices_agree = false; return 1.0; }
const json& g = got[kv.key()];
if (g["type"] != w["type"]) { *choices_agree = false; return 1.0; }
if (w["type"] == "noul") { d(g["noul"], w["noul"]); continue; }
d(g["confidence"], w["confidence"]);
if (w["type"] == "score") d(g["score"], w["score"]);
std::vector<double> top;
for (const auto& p : w["probabilities"].items()) {
if (!g["probabilities"].contains(p.key())) { *choices_agree = false; return 1.0; }
d(g["probabilities"][p.key()], p.value());
top.push_back(p.value().get<double>());
}
if (w["type"] == "choice") {
std::sort(top.rbegin(), top.rend());
if (top.size() < 2 || top[0] - top[1] > 0.02) *choices_agree = *choices_agree && g["choice"] == w["choice"];
CHECK(!g.contains("legend"));
} else {
CHECK(g["legend"] == w["legend"]);
}
}
return worst;
}
} /* namespace */
TEST(a_laya_container_answers_every_question_and_matches_the_package) {
const bool keep = std::getenv("RAD_E2E_KEEP") != nullptr;
tiny::TempDir dir{ "laya", keep };
REQUIRE(dir.ok());
const std::string ck = dir / "laya-tiny";
REQUIRE_EQ(mkdir(ck.c_str(), 0755), 0);
REQUIRE(write_tiny_laya(ck, 11));
if (keep) fprintf(stderr, " the tiny Laya is kept at %s (tests/mklayagolden.py)\n", ck.c_str());
const std::string rad = dir / "laya-tiny.rad";
std::string log;
const int st = tiny::run({ RAD_E2E_CONVERT, ck, "-o", rad, "--set", "decision.type=laya" },
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("encoder 3 x 64, head 2 layers, max_len 128, head_max_len 48") != std::string::npos);
std::ifstream gf(RAD_LAYA_GOLDEN);
if (!gf.is_open())
fprintf(stderr, " no golden at %s: run this test with RAD_E2E_KEEP=1, then "
"tests/mklayagolden.py on the kept directory\n", RAD_LAYA_GOLDEN);
REQUIRE(gf.is_open());
const json gold = json::parse(gf);
const std::string wf = hex16(fnv1a(ck + "/model.safetensors"));
if (gold["weights_fnv"] != wf)
fprintf(stderr, " the golden was made from other weights (%s here): regenerate it with "
"tests/mklayagolden.py\n", wf.c_str());
REQUIRE(gold["weights_fnv"] == wf);
Server s;
REQUIRE(s.start(rad, { "--max-num-seqs", "4", "--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"] == "laya");
CHECK(models["data"][0]["capabilities"]["embedding"] == false);
double worst = 0.0;
for (size_t i = 0; i < gold["requests"].size(); ++i) {
const json& req = gold["requests"][i];
const json& want = gold["results"][i];
const json a = call(s.port, "POST", "/v1/systemone", req, &status);
if (status != 200) fprintf(stderr, " %s\n%s\n", a.dump().c_str(), tail(s.output()).c_str());
REQUIRE_EQ(status, 200);
/* The sequences and the cut are the package's to the token. */
for (const char* k : { "input_tokens", "output_tokens", "state_tokens", "state_tokens_dropped",
"truncated", "truncated_questions" }) {
if (a["usage"][k] != want["usage"][k])
fprintf(stderr, " request %zu: usage.%s %s, the package's %s\n", i, k,
a["usage"][k].dump().c_str(), want["usage"][k].dump().c_str());
CHECK(a["usage"][k] == want["usage"][k]);
}
bool agree = true;
const double w = compare(a["answers"], want["answers"], &agree);
fprintf(stderr, " request %zu: largest difference from the package %.4f\n", i, w);
CHECK(agree);
worst = std::max(worst, w);
/* The same request again: no cache, the same step, the same answer. */
const json b = call(s.port, "POST", "/v1/decisions", req, &status);
CHECK_EQ(status, 200);
CHECK(b["answers"] == a["answers"]);
}
CHECK(worst < 0.03);
/* The refusals. */
json base = gold["requests"][0];
json many = base;
many["questions"] = { { "q", { { "type", "choice" }, { "instructions", "x" }, { "criteria", json::array() } } } };
for (int i = 0; i <= RAD_LAYA_MAX_OPTIONS; ++i) many["questions"]["q"]["criteria"].push_back("o" + std::to_string(i));
call(s.port, "POST", "/v1/systemone", many, &status);
CHECK_EQ(status, 400);
json empty = base;
empty["state"] = "";
call(s.port, "POST", "/v1/systemone", empty, &status);
CHECK_EQ(status, 400);
json img = base;
img["images"] = json::array({ "data:image/png;base64,AAAA" });
call(s.port, "POST", "/v1/systemone", img, &status);
CHECK_EQ(status, 501);
call(s.port, "POST", "/v1/embeddings", json{ { "input", "hello" } }, &status);
CHECK_EQ(status, 501);
CHECK_EQ(s.stop(), 0);
}
/* The checkpoint names its own type, so --set is optional; a checkpoint that is not Laya's is
* refused by name. */
TEST(a_laya_checkpoint_converts_without_flags_and_another_is_refused) {
tiny::TempDir dir{ "laya" };
REQUIRE(dir.ok());
const std::string ck = dir / "laya-tiny";
REQUIRE_EQ(mkdir(ck.c_str(), 0755), 0);
REQUIRE(write_tiny_laya(ck, 11));
std::string log;
CHECK_EQ(tiny::run({ RAD_E2E_CONVERT, ck, "-o", dir / "plain.rad" }, engine_env(), &log, 300), 0);
CHECK(log.find("laya ") != std::string::npos);
const std::string other = dir / "qwen";
REQUIRE_EQ(mkdir(other.c_str(), 0755), 0);
REQUIRE(tiny::write_qwen35(other, tiny::Qwen35{}));
log.clear();
CHECK(tiny::run({ RAD_E2E_CONVERT, other, "-o", dir / "no.rad", "--set", "decision.type=laya" },
engine_env(), &log, 300) != 0);
CHECK(log.find("model_type laya") != std::string::npos);
}
RAD_TEST_MAIN()
+237
View File
@@ -0,0 +1,237 @@
/* laya_test.cpp -- Laya's sequences, words and answers (core/server/laya.h).
*
* A byte tokenizer makes every piece of a sequence decode back to its exact text, so the layout
* build_head and build_sequence produce is checked as text: [CLS], "<type> question: ...", [SEP],
* each option behind its [MASK], [SEP], the state, [SEP]. The state cut, the option budget, the
* refusals and the answer arithmetic (temperature bucket and clamp, softmax, confidence) follow
* laya's own common.py and agent.py; tests/laya_decision_test.cpp checks the whole path against
* the package's Agent.predict.
*/
#include "rad_test.h"
#include "server/laya.h"
#include "text/tokenizer.h"
#include "rad_laya.h"
#include <nlohmann/json.hpp>
#include <cmath>
using namespace rad;
using namespace rad::server;
namespace {
enum : int32_t { kCls = 1000, kSep = 1001, kMask = 1002 };
/* One id a byte; the specials above the bytes. */
struct ByteTokenizer : ITokenizer {
std::vector<int32_t> encode(const std::string& s, bool, bool) const override {
std::vector<int32_t> v;
for (unsigned char c : s) v.push_back(c);
return v;
}
std::string token_bytes(int32_t id) const override { return std::string(1, (char)id); }
std::string decode(const std::vector<int32_t>& t) const override {
std::string s;
for (int32_t x : t) s += x == kCls ? "<CLS>" : x == kSep ? "<SEP>" : x == kMask ? "<MASK>" : std::string(1, (char)x);
return s;
}
int32_t eos() const override { return 0; }
int32_t bos() const override { return -1; }
std::unique_ptr<IDetokenizer> detokenizer(const std::vector<std::string>&,
const std::vector<std::string>&) const override {
return nullptr;
}
};
LayaSettings settings(int64_t max_len = 512, int64_t head_max_len = 192) {
LayaSettings s;
s.max_len = max_len;
s.head_max_len = head_max_len;
s.cls = kCls;
s.sep = kSep;
s.mask = kMask;
s.mask_token = "[MASK]";
return s;
}
int parse(const std::string& body, LayaRequest* r, ApiError* e, const LayaSettings& s = settings()) {
static ByteTokenizer tok;
OaiDeps d;
d.tok = &tok;
OaiLimits l;
l.model_id = "laya";
return parse_laya_request(body, d, l, "laya", s, r, e);
}
std::string text(const LayaQuestion& q) { return ByteTokenizer().decode(q.tokens); }
} /* namespace */
TEST(laya_render_is_python_json_dumps_with_the_request_order_kept) {
const json v = json::parse(R"({"b": [1, 2.5, "x", null], "a": {"é": true, "q": "say \"hi\"\n"}})");
CHECK_EQ(laya_render(v), std::string(R"({"b": [1, 2.5, "x", null], "a": {"é": true, "q": "say \"hi\"\n"}})"));
CHECK_EQ(laya_render(json::parse("[]")), std::string("[]"));
CHECK_EQ(laya_render(json::parse("{}")), std::string("{}"));
CHECK_EQ(laya_render(json::parse("1.0")), std::string("1.0"));
}
TEST(each_question_is_its_own_sequence_with_the_state_after_its_options) {
LayaRequest r;
ApiError e;
CHECK_EQ(parse(R"({"state": "Charged [MASK] twice.", "questions": {
"team": {"type": "choice", "instructions": "Which team?",
"criteria": {"billing": "Charges", "tech": "", "other": null}},
"level": {"type": "score", "instructions": {"ask": "How urgent?"}, "criteria": ["Low", {"x": 1}]},
"refund": {"type": "noul", "instructions": "Refund?", "criteria": {"True": "asks for money"}}}})",
&r, &e), RAD_OK);
CHECK_EQ(r.questions.size(), (size_t)3);
CHECK_EQ(r.state_tokens, (int64_t)std::string("Charged twice.").size());
const LayaQuestion& t = r.questions[0];
CHECK_EQ(text(t), std::string("<CLS>choice question: Which team?<SEP><MASK> billing: Charges"
"<MASK> tech<MASK> other<SEP>Charged twice.<SEP>"));
CHECK_EQ(t.type_id, (int)RAD_LAYA_CHOICE);
CHECK_EQ(t.markers.size(), (size_t)3);
for (int32_t m : t.markers) CHECK_EQ(t.tokens[(size_t)m], (int32_t)kMask);
CHECK(t.keys == std::vector<std::string>({ "billing", "tech", "other" }));
const LayaQuestion& l = r.questions[1];
CHECK_EQ(text(l), std::string("<CLS>score question: {\"ask\": \"How urgent?\"}<SEP><MASK> level 0: Low"
"<MASK> level 1: {\"x\": 1}<SEP>Charged twice.<SEP>"));
CHECK(l.legend == std::vector<std::string>({ "Low", "{\"x\": 1}" }));
const LayaQuestion& n = r.questions[2];
CHECK_EQ(text(n), std::string("<CLS>noul question: Refund?<SEP><MASK> false: no, the statement does "
"not hold<MASK> true: asks for money<SEP>Charged twice.<SEP>"));
CHECK(n.keys == std::vector<std::string>({ "false", "true" }));
const std::vector<int32_t> w = laya_words(t);
CHECK_EQ(w.size(), (size_t)RAD_LAYA_W_MARKERS + 3);
CHECK_EQ(w[RAD_LAYA_W_N], (int32_t)t.tokens.size());
CHECK_EQ(w[RAD_LAYA_W_TYPE], (int32_t)RAD_LAYA_CHOICE);
CHECK_EQ(w[RAD_LAYA_W_K], 3);
CHECK_EQ(w[RAD_LAYA_W_MARKERS + 2], t.markers[2]);
const json u = laya_usage(r);
CHECK_EQ(u["input_tokens"].get<int64_t>(),
(int64_t)(t.tokens.size() + l.tokens.size() + n.tokens.size()));
CHECK(u["truncated"] == false);
CHECK_EQ(u["state_tokens_dropped"].get<int64_t>(), (int64_t)0);
CHECK(u["truncated_questions"].empty());
}
TEST(a_long_state_is_cut_to_the_room_its_question_leaves_and_usage_says_so) {
LayaRequest r;
ApiError e;
std::string state(200, 'a');
state += "END";
const std::string q = R"(, "questions": {"q": {"type": "noul", "instructions": "Ok?"}}})";
CHECK_EQ(parse("{\"state\": \"" + state + "\"" + q, &r, &e, settings(128, 64)), RAD_OK);
const LayaQuestion& a = r.questions[0];
CHECK_EQ(a.tokens.size(), (size_t)128);
CHECK_EQ(a.tokens.back(), (int32_t)kSep);
CHECK_EQ(a.tokens[a.tokens.size() - 2], (int32_t)'a'); /* the start is kept */
const json u = laya_usage(r);
CHECK(u["truncated"] == true);
CHECK_EQ(u["state_tokens"].get<int64_t>(), (int64_t)state.size());
CHECK_EQ(u["state_tokens_dropped"].get<int64_t>(), (int64_t)state.size() - a.state_used);
CHECK(u["truncated_questions"] == json::array({ "q" }));
/* A list of turns keeps its end. */
CHECK_EQ(parse("{\"state\": [\"" + state + "\"]" + q, &r, &e, settings(128, 64)), RAD_OK);
const std::string s = text(r.questions[0]);
CHECK(s.size() > 11 && s.substr(s.size() - 11) == "aEND\"]<SEP>");
}
TEST(many_options_share_the_head_budget_and_too_many_are_refused) {
LayaRequest r;
ApiError e;
/* Fifteen options of ~44 bytes leave fewer than 16 of 64: each is cut to
* max(4, (64 - 16) / 15) = 4, and the instruction keeps max(8, 64 - 60) = 8 tokens. */
json c = json::object();
for (int i = 0; i < 15; ++i) c["option number " + std::to_string(i)] = "a fairly long description";
json body = { { "state", "s" }, { "questions", { { "q", { { "type", "choice" }, { "instructions", "Which?" },
{ "criteria", c } } } } } };
CHECK_EQ(parse(body.dump(), &r, &e, settings(512, 64)), RAD_OK);
const LayaQuestion& q = r.questions[0];
for (size_t i = 0; i + 1 < q.markers.size(); ++i) CHECK_EQ(q.markers[i + 1] - q.markers[i], 4);
CHECK_EQ(text(q).substr(0, 18), std::string("<CLS>choice q<SEP>"));
/* Options past the sequence are refused, not answered with fewer options. */
CHECK(parse(body.dump(), &r, &e, settings(24, 64)) < 0);
CHECK_EQ(e.status, 400);
}
TEST(what_the_package_refuses_is_a_400_and_images_are_a_501) {
LayaRequest r;
ApiError e;
const char* bad[] = {
R"({"questions": {"q": {"type": "noul", "instructions": "x"}}})",
R"({"state": "", "questions": {"q": {"type": "noul", "instructions": "x"}}})",
R"({"state": "s", "questions": {}})",
R"({"state": "s", "questions": {"q": {"type": "rank", "instructions": "x"}}})",
R"({"state": "s", "questions": {"q": {"type": "noul", "instructions": " "}}})",
R"({"state": "s", "questions": {"q": {"type": "choice", "instructions": "x", "criteria": []}}})",
R"({"state": "s", "questions": {"q": {"type": "choice", "instructions": "x", "criteria": [1, 1.0]}}})",
R"({"state": "s", "questions": {"q": {"type": "choice", "instructions": "x", "criteria": ["a", null]}}})",
R"({"state": "s", "questions": {"q": {"type": "score", "instructions": "x", "criteria": ["a", null]}}})",
R"({"state": "s", "questions": {"q": {"type": "noul", "instructions": "x", "criteria": {"maybe": "?"}}}})",
R"({"state": "s", "questions": {"q": {"type": "noul", "instructions": "x", "labels": {}}}})",
R"({"state": "s", "questions": {" ": {"type": "noul", "instructions": "x"}}})",
};
for (const char* b : bad) {
e = ApiError{};
CHECK(parse(b, &r, &e) < 0);
CHECK_EQ(e.status, 400);
}
CHECK(parse(R"({"state": "s", "images": ["data:image/png;base64,AA"], "questions": {"q": {"type": "noul", "instructions": "x"}}})",
&r, &e) < 0);
CHECK_EQ(e.status, 501);
}
TEST(the_answer_is_the_packages_softmax_rounding_and_confidence) {
LayaRequest r;
ApiError e;
CHECK_EQ(parse(R"({"state": "s", "questions": {
"c": {"type": "choice", "instructions": "x", "criteria": [1, 2.5, false]},
"s": {"type": "score", "instructions": "x", "criteria": ["lo", "mid", "hi"]},
"n": {"type": "noul", "instructions": "x"}}})", &r, &e), RAD_OK);
LayaSettings s = settings();
s.temperature[RAD_LAYA_CHOICE] = 9.0; /* clamped to 5 */
s.temperature_by_options["score:3-5"] = 0.1; /* clamped to 0.5 */
s.temperature[RAD_LAYA_NOUL] = 2.0;
auto softmax = [](std::vector<double> z) {
double m = *std::max_element(z.begin(), z.end()), t = 0;
for (double& v : z) t += (v = std::exp(v - m));
for (double& v : z) v /= t;
return z;
};
auto conf = [](const std::vector<double>& p) {
double h = 0;
for (double v : p) h -= v * std::log(v);
return 1.0 - h / std::log((double)p.size());
};
auto near = [](double a, double b) { return std::fabs(a - b) < 1.5e-4; };
json a;
CHECK_EQ(laya_answer(r.questions[0], { 3.0f, 1.0f, 0.0f, -1e4f }, s, &a, &e), RAD_OK);
const std::vector<double> pc = softmax({ 3.0 / 5, 1.0 / 5, 0.0 });
CHECK(a["choice"] == 1);
CHECK(near(a["probabilities"]["1"].get<double>(), pc[0]));
CHECK(near(a["probabilities"]["2.5"].get<double>(), pc[1]));
CHECK(near(a["probabilities"]["false"].get<double>(), pc[2]));
CHECK(near(a["confidence"].get<double>(), conf(pc)));
CHECK(text(r.questions[0]).find("<MASK> 2.5<MASK> False<SEP>") != std::string::npos);
CHECK_EQ(laya_answer(r.questions[1], { 0.0f, 0.5f, 0.25f }, s, &a, &e), RAD_OK);
const std::vector<double> ps = softmax({ 0.0, 1.0, 0.5 });
CHECK(near(a["score"].get<double>(), ps[1] + 2 * ps[2]));
CHECK(near(a["confidence"].get<double>(), conf(ps)));
CHECK(a["legend"] == json::parse(R"({"0": "lo", "1": "mid", "2": "hi"})"));
CHECK_EQ(laya_answer(r.questions[2], { -1.0f, 1.0f }, s, &a, &e), RAD_OK);
CHECK(near(a["noul"].get<double>(), softmax({ -0.5, 0.5 })[1]));
CHECK(!a.contains("confidence"));
CHECK(laya_answer(r.questions[2], { NAN, 1.0f }, s, &a, &e) < 0);
}
RAD_TEST_MAIN()
+66
View File
@@ -0,0 +1,66 @@
"""mklayagolden.py CKPTDIR OUT.json -- the golden for tests/laya_decision_test.cpp: laya's own
Agent.predict (the package in LAYA_SRC, a checkout of github.com/NandhaKishorM/laya) on the tiny
Laya the test writes, on the CPU in float32, for the requests below.
CKPTDIR is the tiny Laya's directory as the test keeps it: run `RAD_E2E_KEEP=1
build/tests/laya_decision_test` and pass the directory it prints. The golden records the FNV-1a hash
of model.safetensors (the test refuses a golden made from other weights), the package's commit
(LAYA_COMMIT), each request, and the package's answers and usage for it.
The three requests: one whose state fits every question's sequence; one whose JSON-object state
is cut to the room each question leaves, with a 12-option choice (the 11+ temperature bucket,
whose fitted 0.1 the package clamps to 0.5); one whose state is a list of turns, which keeps its
end."""
import json
import os
import sys
ckpt_dir, out = sys.argv[1], sys.argv[2]
sys.path.insert(0, os.environ["LAYA_SRC"])
from laya.agent import Agent # noqa: E402
LONG = ("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, and please tell the courier.")
REQUESTS = [
{"state": "Charged twice for one order; refund one please.",
"questions": {
"refund": {"type": "noul", "instructions": "Does the customer ask for money back?"},
"team": {"type": "choice", "instructions": "Which team should take this?",
"criteria": {"billing": "Charges and refunds", "shipping": "Delivery",
"product": ""}},
"tone": {"type": "score", "instructions": "How upset is the customer?",
"criteria": ["Calm", "Mildly annoyed", "Angry"]}}},
{"state": {"message": LONG, "channel": "email"},
"questions": {
"topic": {"type": "choice", "instructions": "Topic?",
"criteria": ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l"]},
"spam": {"type": "noul", "instructions": {"ask": "Is this unsolicited?"},
"criteria": {"true": "unsolicited bulk mail"}},
"team": {"type": "choice", "instructions": "Route it.",
"criteria": ["billing", "technical", "sales", "other"]}}},
{"state": [{"role": "user", "content": LONG}, {"role": "agent", "content": "Sorry, checking."},
{"role": "user", "content": "Any news on the refund?"}],
"questions": {
"waiting": {"type": "noul", "instructions": "Is the customer still waiting?"}}},
]
def fnv(path):
h = 0xcbf29ce484222325
for b in open(path, "rb").read():
h = ((h ^ b) * 0x100000001b3) & (2**64 - 1)
return h
agent = Agent(ckpt_dir, device="cpu")
results = [agent.predict(r["state"], r["questions"]) for r in REQUESTS]
golden = {
"weights_fnv": "%016x" % fnv(os.path.join(ckpt_dir, "model.safetensors")),
"laya_commit": os.environ.get("LAYA_COMMIT", ""),
"requests": REQUESTS,
"results": [{"answers": r["answers"], "usage": r["usage"]} for r in results],
}
with open(out, "w") as f:
json.dump(golden, f, indent=1, ensure_ascii=False)
f.write("\n")
print(json.dumps([r["usage"] for r in results]))
+1 -1
View File
@@ -96,7 +96,7 @@ TEST(the_shipped_architectures_load_with_distinct_selection_keys) {
{ "gemma3", "" }, { "gemma4", "" },
{ "gemma4", "compressed-tensors" }, { "glm5next", "" },
{ "hyv3", "" }, { "hyv3", "fp8" }, { "hyv3", "gguf_ftype_15" },
{ "lfm2", "" }, { "llama", "" },
{ "laya", "" }, { "lfm2", "" }, { "llama", "" },
{ "llama", "fp8_e4m3" }, { "nomicbert", "" }, { "qwen35", "" },
{ "qwen35", "fp8_e4m3" }, { "qwen35", "w8a8_fwht128" }, { "qwen35moe", "fp8_e4m3" },
{ "qwen3asr", "" }, { "krea2", "" }, { "ltx2", "" }, { "minimaxh3", "" },
+113
View File
@@ -123,6 +123,115 @@ int clef_metadata(const std::string& in, const std::string& config_dir, const Ch
return 0;
}
/* Laya (a checkpoint whose config.json says model_type laya, or --set decision.type=laya): the
* release keeps its parts in folders, so the encoder's geometry comes from encoder/config.json,
* the head's settings from rl_agent_config.json and the vocabulary from tokenizer/. The plugin
* declares from the geometry (arch/laya); the server builds each question's sequence from the
* special tokens and lengths and applies the fitted temperatures (core/server/laya.h). */
int laya_metadata(const std::string& in, const std::string& config_dir, MetaOwn& meta,
std::string* tokjson) {
if (meta.arch != "laya") {
RAD_ERR("%s: decision.type=laya needs a Laya checkpoint directory, whose config.json says "
"model_type laya (this one's architecture is '%s')", in.c_str(), meta.arch.c_str());
return -1;
}
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);
}
}
auto read_json = [](const std::string& path, nlohmann::json* j) {
std::ifstream f(path);
if (!f) { RAD_ERR("%s: a Laya checkpoint carries it; cannot read it", path.c_str()); return -1; }
try { f >> *j; } catch (const std::exception& e) {
RAD_ERR("%s: %s", path.c_str(), e.what());
return -1;
}
return j->is_object() ? 0 : -1;
};
/* The encoder's own config: its geometry and free-form keys (layer_types, local_attention,
* the rotary thetas), keeping the checkpoint's model_type, which named the plugin. */
MetaOwn enc;
if (meta_from_config_json(dir + "/encoder", &enc) != RAD_OK) return -1;
for (size_t i = 0; i < enc.keys.size(); ++i)
if (enc.keys[i] != "model_type" && enc.keys[i] != "architectures") meta.set(enc.keys[i], enc.vals[i]);
meta.m = enc.m;
nlohmann::json rl;
if (read_json(dir + "/rl_agent_config.json", &rl) < 0) return -1;
const std::pair<const char*, long long> counts[] = { { "max_len", 1 }, { "head_max_len", 1 },
{ "head_layers", 0 } };
for (const auto& [k, least] : counts) {
if (!rl.contains(k) || !rl[k].is_number_integer() || rl[k].get<long long>() < least) {
RAD_ERR("%s/rl_agent_config.json: `%s` is missing or not a count", dir.c_str(), k);
return -1;
}
meta.set(std::string("decision.laya.") + k, std::to_string(rl[k].get<long long>()));
}
if (rl.contains("option_layout") && rl["option_layout"] != "sequential") {
RAD_ERR("%s/rl_agent_config.json: option_layout '%s'; the sequential layout every "
"published checkpoint uses is served", dir.c_str(), rl["option_layout"].dump().c_str());
return -1;
}
auto num = [](double v) { char s[32]; std::snprintf(s, sizeof s, "%.9g", v); return std::string(s); };
std::string temps = "1 1 1";
if (rl.contains("temperature")) {
const nlohmann::json& t = rl["temperature"];
if (!t.is_array() || t.size() != 3 || !t[0].is_number() || !t[1].is_number() || !t[2].is_number()) {
RAD_ERR("%s/rl_agent_config.json: `temperature` is not three numbers (choice, score, "
"noul)", dir.c_str());
return -1;
}
temps = num(t[0].get<double>()) + " " + num(t[1].get<double>()) + " " + num(t[2].get<double>());
}
meta.set("decision.laya.temperature", temps);
if (rl.contains("temperature_by_options") && rl["temperature_by_options"].is_object())
for (const auto& kv : rl["temperature_by_options"].items())
if (kv.value().is_number())
meta.set("decision.laya.temperature_by_options." + kv.key(), num(kv.value().get<double>()));
/* The special tokens by name (tokenizer_config.json), their ids from tokenizer.json. */
const std::string tdir = dir + "/tokenizer";
if (tokjson->empty()) *tokjson = tdir + "/tokenizer.json";
nlohmann::json tc, tj;
if (read_json(tdir + "/tokenizer_config.json", &tc) < 0 || read_json(*tokjson, &tj) < 0) return -1;
for (const char* which : { "cls_token", "sep_token", "mask_token" }) {
const nlohmann::json* v = tc.contains(which) ? &tc[which] : nullptr;
if (v && v->is_object() && v->contains("content")) v = &(*v)["content"];
if (!v || !v->is_string()) {
RAD_ERR("%s/tokenizer_config.json: no `%s`", tdir.c_str(), which);
return -1;
}
const std::string tok = v->get<std::string>();
long long id = -1;
if (tj.contains("added_tokens"))
for (const auto& a : tj["added_tokens"])
if (a.contains("content") && a["content"] == tok && a.contains("id")) id = a["id"].get<long long>();
if (id < 0 && tj.contains("model") && tj["model"].contains("vocab") && tj["model"]["vocab"].is_object() &&
tj["model"]["vocab"].contains(tok))
id = tj["model"]["vocab"][tok].get<long long>();
if (id < 0) {
RAD_ERR("%s: the %s '%s' is not in the vocabulary", tokjson->c_str(), which, tok.c_str());
return -1;
}
const std::string base = std::string(which).substr(0, std::strlen(which) - 6);
meta.set("decision.laya." + base, std::to_string(id));
if (base == "mask") meta.set("decision.laya.mask_token", tok);
}
meta.set("decision.type", "laya");
meta.finish();
RAD_INFO("laya %s: encoder %lld x %lld, head %s layers, max_len %s, head_max_len %s",
dir.c_str(), (long long)meta.m.n_layers, (long long)meta.m.n_embd,
meta.get("decision.laya.head_layers"), meta.get("decision.laya.max_len"),
meta.get("decision.laya.head_max_len"));
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;
@@ -483,6 +592,10 @@ int main(int argc, char** argv) {
if (const char* dt = meta.get("decision.type"); dt && !std::strcmp(dt, "clef") &&
clef_metadata(in, config_dir, ck, meta) < 0)
return 1;
if (const char* dt = meta.get("decision.type");
(meta.arch == "laya" || (dt && !std::strcmp(dt, "laya"))) &&
laya_metadata(in, config_dir, meta, &tokjson) < 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