radiance 1.3.0

- #47: llama-server's request fields, routes and sampler order, and /props (with baKon's model
  entry: max_model_len, root and capabilities on /v1/models, and /v1/models/:id)
- new APIs: Anthropic's Messages API (/v1/messages), OpenAI's Responses API (/v1/responses),
  llama-server's /completion and /infill, logprobs (OpenAI's logprobs and top_logprobs, up to
  20; llama-server's n_probs), OpenAI's legacy `functions`, and X-Api-Key beside the bearer key
- #4: --model takes a Hugging Face repo id (owner/name), fetched before startup into
  ~/.cache/radiance/hf or --download-dir and checked for changes at every start (redxherring)
- #46: --tp 3 --tp-wire wht6 serves -- a three-rank two-shot all-reduce with uneven shards and
  the tiered-int8 wire over it (baKon); scripts/cardclock.py names what holds each card's clock
  under load (baKon)
- CPU-only serving works again; --kernels names the kernel libraries to load; a model the
  loaded libraries cannot fully serve refuses at startup instead of failing its first request;
  --vram-kv-mib and --vram-weights-mib are gone (the split is automatic)
- --embedding-placement ram is the default, and `auto` is gone
- #40: Swift 1.5 recipes; rad-convert reads which shard holds a tensor from the index
- #53: the pinned host pool gets huge pages where shmem THP is off; #57: a crash on video with
  an odd frame width is fixed
This commit is contained in:
Deadcode committed 2026-10-08 18:22:08 +02:00
1 parent 6a2ee986d6
commit 89cee7ce41
107 files changed
+6849 -1091

No files matched your search

+34
View File
@@ -622,6 +622,40 @@ TEST(an_op_with_no_host_kernel_is_a_miss_per_band_not_a_failure) {
CHECK(host_miss);
}
/* A DEVICE HOLE IS DECIDED PER INSTANCE. Two declarations of one op, one with a weight and one
* without, are two instances with bands of their own: the weighted one's device miss is covered
* by its host kernel, because the planner moves it to the host by placing its weight there, and
* on a card only the weightless instance's miss is a hole. */
TEST(a_device_hole_is_decided_per_instance) {
Program p;
p.ops.resize(3);
p.ops[1].op = "rmsnorm"; /* no weight */
p.ops[1].index = 1;
p.ops[2].op = "rmsnorm";
p.ops[2].index = 2;
p.ops[2].weights = { 1 };
auto miss = [](int32_t index, int domain) {
Program::Miss m;
m.op = "rmsnorm";
m.span = "M <= 64";
m.why = "no kernel matched";
m.domain = domain;
m.index = index;
return m;
};
p.misses.push_back(miss(2, RAD_DOMAIN_DEVICE)); /* the weighted one; its host kernel exists */
CHECK_EQ((int)p.device_holes(false).size(), 0);
p.misses.push_back(miss(1, RAD_DOMAIN_DEVICE)); /* the weightless one */
CHECK_EQ((int)p.device_holes(false).size(), 1);
CHECK_EQ(p.device_holes(false)[0]->index, 1);
CHECK_EQ((int)p.device_holes(true).size(), 0); /* the host backend runs both on the host */
p.misses.push_back(miss(2, RAD_DOMAIN_HOST)); /* no host kernel for the weighted one */
CHECK_EQ((int)p.device_holes(true).size(), 1);
CHECK_EQ(p.device_holes(true)[0]->index, 2);
}
/* ================================================================== init, after the whole graph */
TEST(a_refusing_init_becomes_a_miss_and_not_an_abort) {
NEED_PLUGIN(reg)
+1 -1
View File
@@ -1332,7 +1332,7 @@ TEST(what_a_streaming_client_assembles_is_the_buffered_answer) {
for (size_t i = 0; i < reply.size(); ++i)
sse += st.push(std::string_view(reply).substr(i, 1), false);
sse += st.push(std::string_view(), true);
sse += st.final_chunk(server::Finish::Stop);
sse += st.final_chunk(server::Finish::Stop, server::TimingsOut(), server::UsageOut());
std::string content, reasoning, finish;
std::vector<std::string> ids, names, args;
+70 -6
View File
@@ -36,10 +36,8 @@ std::string dir_path() {
std::to_string((long long)getpid());
}
/* One model.safetensors and a config.json in a fresh directory. */
std::string write_checkpoint(const std::vector<T>& ts, const std::string& config) {
const std::string dir = dir_path();
::mkdir(dir.c_str(), 0755);
/* One safetensors file holding `ts`, in order. */
void write_shard(const std::string& path, const std::vector<T>& ts) {
std::string hdr = "{";
uint64_t off = 0;
for (size_t i = 0; i < ts.size(); ++i) {
@@ -53,13 +51,20 @@ std::string write_checkpoint(const std::vector<T>& ts, const std::string& config
}
hdr += "}";
while (hdr.size() % 8) hdr += ' ';
FILE* f = std::fopen((dir + "/model.safetensors").c_str(), "wb");
FILE* f = std::fopen(path.c_str(), "wb");
const uint64_t n = hdr.size();
std::fwrite(&n, 8, 1, f);
std::fwrite(hdr.data(), 1, hdr.size(), f);
for (const T& t : ts) std::fwrite(t.bytes.data(), 1, t.bytes.size(), f);
std::fclose(f);
f = std::fopen((dir + "/config.json").c_str(), "wb");
}
/* One model.safetensors and a config.json in a fresh directory. */
std::string write_checkpoint(const std::vector<T>& ts, const std::string& config) {
const std::string dir = dir_path();
::mkdir(dir.c_str(), 0755);
write_shard(dir + "/model.safetensors", ts);
FILE* f = std::fopen((dir + "/config.json").c_str(), "wb");
std::fwrite(config.data(), 1, config.size(), f);
std::fclose(f);
return dir;
@@ -122,6 +127,23 @@ TEST(the_metadata_names_the_architecture_and_the_quantisation) {
remove_checkpoint(dir);
}
/* rad-convert's --set of quantization_config re-derives the descriptor from the same keys, so a
* bf16 checkpoint whose recipe writes block fp8 is converted for the fp8 plugin by stating the
* format, and the container never states one format while selecting the plugin of another. */
TEST(the_descriptor_is_quant_method_and_fmt_whoever_set_them) {
const std::string dir = write_checkpoint({ bf16("x", { 2, 2 }, 0) },
"{\"model_type\":\"qwen3_5\",\"hidden_size\":256}");
Checkpoint ck;
REQUIRE_EQ(ck.open(dir), RAD_OK);
CHECK_EQ(ck.meta().quant, std::string());
MetaOwn m = ck.meta();
m.set("quantization_config.quant_method", "fp8");
CHECK_EQ(quant_descriptor(m), std::string("fp8"));
m.set("quantization_config.fmt", "e4m3");
CHECK_EQ(quant_descriptor(m), std::string("fp8_e4m3"));
remove_checkpoint(dir);
}
TEST(a_plain_tensor_is_its_own_encoding_and_reads_back_as_itself) {
const std::string dir = write_checkpoint({ bf16("a.weight", { 4, 8 }, 1.0f) }, "{}");
Checkpoint ck;
@@ -620,3 +642,45 @@ TEST(a_quark_mxfp4_weight_is_its_codes_and_exponents) {
CHECK(w.trivial && rad_enc_is(&w.enc, "plain"));
remove_checkpoint(dir);
}
/* A DIRECTORY THAT MERGES TWO CHECKPOINTS holds some tensors in two shards: a finetune's changed
* tensors in shards of its own beside links to every shard of the base model, which still carry
* the old copies. The index is what says which copy is the model's, so it is what decides; a name
* in two shards that no index entry settles is refused rather than read from whichever shard sorts
* first. */
TEST(the_index_decides_which_shard_a_tensor_is_read_from) {
const std::string dir = dir_path();
::mkdir(dir.c_str(), 0755);
const T base_x = bf16("x.weight", { 2, 4 }, 1.0f), base_y = bf16("y.weight", { 4 }, 2.0f);
const T ft_x = bf16("x.weight", { 2, 4 }, 5.0f);
write_shard(dir + "/a.safetensors", { base_x, base_y }); /* sorts first */
write_shard(dir + "/b.safetensors", { ft_x });
auto put = [&](const char* name, const std::string& body) {
FILE* f = std::fopen((dir + "/" + name).c_str(), "wb");
std::fwrite(body.data(), 1, body.size(), f);
std::fclose(f);
};
put("config.json", kConfig);
put("model.safetensors.index.json",
R"({"weight_map":{"x.weight":"b.safetensors","y.weight":"a.safetensors"}})");
{
Checkpoint ck;
REQUIRE_EQ(ck.open(dir), RAD_OK);
const SrcTensor* x = ck.find("x.weight");
const SrcTensor* y = ck.find("y.weight");
REQUIRE(x && y);
CHECK_EQ(std::memcmp(x->data, ft_x.bytes.data(), ft_x.bytes.size()), 0);
CHECK_EQ(std::memcmp(y->data, base_y.bytes.data(), base_y.bytes.size()), 0);
}
/* the index names both shards but not x: two copies and nothing to choose between them */
put("model.safetensors.index.json",
R"({"weight_map":{"y.weight":"a.safetensors","z.weight":"b.safetensors"}})");
{
Checkpoint ck;
CHECK_EQ(ck.open(dir), RAD_E_FORMAT);
}
for (const char* f : { "a.safetensors", "b.safetensors", "config.json",
"model.safetensors.index.json" })
std::remove((dir + "/" + f).c_str());
::rmdir(dir.c_str());
}
+41 -14
View File
@@ -161,14 +161,21 @@ TEST(the_model_is_required_and_nothing_else_is) {
/* ================================================================== taken */
TEST(the_pool_size_flags_are_gone_and_say_what_replaced_them) {
/* The card's split is the resolver's (core/mem/vram_budget.h); a launch line that sizes a
* pool is refused by name, not served with a split other than the one it asked for. */
Config c;
CHECK_EQ(parse({ "--vram-weights-mib", "20480" }, &c), RAD_E_INVAL);
Config k;
CHECK_EQ(parse({ "--vram-kv-mib", "6144" }, &k), RAD_E_INVAL);
}
TEST(the_sizes_and_counts_reach_the_fields_they_name) {
Config c;
CHECK_EQ(parse({ "--tp", "2",
"--max-num-batched-tokens", "512",
"--max-num-seqs", "8",
"--max-model-len", "200000",
"--vram-weights-mib", "20480",
"--vram-kv-mib", "6144",
"--host-pool-mib", "12288",
"--prefix-cache-host-mib", "4096",
"--prefix-cache-disk-mib", "65536",
@@ -180,8 +187,6 @@ TEST(the_sizes_and_counts_reach_the_fields_they_name) {
CHECK_EQ(c.max_tok, 512ll);
CHECK_EQ(c.max_seqs, 8ll);
CHECK_EQ(c.max_ctx, 200000ll);
CHECK_EQ(c.vram_weights_mib, 20480ll);
CHECK_EQ(c.vram_kv_mib, 6144ll);
CHECK_EQ(c.host_pool_mib, 12288ll);
CHECK_EQ(c.prefix_cache_host_mib, 4096ll);
CHECK_EQ(c.prefix_cache_disk_mib, 65536ll);
@@ -339,22 +344,32 @@ TEST(the_kv_cache_dtype_is_one_of_two_names) {
CHECK_EQ(d.kv_cache_dtype, std::string("bf16"));
}
/* THE TWO TABLE PLACEMENTS take the same four names and nothing else, default to auto, and leave
* the resolved values to Engine::plan: a parse never decides a tier. Where each table may go is
* the engine's to refuse, with the model in hand -- not the parser's. */
TEST(the_table_placements_are_auto_vram_ram_or_disk) {
/* THE TWO TABLE PLACEMENTS: the embedding takes ram (the default) or vram, the n-gram table auto
* (the default), vram, ram or disk, and nothing else. A parse records whether the embedding's was
* named and leaves the resolved values to Engine::plan: where each table may go is the engine's to
* refuse, with the model in hand -- not the parser's. */
TEST(the_embedding_is_ram_or_vram_and_the_ngram_table_takes_four) {
Config d;
CHECK_EQ(parse({}, &d), RAD_OK);
CHECK(d.embedding_placement == TablePlacement::Auto);
CHECK(d.embedding_placement == TablePlacement::Ram);
CHECK(!d.embedding_placement_given);
CHECK(d.ngram_placement == TablePlacement::Auto);
CHECK_EQ(d.embedding_host_mib, 0ll); /* the resolver's */
Config c;
CHECK_EQ(parse({ "--embedding-placement", "ram", "--ngram-placement", "disk" }, &c), RAD_OK);
CHECK(c.embedding_placement == TablePlacement::Ram);
CHECK(c.embedding_placement_given);
CHECK(c.ngram_placement == TablePlacement::Disk);
CHECK_EQ(parse({ "--embedding-placement", "vram", "--ngram-placement", "auto" }, &c), RAD_OK);
CHECK(c.embedding_placement == TablePlacement::Vram);
CHECK(c.ngram_placement == TablePlacement::Auto);
CHECK(c.embedding_resolved == TablePlacement::Vram); /* untouched until plan */
Config v;
CHECK_EQ(parse({ "--embedding-placement", "vram", "--ngram-placement", "auto" }, &v), RAD_OK);
CHECK(v.embedding_placement == TablePlacement::Vram);
CHECK(v.embedding_placement_given);
CHECK(v.ngram_placement == TablePlacement::Auto);
CHECK(v.embedding_resolved == TablePlacement::Vram); /* untouched until plan */
CHECK_EQ(parse({ "--ngram-placement", "ram" }, &v), RAD_OK);
CHECK(v.ngram_placement == TablePlacement::Ram);
for (const char* bad : { "auto", "disk" })
CHECK_EQ(parse({ "--embedding-placement", bad }, &c), RAD_E_INVAL);
for (const char* bad : { "RAM", "memory", "host", "" }) {
CHECK_EQ(parse({ "--embedding-placement", bad }, &c), RAD_E_INVAL);
CHECK_EQ(parse({ "--ngram-placement", bad }, &c), RAD_E_INVAL);
@@ -794,6 +809,17 @@ TEST(the_environment_supplies_what_the_line_left_unsaid) {
/* LATER WINS, for every flag that takes a value. Scripts build these lines by appending, and a
* parser that kept the first occurrence would make an override a no-op. */
TEST(the_download_dir_is_taken_and_left_empty_until_given) {
/* Empty means "the XDG cache", which hf_model.cpp resolves only when --model is a repo id:
* a server started on a local file never reads HOME for it. */
Config c;
CHECK_EQ(parse({}, &c), 0);
CHECK(c.download_dir.empty());
Config d;
CHECK_EQ(parse({ "--download-dir", "/big/models" }, &d), 0);
CHECK_EQ(d.download_dir, std::string("/big/models"));
}
TEST(a_repeated_flag_takes_the_last_one) {
Config c;
CHECK_EQ(parse({ "--port", "1", "--port", "8100" }, &c), RAD_OK);
@@ -844,7 +870,8 @@ TEST(usage_names_every_flag_it_documents) {
"--dry-sequence-breakers", "--chat-template-kwargs",
"--reasoning-format", "--max-n", "--max-queued-requests",
"--max-stop-strings", "--http-threads", "--max-body-mib", "--no-cors",
"--image-max-pixels", "--video-fps", "--max-source-pixels" })
"--image-max-pixels", "--video-fps", "--max-source-pixels",
"--download-dir" })
CHECK(text.find(f) != std::string::npos);
CHECK(text.size() > 1000);
}
+4
View File
@@ -11,6 +11,7 @@ V="-f lavfi -i color=c=red:s=64x64:d=1:r=4"
ffmpeg $I -frames:v 1 red.png
ffmpeg $I -frames:v 2 -f apng red.apng
ffmpeg $I -frames:v 1 red.jpg
ffmpeg -f lavfi -i color=c=red:s=1788x282:d=1:r=1 -frames:v 1 red-1788x282.jpg
ffmpeg $I -frames:v 1 -c:v libwebp red.webp
ffmpeg $I -frames:v 1 red.gif
ffmpeg $I -frames:v 1 red.bmp
@@ -30,5 +31,8 @@ ffmpeg $V -c:v mpeg4 red-mpeg4.avi
ffmpeg $V -c:v libtheora red-theora.ogv
```
`red-1788x282.jpg` is 4:2:0 at a width the scaler's vectors do not divide: converted to RGB it
is written 12 bytes past width x 3 (`a_picture_of_an_awkward_width_converts_inside_its_buffer`).
The Theora clip repeats its first frame with empty packets, which is how Ogg Theora encodes a frame
that does not change.
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.2 KiB

+124
View File
@@ -0,0 +1,124 @@
/* hf_model_test.cpp -- a --model that names a Hugging Face repo (core/hf_model.h).
*
* Two questions, both answered before anything is fetched, and both wrong in a way that costs a
* download or a confusing refusal:
*
* IS IT A REPO a path that exists is never looked up, and a missing model FILE is reported as
* missing rather than sent to the hub as a repo name
* WHAT TO SERVE the hub's model repos hold one container beside a README, a recipe and a
* licence; a checkpoint repo holds none and is served as the directory
*
* No network: the fetch itself is scripts/hfget.sh, which this does not run.
*/
#include "rad_test.h"
#include "hf_model.h"
#include <cstdio>
#include <cstdlib>
#include <filesystem>
#include <string>
#include <unistd.h>
using namespace rad;
namespace fs = std::filesystem;
namespace {
/* A scratch directory of its own, removed with everything in it. */
struct TempDir {
std::string path;
TempDir() {
char t[] = "/tmp/hf_model_test.XXXXXX";
path = mkdtemp(t) ? t : "";
}
~TempDir() {
std::error_code ec;
if (!path.empty()) fs::remove_all(path, ec);
}
void touch(const std::string& name) const {
if (FILE* f = std::fopen((path + "/" + name).c_str(), "w")) std::fclose(f);
}
};
} /* namespace */
TEST(a_repo_id_is_two_names_of_the_hubs_characters) {
CHECK(hf_repo_id("StillDeadcode/minicpm5-2b-fp8"));
CHECK(hf_repo_id("StillDeadcode/qwen3.8-27b-mxfp4"));
CHECK(hf_repo_id("Qwen/Qwen3.8-Flash-Next"));
CHECK(hf_repo_id("hf-internal-testing/tiny_random.v2"));
CHECK(!hf_repo_id(""));
CHECK(!hf_repo_id("minicpm5-2b-fp8")); /* no owner */
CHECK(!hf_repo_id("/abs/model")); /* absolute */
CHECK(!hf_repo_id("a/b/c")); /* a path, not a repo */
CHECK(!hf_repo_id("owner/"));
CHECK(!hf_repo_id("/name"));
CHECK(!hf_repo_id("../x")); /* a relative path, not a name */
CHECK(!hf_repo_id("./x"));
CHECK(!hf_repo_id("owner/.hidden"));
CHECK(!hf_repo_id("-x/y")); /* would read as an option */
CHECK(!hf_repo_id("owner/name with space"));
CHECK(!hf_repo_id("owner/na$me"));
CHECK(!hf_repo_id("C:/models"));
}
TEST(a_missing_model_file_is_not_sent_to_the_hub) {
CHECK(!hf_repo_id("models/qwen.rad"));
CHECK(!hf_repo_id("ckpt/model.safetensors"));
CHECK(!hf_repo_id("ckpt/model.gguf"));
CHECK(!hf_repo_id("ckpt/model.safetensors.index.json"));
}
TEST(a_path_that_exists_is_never_a_repo) {
TempDir t;
CHECK(!t.path.empty());
const std::string cwd = fs::current_path().string();
CHECK_EQ(chdir(t.path.c_str()), 0);
fs::create_directories("owner/name");
CHECK(!hf_repo_id("owner/name")); /* exists: a checkpoint directory */
CHECK(hf_repo_id("owner/other")); /* does not: a repo */
CHECK_EQ(chdir(cwd.c_str()), 0);
}
TEST(the_one_container_in_a_repo_is_what_is_served) {
TempDir t;
t.touch("README.md");
t.touch("LICENSE");
t.touch("q38-27b.recipe");
t.touch(".hfget-manifest");
std::string why;
CHECK_EQ(hf_served_path(t.path, &why), t.path); /* no container: a checkpoint */
t.touch("qwen3.8-27b-mxfp4.rad");
CHECK_EQ(hf_served_path(t.path, &why), t.path + "/qwen3.8-27b-mxfp4.rad");
fs::create_directories(t.path + "/sub");
t.touch("sub/other.rad"); /* only the top level counts */
CHECK_EQ(hf_served_path(t.path, &why), t.path + "/qwen3.8-27b-mxfp4.rad");
}
TEST(two_containers_are_refused_by_name) {
TempDir t;
t.touch("a.rad");
t.touch("b.rad");
std::string why;
CHECK_EQ(hf_served_path(t.path, &why), std::string());
CHECK(why.find("a.rad") != std::string::npos);
CHECK(why.find("b.rad") != std::string::npos);
CHECK(why.find("--model") != std::string::npos);
}
TEST(the_download_dir_defaults_to_the_xdg_cache) {
const char* x = std::getenv("XDG_CACHE_HOME");
const std::string saved = x ? x : "";
setenv("XDG_CACHE_HOME", "/c", 1);
CHECK_EQ(hf_default_download_dir(), std::string("/c/radiance/hf"));
unsetenv("XDG_CACHE_HOME");
if (const char* h = std::getenv("HOME"); h && *h)
CHECK_EQ(hf_default_download_dir(), std::string(h) + "/.cache/radiance/hf");
if (x) setenv("XDG_CACHE_HOME", saved.c_str(), 1);
}
RAD_TEST_MAIN()
+43 -25
View File
@@ -126,14 +126,14 @@ static void publish(Fixture& f, uint64_t id, const std::vector<int32_t>& tokens,
/* ================================================================== pools */
TEST(pool_budgets_are_stated_not_inferred) {
TEST(pools_refuse_a_split_the_resolver_never_made) {
Config c;
c.vram_weights_mib = 0; /* the operator said nothing */
c.vram_weights_mib = 0; /* the resolver never ran */
c.vram_kv_mib = 0;
Pools p;
CHECK_EQ(p.configure(c, 0, &rad_malloc_allocator(), &rad_malloc_allocator()), RAD_E_INVAL);
CHECK(p.fit_report().find("--vram-weights-mib") != std::string::npos);
CHECK(p.fit_report().find("--vram-kv-mib") != std::string::npos);
CHECK(p.fit_report().find("vram_weights resolved to 0 MiB") != std::string::npos);
CHECK(p.fit_report().find("vram_kv resolved to 0 MiB") != std::string::npos);
CHECK(!p.configured());
}
@@ -198,6 +198,44 @@ TEST(a_refused_backing_allocation_says_it_was_refused_and_why) {
/* ================================================================== the derived budget */
TEST(a_device_with_no_capacity_sizes_its_pools_from_the_program) {
/* A device that reports no capacity: the pools are still derived, from what the program
* needs rather than from a share of anything. */
Config c = small_config();
c.vram_weights_mib = 0;
c.vram_kv_mib = 0;
VramFacts f{};
f.statics = 0; /* every op on the host: its weights stay in the mapping */
f.kv_ceiling = 300LL << 20;
VramBudget b;
CHECK_OK(vram_budget_resolve(c, { f }, &b));
CHECK_EQ(c.vram_weights_mib, (int64_t)1); /* a pool nothing is placed in */
CHECK_EQ(c.vram_kv_mib, (int64_t)300); /* every sequence at the full context */
f.statics = 5LL << 20; /* a device-domain op's weights */
Config c2 = small_config();
c2.vram_weights_mib = 0;
c2.vram_kv_mib = 0;
CHECK_OK(vram_budget_resolve(c2, { f }, &b));
CHECK_EQ(c2.vram_weights_mib, (int64_t)5);
}
TEST(a_program_that_copies_no_weight_still_gets_a_weights_pool) {
/* Every op on the host -- CPU-only serving -- reads its weights where the container's mapping
* has them, so nothing is copied to the weights pool. It still has to exist: a zero budget is
* what the pools refuse as a resolver that never ran. */
Config c = small_config();
VramFacts f{};
f.capacity = 16LL << 30; /* the host backend presents half the machine as a card */
f.free = f.capacity;
f.arena = 64LL << 20;
f.kv_ceiling = 300LL << 20;
VramBudget b;
CHECK_OK(vram_budget_resolve(c, { f }, &b));
CHECK_EQ(c.vram_weights_mib, (int64_t)1);
CHECK(c.vram_kv_mib >= 299);
}
TEST(derived_budget_takes_the_statics_off_the_top_then_divides_the_rest) {
/* With no lender stated the experts come first; what each side gets is the subject of the
* cases below. */
@@ -223,7 +261,6 @@ TEST(derived_budget_takes_the_statics_off_the_top_then_divides_the_rest) {
/* Held, the driver's drift on it, the headroom and the arena. */
CHECK_EQ(b.drift, 16LL << 20);
CHECK_EQ(b.claimable, f.capacity - (512LL << 20) - (16LL << 20) - (96LL << 20) - (144LL << 20));
CHECK(b.derived_weights && b.derived_kv);
/* THE FLOOR IS NOT A SHARE. The statics come out whole before the split sees anything, so
* nothing the cache is given can demote an attention projection to host memory. */
@@ -425,25 +462,6 @@ TEST(the_engine_s_queues_come_off_the_card_before_the_split) {
CHECK(unclaimed < 114 * MiB);
}
TEST(a_stated_budget_still_wins_and_the_other_side_still_derives) {
Config c = small_config();
c.vram_weights_mib = 20000; /* stated */
c.vram_kv_mib = 0; /* derived */
c.gpu_headroom_mib = 96;
VramFacts f{};
f.capacity = 32LL << 30;
f.free = f.capacity - (512LL << 20);
f.arena = 144LL << 20;
f.kv_ceiling = 100LL << 30;
VramBudget b;
CHECK_OK(vram_budget_resolve(c, { f }, &b));
CHECK_EQ(c.vram_weights_mib, 20000ll); /* untouched */
CHECK(!b.derived_weights && b.derived_kv);
CHECK_EQ(b.kv, b.claimable); /* the KV pool gets everything that is left */
}
TEST(the_smallest_card_binds_and_a_short_one_refuses_by_name) {
Config c = small_config();
c.vram_weights_mib = 0;
@@ -756,7 +774,7 @@ TEST(kv_refuses_a_group_with_no_block_size) {
TEST(kv_refuses_when_fixed_costs_do_not_fit) {
/* --max-seqs 128 at 16 KiB of GDN state each is 2 MiB of fixed cost against a 1 MiB
* --vram-kv-mib. Refused by name, with the arithmetic printed; not silently served at fewer
* the KV pool. Refused by name, with the arithmetic printed; not silently served at fewer
* sequences than the operator asked for. */
Fixture f;
f.cfg.max_seqs = 128;
+26
View File
@@ -22,6 +22,7 @@
#include <cstdio>
#include <memory>
#include <fstream>
#include <malloc.h>
#include <iterator>
#include <string>
#include <vector>
@@ -283,6 +284,31 @@ TEST(every_admitted_picture_format_decodes) {
}
}
/* A PICTURE WIDER THAN A WHOLE NUMBER OF THE SCALER'S VECTORS: 4:2:0 at 1788 wide is converted to
* RGB 12 bytes past 1788 x 3. Into a buffer of exactly that size those bytes were the next heap
* chunk's header, and the server aborted at a later allocation (Codeberg #57). The mmap threshold
* is raised so the RGB comes from the heap proper, as it does in a server that has freed large
* buffers before; glibc then checks the neighbouring headers on every free below. */
TEST(a_picture_of_an_awkward_width_converts_inside_its_buffer) {
if (!decoder_available()) { std::printf(" SKIP no media decoder in this build\n"); return; }
const std::vector<uint8_t> b = media_file("red-1788x282.jpg");
REQUIRE(!b.empty());
mallopt(M_MMAP_THRESHOLD, 64 << 20);
for (int i = 0; i < 8; ++i) {
Frame f;
std::string why;
const int rc = decode_image(b.data(), b.size(), int64_t(1) << 24, &f, &why);
if (rc != RAD_OK) std::printf(" %s\n", why.c_str());
CHECK_EQ(rc, RAD_OK);
CHECK_EQ(f.w, 1788);
CHECK_EQ(f.h, 282);
CHECK(is_red(f));
std::vector<uint8_t> behind(4096, 1);
CHECK_EQ(behind[0], 1);
}
mallopt(M_MMAP_THRESHOLD, 128 << 10);
}
TEST(every_admitted_video_format_decodes) {
if (!decoder_available()) { std::printf(" SKIP no media decoder in this build\n"); return; }
for (const char* name : { "red-h264.mp4", "red-hevc.mp4", "red-av1.mp4", "red-vp8.webm",
+99 -19
View File
@@ -392,13 +392,13 @@ TEST(planner_spills_experts_before_dense_weights) {
CHECK_OK(Planner(in).plan(&p));
/* THREE resident, not four, and the fourth slot is the shadow. Spare slots come out of
* --vram-weights-mib like everything else in the slab -- there is nowhere else for them to
* the weights pool like everything else in the slab -- there is nowhere else for them to
* come from, because --gpu-headroom-mib is memory the engine promises not to touch -- so
* dynamic placement costs a resident unit and the report says how many. */
CHECK_EQ(p.totals.bytes[(int)Tier::VRAM], 3 * MiB);
CHECK_EQ(p.totals.bytes[(int)Tier::HostPinned], 6 * MiB);
CHECK_EQ(p.slab_overhead, 1 * MiB + RAD_ALIGN_UNIT);
/* And the whole of it fits the budget the operator stated, which is the property that stops
/* And the whole of it fits the budget the plan was given, which is the property that stops
* the mover overrunning the pool that was sized for it. */
CHECK(p.totals.bytes[(int)Tier::VRAM] + p.slab_overhead <= p.vram_budget);
@@ -475,7 +475,7 @@ TEST(the_expert_floor_places_every_expert) {
f.op("moe_gemm", d, false);
}
WeightFootprint wf;
weight_footprint(f.prog, &wf, TablePlacement::Vram, TablePlacement::Disk);
weight_footprint(f.prog, &wf, TablePlacement::Vram, TablePlacement::Disk, false, true);
CHECK(wf.expert_spare > 0);
const int64_t host = 100 * MiB;
@@ -633,7 +633,7 @@ TEST(planner_reads_routed_experts_it_cannot_hold_from_the_container) {
/* The buffers are the largest layer's file-tier units, twice, at the stager's packing. */
CHECK_EQ(p.file_layer_max, std::max(per_layer[0], per_layer[1]));
CHECK(p.file_stage_vram >= 2 * p.file_layer_max + (int64_t)RAD_ALIGN_UNIT);
/* And everything the VRAM side holds fits the budget the operator stated -- the residents,
/* And everything the VRAM side holds fits the budget the plan was given -- the residents,
* the shadow slots and the two buffers -- so the mover cannot overrun the pool. */
CHECK(p.totals.bytes[(int)Tier::VRAM] + p.slab_overhead + p.file_stage_vram <= p.vram_budget);
/* The exact prefetch's ring is not for these: the file stager reads into its own buffers. */
@@ -2169,7 +2169,7 @@ TEST(the_stager_stages_each_layer_one_layer_ahead_and_releases_it_when_the_next_
}
TEST(mover_reserves_from_the_weight_pool_rather_than_beside_it) {
/* THE PRODUCTION PATH. Pools has already allocated --vram-weights-mib as one block; a mover
/* THE PRODUCTION PATH. Pools has already allocated the weights pool as one block; a mover
* that called the allocator beside it would spend that budget twice and the overrun would
* surface as an out-of-memory from some unrelated launch much later. Reserving from
* Pools::weights() is also what makes it structurally impossible for a promotion to reach a
@@ -2189,7 +2189,7 @@ TEST(mover_reserves_from_the_weight_pool_rather_than_beside_it) {
MoverConfig mc;
CHECK_OK(m.init(hf.f.prog, hf.plan, mc, &pools));
/* Every byte the mover took came out of the stated budgets, and none of it out of KV. */
/* Every byte the mover took came out of the pools' budgets, and none of it out of KV. */
CHECK(pools.weights().used() > weights_before);
CHECK(pools.host_pinned().used() > host_before);
CHECK_EQ(pools.kv().used(), (int64_t)0);
@@ -2331,7 +2331,7 @@ TEST(the_weight_footprint_splits_statics_from_the_elastic_expert_plane) {
build_moe(f, /*n=*/4, /*each=*/2 * MiB, &experts);
WeightFootprint fp;
weight_footprint(f.prog, &fp, TablePlacement::Vram, TablePlacement::Disk);
weight_footprint(f.prog, &fp, TablePlacement::Vram, TablePlacement::Disk, false, true);
/* One model-level weight and four experts: five units. */
CHECK_EQ(fp.n_units, 5ll);
@@ -2361,12 +2361,12 @@ TEST(weights_in_one_layer_are_one_unit_and_are_aligned_once_each) {
}
WeightFootprint fp;
weight_footprint(f.prog, &fp, TablePlacement::Vram, TablePlacement::Disk);
weight_footprint(f.prog, &fp, TablePlacement::Vram, TablePlacement::Disk, false, true);
CHECK_EQ(fp.n_units, 2ll); /* the declared group is the unit, not the weight */
/* ONE align_up A UNIT AND ONE INSIDE IT, which is how Mover::init spends the slab. A budget
that summed raw bytes would be short by an alignment per unit -- on a 512-expert MoE that
is real memory, and the failure is an overrun of the pool the operator sized. */
is real memory, and the failure is an overrun of the weights pool. */
const int64_t per_unit = align_up(align_up(odd, RAD_ALIGN_UNIT) + odd, RAD_ALIGN_UNIT);
CHECK_EQ(fp.statics, 2 * per_unit);
CHECK(fp.statics > 4 * odd);
@@ -2394,12 +2394,67 @@ TEST(a_weight_with_no_device_band_takes_its_whole_unit_to_the_mapped_tier) {
f.prog.ops.push_back(host_only);
WeightFootprint fp;
weight_footprint(f.prog, &fp, TablePlacement::Vram, TablePlacement::Disk);
weight_footprint(f.prog, &fp, TablePlacement::Vram, TablePlacement::Disk, false, true);
CHECK_EQ(fp.n_units, 1ll);
CHECK_EQ(fp.statics, 0ll);
CHECK_EQ(fp.mapped, 6 * MiB); /* both weights: the unit is what moves */
}
/* ON THE HOST BACKEND THE WEIGHTS POOL IS HOST MEMORY, so a weight only a host kernel reads stays in
* the container's mapping only when it lies there as its kernel reads it. One its host kernel
* widened at load has no such place, and CPU-only serving would refuse at load; it takes a copy in
* the pool instead, and the footprint the budget sizes that pool from counts it the same way. */
TEST(on_the_host_backend_a_converted_host_only_weight_takes_a_pool_copy) {
Fixture f;
const rad_weight direct = f.weight("blk.0.a.weight", 4 * MiB, RAD_ACCESS_PER_TOKEN, 0, -1);
const rad_weight widened = f.weight("output_norm.weight", 2 * MiB, RAD_ACCESS_PER_TOKEN, -1, -1);
f.prog.weights[widened].widen = true;
for (rad_weight w : { direct, widened }) {
OpInfo o;
o.op = "host_op";
o.index = (int32_t)f.prog.ops.size();
o.weights = { w };
Band hb;
hb.hi = 1 << 20;
hb.dom[RAD_DOMAIN_HOST].row = &g_host_row; /* no device band */
hb.miss[RAD_DOMAIN_DEVICE] = "no device kernel";
o.bands.push_back(hb);
f.prog.ops.push_back(o);
}
WeightFootprint card, host;
weight_footprint(f.prog, &card, TablePlacement::Vram, TablePlacement::Disk, false, true);
weight_footprint(f.prog, &host, TablePlacement::Vram, TablePlacement::Disk, true, true);
CHECK_EQ(card.mapped, 6 * MiB); /* on a card both stay where a host kernel reads them */
CHECK_EQ(card.statics, 0ll);
CHECK_EQ(host.mapped, 4 * MiB);
CHECK_EQ(host.statics, 2 * MiB); /* the widened one is the pool's */
Config cfg = base_config();
cfg.vram_weights_mib = 8;
Plan plan;
PlannerInput in{&f.prog, &cfg, 0, 1, nullptr, 0};
in.host_backend = true;
CHECK_OK(Planner(in).plan(&plan));
CHECK(plan.weight[direct].tier == Tier::Mapped);
CHECK(plan.weight[widened].tier == Tier::VRAM); /* the weights pool, host memory here */
/* A CHECKPOINT SERVED DIRECTLY has no container mapping for either weight to stay in, so on
* the host backend both take a pool copy, and the footprint counts both: a budget sized from
* a footprint that left one in the mapping is a pool the planner then overfills. */
WeightFootprint ckpt;
weight_footprint(f.prog, &ckpt, TablePlacement::Vram, TablePlacement::Disk, true, false);
CHECK_EQ(ckpt.mapped, 0ll);
CHECK_EQ(ckpt.statics, 6 * MiB);
Plan cplan;
PlannerInput cin{&f.prog, &cfg, 0, 1, nullptr, 0};
cin.host_backend = true;
cin.container = false;
CHECK_OK(Planner(cin).plan(&cplan));
CHECK(cplan.weight[direct].tier == Tier::VRAM);
CHECK(cplan.weight[widened].tier == Tier::VRAM);
}
/* --embedding-placement. The fixture's embedding is read by an `embed_lookup`, as every arch
* declares it, and its head by a GEMM: the first is the table the flag moves, the second never. */
void build_dense_lookup(Fixture& f, int layers, int64_t per_layer, int64_t emb = 1 * MiB) {
@@ -2441,7 +2496,7 @@ TEST(the_placement_flags_find_their_tables_by_what_reads_them) {
add_ngram_table(f, 8 * MiB);
WeightFootprint fp;
weight_footprint(f.prog, &fp, TablePlacement::Vram, TablePlacement::Disk);
weight_footprint(f.prog, &fp, TablePlacement::Vram, TablePlacement::Disk, false, true);
CHECK_EQ(fp.embedding, 1 * MiB);
CHECK_EQ(fp.ngram, 8 * MiB);
CHECK(!fp.ngram_device);
@@ -2449,7 +2504,7 @@ TEST(the_placement_flags_find_their_tables_by_what_reads_them) {
CHECK_EQ(fp.statics, 2 * 4 * MiB + 2 * MiB);
CHECK_EQ(fp.mapped, 8 * MiB);
weight_footprint(f.prog, &fp, TablePlacement::Ram, TablePlacement::Disk);
weight_footprint(f.prog, &fp, TablePlacement::Ram, TablePlacement::Disk, false, true);
CHECK_EQ(fp.embedding, 1 * MiB);
CHECK_EQ(fp.hosted, 1 * MiB);
CHECK_EQ(fp.statics, 2 * 4 * MiB + 1 * MiB);
@@ -2466,7 +2521,7 @@ TEST(the_placement_flags_find_their_tables_by_what_reads_them) {
t.op("embed_lookup", {m}, false);
t.op("logits_gemm", {m}, false);
CHECK(!is_embedding_table(t.prog, m));
weight_footprint(t.prog, &fp, TablePlacement::Ram, TablePlacement::Disk);
weight_footprint(t.prog, &fp, TablePlacement::Ram, TablePlacement::Disk, false, true);
CHECK_EQ(fp.embedding, 0ll);
CHECK_EQ(fp.hosted, 0ll);
}
@@ -2492,7 +2547,7 @@ TEST(embedding_ram_goes_to_the_pinned_pool_read_in_place_and_costs_no_vram) {
for (rad_weight w = 2; (size_t)w < f.prog.weights.size(); ++w)
CHECK(plan.weight[w].tier == Tier::VRAM);
/* Vram, the default, leaves it with the other weights. */
/* Vram leaves it with the other weights. */
cfg.embedding_resolved = TablePlacement::Vram;
cfg.vram_weights_mib = 10;
Plan plan2;
@@ -2501,6 +2556,31 @@ TEST(embedding_ram_goes_to_the_pinned_pool_read_in_place_and_costs_no_vram) {
CHECK_EQ(plan2.embedding_host_bytes, 0ll);
}
/* THE EMBEDDING'S OWN ROOM: the resolver sizes Config::embedding_host_mib on top of
* --host-pool-mib, so a dense model with no pool still places the table, and a pool the experts
* share keeps all of --host-pool-mib for them after the table is pinned. */
TEST(embedding_ram_brings_its_own_room_beside_the_host_pool) {
Fixture f;
build_dense_lookup(f, /*layers=*/2, /*per_layer=*/4 * MiB);
Config cfg = base_config();
cfg.placement = "all_vram";
cfg.vram_weights_mib = 9;
cfg.host_pool_mib = 0; /* no pool of weights at all */
cfg.embedding_host_mib = 1;
cfg.embedding_resolved = TablePlacement::Ram;
Plan plan;
PlannerInput in{&f.prog, &cfg, 0, 1, nullptr, 0};
CHECK_OK(Planner(in).plan(&plan));
CHECK(plan.weight[1].tier == Tier::HostPinned);
CHECK_EQ(plan.host_budget, 0ll);
cfg.host_pool_mib = 3;
Plan plan2;
CHECK_OK(Planner(in).plan(&plan2));
CHECK(plan2.weight[1].tier == Tier::HostPinned);
CHECK_EQ(plan2.host_budget, 3 * MiB); /* --host-pool-mib, whole */
}
/* A TABLE THAT IS NOT A WHOLE NUMBER OF PAGES still leaves the report's pinned total at what the
* pooled units use: the pool slot is charged rounded up and the tier total counts weight bytes, so
* the report subtracts the same weight bytes it added. */
@@ -2595,14 +2675,14 @@ TEST(an_ngram_table_a_device_kernel_reads_goes_where_the_placement_says) {
f.op("embed_lookup_q", {t}, /*host_kernel=*/true);
WeightFootprint fp;
weight_footprint(f.prog, &fp, TablePlacement::Vram, TablePlacement::Vram);
weight_footprint(f.prog, &fp, TablePlacement::Vram, TablePlacement::Vram, false, true);
CHECK(fp.ngram_device);
CHECK(fp.ngram_host);
CHECK_EQ(fp.ngram, 8 * MiB);
CHECK_EQ(fp.mapped, 0ll);
CHECK_EQ(fp.statics, 4 * MiB + 2 * MiB + 8 * MiB);
for (TablePlacement off : { TablePlacement::Ram, TablePlacement::Disk }) {
weight_footprint(f.prog, &fp, TablePlacement::Vram, off);
weight_footprint(f.prog, &fp, TablePlacement::Vram, off, false, true);
CHECK_EQ(fp.ngram, 8 * MiB);
CHECK_EQ(fp.mapped, 8 * MiB);
CHECK_EQ(fp.statics, 4 * MiB + 2 * MiB);
@@ -2646,7 +2726,7 @@ TEST(an_ngram_table_with_no_host_kernel_cannot_stay_on_disk) {
const rad_weight t = f.weight("ngram.weight", 8 * MiB, RAD_ACCESS_VOCAB, -1, -1);
f.op("embed_lookup_q", {t}, /*host_kernel=*/false);
WeightFootprint fp;
weight_footprint(f.prog, &fp, TablePlacement::Vram, TablePlacement::Disk);
weight_footprint(f.prog, &fp, TablePlacement::Vram, TablePlacement::Disk, false, true);
CHECK(fp.ngram_device);
CHECK(!fp.ngram_host);
}
@@ -2655,13 +2735,13 @@ TEST(an_empty_program_has_an_empty_footprint) {
Fixture f;
WeightFootprint fp;
fp.statics = 1; /* and the out parameter is reset, not accumulated */
weight_footprint(f.prog, &fp, TablePlacement::Vram, TablePlacement::Disk);
weight_footprint(f.prog, &fp, TablePlacement::Vram, TablePlacement::Disk, false, true);
CHECK_EQ(fp.statics, 0ll);
CHECK_EQ(fp.experts, 0ll);
CHECK_EQ(fp.mapped, 0ll);
CHECK_EQ(fp.n_units, 0ll);
/* and a null one is not a crash */
weight_footprint(f.prog, nullptr, TablePlacement::Vram, TablePlacement::Disk);
weight_footprint(f.prog, nullptr, TablePlacement::Vram, TablePlacement::Disk, false, true);
}
RAD_TEST_MAIN()
+55 -15
View File
@@ -128,17 +128,22 @@ TEST(loading_reads_identity_and_calls_open) {
if (open_calls) CHECK(open_calls() >= 1);
}
/* The hierarchy is CONFIGURED, not discovered: a named plugin takes its position and one present
* on disk but absent from the list loads at the end, after everything named. */
/* The hierarchy is CONFIGURED, not discovered: a named plugin takes its position, and a kernel
* library present on disk but absent from the list is not loaded at all -- naming the libraries
* is choosing them. With no list, everything on disk loads. */
TEST(hierarchy_order_is_configured) {
Registry r;
CHECK_OK(r.load_dir(kernels_dir(), { "radtest_base" }));
const Plugin* base = r.plugin("radtest_base");
const Plugin* over = r.plugin("radtest_over");
CHECK(base && over);
if (!base || !over) return;
CHECK(base != nullptr);
if (!base) return;
CHECK_EQ(base->order, 0);
CHECK_EQ(over->order, 1); /* unnamed, so it loads behind everything named */
CHECK(r.plugin("radtest_over") == nullptr); /* unnamed, so not loaded */
for (const KernelRow& row : r.rows()) CHECK(row.plugin != "radtest_over");
Registry all;
CHECK_OK(all.load_dir(kernels_dir(), {}));
CHECK(all.plugin("radtest_base") && all.plugin("radtest_over"));
Registry r2;
CHECK_OK(r2.load_dir(kernels_dir(), { "radtest_over", "radtest_base" }));
@@ -175,9 +180,14 @@ TEST(the_reference_library_sorts_last_with_no_hierarchy) {
/* Naming it is still an override: an operator comparing a library against the reference puts
* the reference in front on purpose, and the pin must not defeat that. */
Registry r2;
CHECK_OK(r2.load_dir(order_dir(), { "radtest_reference" }));
CHECK_OK(r2.load_dir(order_dir(), { "radtest_reference", "radtest_base" }));
CHECK_EQ(r2.plugin("radtest_reference")->order, 0);
CHECK(r2.plugin("radtest_base")->order > 0);
/* And a list that leaves it out leaves it out: the reference is a library like any other. */
Registry r3;
CHECK_OK(r3.load_dir(order_dir(), { "radtest_base" }));
CHECK(r3.plugin("radtest_reference") == nullptr);
}
TEST(abi_mismatch_is_refused_by_name_with_both_versions) {
@@ -818,14 +828,37 @@ TEST(a_device_fact_constraint_is_matched_against_the_machine) {
CHECK(has(why, "measured at launch"));
}
/* THE SHIPPED libr4d PICKS THE ALL-REDUCE BY MESSAGE SIZE, and the selector is what says so. At 4
* and 8 ranks the exact sum is a one-shot for a decode-sized message and a two-shot for a prefill
* chunk; the two-shot rows start one element above the one-shot bound, so that bound is a band
* edge of the blocks' ranged `numel`. The band at or under the edge has to stay resolvable for
* every row that places a DIV on `numel` -- the two-rank wht6 wire (64) and the four-rank ti8 wire
* (128) among them -- or a lossy two-rank serve would lose its decode band. Checked here against
* the real plugin, because nothing else can run a four- or eight-rank resolution on a two-card
* machine. Geometry is Qwen3.8-Flash-Next's: 2560 wide, a 2048-token chunk. */
/* AN ENGINE SERVING WITH NO CARD LEAVES A GPU LIBRARY'S DEVICE ROWS OUT. On the host backend no
* GPU code object runs, and a device row that resolved anyway would be launched at the first step
* and fail -- CPU-only serving with the shipped libraries installed was exactly that. Only the
* engine says so (set_no_device_code); a registry that only selects keeps every row, which the
* libr4d tests below rely on wherever they run. First of the libr4d tests in this file, so its
* dlopen is the one that registers the library's fat binaries. */
TEST(an_engine_with_no_card_leaves_a_gpu_librarys_device_rows_out) {
const std::string so = home() + "/kernels/libr4d.so";
if (access(so.c_str(), R_OK) != 0) {
fprintf(stderr, " SKIP %s: no %s (a build without HIP)\n", ::radtest::current(),
so.c_str());
return;
}
Registry r;
r.set_no_device_code(true);
CHECK(r.load_plugin(so, 0) >= 0);
const Plugin* p = r.plugin("libr4d");
CHECK(p != nullptr);
if (!p) return;
CHECK(p->device_code_absent);
for (const KernelRow& row : r.rows()) CHECK(row.info->domain != RAD_DOMAIN_DEVICE);
}
/* THE SHIPPED libr4d PICKS THE ALL-REDUCE BY MESSAGE SIZE, and the selector is what says so. At 3,
* 4 and 8 ranks the exact sum is a one-shot for a decode-sized message and a two-shot for a
* prefill chunk; the two-shot rows start one element above the one-shot bound, so that bound is a
* band edge of the blocks' ranged `numel`. The band at or under the edge has to stay resolvable
* for every row that places a DIV on `numel` -- the two-rank wht6 wire (64) and the three- and
* four-rank ti8 wires (32, 128) among them -- or a lossy serve would lose its decode band. Checked
* here against the real plugin, because nothing else can run a resolution above two ranks on a
* two-card machine. Geometry is Qwen3.8-Flash-Next's: 2560 wide, a 2048-token chunk. */
TEST(libr4d_resolves_the_all_reduce_by_message_size) {
const std::string so = home() + "/kernels/libr4d.so";
if (access(so.c_str(), R_OK) != 0) {
@@ -853,10 +886,14 @@ TEST(libr4d_resolves_the_all_reduce_by_message_size) {
return s;
};
CHECK_EQ(names(bands(3, 1, chunk)),
"524288:ar_oneshot_3rank_exact 5242880:ar_twoshot_3rank_exact ");
CHECK_EQ(names(bands(4, 1, chunk)),
"524288:ar_oneshot_4rank_exact 5242880:ar_twoshot_4rank_exact ");
CHECK_EQ(names(bands(8, 1, chunk)),
"524288:ar_oneshot_8rank_exact 5242880:ar_twoshot_8rank_exact ");
CHECK_EQ(names(bands(3, 0, chunk)),
"524288:ar_twoshot_3rank_ti8 5242880:ar_twoshot_3rank_ti8 ");
CHECK_EQ(names(bands(4, 0, chunk)),
"524288:ar_twoshot_4rank_ti8 5242880:ar_twoshot_4rank_ti8 ");
CHECK_EQ(names(bands(2, 0, chunk)),
@@ -868,6 +905,9 @@ TEST(libr4d_resolves_the_all_reduce_by_message_size) {
CHECK_EQ(names(bands(4, 1, 16384)),
"524288:ar_oneshot_4rank_exact 20971520:ar_twoshot_4rank_exact "
"41943040:ar_oneshot_4rank_exact ");
CHECK_EQ(names(bands(3, 1, 16384)),
"524288:ar_oneshot_3rank_exact 20971520:ar_twoshot_3rank_exact "
"41943040:ar_oneshot_3rank_exact ");
/* A step that never exceeds the bound has one band, and it is the one-shot's. */
CHECK_EQ(names(bands(4, 1, 128)), "327680:ar_oneshot_4rank_exact ");
+22 -1
View File
@@ -279,7 +279,7 @@ TEST(op_vocabulary) {
"embed_lookup", "logits_gemm",
"sample_penalties", "sample_dry", "sample_temp", "sample_topk", "sample_topp",
"sample_minp", "sample_typical", "sample_xtc", "sample_mask", "sample_pick",
"sample_argmax", "sample_merge_topk",
"sample_argmax", "sample_merge_topk", "sample_logprobs",
};
for (const char* op : kOps) {
if (!kern(op)) fprintf(stderr, " missing op '%s'\n", op);
@@ -3084,6 +3084,27 @@ TEST(op_sample_temp_topk_argmax) {
CHECK_EQ(lg.at(1), 6.0f);
}
/* The raw distribution's summary: max, sum of exp(l - max), the k largest with the lower id first
* on a tie, slots past the vocabulary as holes, global ids under an offset, and a row without the
* flag left as it was. */
TEST(op_sample_logprobs) {
T lg(RAD_F32, {2, 4}); lg.f({1, 3, 2, 3, 0, 0, 0, 0});
T st(RAD_F32, {2, 2 + 2 * 5});
st.f(std::vector<float>(2 * 12, 9.0f));
SP sp(2); sp[0].flags = RAD_SP_LOGPROBS;
A a; a.t(lg).t(sp.operand()).t(st).i("M", 2).i("n_vocab", 4).i("k", 5).i("vocab_off", 100);
CHECK_OK(run("sample_logprobs", a));
CHECK_EQ(st.at(0), 3.0f);
CHECK_NEAR(st.at(1), std::exp(-2.0f) + 1.0f + std::exp(-1.0f) + 1.0f, 1e-6);
CHECK_EQ(st.at(2), 101.0f); CHECK_EQ(st.at(3), 3.0f); /* the tie: id 1 before id 3 */
CHECK_EQ(st.at(4), 103.0f); CHECK_EQ(st.at(5), 3.0f);
CHECK_EQ(st.at(6), 102.0f); CHECK_EQ(st.at(7), 2.0f);
CHECK_EQ(st.at(8), 100.0f); CHECK_EQ(st.at(9), 1.0f);
CHECK_EQ(st.at(10), -1.0f); /* four tokens, five slots */
CHECK(st.at(11) == -INFINITY);
CHECK_EQ(st.at(12), 9.0f); /* row 1 asked for nothing */
}
TEST(op_sample_narrowing) {
/* Two candidates whose probabilities are 3/4 and 1/4. */
const float ln3 = 1.09861229f;
+282
View File
@@ -25,6 +25,7 @@
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <set>
#include <string>
#include <vector>
@@ -449,6 +450,33 @@ TEST(chain_order_temperature_before_the_cuts_is_observable) {
CHECK(a.c.size() != b.c.size());
}
TEST(temp_last_draws_only_from_the_untempered_nucleus) {
/* The same numbers through the whole chain. Temperature last is llama.cpp's order, asked for
* with `samplers`: the nucleus is cut on the untempered distribution, so a hot temperature
* flattens only what survived the cut and never revives a token it removed. Temperature first
* cuts on the flattened distribution and keeps more. */
const float logits[3] = { 3.0f, 2.0f, 1.0f };
auto b = set_of({ 3.0f, 2.0f, 1.0f });
host_top_p(b, 0.5f, 1);
std::set<int32_t> nucleus;
for (const auto& e : b.c) nucleus.insert(e.id);
SamplingParams sp;
sp.temp = 5.0f;
sp.top_p = 0.5f;
std::set<int32_t> first, last;
for (uint64_t seed = 0; seed < 256; ++seed) {
sp.seed = seed;
HostRefInput in;
sp.temp_last = false;
first.insert(host_sample(logits, 3, sp, in));
sp.temp_last = true;
last.insert(host_sample(logits, 3, sp, in));
}
for (int32_t t : last) CHECK(nucleus.count(t) == 1);
CHECK(first.size() > last.size());
}
/* ================================================================== GBNF */
@@ -1685,6 +1713,260 @@ TEST(a_top_k_of_zero_samples_this_steps_candidates) {
CHECK_EQ(tok[0], 3);
}
/* LOGPROBS ARE THE RAW DISTRIBUTION'S, read before any stage. A greedy row asking for them is
* staged as a top-1 chain row, and its token and alternatives come back against the normaliser of
* the logits the model wrote. */
TEST(logprobs_are_the_raw_distributions) {
HostChain ch(32, 1, 0);
NEED_CHAIN(ch)
SamplingParams sp = greedy_params();
sp.n_probs = 3;
Request a = make_req(1, { 30 }, sp);
std::vector<float> lg(32, 0.0f);
lg[7] = 4.0f; lg[3] = 4.0f; lg[9] = 2.0f;
std::vector<int32_t> tok;
CHECK_OK(ch.step({ &a }, lg, &tok));
CHECK_EQ(tok[0], 3); /* the tie goes to the lower id */
int64_t n = 0;
const DeviceSampleParams* p = ch.s.staged_params(&n);
CHECK((p[0].flags & RAD_SP_LOGPROBS) != 0);
CHECK((p[0].flags & RAD_SP_GREEDY) == 0);
CHECK_EQ(p[0].top_k, 1);
double z = 0.0;
for (float v : lg) z += std::exp((double)v);
const double lz = std::log(z);
TokenLogprobs lp;
CHECK_OK(ch.s.logprobs_for(0, tok[0], &lp));
CHECK_NEAR(lp.logprob, 4.0 - lz, 1e-5);
CHECK_EQ(lp.n_top, 3);
CHECK_EQ(lp.top_id[0], 3);
CHECK_EQ(lp.top_id[1], 7);
CHECK_EQ(lp.top_id[2], 9);
CHECK_NEAR(lp.top_lp[2], 2.0 - lz, 1e-5);
/* A row that was not staged for logprobs has none, and asking is the caller's error. */
CHECK_EQ(ch.s.logprobs_for(1, 0, &lp), RAD_E_STATE);
}
namespace {
/* THE SUMMARY HOLDS 21 PAIRS (RAD_MAX_LOGPROBS + 1), so a token is outside it only behind 21
* larger or tied ones: tokens 0..20 at `hi` fill it, and token 21 at `at` is the first outside --
* at `hi` too, it loses the tie to every lower id. The rest of a 32-token vocabulary sits at
* `rest`. The prompt is `head`, 0..20 twice, then `tail`, so the penalties count each of 0..20
* twice. */
std::vector<float> outside_logits(float hi, float at, float rest) {
std::vector<float> lg(32, rest);
for (int t = 0; t <= 20; ++t) lg[(size_t)t] = hi;
lg[21] = at;
return lg;
}
std::vector<int32_t> outside_prompt(std::vector<int32_t> head, const std::vector<int32_t>& tail) {
for (int k = 0; k < 2; ++k)
for (int32_t t = 0; t <= 20; ++t) head.push_back(t);
head.insert(head.end(), tail.begin(), tail.end());
return head;
}
double log_sum_exp(const std::vector<float>& lg) {
double z = 0.0;
for (float v : lg) z += std::exp((double)v);
return std::log(z);
}
} /* namespace */
/* A TOKEN OUTSIDE THE RAW SUMMARY IS RECOVERED FROM THE VALUE IT WAS DRAWN AT. Tokens 0..21 tie at
* 5, so the summary holds 0..20; the penalties push those to 5/1.25 - 2 = 2 and token 21 to
* 5/1.25 - 1 = 3, which is chosen, and its raw logit is the candidate value with temperature,
* frequency and repetition undone. */
TEST(a_chosen_token_outside_the_summary_has_its_raw_logprob) {
HostChain ch(32, 1, 0);
NEED_CHAIN(ch)
SamplingParams sp;
sp.top_k = 1;
sp.temp = 0.5f;
sp.rep_penalty = 1.25f;
sp.freq_penalty = 1.0f;
sp.n_probs = 0;
Request a = make_req(1, outside_prompt({}, { 21 }), sp);
const std::vector<float> lg = outside_logits(5.0f, 5.0f, 0.0f);
std::vector<int32_t> tok;
CHECK_OK(ch.step({ &a }, lg, &tok));
CHECK_EQ(tok[0], 21);
TokenLogprobs lp;
CHECK_OK(ch.s.logprobs_for(0, tok[0], &lp));
CHECK_NEAR(lp.logprob, 5.0 - log_sum_exp(lg), 1e-5);
CHECK_EQ(lp.n_top, 0);
}
/* A NEGATIVE LOGIT'S REPETITION PENALTY IS UNDONE ON ITS OWN SIDE OF ZERO, and the presence penalty
* is added back with the frequency one. Token 21's raw logit is -1: repetition multiplies it to
* -1.25, frequency (once) and presence take it to -13.25, and tokens 0..20 (5/1.25 - 20 - 2 = -18)
* and the rest (-30) fall below it. Inverting: -13.25 + 10 + 2 = -1.25, divided by 1.25 is -1. */
TEST(a_negative_penalised_logit_has_its_raw_logprob) {
HostChain ch(32, 1, 0);
NEED_CHAIN(ch)
SamplingParams sp;
sp.top_k = 1;
sp.temp = 0.5f;
sp.rep_penalty = 1.25f;
sp.freq_penalty = 10.0f;
sp.pres_penalty = 2.0f;
sp.n_probs = 2;
Request a = make_req(1, outside_prompt({}, { 21 }), sp);
const std::vector<float> lg = outside_logits(5.0f, -1.0f, -30.0f);
std::vector<int32_t> tok;
CHECK_OK(ch.step({ &a }, lg, &tok));
CHECK_EQ(tok[0], 21);
const double lz = log_sum_exp(lg);
TokenLogprobs lp;
CHECK_OK(ch.s.logprobs_for(0, tok[0], &lp));
CHECK_NEAR(lp.logprob, -1.0 - lz, 1e-5);
CHECK_EQ(lp.n_top, 2);
CHECK_EQ(lp.top_id[0], 0);
CHECK_NEAR(lp.top_lp[0], 5.0 - lz, 1e-5);
}
/* ONLY THE PENALTY WINDOW IS COUNTED BACK. Token 21 opens the history three times, but the last 42
* tokens -- penalty_last_n -- are 0..20 twice, so the stage never penalised it: 0..20 drop to 2 and
* 21 stays at 5. Counting the whole staged history would add 3 back and multiply by 1.25. */
TEST(a_logprob_counts_only_the_penalty_window_back) {
HostChain ch(32, 1, 0);
NEED_CHAIN(ch)
SamplingParams sp;
sp.top_k = 1;
sp.temp = 0.5f;
sp.rep_penalty = 1.25f;
sp.freq_penalty = 1.0f;
sp.penalty_last_n = 42;
sp.n_probs = 0;
Request a = make_req(1, outside_prompt({ 21, 21, 21 }, {}), sp);
const std::vector<float> lg = outside_logits(5.0f, 5.0f, 0.0f);
std::vector<int32_t> tok;
CHECK_OK(ch.step({ &a }, lg, &tok));
CHECK_EQ(tok[0], 21);
int64_t n = 0;
CHECK_EQ(ch.s.staged_params(&n)[0].hist_len, 45);
TokenLogprobs lp;
CHECK_OK(ch.s.logprobs_for(0, tok[0], &lp));
CHECK_NEAR(lp.logprob, 5.0 - log_sum_exp(lg), 1e-5);
}
/* TEMPERATURE LAST IS UNDONE FROM THE LATE STAGE'S ROW. A sampled row (top_k 2: top_k 1 is greedy,
* which has no late stage), so the early row runs at 1 and the late one at 0.5 over the two
* candidates: token 21 at (5/1.25 - 20) / 0.5 = -32 against -72 for the runner-up, a draw that
* cannot go the other way. Only the late temperature takes -32 back to -16 before the penalties
* are undone. */
TEST(a_temperature_last_row_has_its_raw_logprob) {
HostChain ch(32, 1, 0);
NEED_CHAIN(ch)
SamplingParams sp;
sp.top_k = 2;
sp.temp = 0.5f;
sp.temp_last = true;
sp.rep_penalty = 1.25f;
sp.freq_penalty = 20.0f;
sp.n_probs = 0;
Request a = make_req(1, outside_prompt({}, { 21 }), sp);
const std::vector<float> lg = outside_logits(5.0f, 5.0f, -100.0f);
std::vector<int32_t> tok;
CHECK_OK(ch.step({ &a }, lg, &tok));
CHECK_EQ(tok[0], 21);
int64_t n = 0;
CHECK_EQ(ch.s.staged_params(&n)[0].temp, 1.0f);
TokenLogprobs lp;
CHECK_OK(ch.s.logprobs_for(0, tok[0], &lp));
CHECK_NEAR(lp.logprob, 5.0 - log_sum_exp(lg), 1e-5);
}
/* A ROW WITH NO FINITE LOGIT HAS NO LOGPROBS, and says so, rather than reporting -inf or NaN: the
* step itself still runs, and the engine fails the one request (Engine::row_logprobs). */
TEST(a_row_with_no_finite_logit_has_no_logprobs) {
HostChain ch(32, 1, 0);
NEED_CHAIN(ch)
SamplingParams sp = greedy_params();
sp.n_probs = 3;
Request a = make_req(1, { 1 }, sp);
std::vector<int32_t> tok;
CHECK_OK(ch.step({ &a }, std::vector<float>(32, -INFINITY), &tok));
TokenLogprobs lp;
lp.token = 7;
CHECK_EQ(ch.s.logprobs_for(0, tok[0], &lp), RAD_E_INVAL);
CHECK_EQ(lp.token, -1);
}
/* THE RANKS' SUMMARIES MERGE BY RESCALING TO THE LARGER MAXIMUM. Rank 0's shard has maximum 2 and
* normaliser 3, rank 1's maximum 5 and normaliser 1.5; their pairs interleave by value, a tie
* across ranks going to the lower id. A rank whose normaliser is not finite contributes nothing,
* and with no rank left there is no normaliser. */
TEST(split_vocabulary_logprob_summaries_merge_across_ranks) {
const float rows[2][8] = {
{ 2.0f, 3.0f, 5.0f, 2.0f, 1.0f, 1.0f, -1.0f, -INFINITY },
{ 5.0f, 1.5f, 40.0f, 5.0f, 41.0f, 2.0f, 42.0f, 0.5f },
};
double lz = 0.0;
int32_t id[8];
float v[8];
CHECK_EQ(merge_logprob_rows(&rows[0][0], 2, 3, &lz, id, v, 8), 5);
CHECK_NEAR(lz, std::log(3.0 * std::exp(2.0) + 1.5 * std::exp(5.0)), 1e-6);
const int32_t want[5] = { 40, 5, 41, 1, 42 };
for (int j = 0; j < 5; ++j) CHECK_EQ(id[j], want[j]);
CHECK_EQ(v[1], 2.0f);
CHECK_EQ(merge_logprob_rows(&rows[0][0], 2, 3, &lz, id, v, 2), 2);
float dead[2][8];
std::memcpy(dead, rows, sizeof dead);
dead[1][1] = NAN;
CHECK_EQ(merge_logprob_rows(&dead[0][0], 2, 3, &lz, id, v, 8), 2);
CHECK_NEAR(lz, 2.0 + std::log(3.0), 1e-6);
CHECK_EQ(id[0], 5);
dead[0][1] = 0.0f;
CHECK_EQ(merge_logprob_rows(&dead[0][0], 2, 3, &lz, id, v, 8), 0);
CHECK(std::isnan(lz));
}
/* AND DRY IS UNDONE TOO. "22 23" ended the history once before, followed by 21, so DRY takes its
* multiplier off token 21 (5 - 1 - 0.5 = 3.5); tokens 0..20 appear twice and lose more to the
* frequency penalty (5 - 2 = 3), so 21 is chosen from outside the summary and its raw logit needs
* DRY, the penalties and temperature all undone. */
TEST(a_dry_penalised_token_has_its_raw_logprob) {
HostChain ch(32, 1, 0);
NEED_CHAIN(ch)
SamplingParams sp;
sp.top_k = 1;
sp.temp = 0.8f;
sp.freq_penalty = 1.0f;
sp.dry_multiplier = 0.5f;
sp.dry_base = 1.75f;
sp.dry_allowed_length = 2;
sp.n_probs = 0;
Request a = make_req(1, outside_prompt({ 22, 23, 21 }, { 22, 23 }), sp);
const std::vector<float> lg = outside_logits(5.0f, 5.0f, 0.0f);
std::vector<int32_t> tok;
CHECK_OK(ch.step({ &a }, lg, &tok));
CHECK_EQ(tok[0], 21);
int64_t n = 0;
CHECK((ch.s.staged_params(&n)[0].flags & RAD_SP_DRY) != 0);
TokenLogprobs lp;
CHECK_OK(ch.s.logprobs_for(0, tok[0], &lp));
CHECK_NEAR(lp.logprob, 5.0 - log_sum_exp(lg), 1e-5);
}
TEST(admission_refuses_more_than_twenty_logprobs) {
Sampler s;
SamplingParams sp;
sp.n_probs = RAD_MAX_LOGPROBS + 1;
std::string why;
CHECK(s.check_request(sp, &why) < 0);
CHECK(why.find("logprobs") != std::string::npos);
}
/* repeat_last_n = 0 TURNS THE PENALTIES OFF, as it does in llama.cpp -- it is not "the whole
* history". */
TEST(a_penalty_window_of_zero_leaves_the_logits_alone) {
+806 -16
View File
@@ -64,8 +64,16 @@ struct FakeDetok : IDetokenizer {
struct FakeTokenizer : ITokenizer {
mutable bool last_parse_special = false;
/* A vocabulary with llama's three fill-in-the-middle markers as special tokens, for /infill. */
bool fim = false;
static const char* fim_name(int32_t id) {
return id == 1001 ? "<PRE>" : id == 1002 ? "<SUF>" : id == 1003 ? "<MID>" : nullptr;
}
std::vector<int32_t> encode(const std::string& s, bool, bool parse_special) const override {
last_parse_special = parse_special;
if (fim && parse_special)
for (int32_t id = 1001; id <= 1003; ++id)
if (s == fim_name(id)) return { id };
std::vector<int32_t> v;
v.reserve(s.size());
for (unsigned char c : s) v.push_back((int32_t)c);
@@ -73,9 +81,13 @@ struct FakeTokenizer : ITokenizer {
}
std::string decode(const std::vector<int32_t>& t) const override {
std::string s;
for (int32_t x : t) if (x > 0) s.push_back((char)x);
for (int32_t x : t) if (x > 0) s += token_bytes(x);
return s;
}
std::string token_bytes(int32_t id) const override {
if (fim && fim_name(id)) return fim_name(id);
return std::string(1, (char)id);
}
int32_t eos() const override { return 0; }
int32_t bos() const override { return 1; }
/* Stop strings are deliberately NOT given to the fake decoder, so the server's own scan is
@@ -268,6 +280,8 @@ struct FakeScheduler : IScheduler {
std::vector<uint64_t> submitted;
SamplingParams last_sp; /* what the last submitted request was to sample with */
std::vector<std::string> last_stop; /* ...and the stop strings it was handed */
std::string last_label; /* ...its session label */
int32_t last_max_tokens = 0; /* ...and its max_tokens */
std::vector<uint64_t> cancelled;
std::vector<std::thread> workers;
std::atomic<uint64_t> next_id{1};
@@ -286,6 +300,8 @@ struct FakeScheduler : IScheduler {
submitted.push_back(id);
last_sp = r.sp;
last_stop = r.stop;
last_label = r.session_label;
last_max_tokens = r.max_tokens;
}
void* sink = r.sink;
int32_t cap = r.max_tokens;
@@ -294,9 +310,10 @@ struct FakeScheduler : IScheduler {
const int fst = fail_status;
const char* fwhy = fail_why;
const int32_t nd = drafts;
const int np = r.sp.n_probs;
/* Under the lock: over a real socket, submits arrive from several HTTP workers at once. */
std::lock_guard<std::mutex> lk(mu);
workers.emplace_back([sink, cap, text, h, fst, fwhy, nd] {
workers.emplace_back([sink, cap, text, h, fst, fwhy, nd, np] {
sink_admitted(sink);
sink_prompt_stats(sink, 8, 4);
int32_t n = 0;
@@ -304,7 +321,17 @@ struct FakeScheduler : IScheduler {
if (n >= cap) break;
if (sink_cancelled(sink)) { sink_finish(sink, Finish::Cancelled); return; }
if (n > 0 && nd > 0) sink_drafts(sink, nd, 1);
if (!sink_push(sink, (int32_t)(unsigned char)c)) return;
/* Logprobs when asked: the n-th token at -(n+1)/4, and alternatives 'x', 'y', ...
* at -1, -2, ... */
TokenLogprobs lp;
lp.token = (int32_t)(unsigned char)c;
lp.logprob = -0.25f * (float)(n + 1);
lp.n_top = np > 0 ? np : 0;
for (int j = 0; j < lp.n_top; ++j) {
lp.top_id[j] = 'x' + j;
lp.top_lp[j] = -1.0f - (float)j;
}
if (!sink_push(sink, (int32_t)(unsigned char)c, np >= 0 ? &lp : nullptr)) return;
++n;
if (h && n >= 3) break;
}
@@ -343,7 +370,8 @@ struct Fixture {
FakeGrammar gram;
std::unique_ptr<Server> srv;
explicit Fixture(bool with_tools = true, int64_t max_ctx = 0, const char* model_path = "") {
explicit Fixture(bool with_tools = true, int64_t max_ctx = 0, const char* model_path = "",
bool logprobs = false) {
Deps d;
d.sched = &sched;
d.tok = &tok;
@@ -358,6 +386,7 @@ struct Fixture {
o.max_seqs = 4;
o.max_ctx = max_ctx;
o.model_path = model_path;
o.supports_logprobs = logprobs;
srv.reset(new Server(d, o));
}
@@ -842,12 +871,25 @@ TEST(unsupported_parameters_are_400_and_name_themselves) {
CHECK_EQ(e["error"]["code"].get<std::string>(), std::string("unsupported_parameter"));
CHECK(e["error"]["message"].get<std::string>().find("logit_bias") != std::string::npos);
/* A parameter nobody has heard of is refused too, rather than silently dropped. */
/* A parameter nobody has heard of is a client's own extension, and is ignored as llama.cpp
* and vLLM ignore it (#47: OpenRouter's session_id, refused, broke the client). */
HttpResponse r2 = f.post("/v1/chat/completions",
R"({"messages":[{"role":"user","content":"hi"},{}],
"wobble":1})");
CHECK_EQ(r2.status, 400);
CHECK(r2.body.find("wobble") != std::string::npos);
R"({"messages":[{"role":"user","content":"hi"}],
"wobble":1,"session_id":"abc"})");
CHECK_EQ(r2.status, 200);
/* What llama.cpp-built clients send on every request: the samplers this server does not run,
* at their off values. Accepted there, and refused by name the moment one is switched on. */
HttpResponse off = f.post("/v1/chat/completions",
R"({"messages":[{"role":"user","content":"hi"}],
"mirostat":0,"top_n_sigma":-1,"dynatemp_range":0,
"logit_bias":{},"cache_prompt":true,"id_slot":-1,
"backend_sampling":false,"speculative.n_max":16})");
CHECK_EQ(off.status, 200);
HttpResponse on = f.post("/v1/chat/completions",
R"({"messages":[{"role":"user","content":"hi"}],"mirostat":2})");
CHECK_EQ(on.status, 400);
CHECK_EQ(json::parse(on.body)["error"]["param"].get<std::string>(), std::string("mirostat"));
/* Out-of-range values name the field and the range. */
HttpResponse r3 = f.post("/v1/chat/completions",
@@ -1436,9 +1478,10 @@ TEST(preserve_thinking_at_the_top_level_reaches_the_template) {
CHECK_EQ(parse_chat_request(R"({"messages":[{"role":"user","content":"hi"}],"preserve_thinking":"yes"})",
f.odeps(), lim, &r, &e), RAD_E_INVAL);
CHECK_EQ(e.param, std::string("preserve_thinking"));
/* A chat field, not a completion one: /v1/completions has no template to hand it to. */
/* A chat field, not a completion one: /v1/completions has no template to hand it to, and
* ignores it as it ignores any field it does not read. */
CHECK_EQ(parse_completion_request(R"({"prompt":"ab","preserve_thinking":true})", f.odeps(), lim,
&r, &e), RAD_E_INVAL);
&r, &e), RAD_OK);
}
/* parallel_tool_calls reaches the template, because it is the one tool-choice knob the generated
@@ -1969,14 +2012,16 @@ TEST(stop_strings_wait_for_the_reasoning_closer) {
CHECK(!f.sched.saw_cancel()); /* ended by the reply itself, not cut */
}
/* THE BUDGET REACHES THE ENGINE in either spelling, with the block it is held on; one the block
* cannot hold, a negative one, and two spellings that disagree are 400s naming the field. */
/* THE BUDGET REACHES THE ENGINE in every spelling -- vLLM's, Qwen's and llama.cpp's two -- with
* the block it is held on; one the block cannot hold and two spellings that disagree are 400s
* naming the field, and a negative one is llama.cpp's "no budget". */
TEST(a_thinking_budget_reaches_the_engine_or_is_refused_by_name) {
Fixture f;
f.tmpl.think_open = "{";
f.tmpl.think_close = "|";
f.tmpl.think_starts_open = true;
for (const char* k : { "thinking_token_budget", "thinking_budget" }) {
for (const char* k : { "thinking_token_budget", "thinking_budget", "thinking_budget_tokens",
"reasoning_budget_tokens" }) {
HttpResponse r = f.post("/v1/chat/completions",
std::string(R"({"messages":[{"role":"user","content":"hi"}],")") +
k + R"(":7})");
@@ -1990,8 +2035,7 @@ TEST(a_thinking_budget_reaches_the_engine_or_is_refused_by_name) {
}
struct Case { const char* extra; const char* param; };
for (const Case& c : { Case{ R"("thinking_token_budget":-1)", "thinking_token_budget" },
Case{ R"("thinking_token_budget":3,"thinking_budget":4)",
for (const Case& c : { Case{ R"("thinking_token_budget":3,"thinking_budget":4)",
"thinking_budget" },
Case{ R"("thinking_budget":"3")", "thinking_budget" } }) {
HttpResponse r = f.post("/v1/chat/completions",
@@ -2001,6 +2045,16 @@ TEST(a_thinking_budget_reaches_the_engine_or_is_refused_by_name) {
CHECK_EQ(json::parse(r.body)["error"]["param"].get<std::string>(), std::string(c.param));
}
{
HttpResponse r = f.post("/v1/chat/completions",
R"({"messages":[{"role":"user","content":"hi"}],
"reasoning_budget_tokens":-1})");
CHECK_EQ(r.status, 200);
f.sched.join_all();
std::lock_guard<std::mutex> lk(f.sched.mu);
CHECK_EQ(f.sched.last_sp.thinking_budget, -1);
}
Fixture multi;
multi.tmpl.think_close = "</t>";
multi.tmpl.think_starts_open = true;
@@ -2031,6 +2085,7 @@ TEST(the_deployment_s_thinking_budget_is_a_default_a_request_can_override) {
lim.default_thinking_budget = 64;
CHECK_EQ(chat_with(f, lim, "").sp.thinking_budget, 64);
CHECK_EQ(chat_with(f, lim, R"("thinking_token_budget":3)").sp.thinking_budget, 3);
CHECK_EQ(chat_with(f, lim, R"("reasoning_budget_tokens":-1)").sp.thinking_budget, -1);
CHECK_EQ(chat_with(f, f.limits(), "").sp.thinking_budget, -1);
f.tmpl.think_close.clear();
@@ -3185,4 +3240,739 @@ TEST(a_429_carries_the_deployments_retry_after) {
srv.reset();
}
/* ================================================================== llama-server parity */
/* llama-server's spellings reach the engine as the fields they name, and two spellings of one
* field that disagree are refused. -1 is llama-server's "no limit": not the deployment's default
* (the fixture's is 32) and not a refusal. */
TEST(llama_server_spellings_reach_the_engine) {
Fixture f;
auto post = [&](const std::string& extra) {
HttpResponse r = f.post("/v1/chat/completions",
R"({"messages":[{"role":"user","content":"hi"}])" + extra + "}");
f.sched.join_all();
return r;
};
CHECK_EQ(post(R"(,"repeat_penalty":1.25,"n_predict":5)").status, 200);
{
std::lock_guard<std::mutex> lk(f.sched.mu);
CHECK_NEAR(f.sched.last_sp.rep_penalty, 1.25, 1e-6);
CHECK_EQ(f.sched.last_max_tokens, 5);
}
CHECK_EQ(post(R"(,"repeat_penalty":1.2,"repetition_penalty":1.3)").status, 400);
CHECK_EQ(post(R"(,"max_tokens":4,"n_predict":5)").status, 400);
CHECK_EQ(post("").status, 200);
{ std::lock_guard<std::mutex> lk(f.sched.mu); CHECK_EQ(f.sched.last_max_tokens, 32); }
CHECK_EQ(post(R"(,"max_tokens":-1)").status, 200);
{ std::lock_guard<std::mutex> lk(f.sched.mu); CHECK(f.sched.last_max_tokens != 32); }
CHECK_EQ(post(R"(,"max_tokens":0)").status, 400);
}
/* `samplers`: a stage left out is off, temperature after the cuts sets temp_last, and an order
* the chain cannot run is refused by name -- as is a sampler it does not have. */
TEST(the_sampler_order_is_honoured_or_refused) {
Fixture f;
auto post = [&](const std::string& extra) {
HttpResponse r = f.post("/v1/chat/completions",
R"({"messages":[{"role":"user","content":"hi"}],"temperature":1.5,)"
R"("top_p":0.5,"top_k":40)" + extra + "}");
f.sched.join_all();
return r;
};
CHECK_EQ(post(R"(,"samplers":"kpt")").status, 200);
{ std::lock_guard<std::mutex> lk(f.sched.mu); CHECK(f.sched.last_sp.temp_last); }
CHECK_EQ(post(R"(,"samplers":["top_k","temperature","top_p"])").status, 200);
{ std::lock_guard<std::mutex> lk(f.sched.mu); CHECK(!f.sched.last_sp.temp_last); }
/* llama.cpp's default list, typ_p before top_p: typical is off, so its place is free. */
CHECK_EQ(post(R"(,"samplers":["penalties","dry","top_n_sigma","top_k","typ_p","top_p","min_p","xtc","temperature"])").status, 200);
{ std::lock_guard<std::mutex> lk(f.sched.mu); CHECK(f.sched.last_sp.temp_last); }
CHECK_EQ(post(R"(,"samplers":["top_p"])").status, 200);
{
std::lock_guard<std::mutex> lk(f.sched.mu);
CHECK_EQ(f.sched.last_sp.top_k, 0); /* left out: off */
CHECK_NEAR(f.sched.last_sp.temp, 1.0, 1e-6);
}
HttpResponse bad = post(R"(,"min_p":0.1,"samplers":["top_p","temperature","min_p"])");
CHECK_EQ(bad.status, 400);
CHECK_EQ(json::parse(bad.body)["error"]["param"].get<std::string>(), std::string("samplers"));
CHECK_EQ(post(R"(,"samplers":["infill"])").status, 400);
}
/* OpenRouter's session_id travels to the engine as the conversation's label, and nothing else. */
TEST(the_session_id_labels_the_request) {
Fixture f;
CHECK_EQ(f.post("/v1/chat/completions",
R"({"messages":[{"role":"user","content":"hi"}],"session_id":"conv-7"})").status,
200);
f.sched.join_all();
std::lock_guard<std::mutex> lk(f.sched.mu);
CHECK_EQ(f.sched.last_label, std::string("conv-7"));
}
/* ASSISTANT PREFILL: a conversation ending in an assistant message is continued unless the
* request asks for a generation prompt; asking for both explicitly is refused. */
TEST(a_trailing_assistant_message_is_continued) {
Fixture f;
const std::string msgs =
R"("messages":[{"role":"user","content":"hi"},{"role":"assistant","content":"The"}])";
CHECK_EQ(f.post("/v1/chat/completions", "{" + msgs + "}").status, 200);
CHECK_EQ(f.tmpl.last_opt.continue_final, std::string("auto"));
CHECK(!f.tmpl.last_opt.add_generation_prompt);
CHECK_EQ(f.post("/v1/chat/completions",
"{" + msgs + R"(,"continue_final_message":"content"})").status, 200);
CHECK_EQ(f.tmpl.last_opt.continue_final, std::string("content"));
CHECK_EQ(f.post("/v1/chat/completions",
"{" + msgs + R"(,"add_generation_prompt":true})").status, 200);
CHECK(f.tmpl.last_opt.continue_final.empty());
CHECK(f.tmpl.last_opt.add_generation_prompt);
CHECK_EQ(f.post("/v1/chat/completions",
"{" + msgs + R"(,"continue_final_message":true,"add_generation_prompt":true})")
.status, 400);
CHECK_EQ(f.post("/v1/chat/completions",
R"({"messages":[{"role":"user","content":"hi"}],"continue_final_message":true})")
.status, 400);
f.sched.join_all();
}
/* The deprecated functions API, llama-server's json_schema and reasoning_format reach the
* template as the fields they spell. */
TEST(older_and_llama_server_chat_spellings_reach_the_template) {
Fixture f;
CHECK_EQ(f.post("/v1/chat/completions",
R"({"messages":[{"role":"user","content":"hi"}],
"functions":[{"name":"f","parameters":{"type":"object"}}]})").status, 200);
CHECK_EQ(f.tmpl.last_n_tools, 1);
CHECK_EQ(f.post("/v1/chat/completions",
R"({"messages":[{"role":"user","content":"hi"}],"functions":[],"tools":[]})")
.status, 400);
CHECK_EQ(f.post("/v1/chat/completions",
R"({"messages":[{"role":"user","content":"hi"}],"reasoning_format":"none"})")
.status, 200);
CHECK_EQ(f.tmpl.last_opt.reasoning_format, std::string("none"));
CHECK_EQ(f.post("/v1/chat/completions",
R"({"messages":[{"role":"user","content":"hi"}],
"reasoning_format":"deepseek-legacy"})").status, 400);
/* The fake template makes no grammar of a schema, so this one is refused after the render;
* what is checked is that the schema reached it. */
(void)f.post("/v1/chat/completions",
R"({"messages":[{"role":"user","content":"hi"}],"json_schema":{"type":"object"}})");
CHECK_EQ(f.tmpl.last_opt.json_schema, std::string(R"({"type":"object"})"));
f.sched.join_all();
}
/* The routes llama-server answers and this server now does too: without /v1, the token count,
* the rendered prompt, and llama-server's /tokenize and /detokenize shapes. */
TEST(llama_server_routes_answer) {
Fixture f;
CHECK_EQ(f.post("/chat/completions", R"({"messages":[{"role":"user","content":"hi"}]})").status,
200);
CHECK_EQ(f.post("/completions", R"({"prompt":"ab"})").status, 200);
CHECK_EQ(f.get("/models").status, 200);
CHECK_EQ(f.get("/v1/health").status, 200);
f.sched.join_all();
HttpResponse at = f.post("/apply-template", R"({"messages":[{"role":"user","content":"hi"}]})");
CHECK_EQ(at.status, 200);
const std::string prompt = json::parse(at.body).value("prompt", std::string());
CHECK(has(prompt, "<user>hi"));
HttpResponse it = f.post("/v1/chat/completions/input_tokens",
R"({"messages":[{"role":"user","content":"hi"}]})");
CHECK_EQ(it.status, 200);
CHECK_EQ(json::parse(it.body).value("input_tokens", (int64_t)-1), (int64_t)prompt.size());
HttpResponse t = f.post("/tokenize", R"({"content":["ab",7]})");
CHECK_EQ(t.status, 200);
CHECK(json::parse(t.body)["tokens"] == json::array({ 97, 98, 7 }));
HttpResponse tp = f.post("/tokenize", R"({"content":"a","with_pieces":true})");
CHECK_EQ(json::parse(tp.body)["tokens"][0].value("piece", std::string()), std::string("a"));
HttpResponse d = f.post("/detokenize", R"({"tokens":[104,105]})");
CHECK_EQ(json::parse(d.body).value("content", std::string()), std::string("hi"));
CHECK_EQ(json::parse(d.body).value("prompt", std::string()), std::string("hi"));
const json p = json::parse(f.get("/props").body);
CHECK_EQ(p.value("role", std::string()), std::string("model"));
CHECK(p["default_generation_settings"]["params"]["samplers"].is_array());
CHECK_EQ(p["default_generation_settings"]["params"].value("mirostat", -1), 0);
}
/* A prompt the context cannot hold names itself in both of the phrasings the agents that compact
* on overflow look for, with llama-server's two numbers beside OpenAI's code. */
TEST(an_overflow_reads_as_one_to_the_clients_that_compact) {
FakeScheduler sched;
FakeTokenizer tok;
FakeChatTemplate tmpl;
FakeGrammar gram;
Deps d;
d.sched = &sched;
d.tok = &tok;
d.chat = &tmpl;
d.grammar = &gram;
ServerOptions o;
o.model_id = "test-model";
o.max_ctx = 8;
Server srv(d, o);
HttpResponse r = srv.router().call("POST", "/v1/chat/completions",
R"({"messages":[{"role":"user","content":"a long prompt"}]})");
CHECK_EQ(r.status, 400);
const json e = json::parse(r.body)["error"];
CHECK_EQ(e.value("code", std::string()), std::string("context_length_exceeded"));
CHECK(has(e.value("message", std::string()), "maximum context length is 8 tokens"));
CHECK(has(e.value("message", std::string()), "exceeds the available context size"));
CHECK_EQ(e.value("n_ctx", (int64_t)0), (int64_t)8);
CHECK(e.value("n_prompt_tokens", (int64_t)0) > 8);
sched.join_all();
}
/* ================================================================== Anthropic's Messages API */
/* The translation is the chat request the Anthropic one means: the system blocks as one system
* message with Claude Code's billing stamp held still, a tool result as a tool message ahead of
* the user's own words, the tools and the choice, thinking, stop sequences and the label. */
TEST(an_anthropic_request_becomes_the_chat_request_it_means) {
OaiLimits lim;
std::string chat, label;
ApiError e;
CHECK_OK(anthropic_to_chat(R"({
"model":"x","max_tokens":9,"stop_sequences":["END"],
"system":[{"type":"text","text":"x-anthropic-billing-header: cc_version=1; cch=a5145;"},
{"type":"text","text":"Be terse.","cache_control":{"type":"ephemeral"}}],
"metadata":{"user_id":"user_1_session_9"},
"thinking":{"type":"disabled"},
"tools":[{"name":"get","description":"d","input_schema":{"type":"object"}}],
"tool_choice":{"type":"any","disable_parallel_tool_use":true},
"messages":[
{"role":"user","content":"weather?"},
{"role":"assistant","content":[{"type":"text","text":"Looking."},
{"type":"tool_use","id":"t1","name":"get","input":{"c":"P"}}]},
{"role":"user","content":[{"type":"tool_result","tool_use_id":"t1","content":"sun"},
{"type":"text","text":"thanks"}]}]})",
lim, &chat, &label, &e));
const json c = json::parse(chat);
CHECK_EQ(c["messages"][0].value("role", ""), std::string("system"));
CHECK(has(c["messages"][0].value("content", ""), "cch=fffff;"));
CHECK(has(c["messages"][0].value("content", ""), "Be terse."));
CHECK_EQ(c["messages"][2]["tool_calls"][0]["function"].value("arguments", ""),
std::string(R"({"c":"P"})"));
CHECK_EQ(c["messages"][3].value("role", ""), std::string("tool")); /* result first */
CHECK_EQ(c["messages"][3].value("tool_call_id", ""), std::string("t1"));
CHECK_EQ(c["messages"][4].value("role", ""), std::string("user")); /* then the words */
CHECK_EQ(c.value("tool_choice", ""), std::string("required"));
CHECK(!c.value("parallel_tool_calls", true));
CHECK(!c.value("enable_thinking", true));
CHECK_EQ(c["stop"][0].get<std::string>(), std::string("END"));
CHECK_EQ(label, std::string("user_1_session_9"));
/* What would change the answer and cannot be served is refused, by name. */
CHECK(anthropic_to_chat(R"({"messages":[{"role":"user","content":[{"type":"document"}]}]})",
lim, &chat, &label, &e) < 0);
CHECK(anthropic_to_chat(R"({"messages":[{"role":"user","content":"x"}],
"tools":[{"type":"web_search_20250305","name":"web_search"}]})",
lim, &chat, &label, &e) < 0);
}
/* The answer and the errors in Anthropic's shapes, through the server. */
TEST(the_messages_api_answers_in_anthropics_shapes) {
Fixture f;
HttpResponse r = f.post("/v1/messages",
R"({"model":"x","max_tokens":16,"messages":[{"role":"user","content":"hi"}]})");
CHECK_EQ(r.status, 200);
const json m = json::parse(r.body);
CHECK_EQ(m.value("type", ""), std::string("message"));
CHECK(has(m.value("id", ""), "msg_"));
CHECK_EQ(m["content"][0].value("type", ""), std::string("text"));
CHECK_EQ(m["content"][0].value("text", ""), std::string("hello"));
CHECK_EQ(m.value("stop_reason", ""), std::string("end_turn"));
CHECK(m["usage"].contains("input_tokens") && m["usage"].contains("output_tokens"));
f.sched.join_all();
HttpResponse bad = f.post("/v1/messages", R"({"model":"x","max_tokens":16})");
CHECK_EQ(bad.status, 400);
const json e = json::parse(bad.body);
CHECK_EQ(e.value("type", ""), std::string("error"));
CHECK_EQ(e["error"].value("type", ""), std::string("invalid_request_error"));
HttpResponse n = f.post("/v1/messages/count_tokens",
R"({"model":"x","messages":[{"role":"user","content":"hi"}]})");
CHECK_EQ(n.status, 200);
CHECK(json::parse(n.body).value("input_tokens", (int64_t)0) > 0);
/* The stream: message_start, a text block opened, filled and stopped, then message_delta
* and message_stop -- and no [DONE]. */
HttpResponse s = f.post("/v1/messages", R"({"model":"x","max_tokens":16,"stream":true,
"messages":[{"role":"user","content":"hi"}]})");
CHECK_EQ(s.status, 200);
const std::string body = drain(s);
std::vector<std::string> types;
for (size_t at = 0; (at = body.find("event: ", at)) != std::string::npos;) {
const size_t nl = body.find('\n', at);
types.push_back(body.substr(at + 7, nl - at - 7));
at = nl;
}
CHECK(!types.empty() && types.front() == "message_start");
CHECK(types.size() >= 2 && types.back() == "message_stop");
CHECK(std::find(types.begin(), types.end(), "content_block_start") != types.end());
CHECK(std::find(types.begin(), types.end(), "message_delta") != types.end());
CHECK(!has(body, "[DONE]"));
f.sched.join_all();
}
/* ================================================================== OpenAI's Responses API */
/* The translation: instructions as the system message, input items as the turns they are --
* a reasoning item and a call joined into one assistant turn, the call's output as a tool message
* -- function tools only, max_output_tokens, reasoning.effort, text.format, and every field the
* Responses API does not define passed through. */
TEST(a_responses_request_becomes_the_chat_request_it_means) {
OaiLimits lim;
std::string chat, echo;
ApiError e;
CHECK_OK(responses_to_chat(R"({
"model":"m","instructions":"Be terse.","max_output_tokens":7,
"reasoning":{"effort":"low"},"top_k":5,
"text":{"format":{"type":"json_schema","name":"a","schema":{"type":"object"}}},
"tools":[{"type":"function","name":"get","parameters":{"type":"object"}},
{"type":"web_search"}],
"input":[
{"role":"user","content":"weather?"},
{"type":"reasoning","summary":[],"content":[{"type":"reasoning_text","text":"think"}]},
{"type":"function_call","call_id":"c1","name":"get","arguments":"{}"},
{"type":"function_call_output","call_id":"c1","output":"sun"}]})",
lim, &chat, &echo, &e));
const json c = json::parse(chat);
CHECK_EQ(c["messages"][0].value("role", ""), std::string("system"));
CHECK_EQ(c["messages"][1].value("role", ""), std::string("user"));
CHECK_EQ(c["messages"][2].value("reasoning_content", ""), std::string("think"));
CHECK_EQ(c["messages"][2]["tool_calls"][0].value("id", ""), std::string("c1"));
CHECK_EQ(c["messages"][3].value("role", ""), std::string("tool"));
CHECK_EQ(c["tools"].size(), (size_t)1); /* web_search left out */
CHECK_EQ(c.value("max_tokens", 0), 7);
CHECK_EQ(c.value("reasoning_effort", ""), std::string("low"));
CHECK_EQ(c.value("top_k", 0), 5); /* passed through */
CHECK_EQ(c["response_format"].value("type", ""), std::string("json_schema"));
CHECK(!c.contains("input") && !c.contains("text") && !c.contains("instructions"));
CHECK_EQ(json::parse(echo).value("instructions", ""), std::string("Be terse."));
CHECK(responses_to_chat(R"({"input":"x","previous_response_id":"resp_1"})", lim, &chat,
&echo, &e) < 0);
}
TEST(the_responses_api_answers_with_a_response_object_and_its_events) {
Fixture f;
HttpResponse r = f.post("/v1/responses", R"({"model":"m","input":"hi"})");
CHECK_EQ(r.status, 200);
const json o = json::parse(r.body);
CHECK_EQ(o.value("object", ""), std::string("response"));
CHECK(has(o.value("id", ""), "resp_"));
CHECK_EQ(o.value("status", ""), std::string("completed"));
CHECK_EQ(o["output"][0].value("type", ""), std::string("message"));
CHECK_EQ(o["output"][0]["content"][0].value("text", ""), std::string("hello"));
CHECK(o["usage"].contains("total_tokens"));
f.sched.join_all();
HttpResponse n = f.post("/v1/responses/input_tokens", R"({"model":"m","input":"hi"})");
CHECK_EQ(json::parse(n.body).value("object", ""), std::string("response.input_tokens"));
HttpResponse s = f.post("/v1/responses", R"({"model":"m","input":"hi","stream":true})");
const std::string body = drain(s);
std::vector<std::string> types;
int64_t last_seq = -1;
bool ordered = true;
for (size_t at = 0; (at = body.find("data: ", at)) != std::string::npos;) {
const size_t nl = body.find('\n', at);
const json ev = json::parse(body.substr(at + 6, nl - at - 6), nullptr, false);
at = nl;
if (!ev.is_object()) continue;
types.push_back(ev.value("type", ""));
const int64_t q = ev.value("sequence_number", (int64_t)-1);
ordered = ordered && q == last_seq + 1;
last_seq = q;
}
CHECK(ordered);
CHECK(!types.empty() && types.front() == "response.created");
CHECK(!types.empty() && types.back() == "response.completed");
CHECK(std::find(types.begin(), types.end(), "response.output_text.delta") != types.end());
CHECK(!has(body, "[DONE]"));
f.sched.join_all();
}
/* ================================================================== llama-server's native shape */
/* /completion and /completions answer llama-server's native result: the text, how it ended, the
* counts, the settings it ran with -- with the generated ids when asked -- and a prompt of strings
* and ids mixed is one prompt. */
TEST(the_native_completion_answers_in_llama_servers_shape) {
Fixture f;
HttpResponse r = f.post("/completion", R"({"prompt":["a",98],"n_predict":10,"return_tokens":true})");
CHECK_EQ(r.status, 200);
const json o = json::parse(r.body);
CHECK_EQ(o.value("content", ""), std::string("hello"));
CHECK(o.value("stop", false));
CHECK_EQ(o.value("stop_type", ""), std::string("eos"));
CHECK_EQ(o.value("tokens_evaluated", (int64_t)0), (int64_t)2); /* 'a' and 98: one prompt */
CHECK_EQ(o["tokens"].size(), (size_t)5);
CHECK(o.contains("generation_settings") && o["generation_settings"].contains("samplers"));
f.sched.join_all();
/* The stream: chunks with the ids that made them, a final result, no [DONE]. */
HttpResponse s = f.post("/completions", R"({"prompt":"ab","stream":true})");
const std::string body = drain(s);
CHECK(has(body, "\"tokens\":["));
CHECK(has(body, "\"stop\":true"));
CHECK(!has(body, "[DONE]"));
f.sched.join_all();
/* return_tokens is the native endpoint's own; elsewhere it is guarded at its off value. */
CHECK_EQ(f.post("/v1/completions", R"({"prompt":"ab","return_tokens":true})").status, 400);
}
/* ================================================================== logprobs */
/* A sink carries each token's alternatives beside it, for a request that enabled them. */
TEST(the_sink_carries_a_tokens_alternatives) {
Sink s(16);
s.enable_logprobs(3);
TokenLogprobs lp;
lp.logprob = -0.5f;
lp.n_top = 2;
lp.top_id[0] = 7; lp.top_lp[0] = -0.1f;
lp.top_id[1] = 9; lp.top_lp[1] = -2.0f;
CHECK(s.push(5, &lp));
CHECK(s.push(6));
SinkToken buf[4];
SinkAlt alts[4 * 3];
CHECK_EQ((long long)s.read(buf, 4, alts), 2LL);
CHECK_EQ(buf[0].token, 5);
CHECK_EQ(buf[0].logprob, -0.5f);
CHECK_EQ(buf[0].n_alt, 2);
CHECK_EQ(alts[0].id, 7);
CHECK_EQ(alts[1].id, 9);
CHECK_EQ(alts[1].logprob, -2.0f);
CHECK_EQ(buf[1].n_alt, 0);
}
/* Chat: `logprobs` and `top_logprobs` reach the sampler as n_probs, and every token comes back in
* OpenAI's shape with llama-server's id beside it. */
TEST(chat_logprobs_come_back_per_token_with_their_alternatives) {
Fixture f(true, 0, "", true);
f.sched.reply = "abc";
HttpResponse r = f.post("/v1/chat/completions",
R"({"messages":[{"role":"user","content":"hi"}],
"logprobs":true,"top_logprobs":2})");
CHECK_EQ(r.status, 200);
CHECK_EQ(f.sched.last_sp.n_probs, 2);
const json c = json::parse(r.body)["choices"][0]["logprobs"]["content"];
CHECK_EQ(c.size(), (size_t)3);
CHECK_EQ(c[1]["token"].get<std::string>(), std::string("b"));
CHECK_EQ(c[1]["id"].get<int>(), (int)'b');
CHECK_EQ(c[1]["logprob"].get<float>(), -0.5f);
CHECK_EQ(c[1]["bytes"][0].get<int>(), (int)'b');
CHECK_EQ(c[1]["top_logprobs"].size(), (size_t)2);
CHECK_EQ(c[1]["top_logprobs"][1]["token"].get<std::string>(), std::string("y"));
CHECK_EQ(c[1]["top_logprobs"][1]["logprob"].get<float>(), -2.0f);
f.sched.join_all();
/* `logprobs` alone is the token's own and no alternatives -- OpenAI's default of 0. */
HttpResponse z = f.post("/v1/chat/completions",
R"({"messages":[{"role":"user","content":"hi"}],"logprobs":true})");
CHECK_EQ(f.sched.last_sp.n_probs, 0);
const json zc = json::parse(z.body)["choices"][0]["logprobs"]["content"];
CHECK_EQ(zc.size(), (size_t)3);
CHECK(zc[0]["top_logprobs"].empty());
f.sched.join_all();
/* Streamed: each token's entry rides a chunk, and together they are the reply's. */
HttpResponse s = f.post("/v1/chat/completions",
R"({"messages":[{"role":"user","content":"hi"}],"stream":true,
"logprobs":true,"top_logprobs":1})");
const std::string body = drain(s);
size_t n = 0;
for (size_t at = body.find("data: {"); at != std::string::npos;
at = body.find("data: {", at + 1)) {
const json ev = json::parse(body.substr(at + 6, body.find("\n\n", at) - at - 6));
const json& ch = ev["choices"][0];
if (ch.contains("logprobs") && ch["logprobs"].is_object())
n += ch["logprobs"]["content"].size();
}
CHECK_EQ(n, (size_t)3);
f.sched.join_all();
}
TEST(logprobs_are_refused_out_of_range_and_with_echo) {
Fixture f(true, 0, "", true);
CHECK_EQ(f.post("/v1/chat/completions",
R"({"messages":[{"role":"user","content":"hi"}],"logprobs":true,
"top_logprobs":21})").status, 400);
CHECK_EQ(f.post("/v1/chat/completions",
R"({"messages":[{"role":"user","content":"hi"}],"top_logprobs":2})").status,
400);
CHECK_EQ(f.post("/v1/completions", R"({"prompt":"hi","logprobs":2,"echo":true})").status,
400);
CHECK_EQ(f.post("/completion", R"({"prompt":"hi","n_probs":2,"post_sampling_probs":true})")
.status, 400);
}
/* Legacy completions: OpenAI's parallel arrays, with llama-server's content array beside them. */
TEST(completion_logprobs_have_the_legacy_shape) {
Fixture f(true, 0, "", true);
f.sched.reply = "abc";
HttpResponse r = f.post("/v1/completions", R"({"prompt":"hi","logprobs":2})");
CHECK_EQ(r.status, 200);
const json lp = json::parse(r.body)["choices"][0]["logprobs"];
CHECK_EQ(lp["tokens"].size(), (size_t)3);
CHECK_EQ(lp["tokens"][2].get<std::string>(), std::string("c"));
CHECK_EQ(lp["token_logprobs"][2].get<float>(), -0.75f);
CHECK_EQ(lp["top_logprobs"][0]["x"].get<float>(), -1.0f);
CHECK_EQ(lp["text_offset"][2].get<int>(), 2);
CHECK_EQ(lp["content"].size(), (size_t)3);
f.sched.join_all();
}
/* A stop string's own tokens never went out, so their logprobs do not either. */
TEST(logprobs_end_where_the_stop_string_cut_the_reply) {
Fixture f(true, 0, "", true);
f.sched.reply = "abXYc";
HttpResponse r = f.post("/v1/completions", R"({"prompt":"hi","logprobs":1,"stop":["XY"]})");
const json o = json::parse(r.body)["choices"][0];
CHECK_EQ(o["text"].get<std::string>(), std::string("ab"));
CHECK_EQ(o["logprobs"]["tokens"].size(), (size_t)2);
f.sched.join_all();
}
/* llama-server's native n_probs: completion_probabilities on the answer, and on each streamed
* chunk instead when streaming. */
TEST(native_n_probs_return_completion_probabilities) {
Fixture f(true, 0, "", true);
f.sched.reply = "ab";
HttpResponse r = f.post("/completion", R"({"prompt":"hi","n_probs":3})");
CHECK_EQ(r.status, 200);
const json o = json::parse(r.body);
CHECK_EQ(o["completion_probabilities"].size(), (size_t)2);
CHECK_EQ(o["completion_probabilities"][0]["top_logprobs"].size(), (size_t)3);
CHECK_EQ(o["completion_probabilities"][0]["id"].get<int>(), (int)'a');
CHECK_EQ(o["generation_settings"]["n_probs"].get<int>(), 3);
f.sched.join_all();
HttpResponse s = f.post("/completion", R"({"prompt":"hi","n_probs":1,"stream":true})");
const std::string body = drain(s);
CHECK(has(body, "\"completion_probabilities\":[{"));
f.sched.join_all();
}
/* A model with no fill-in-the-middle tokens -- the fixture's -- cannot infill, and says so. */
TEST(infill_without_fim_tokens_is_refused_by_name) {
Fixture f;
HttpResponse r = f.post("/infill", R"({"input_prefix":"def f():\n ","input_suffix":"\n"})");
CHECK_EQ(r.status, 501);
CHECK(has(r.body, "fill-in-the-middle"));
}
/* With the markers, a fill is served; a field of the wrong type, or a body nested past the
* bound every generation endpoint holds, is a 400. */
TEST(infill_serves_a_fill_and_refuses_a_malformed_body) {
Fixture f;
f.tok.fim = true;
CHECK_EQ(f.post("/infill", R"({"input_prefix":"a","input_suffix":"b",
"input_extra":[{"filename":"x.py","text":"y"}]})").status, 200);
f.sched.join_all();
for (const char* body : { R"({"input_prefix":"a","n_predict":"many"})",
R"({"input_prefix":"a","max_tokens":1.5})",
R"({"input_prefix":"a","input_extra":[{"filename":5}]})",
R"({"input_prefix":"a","input_extra":[{"text":["y"]}]})" })
CHECK_EQ(f.post("/infill", body).status, 400);
const std::string deep = R"({"input_prefix":"a","input_extra":)" + std::string(2000, '[') +
std::string(2000, ']') + "}";
CHECK_EQ(f.post("/infill", deep).status, 400);
}
/* ================================================================== malformed and failed */
/* A FIELD OF THE WRONG TYPE is a 400 naming it on every API, never a 500: the translators read
* the client's fields before the chat parser checks them, and the chat parser reads a few before
* its own validation. */
TEST(a_field_of_the_wrong_type_is_a_400_on_every_api) {
Fixture f;
struct Case { const char* path; const char* body; const char* param; };
for (const Case& c : {
Case{ "/v1/messages", R"({"model":"x","max_tokens":9,"messages":[{"role":1,"content":"hi"}]})",
"messages[].role" },
Case{ "/v1/messages", R"({"model":"x","max_tokens":9,"messages":[{"role":"user",
"content":[{"type":"text","text":5}]}]})", "messages[].content[].text" },
Case{ "/v1/messages", R"({"model":"x","max_tokens":9,"messages":[{"role":"user",
"content":[{"type":"image","source":"x"}]}]})", "messages[].content[].source" },
Case{ "/v1/messages", R"({"model":"x","max_tokens":9,"system":[{"type":"text","text":[]}],
"messages":[{"role":"user","content":"hi"}]})", "system[].text" },
Case{ "/v1/messages", R"({"model":"x","max_tokens":9,"tool_choice":{"type":"auto",
"disable_parallel_tool_use":"yes"},"messages":[{"role":"user","content":"hi"}]})",
"disable_parallel_tool_use" },
Case{ "/v1/chat/completions", R"({"messages":["x",{"role":"assistant","content":"hi"}]})",
"messages[]" },
Case{ "/v1/chat/completions", R"({"messages":[{"role":"user",
"content":[{"type":"text","text":5}]}]})", "messages[].content[].text" },
Case{ "/v1/responses", R"({"input":[{"type":5}]})", "input[].type" },
Case{ "/v1/responses", R"({"input":[{"role":"user","content":[{"type":"input_text",
"text":5}]}]})", "input[].content[].text" },
Case{ "/v1/responses", R"({"input":[{"type":"function_call","name":"f","arguments":{}}]})",
"input[].arguments" },
Case{ "/v1/responses", R"({"input":"hi","tool_choice":{"type":"function","name":7}})",
"tool_choice.name" } }) {
HttpResponse r = f.post(c.path, c.body);
CHECK_EQ(r.status, 400);
const json e = json::parse(r.body, nullptr, false);
CHECK(e.is_object() && e.contains("error"));
if (e.is_object() && e["error"].contains("param"))
CHECK_EQ(e["error"]["param"].get<std::string>(), std::string(c.param));
else
CHECK(has(r.body, c.param));
}
}
/* A STREAM THE ENGINE FAILED ends in its API's own failure, never in its success event: a
* client that stops reading at the terminal event must not take the partial reply as whole. */
TEST(a_failed_stream_ends_in_its_apis_own_failure) {
Fixture f;
f.sched.reply = "he";
f.sched.fail_status = RAD_E_UNSUPPORTED;
f.sched.fail_why = "boom";
HttpResponse a = f.post("/v1/messages", R"({"model":"x","max_tokens":16,"stream":true,
"messages":[{"role":"user","content":"hi"}]})");
const std::string ab = drain(a);
CHECK(has(ab, "event: error\ndata: {\"type\":\"error\""));
CHECK(has(ab, "boom"));
CHECK(!has(ab, "message_delta"));
CHECK(!has(ab, "message_stop"));
f.sched.join_all();
HttpResponse r = f.post("/v1/responses", R"({"model":"m","input":"hi","stream":true})");
const std::string rb = drain(r);
CHECK(has(rb, "event: response.failed"));
CHECK(has(rb, "\"status\":\"failed\""));
CHECK(has(rb, "boom"));
CHECK(!has(rb, "response.completed"));
f.sched.join_all();
HttpResponse c = f.post("/v1/chat/completions", R"({"stream":true,
"messages":[{"role":"user","content":"hi"}]})");
const std::string cb = drain(c);
CHECK(has(cb, "\"finish_reason\":\"error\""));
CHECK(has(cb, "boom"));
f.sched.join_all();
}
/* ================================================================== the functions API */
/* OpenAI's DEPRECATED functions API end to end: the reply's call is `function_call` with
* finish_reason "function_call", streamed and not, one call at most; and the next turn -- the
* assistant's function_call and the `function` message with its result -- is served. */
TEST(the_functions_api_answers_and_continues_in_its_own_shape) {
Fixture f;
f.sched.reply = R"(TOOL:get:{"c":"P"})";
const std::string fns = R"("functions":[{"name":"get","parameters":{"type":"object"}}],)";
HttpResponse r = f.post("/v1/chat/completions",
"{" + fns + R"("messages":[{"role":"user","content":"weather?"}]})");
CHECK_EQ(r.status, 200);
CHECK(!f.tmpl.last_opt.parallel_tool_calls);
const json c = json::parse(r.body)["choices"][0];
CHECK_EQ(c["finish_reason"].get<std::string>(), std::string("function_call"));
CHECK_EQ(c["message"]["function_call"]["name"].get<std::string>(), std::string("get"));
CHECK_EQ(c["message"]["function_call"]["arguments"].get<std::string>(),
std::string(R"({"c":"P"})"));
CHECK(!c["message"].contains("tool_calls"));
f.sched.join_all();
HttpResponse s = f.post("/v1/chat/completions",
"{" + fns + R"("stream":true,"messages":[{"role":"user","content":"w"}]})");
const std::string body = drain(s);
CHECK(has(body, R"("delta":{"function_call":{"name":"get","arguments":""}})"));
CHECK(has(body, R"("finish_reason":"function_call")"));
CHECK(!has(body, "tool_calls"));
f.sched.join_all();
f.sched.reply = "sunny";
HttpResponse t = f.post("/v1/chat/completions", "{" + fns + R"("messages":[
{"role":"user","content":"weather?"},
{"role":"assistant","content":null,"function_call":{"name":"get","arguments":"{\"c\":\"P\"}"}},
{"role":"function","name":"get","content":"sun"}]})");
CHECK_EQ(t.status, 200);
CHECK_EQ(json::parse(t.body)["choices"][0]["message"]["content"].get<std::string>(),
std::string("sunny"));
f.sched.join_all();
}
/* ================================================================== odds and ends */
/* What the Responses API cannot carry is refused rather than computed and dropped: several
* choices, and logprobs in any spelling. The chat stream's own extras are dropped. */
TEST(the_responses_api_refuses_what_a_response_cannot_carry) {
Fixture f(true, 0, "", true);
for (const char* extra : { R"("n":2)", R"("logprobs":true)", R"("top_logprobs":3)",
R"("n_probs":2)", R"("include":["message.output_text.logprobs"])" })
CHECK_EQ(f.post("/v1/responses", std::string(R"({"input":"hi",)") + extra + "}").status, 400);
HttpResponse ok = f.post("/v1/responses", R"({"input":"hi","stream":true,"return_progress":true,
"stream_options":{"include_usage":true},
"include":["reasoning.encrypted_content"]})");
CHECK_EQ(ok.status, 200);
const std::string body = drain(ok);
CHECK(!has(body, "chat.completion.chunk"));
CHECK(has(body, "response.completed"));
f.sched.join_all();
}
/* text_offset is where each token's text starts in the reply, streamed or not, even where a token
* carries half a character and its own text is empty. */
TEST(text_offset_is_the_same_streamed_and_not_past_a_split_character) {
Fixture f(true, 0, "", true);
f.sched.reply = "a\xC3\xA9" "b";
HttpResponse r = f.post("/v1/completions", R"({"prompt":"hi","logprobs":1})");
CHECK_EQ(r.status, 200);
const json want = json::array({ 0, 1, 2, 3 });
CHECK(json::parse(r.body)["choices"][0]["logprobs"]["text_offset"] == want);
f.sched.join_all();
HttpResponse s = f.post("/v1/completions", R"({"prompt":"hi","logprobs":1,"stream":true})");
json got = json::array();
int bad = 0;
for (const std::string& p : sse_payloads(drain(s), &bad)) {
if (p == "[DONE]") continue;
const json j = json::parse(p);
const json& lp = j["choices"][0]["logprobs"];
if (lp.is_object()) for (const json& o : lp["text_offset"]) got.push_back(o);
}
CHECK_EQ(bad, 0);
CHECK(got == want);
f.sched.join_all();
}
/* A piece that is not whole UTF-8 goes as its bytes, 0 to 255, as llama-server sends it. */
TEST(tokenize_pieces_carry_bytes_unsigned) {
Fixture f;
HttpResponse r = f.post("/tokenize", R"({"content":"\u00e9","with_pieces":true})");
CHECK_EQ(r.status, 200);
const json t = json::parse(r.body)["tokens"];
CHECK_EQ(t.size(), (size_t)2);
CHECK(t[0]["piece"] == json::array({ 0xC3 }));
CHECK(t[1]["piece"] == json::array({ 0xA9 }));
}
/* A conversation label is cut to 128 bytes where a character starts, so it stays text. */
TEST(a_long_session_label_is_cut_on_a_character) {
Fixture f;
const std::string id = std::string(127, 'a') + "\xC3\xA9";
CHECK_EQ(f.post("/v1/chat/completions", R"({"messages":[{"role":"user","content":"hi"}],
"session_id":")" + id + "\"}").status, 200);
f.sched.join_all();
std::lock_guard<std::mutex> lk(f.sched.mu);
CHECK_EQ(f.sched.last_label, std::string(127, 'a'));
}
/* Anthropic's reply names the model the request asked for, as Anthropic's does. */
TEST(the_messages_api_names_the_requested_model) {
Fixture f;
HttpResponse r = f.post("/v1/messages", R"({"model":"claude-x","max_tokens":4,
"messages":[{"role":"user","content":"hi"}]})");
CHECK_EQ(r.status, 200);
CHECK_EQ(json::parse(r.body).value("model", ""), std::string("claude-x"));
f.sched.join_all();
}
RAD_TEST_MAIN()
+10 -2
View File
@@ -546,11 +546,19 @@ TEST(a_text_completion_body_is_the_other_shape_entirely) {
/* THE LOGPROB SHAPES DIFFER BETWEEN THE TWO ENDPOINTS and both are fixed by the schema: chat
* nests an array of per-token objects under `content`, completions carries four parallel arrays.
* text_offset is cumulative over the token texts, which is what makes it an offset into `text`. */
* text_offset is where each token's text starts in `text`: where the token before it ended. */
TEST(logprobs_take_each_endpoints_own_shape) {
ChoiceOut c;
c.text = "abcd";
c.logprobs = { { 1, "ab", -0.5f }, { 2, "cd", -1.5f } };
auto entry = [](int32_t id, const char* t, float lp, size_t end) {
LogprobEntry e;
e.token = id;
e.text = e.bytes = t;
e.logprob = lp;
e.end = end;
return e;
};
c.logprobs = { entry(1, "ab", -0.5f, 2), entry(2, "cd", -1.5f, 4) };
OaiRequest r = a_request("x", "m");
r.want_logprobs = true;