Archived
The gemma4_bf16 architecture (sliding and global attention, the proportional RoPE ladder, the assistant head as a drafter that reads the trunk's cache, the vision tower), its w4a8 decode junctions, the h512/gqa8 and h256/gqa2 attention kernels, compressed-tensors int4 import, multi-EOS from generation_config, the call/reasoning reply format, a window group that keeps the keys a prefill chunk still reads, and window snapshots in checkpoint slots so a prefix hit on a sliding-window trunk resumes. Fixes on top: the investigation switches and diagnostic blocks out of the served paths; int4 import through the checkpoint import framework; attention_k_eq_v from the config; the fused junctions only where every reader takes their pair; a shared-KV head binds no group of its own; the compose file without HSA_ENABLE_IPC_MODE_LEGACY (TP2 fails with it on ROCm 10.1); a checkpoint carries a window only where a hit resumes from it; the README says the linked container is keptn42's calibrated GPTQ build and what the in-tree recipe gives.
This commit is contained in:
commit
7c7f755931
84 files changed
+10292
-230
No files matched your search
@@ -134,6 +134,7 @@ public:
|
||||
int declare_logits(rad_buf b);
|
||||
int declare_pooled(rad_buf b);
|
||||
int declare_drafter(const RadDrafterDecl* d);
|
||||
int drafter_shared_kv(int pos_offset);
|
||||
int declare_encoder(const RadEncoderDecl* d);
|
||||
void note_v (const char* f, va_list ap);
|
||||
|
||||
|
||||
@@ -1272,6 +1272,32 @@ int Builder::declare_drafter(const RadDrafterDecl* d) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* A SERIAL HEAD THAT READS THE TRUNK'S CACHE AND KEEPS NONE (rad_builder.h). Checked here for the
|
||||
* reason declare_drafter checks everything: the driver only reaches the head once a request
|
||||
* speculates, and a head staged the wrong way round costs acceptance and says nothing. */
|
||||
int Builder::drafter_shared_kv(int pos_offset) {
|
||||
if (finished_) {
|
||||
err(RAD_E_STATE, "drafter_shared_kv after declare finished");
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
if (prog_.drafter.kind != RAD_DRAFT_SERIAL) {
|
||||
err(RAD_E_STATE, "drafter_shared_kv: %s. Only a SERIAL head runs round after round at one "
|
||||
"position; declare it with rad_declare_drafter first.",
|
||||
prog_.drafter.kind == RAD_DRAFT_NONE ? "no drafter is declared"
|
||||
: "the declared drafter is a BLOCK drafter");
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
if (pos_offset != 0 && pos_offset != 1) {
|
||||
err(RAD_E_INVAL, "drafter_shared_kv '%s': pos_offset %d. The rows sit at the committed "
|
||||
"position (0) or one past it (1); nothing else names a position the head "
|
||||
"was trained at.", prog_.drafter_name.c_str(), pos_offset);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
prog_.drafter_shared_kv = true;
|
||||
prog_.drafter_pos_offset = pos_offset;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
void Builder::note_v(const char* f, va_list ap) {
|
||||
char msg[1024];
|
||||
vsnprintf(msg, sizeof msg, f ? f : "", ap);
|
||||
@@ -1522,6 +1548,8 @@ void Builder::finish_kv_groups() {
|
||||
default: break;
|
||||
}
|
||||
std::sort(gi.layers.begin(), gi.layers.end());
|
||||
gi.drafter = prog_.meta.n_layers > 0 && !gi.layers.empty() &&
|
||||
gi.layers.front() >= prog_.meta.n_layers;
|
||||
|
||||
/* A group nothing is bound to is a group the block manager cannot size: how many state
|
||||
* instances a sequence owns is the layer count, and assuming one would make the page size
|
||||
@@ -1628,6 +1656,19 @@ int Builder::finish() {
|
||||
finish_weight_uses();
|
||||
finish_layouts();
|
||||
finish_kv_groups();
|
||||
/* A HEAD DECLARED TO KEEP NO CACHE OF ITS OWN (rad_drafter_shared_kv) is given no history pass:
|
||||
* the scheduler owes it none. A KV group bound at one of its layers -- meta.n_layers and above
|
||||
* are the drafter's -- would then be read without anything ever having written it. */
|
||||
if (prog_.drafter_shared_kv)
|
||||
for (size_t g = 1; g < prog_.kv_groups.size(); ++g)
|
||||
for (int l : prog_.kv_groups[g].layers)
|
||||
if (l >= prog_.meta.n_layers) {
|
||||
err(RAD_E_STATE, "drafter '%s' keeps no cache of its own (rad_drafter_shared_kv) "
|
||||
"and its layer %d is bound to KV group '%s', which no pass "
|
||||
"would ever write", prog_.drafter_name.c_str(), l,
|
||||
prog_.kv_groups[g].name.c_str());
|
||||
break;
|
||||
}
|
||||
finish_buffer_liveness();
|
||||
|
||||
int s = plan_buffers(prog_, &bufrep_);
|
||||
@@ -1762,6 +1803,11 @@ int rad_declare_drafter(RadBuilder* b, const RadDrafterDecl* d) {
|
||||
return B(b)->declare_drafter(d);
|
||||
}
|
||||
|
||||
int rad_drafter_shared_kv(RadBuilder* b, int pos_offset) {
|
||||
if (!b) return RAD_E_INVAL;
|
||||
return B(b)->drafter_shared_kv(pos_offset);
|
||||
}
|
||||
|
||||
int rad_declare_encoder(RadBuilder* b, const RadEncoderDecl* d) {
|
||||
if (!b) return RAD_E_INVAL;
|
||||
return B(b)->declare_encoder(d);
|
||||
|
||||
@@ -289,6 +289,10 @@ std::string dump_graph_str(const Program& p, const std::vector<std::string>* err
|
||||
"%d, drafter window %lld\n",
|
||||
(long long)p.drafter.block, p.drafter.depth,
|
||||
(int)p.drafter.mask_token, (long long)p.drafter.window);
|
||||
if (p.drafter_shared_kv)
|
||||
s += fmt(" cache none of its own: it reads the trunk's, owes no history, and "
|
||||
"every round runs at the committed position%s\n",
|
||||
p.drafter_pos_offset ? " (rotated one past it)" : "");
|
||||
s += "\n";
|
||||
}
|
||||
|
||||
|
||||
+4
-2
@@ -85,7 +85,8 @@ static const Flag g_flags[] = {
|
||||
{ "--prefix-cache-host-mib", "N", "copy finished conversations' KV to host memory, up to N MiB,\n"
|
||||
" so their VRAM can go to experts and a return restores\n"
|
||||
" instead of re-prefilling. 0 is off. Part of it holds\n"
|
||||
" linear-state snapshots on a hybrid model; startup says how many" },
|
||||
" snapshots on a hybrid or sliding-window model;\n"
|
||||
" startup says how many" },
|
||||
{ "--prefix-cache-dir", "DIR", "where the disk tier keeps them. Not --weights-disk-tier, which is\n"
|
||||
" about WEIGHTS" },
|
||||
{ "--prefix-cache-disk-mib", "N", "and copy them on to disk under --prefix-cache-dir, up to N MiB,\n"
|
||||
@@ -104,7 +105,8 @@ static const Flag g_flags[] = {
|
||||
* 2 for the whole server rather than 2 x --max-num-seqs. At the default 8 slots and
|
||||
* 8 sequences that is one snapshot a sequence, which is what an append-only chat wants --
|
||||
* the next turn's hit lands at the end of the last one. */
|
||||
{ "--checkpoint-slots", "N", "linear-state snapshots retained IN TOTAL (not "
|
||||
{ "--checkpoint-slots", "N", "linear-state or sliding-window snapshots "
|
||||
"retained IN TOTAL (not "
|
||||
"per sequence), in pinned host memory; compare "
|
||||
"against --max-num-seqs" },
|
||||
{ "--no-prefix-cache", nullptr, "disable prefix caching" },
|
||||
|
||||
+24
-3
@@ -704,13 +704,21 @@ int Engine::step_loop() {
|
||||
for (const StepEntry& e : plan.e) {
|
||||
if (e.ckpt_restore < 0) continue;
|
||||
if (!state_slots_of(e.seq, &ckpt_slots_)) continue;
|
||||
/* The window behind the hit, in the blocks admit_one seeded at its floor. */
|
||||
if (ranks_[0]->kv.has_window_snapshot() &&
|
||||
!ranks_[0]->kv.window_rows(e.seq, e.ctx_len, &ckpt_win_)) {
|
||||
RAD_ERR("sequence %llu: no window rows at %d to restore into",
|
||||
(unsigned long long)e.seq, (int)e.ctx_len);
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
for (size_t ri = 0; ri < ranks_.size(); ++ri) {
|
||||
auto& rk = ranks_[ri];
|
||||
/* This rank's device, for its own stream and its own state slots. */
|
||||
if (ranks_.size() > 1) (void)rad_dev_set(rk->device);
|
||||
const int s = rk->kv.checkpoint_restore(ckpt_slots_.data(),
|
||||
(int)ckpt_slots_.size(),
|
||||
e.ckpt_restore, rk->ctx.stream());
|
||||
e.ckpt_restore, rk->ctx.stream(),
|
||||
&ckpt_win_);
|
||||
if (s < 0) {
|
||||
RAD_ERR("could not restore sequence %llu from checkpoint slot %d on "
|
||||
"rank %d: %s", (unsigned long long)e.seq,
|
||||
@@ -809,11 +817,23 @@ int Engine::step_loop() {
|
||||
for (const StepEntry& e : plan.e) {
|
||||
if (e.ckpt_slot < 0 || e.ckpt_tok < 0) continue;
|
||||
if (!state_slots_of(e.seq, &ckpt_slots_)) continue;
|
||||
/* The window behind the checkpoint position. The chunk that ends there
|
||||
* still holds it (its ensure kept the window behind the chunk's first
|
||||
* query), so a miss is a broken invariant -- and skipping would leave the
|
||||
* cache a slot it commits as valid with somebody else's pages in it. */
|
||||
if (ranks_[0]->kv.has_window_snapshot() &&
|
||||
!ranks_[0]->kv.window_rows(e.seq, e.ctx_len + e.ckpt_tok + 1,
|
||||
&ckpt_win_)) {
|
||||
RAD_ERR("sequence %llu: the window behind checkpoint %d is not held",
|
||||
(unsigned long long)e.seq, (int)(e.ctx_len + e.ckpt_tok + 1));
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
for (auto& rk : ranks_) {
|
||||
if (ranks_.size() > 1) (void)rad_dev_set(rk->device);
|
||||
const int s = rk->kv.checkpoint_save(ckpt_slots_.data(),
|
||||
(int)ckpt_slots_.size(),
|
||||
e.ckpt_slot, rk->ctx.stream());
|
||||
e.ckpt_slot, rk->ctx.stream(),
|
||||
&ckpt_win_);
|
||||
if (s < 0) {
|
||||
RAD_ERR("rank %d could not snapshot sequence %llu into checkpoint slot "
|
||||
"%d: %s", rk->index, (unsigned long long)e.seq,
|
||||
@@ -1924,7 +1944,8 @@ bool Engine::state_slots_of(uint64_t seq, std::vector<int32_t>* out) const {
|
||||
(*out)[(size_t)g] = s;
|
||||
any = true;
|
||||
}
|
||||
return any;
|
||||
/* A window snapshot is a snapshot with no state slots (KVManager::has_window_snapshot). */
|
||||
return any || (kv.has_window_snapshot() && kv.has_sequence(seq));
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ the HTTP frontend */
|
||||
|
||||
@@ -249,6 +249,7 @@ private:
|
||||
/* Scratch for the checkpoint copies: the state slots of one sequence, reused so the step path
|
||||
* does not allocate. See state_slots_of. */
|
||||
std::vector<int32_t> ckpt_slots_;
|
||||
std::vector<int32_t> ckpt_win_; /* KVManager::window_rows, same reuse */
|
||||
bool state_slots_of(uint64_t seq, std::vector<int32_t>* out) const;
|
||||
|
||||
int load_vocab();
|
||||
|
||||
+21
-6
@@ -2910,15 +2910,17 @@ int Engine::configure_kv() {
|
||||
slot += ranks_[i]->kv.checkpoint_bytes();
|
||||
}
|
||||
const int64_t n = cfg_.checkpoint_slots > 0 ? cfg_.checkpoint_slots : 0;
|
||||
/* A slot holds linear state or a trunk's window, never both (KVGroupPlan::win_snap). */
|
||||
const char* what = ranks_[0]->kv.has_window_snapshot() ? "sliding-window" : "linear-state";
|
||||
if (slot > 0 && n > 0 && cfg_.prefix_cache) {
|
||||
if (ck_store_.open(slot, slot * n) != RAD_OK) {
|
||||
RAD_WARN("checkpoint slots: no pinned host memory for %lld snapshot(s) of %s; a "
|
||||
"hybrid session's prefix hits replay their linear layers from zero. "
|
||||
"Lower --checkpoint-slots.", (long long)n, humanb(slot).c_str());
|
||||
RAD_WARN("checkpoint slots: no pinned host memory for %lld %s snapshot(s) of %s; "
|
||||
"a session's prefix hits prefill from the start. Lower "
|
||||
"--checkpoint-slots.", (long long)n, what, humanb(slot).c_str());
|
||||
} else {
|
||||
RAD_INFO("checkpoint slots: %lld linear-state snapshot(s) of %s in pinned host "
|
||||
"memory (%s), none of it on the card", (long long)n,
|
||||
humanb(slot).c_str(), humanb(ck_store_.cap_bytes()).c_str());
|
||||
RAD_INFO("checkpoint slots: %lld %s snapshot(s) of %s in pinned host memory (%s), "
|
||||
"none of it on the card", (long long)n, what, humanb(slot).c_str(),
|
||||
humanb(ck_store_.cap_bytes()).c_str());
|
||||
}
|
||||
}
|
||||
for (auto& r : ranks_)
|
||||
@@ -3893,6 +3895,19 @@ int Engine::load_vocab() {
|
||||
vb.chat_template = std::move(t);
|
||||
}
|
||||
|
||||
/* The checkpoint's own end-of-generation list travels as metadata, flattened from
|
||||
* generation_config.json -- a space-separated list, or one id. */
|
||||
if (const char* ids = rad_meta_gets(&meta_, "generation.eos_token_id", nullptr)) {
|
||||
const char* q = ids;
|
||||
while (*q) {
|
||||
char* end = nullptr;
|
||||
const long v = std::strtol(q, &end, 10);
|
||||
if (end == q) break;
|
||||
if (v >= 0 && v <= INT32_MAX) vb.eos_ids.push_back((int32_t)v);
|
||||
q = end;
|
||||
}
|
||||
}
|
||||
|
||||
auto v = std::make_shared<Vocab>();
|
||||
RAD_TRY(v->load(std::move(vb)));
|
||||
vocab_ = v;
|
||||
|
||||
+143
-4
@@ -547,6 +547,44 @@ void Checkpoint::detect_import() {
|
||||
else
|
||||
import_why_ = "Quark's weight scheme here is not MXFP4 (fp4, per_group 32, e8m0 scales) "
|
||||
"throughout, which is the one this reads";
|
||||
} else if (qm == "compressed-tensors") {
|
||||
/* COMPRESSED-TENSORS' PACK-QUANTIZED INT4, symmetric and grouped -- Google's Gemma 4 QAT
|
||||
* release (w4a16-ct) is one. Every config group must say so: a zero point, act-order, a
|
||||
* dynamic or activation scheme would each change what a code means. */
|
||||
std::vector<std::string> groups;
|
||||
const std::string cg = "quantization_config.config_groups.";
|
||||
for (const std::string& k : meta_.keys)
|
||||
if (k.rfind(cg, 0) == 0) {
|
||||
const std::string g = k.substr(cg.size(), k.find('.', cg.size()) - cg.size());
|
||||
if (std::find(groups.begin(), groups.end(), g) == groups.end()) groups.push_back(g);
|
||||
}
|
||||
std::string why;
|
||||
int64_t group = 0;
|
||||
if (qc("format") != "pack-quantized")
|
||||
why = "its format is '" + qc("format") + "', and pack-quantized is the one this reads";
|
||||
if (groups.empty() && why.empty()) why = "its quantization_config names no config group";
|
||||
for (const std::string& g : groups) {
|
||||
if (!why.empty()) break;
|
||||
const std::string w = "config_groups." + g + ".weights.";
|
||||
const std::string gs = qc(w + "group_size");
|
||||
const long long gn = gs.empty() ? 0 : std::atoll(gs.c_str());
|
||||
if (qc("config_groups." + g + ".format") != "pack-quantized" ||
|
||||
qc(w + "num_bits") != "4" || qc(w + "type") != "int" || qc(w + "symmetric") != "1" ||
|
||||
qc(w + "strategy") != "group" || qc(w + "dynamic") != "0" || gn <= 0 ||
|
||||
!qc(w + "actorder").empty() || any_under("config_groups." + g + ".input_activations."))
|
||||
why = "config group '" + g + "' is not symmetric 4-bit int weights in groups, packed, "
|
||||
"with no act-order and unquantised activations, which is the one this reads";
|
||||
else if (group && gn != group)
|
||||
why = "its config groups state different group sizes";
|
||||
else
|
||||
group = gn;
|
||||
}
|
||||
if (why.empty()) {
|
||||
import_ = Import::CtInt4;
|
||||
ct_group_ = group;
|
||||
} else {
|
||||
import_why_ = "compressed-tensors: " + why;
|
||||
}
|
||||
}
|
||||
/* THE TOOL'S DESCRIPTION IS KEPT, UNDER ANOTHER NAME. A plugin reads quantization_config as
|
||||
* the statement of the format it serves (qwen35_fp8 checks quant_method is "fp8"), and an
|
||||
@@ -594,6 +632,53 @@ int Checkpoint::import_piece(const std::string& name, const SrcTensor** codes,
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
if (import_ == Import::CtInt4) {
|
||||
/* CT-INT4: `X.weight` is shipped as X.weight_packed (i32 [N, K/8], eight codes a word from
|
||||
* the low bits, unsigned about 8) and X.weight_scale ([N, K/group]). The words are the
|
||||
* logical [N, K] code matrix in row order already; only the offset is left for the
|
||||
* relayout. A layer the config ignores is an ordinary X.weight. */
|
||||
const std::string suffix = ".weight";
|
||||
if (name.size() <= suffix.size() ||
|
||||
name.compare(name.size() - suffix.size(), suffix.size(), suffix) != 0)
|
||||
return RAD_E_NOTFOUND;
|
||||
const SrcTensor* pk = find(name + "_packed");
|
||||
if (!pk) return RAD_E_NOTFOUND;
|
||||
const SrcTensor* sc = find(name + "_scale");
|
||||
const std::string what = "'" + pk->name + "'";
|
||||
if (pk->rad_dtype != RAD_I32 || pk->shape.size() != 2)
|
||||
return refuse(RAD_E_FORMAT, what + " is not an int32 [N, K/8] matrix");
|
||||
if (find(name + "_zero_point"))
|
||||
return refuse(RAD_E_UNSUPPORTED, what + " has a zero point beside it, which a symmetric "
|
||||
"config does not; an asymmetric weight is not read");
|
||||
const int64_t N = pk->shape[0], K = pk->shape[1] * 8;
|
||||
if (K % ct_group_)
|
||||
return refuse(RAD_E_SHAPE, what + " has " + std::to_string(K) + " columns, not whole "
|
||||
"groups of " + std::to_string(ct_group_));
|
||||
if (!sc || sc->shape.size() != 2 || sc->shape[0] != N || sc->shape[1] != K / ct_group_ ||
|
||||
(sc->rad_dtype != RAD_F16 && sc->rad_dtype != RAD_BF16 && sc->rad_dtype != RAD_F32))
|
||||
return refuse(RAD_E_FORMAT, what + " has no float [" + std::to_string(N) + ", " +
|
||||
std::to_string(K / ct_group_) + "] '" + name +
|
||||
"_scale' beside it");
|
||||
if (const SrcTensor* ws = find(name + "_shape")) {
|
||||
int64_t dims[2] = { 0, 0 };
|
||||
for (int i = 0; i < 2 && i < (int)ws->numel(); ++i)
|
||||
dims[i] = (int64_t)rad_load_f32(ws->data, ws->rad_dtype, i);
|
||||
if (ws->numel() != 2 || dims[0] != N || dims[1] != K)
|
||||
return refuse(RAD_E_SHAPE, "'" + ws->name + "' does not state the [" +
|
||||
std::to_string(N) + ", " + std::to_string(K) +
|
||||
"] its codes hold");
|
||||
}
|
||||
SrcTensor c = *pk;
|
||||
c.rad_dtype = RAD_I4;
|
||||
c.shape = { N, K };
|
||||
c.ct_group = ct_group_;
|
||||
sliced_.push_back(std::move(c));
|
||||
*codes = &sliced_.back();
|
||||
*scale = sc;
|
||||
imported_[name] = { *codes, *scale };
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* GPTQ-PACKED: `X.weight` is shipped as X.qweight, X.scales, X.qzeros and, optionally,
|
||||
* X.g_idx. The width is read off the tensors rather than quantization_config, because a
|
||||
* release may mix widths -- int4 experts beside int8 projections -- and say so only per layer. */
|
||||
@@ -965,6 +1050,28 @@ int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, b
|
||||
rad_enc_add_plane(&out->enc, "codes", dt, 1, 1);
|
||||
rad_enc_add_plane(&out->enc, "scale", sdt, br, bc);
|
||||
}
|
||||
} else if (p0.ct_group) {
|
||||
/* CT-INT4, IMPORTED: one group throughout and joined only along rows, as GPTQ's. The codes
|
||||
* become signed i4 (the offset flipped out at relayout) and the scale is the plane as
|
||||
* shipped, one a group of K. A kernel reads that group or a recipe re-quantises it. */
|
||||
out->imported = true;
|
||||
for (size_t k = 1; k < out->pieces.size() && out->imported; ++k)
|
||||
if (out->pieces[k]->ct_group != p0.ct_group ||
|
||||
out->scales[k]->rad_dtype != out->scales[0]->rad_dtype) {
|
||||
out->imported = false;
|
||||
out->why = "its CT-INT4 pieces differ in group or scale dtype";
|
||||
}
|
||||
if (out->imported && d != 0 && out->pieces.size() > 1) {
|
||||
out->imported = false;
|
||||
out->why = "its CT-INT4 pieces are joined along a column, across their groups";
|
||||
}
|
||||
if (out->imported) {
|
||||
rad_enc_clear(&out->enc);
|
||||
rad_enc_copy_str(out->enc.scheme, "affine");
|
||||
rad_enc_add_plane(&out->enc, "codes", RAD_I4, 1, 1);
|
||||
rad_enc_add_plane(&out->enc, "scale", out->scales[0]->rad_dtype, 1, p0.ct_group);
|
||||
out->why = "it is CT-INT4, which rad-convert imports -- serve the container it writes";
|
||||
}
|
||||
} else if (!unscaled) {
|
||||
out->why = "some of its pieces carry a scale plane and some do not";
|
||||
} else if (dt == RAD_F8E4M3 || dt == RAD_F8E5M2) {
|
||||
@@ -1077,6 +1184,18 @@ struct Joined {
|
||||
|
||||
/* `n` elements of a stored-dtype piece from element `e`, as f32. */
|
||||
int piece_f32(const SrcTensor& t, int64_t e, int64_t n, float* out) {
|
||||
if (t.ct_group) {
|
||||
/* the signed code: element (row, k) of the logical [N, K] matrix is nibble k % 8 of word
|
||||
* [row, k / 8], less 8 */
|
||||
const int64_t K = t.shape[1];
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
const int64_t row = (e + i) / K, k = (e + i) % K;
|
||||
uint32_t w;
|
||||
std::memcpy(&w, (const uint8_t*)t.data + (row * (K / 8) + k / 8) * 4, 4);
|
||||
out[i] = (float)((int)((w >> ((k % 8) * 4)) & 0xFu) - 8);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
if (t.gptq_bits) {
|
||||
/* the signed code: element (row, k) of the logical [N, K] matrix is field k % (32/bits)
|
||||
* of word [k / (32/bits), row], less its zero point */
|
||||
@@ -1148,8 +1267,8 @@ int ckpt_rows_f32(const CkptWeight& w, int64_t r0, int64_t nr, float* out, std::
|
||||
: "?")
|
||||
: std::string(rad_dtype_name(w.pieces[0]->rad_dtype))) +
|
||||
")");
|
||||
/* A GPTQ-PACKED CODE TIMES ITS GROUP'S SCALE, the scale read as shipped: the scale tensor is
|
||||
* [groups, N], so row r's scales are a column of it. */
|
||||
/* AN IMPORTED CODE TIMES ITS GROUP'S SCALE, the scale read as shipped: GPTQ's scale tensor is
|
||||
* [groups, N], so row r's scales are a column of it; CT-INT4's is [N, groups], a row. */
|
||||
if (w.imported) {
|
||||
int64_t base = 0;
|
||||
for (size_t k = 0; k < w.pieces.size(); ++k) {
|
||||
@@ -1158,8 +1277,10 @@ int ckpt_rows_f32(const CkptWeight& w, int64_t r0, int64_t nr, float* out, std::
|
||||
const int64_t pr = pk.shape[0];
|
||||
for (int64_t r = std::max(r0, base); r < std::min(r0 + nr, base + pr); ++r)
|
||||
for (int64_t c = 0; c < w.cols; ++c)
|
||||
out[(r - r0) * w.cols + c] *=
|
||||
rad_load_f32(sk.data, sk.rad_dtype, (c / pk.gptq_group) * pr + (r - base));
|
||||
out[(r - r0) * w.cols + c] *= rad_load_f32(
|
||||
sk.data, sk.rad_dtype,
|
||||
pk.ct_group ? (r - base) * (w.cols / pk.ct_group) + c / pk.ct_group
|
||||
: (c / pk.gptq_group) * pr + (r - base));
|
||||
base += pr;
|
||||
}
|
||||
return RAD_OK;
|
||||
@@ -1212,6 +1333,24 @@ int ckpt_plane_rows(const CkptWeight& w, int k, int64_t r0, int64_t nr, void* ds
|
||||
const SrcTensor& c = *w.pieces[p];
|
||||
const SrcTensor& s = *w.scales[p];
|
||||
const int64_t N = c.shape[0], K = c.shape[1];
|
||||
if (c.ct_group) {
|
||||
/* CT-INT4, RE-LAID: a row of codes is a row of the packed words, already two codes
|
||||
* a byte low nibble first, each offset to signed by flipping its top bit; a row of
|
||||
* scales is a row of the scale tensor, as shipped. */
|
||||
for (int64_t r = std::max(r0, base); r < std::min(r0 + nr, base + N); ++r) {
|
||||
const int64_t n = r - base;
|
||||
if (k == 0) {
|
||||
const uint8_t* q = (const uint8_t*)c.data + n * (K / 2);
|
||||
for (int64_t i = 0; i < K / 2; ++i) *o++ = q[i] ^ 0x88;
|
||||
} else {
|
||||
const int64_t g = K / c.ct_group, sb = rad_dtype_bits(s.rad_dtype) / 8;
|
||||
std::memcpy(o, (const uint8_t*)s.data + n * g * sb, (size_t)(g * sb));
|
||||
o += g * sb;
|
||||
}
|
||||
}
|
||||
base += N;
|
||||
continue;
|
||||
}
|
||||
const uint8_t flip = c.gptq_bits == 4 ? 0x88 : 0x80;
|
||||
for (int64_t r = std::max(r0, base); r < std::min(r0 + nr, base + N); ++r) {
|
||||
const int64_t n = r - base;
|
||||
|
||||
@@ -56,6 +56,12 @@ struct SrcTensor {
|
||||
* the K columns one row of its scale tensor covers. 0 for any other tensor. */
|
||||
int32_t gptq_bits = 0;
|
||||
int64_t gptq_group = 0;
|
||||
/* CT-INT4 (compressed-tensors' pack-quantized int4, symmetric): `data` is X.weight_packed's
|
||||
* int32 words [N, K / 8], eight codes a word along K from the low bits up, stored unsigned with
|
||||
* the zero point 8. The tensor this describes is the logical [N, K] code matrix, `rad_dtype`
|
||||
* RAD_I4; `ct_group` is the K columns one scale of X.weight_scale [N, K / group] covers. 0 for
|
||||
* any other tensor. */
|
||||
int64_t ct_group = 0;
|
||||
|
||||
int64_t numel() const {
|
||||
int64_t n = 1;
|
||||
@@ -132,7 +138,7 @@ public:
|
||||
* this does not read stays None, with the reason in import_refusal(). */
|
||||
/* Its quantization_config keys are then renamed `imported_quantization_config.*`: they
|
||||
* describe the tool, not a served format, and a plugin reads the latter there. */
|
||||
enum class Import { None, Gptq, QuarkMx };
|
||||
enum class Import { None, Gptq, QuarkMx, CtInt4 };
|
||||
Import imports() const { return import_; }
|
||||
const std::string& import_refusal() const { return import_why_; }
|
||||
|
||||
@@ -164,6 +170,7 @@ private:
|
||||
int64_t fp8_br_ = 128, fp8_bc_ = 128;
|
||||
Import import_ = Import::None;
|
||||
std::string import_why_;
|
||||
int64_t ct_group_ = 0; /* CtInt4: the group every weight's config states */
|
||||
/* import_piece's answers by name, so a weight resolved twice reads one pair of views. */
|
||||
std::unordered_map<std::string, std::pair<const SrcTensor*, const SrcTensor*>> imported_;
|
||||
};
|
||||
|
||||
+156
-19
@@ -271,7 +271,19 @@ int KVManager::plan_groups(const std::vector<KVGroupInfo>& groups, const Config&
|
||||
|
||||
/* ---- fixed costs first: they are not negotiable and they are not per-token ---- */
|
||||
checkpoint_bytes_ = 0;
|
||||
window_ck_bytes_ = 0;
|
||||
for (const auto& p : plans_) if (p.stateful()) checkpoint_bytes_ += p.bytes_per_state;
|
||||
/* AND THE WINDOW BEHIND A CHECKPOINT, after the linear state (see has_window_snapshot). */
|
||||
bool has_state = false;
|
||||
for (const auto& p : plans_) has_state = has_state || p.stateful();
|
||||
for (size_t i = 1; i < plans_.size(); ++i) {
|
||||
KVGroupPlan& p = plans_[i];
|
||||
p.win_snap = !has_state && p.kind == RAD_KV_WINDOW && p.window_blocks > 0 &&
|
||||
!groups[i].drafter;
|
||||
if (p.win_snap && !p.zero && p.n_layers > 0)
|
||||
window_ck_bytes_ += p.window_blocks * p.bytes_per_block;
|
||||
}
|
||||
checkpoint_bytes_ += window_ck_bytes_;
|
||||
|
||||
/* EVERY RESERVATION IS PADDED TO RAD_ALIGN_UNIT AND THE BUDGET HAS TO SAY SO. Summing the
|
||||
* fixed costs as raw bytes leaves the paged split free to spend the difference, and the plan
|
||||
@@ -307,7 +319,7 @@ int64_t KVManager::ceiling(int64_t ctx) const {
|
||||
if (!p.paged() || p.block_size <= 0) continue;
|
||||
int64_t blocks = max_seqs_ * ((ctx + p.block_size - 1) / p.block_size);
|
||||
if (p.kind == RAD_KV_WINDOW && p.window_blocks > 0)
|
||||
blocks = std::min(blocks, max_seqs_ * p.window_blocks);
|
||||
blocks = std::min(blocks, window_pool_cap(p));
|
||||
need += blocks * p.bytes_per_block;
|
||||
}
|
||||
return need;
|
||||
@@ -382,10 +394,10 @@ int64_t KVManager::paged_split(int64_t budget_bytes, std::vector<int64_t>* block
|
||||
for (int32_t i : open) {
|
||||
const auto& p = plans_[i];
|
||||
if (p.kind != RAD_KV_WINDOW) continue;
|
||||
if (tokens / p.block_size > max_seqs_ * p.window_blocks) { capped = i; break; }
|
||||
if (tokens / p.block_size > window_pool_cap(p)) { capped = i; break; }
|
||||
}
|
||||
if (capped < 0) break;
|
||||
out[capped] = max_seqs_ * plans_[capped].window_blocks;
|
||||
out[capped] = window_pool_cap(plans_[capped]);
|
||||
remaining -= out[capped] * plans_[capped].bytes_per_block;
|
||||
open.erase(std::find(open.begin(), open.end(), capped));
|
||||
}
|
||||
@@ -419,7 +431,7 @@ int64_t KVManager::pool_mib_for_tokens(int64_t tokens, int64_t max_mib) const {
|
||||
int64_t KVManager::zero_blocks(const KVGroupPlan& p, int64_t tokens) const {
|
||||
if (tokens == kUnboundedTokens) return 0;
|
||||
const int64_t b = tokens / p.block_size;
|
||||
if (p.kind == RAD_KV_WINDOW && b > max_seqs_ * p.window_blocks) return max_seqs_ * p.window_blocks;
|
||||
if (p.kind == RAD_KV_WINDOW && b > window_pool_cap(p)) return window_pool_cap(p);
|
||||
return b;
|
||||
}
|
||||
|
||||
@@ -921,7 +933,7 @@ int64_t KVManager::blocks_for(int32_t g, int64_t n_tokens) const {
|
||||
const KVGroupPlan* p = plan(g);
|
||||
if (!p || !p->paged() || n_tokens <= 0) return 0;
|
||||
int64_t n = ceil_div(n_tokens, p->block_size);
|
||||
if (p->kind == RAD_KV_WINDOW) n = std::min(n, p->window_blocks);
|
||||
if (p->kind == RAD_KV_WINDOW) n = std::min(n, window_seq_cap(*p));
|
||||
return n;
|
||||
}
|
||||
|
||||
@@ -1156,19 +1168,29 @@ std::vector<BlockCopy> KVManager::take_pending_copies() {
|
||||
|
||||
/* ------------------------------------------------------------------ ensure */
|
||||
|
||||
int KVManager::ensure(uint64_t id, int64_t n_tokens) {
|
||||
Seq* s = find(id);
|
||||
if (!s) return RAD_E_NOTFOUND;
|
||||
if (n_tokens <= s->n_tokens) return RAD_OK;
|
||||
int64_t KVManager::window_seq_cap(const KVGroupPlan& p) const {
|
||||
return p.window_blocks + (max_tok_ > 0 ? ceil_div(max_tok_, p.block_size) : 0) + 1;
|
||||
}
|
||||
|
||||
/* Pass 0: recycle whatever the window has slid past. This only frees, so it cannot fail, and
|
||||
* doing it first means the availability check below sees the memory it releases. */
|
||||
int64_t KVManager::window_pool_cap(const KVGroupPlan& p) const {
|
||||
return max_seqs_ * p.window_blocks + (max_tok_ > 0 ? ceil_div(max_tok_, p.block_size) : 0) +
|
||||
max_seqs_;
|
||||
}
|
||||
|
||||
/* SLID PAST THE STEP'S FIRST QUERY, NOT ITS LAST. The query at keep_from reads keys down to
|
||||
* keep_from - window + 1, which lies in block keep_from / block - (window_blocks - 1) or later
|
||||
* (window_blocks - 1 >= window / block). A target taken from the END of the step --
|
||||
* ceil(n_tokens / block) - window_blocks -- is the same block for a decode step and drops the keys
|
||||
* every row of a longer prefill chunk still needs. Measured on Gemma 4 (#75: 50 of 60 layers
|
||||
* windowed at 1024): a 2185-token prompt rebased the table at 1152, its sliding layers held no KV
|
||||
* for positions 0..1151, and every prompt past ~1040 tokens came back as nonsense. */
|
||||
void KVManager::recycle_window(Seq* s, int64_t keep_from) {
|
||||
for (size_t g = 0; g < plans_.size(); ++g) {
|
||||
const auto& p = plans_[g];
|
||||
if (p.kind != RAD_KV_WINDOW) continue;
|
||||
int64_t want_end = ceil_div(n_tokens, p.block_size);
|
||||
int64_t first = s->first_block_pos[g] / p.block_size;
|
||||
int64_t target = std::max<int64_t>(first, want_end - p.window_blocks);
|
||||
int64_t target = std::max<int64_t>(first,
|
||||
keep_from / p.block_size - (p.window_blocks - 1));
|
||||
while (first < target && !s->blocks[g].empty()) {
|
||||
drop_block((int32_t)g, s->blocks[g].front());
|
||||
s->blocks[g].erase(s->blocks[g].begin());
|
||||
@@ -1178,6 +1200,24 @@ int KVManager::ensure(uint64_t id, int64_t n_tokens) {
|
||||
if (s->blocks[g].empty()) first = target; /* nothing held: rebase to the window */
|
||||
s->first_block_pos[g] = first * p.block_size;
|
||||
}
|
||||
}
|
||||
|
||||
void KVManager::trim_window(uint64_t id, int64_t keep_from) {
|
||||
Seq* s = find(id);
|
||||
if (!s || keep_from < 0) return;
|
||||
if (keep_from > s->n_tokens) keep_from = s->n_tokens;
|
||||
recycle_window(s, keep_from);
|
||||
}
|
||||
|
||||
int KVManager::ensure(uint64_t id, int64_t n_tokens, int64_t keep_from) {
|
||||
Seq* s = find(id);
|
||||
if (!s) return RAD_E_NOTFOUND;
|
||||
if (n_tokens <= s->n_tokens) return RAD_OK;
|
||||
if (keep_from < 0 || keep_from > s->n_tokens) keep_from = s->n_tokens;
|
||||
|
||||
/* Pass 0: recycle whatever the window has slid past. This only frees, so it cannot fail, and
|
||||
* doing it first means the availability check below sees the memory it releases. */
|
||||
recycle_window(s, keep_from);
|
||||
|
||||
/* Pass 1: can every group serve this? Check before touching anything, so a group that runs
|
||||
* out does not leave the sequence half-extended and the caller unable to say what it owns. */
|
||||
@@ -1316,7 +1356,7 @@ int KVManager::make_room(uint64_t id, int64_t n_tokens,
|
||||
if (p.paged()) {
|
||||
int64_t first = s->first_block_pos[g] / p.block_size;
|
||||
int64_t want = ceil_div(n_tokens, p.block_size) - first;
|
||||
if (p.kind == RAD_KV_WINDOW) want = std::min(want, p.window_blocks);
|
||||
if (p.kind == RAD_KV_WINDOW) want = std::min(want, window_seq_cap(p));
|
||||
int64_t extra = want - (int64_t)s->blocks[g].size() + 1; /* +1 for a COW copy */
|
||||
if (extra > available_blocks((int32_t)g)) return false;
|
||||
} else if (p.stateful() && s->state[g] < 0 && free_states_[g].empty()) return false;
|
||||
@@ -1374,7 +1414,7 @@ void* KVManager::checkpoint_ptr(int32_t slot) const {
|
||||
* exactly one piece of code decides its order. Two functions that agreed today would be two
|
||||
* functions that could stop agreeing. */
|
||||
int KVManager::checkpoint_copy(const int32_t* state_slots, int n_slots, int32_t ck_slot,
|
||||
bool save, RadStream s) {
|
||||
bool save, RadStream s, const std::vector<int32_t>* win) {
|
||||
/* A SLOT NOBODY HOLDS IS NOT ONE TO WRITE. Rank 0 hands the ids out, so a follower checks the
|
||||
* shared store rather than a list of its own. Each refusal says which check it is: a slot the
|
||||
* store gave back is a lifetime fault in whoever handed the id out, and nothing about the copy. */
|
||||
@@ -1438,14 +1478,111 @@ int KVManager::checkpoint_copy(const int32_t* state_slots, int n_slots, int32_t
|
||||
}
|
||||
off += nbytes * p.n_layers;
|
||||
}
|
||||
|
||||
/* THE WINDOW SECTION: window_blocks pages a WINDOW group, page j of the window in slot j, each
|
||||
* page n_layers rows of one layer's block -- one pitched copy a page. `win` names the pages
|
||||
* (window_rows); -1 is a page below position zero and is left alone either way. */
|
||||
if (window_ck_bytes_ > 0) {
|
||||
if (!win) {
|
||||
RAD_ERR("checkpoint %s slot %d: this model snapshots its window and no window rows "
|
||||
"were named", dir, (int)ck_slot);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
size_t wi = 0;
|
||||
for (size_t g = 0; g < plans_.size(); ++g) {
|
||||
const KVGroupPlan& p = plans_[g];
|
||||
if (!p.win_snap) continue;
|
||||
const size_t row0 = wi;
|
||||
wi += (size_t)p.window_blocks;
|
||||
if (p.zero || p.n_layers <= 0) continue;
|
||||
if (wi > win->size() || !p.base) {
|
||||
RAD_ERR("checkpoint %s slot %d: window group %d has %zu row(s) named for %lld",
|
||||
dir, (int)ck_slot, (int)g, win->size(), (long long)wi);
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
const int64_t lb = p.layer_bytes_per_block();
|
||||
for (int64_t j = 0; j < p.window_blocks; ++j) {
|
||||
const int32_t b = (*win)[row0 + (size_t)j];
|
||||
if (b < 0) continue;
|
||||
if (b >= p.n_blocks) return RAD_E_STATE;
|
||||
char* dev = (char*)p.base + (int64_t)b * lb;
|
||||
char* host = ck + off + j * p.bytes_per_block;
|
||||
const int cs = save ? rad_memcpy_2d_async(host, lb, dev, p.layer_stride(), lb,
|
||||
p.n_layers, s)
|
||||
: rad_memcpy_2d_async(dev, p.layer_stride(), host, lb, lb,
|
||||
p.n_layers, s);
|
||||
if (cs < 0) {
|
||||
RAD_ERR("checkpoint %s slot %d: the device refused window page %lld of "
|
||||
"group %d: %s", dir, (int)ck_slot, (long long)j, (int)g,
|
||||
rad_strerror(cs));
|
||||
return cs;
|
||||
}
|
||||
}
|
||||
off += p.window_blocks * p.bytes_per_block;
|
||||
}
|
||||
if (off > checkpoint_bytes_) return RAD_E_STATE;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int KVManager::checkpoint_save(const int32_t* slots, int n, int32_t ck, RadStream s) {
|
||||
return checkpoint_copy(slots, n, ck, /*save=*/true, s);
|
||||
int KVManager::checkpoint_save(const int32_t* slots, int n, int32_t ck, RadStream s,
|
||||
const std::vector<int32_t>* win) {
|
||||
return checkpoint_copy(slots, n, ck, /*save=*/true, s, win);
|
||||
}
|
||||
int KVManager::checkpoint_restore(const int32_t* slots, int n, int32_t ck, RadStream s) {
|
||||
return checkpoint_copy(slots, n, ck, /*save=*/false, s);
|
||||
int KVManager::checkpoint_restore(const int32_t* slots, int n, int32_t ck, RadStream s,
|
||||
const std::vector<int32_t>* win) {
|
||||
return checkpoint_copy(slots, n, ck, /*save=*/false, s, win);
|
||||
}
|
||||
|
||||
bool KVManager::window_rows(uint64_t id, int64_t pos, std::vector<int32_t>* out) const {
|
||||
out->clear();
|
||||
const Seq* s = find(id);
|
||||
if (!s || pos <= 0) return false;
|
||||
for (size_t g = 0; g < plans_.size(); ++g) {
|
||||
const KVGroupPlan& p = plans_[g];
|
||||
if (!p.win_snap) continue;
|
||||
const size_t row0 = out->size();
|
||||
out->resize(row0 + (size_t)p.window_blocks, -1);
|
||||
if (p.zero || p.block_size <= 0 || pos % p.block_size != 0) {
|
||||
if (p.zero) continue;
|
||||
return false;
|
||||
}
|
||||
const int64_t lo = window_lo(p, pos), hi = pos / p.block_size;
|
||||
const int64_t first = s->first_block_pos[g] / p.block_size;
|
||||
if (lo < first || hi - first > (int64_t)s->blocks[g].size()) return false;
|
||||
for (int64_t j = lo; j < hi; ++j)
|
||||
(*out)[row0 + (size_t)(j - lo)] = s->blocks[g][(size_t)(j - first)];
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
int KVManager::seed_window(uint64_t id, int64_t pos) {
|
||||
Seq* s = find(id);
|
||||
if (!s) return RAD_E_NOTFOUND;
|
||||
/* Check every group before taking anything, as ensure() does. */
|
||||
for (size_t g = 0; g < plans_.size(); ++g) {
|
||||
const KVGroupPlan& p = plans_[g];
|
||||
if (!p.win_snap) continue;
|
||||
if (!s->blocks[g].empty()) return RAD_E_STATE;
|
||||
if (pos % p.block_size != 0) return RAD_E_INVAL;
|
||||
const int64_t need = pos / p.block_size - window_lo(p, pos);
|
||||
if (need > available_blocks((int32_t)g)) return RAD_E_FULL;
|
||||
RAD_TRY(grow_for((int32_t)g, need));
|
||||
}
|
||||
for (size_t g = 0; g < plans_.size(); ++g) {
|
||||
const KVGroupPlan& p = plans_[g];
|
||||
if (!p.win_snap) continue;
|
||||
const int64_t lo = window_lo(p, pos), hi = pos / p.block_size;
|
||||
s->first_block_pos[g] = lo * p.block_size;
|
||||
for (int64_t j = lo; j < hi; ++j) {
|
||||
int32_t b = -1;
|
||||
grab_block((int32_t)g, &b);
|
||||
s->blocks[g].push_back(b);
|
||||
}
|
||||
s->dirty_from[g] = 0;
|
||||
}
|
||||
if (s->n_tokens == 0) s->n_tokens = pos;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* HOW MANY COLUMNS A SEQUENCE'S state_index ROW HAS. One per physical copy would be the obvious
|
||||
|
||||
+63
-5
@@ -73,6 +73,11 @@ struct KVGroupPlan {
|
||||
int64_t bytes_per_state = 0; /* LINEAR/CONV: per sequence, every layer */
|
||||
int64_t conv_slots = 0; /* CONV: conv_width - 1 + n_spec */
|
||||
int64_t window_blocks = 0; /* WINDOW: the per-sequence block cap */
|
||||
/* WINDOW: a checkpoint slot carries this group's window (has_window_snapshot). Only a trunk
|
||||
* group of a model with no linear state: a prefix hit there resumes at a checkpoint from the
|
||||
* window behind it. A drafter's own window is recomputed by draft refill, and a model with
|
||||
* linear state re-prefills a hit on a windowed trunk, so neither snapshot would ever be read. */
|
||||
bool win_snap = false;
|
||||
|
||||
int64_t n_blocks = 0; /* paged groups: blocks carved from the pool */
|
||||
/* rad_kv_group_zero: this rank keeps no cache for the group. The plan exists for its position
|
||||
@@ -207,8 +212,31 @@ public:
|
||||
|
||||
/* Grow the sequence's mapping to cover `n_tokens` in every group. Unshares a shared partial
|
||||
* block first (copy-on-write) and appends the copy request to the pending list.
|
||||
* RAD_E_FULL when a group's free list is empty -- the caller preempts and retries. */
|
||||
int ensure(uint64_t seq, int64_t n_tokens);
|
||||
* RAD_E_FULL when a group's free list is empty -- the caller preempts and retries.
|
||||
*
|
||||
* `keep_from` is the position of the FIRST query the coming step runs (the scheduler's
|
||||
* n_computed); -1 means the sequence's current end. A WINDOW group recycles only the blocks no
|
||||
* query at or past it can read -- below keep_from - window + 1 -- and NOT the blocks below the
|
||||
* window of the step's END: a prefill chunk longer than a block would otherwise lose the keys
|
||||
* its first rows attend to (a chunk of C tokens from position 0 rebased the table at
|
||||
* ceil(C/block) - window_blocks and left every position below it with no KV at all). */
|
||||
int ensure(uint64_t seq, int64_t n_tokens, int64_t keep_from = -1);
|
||||
|
||||
/* A WINDOW group's caps: a sequence holds its window behind the step's first query AND the
|
||||
* step's own tokens (window_blocks + ceil(max_tok / block) + 1 at most), and one step carries
|
||||
* at most max_tok tokens across every sequence in it, so the pool needs max_seqs windows plus
|
||||
* one step's worth on top. */
|
||||
int64_t window_seq_cap(const KVGroupPlan& p) const;
|
||||
int64_t window_pool_cap(const KVGroupPlan& p) const;
|
||||
|
||||
/* GIVE BACK A FINISHED CHUNK'S BLOCKS once it is committed. ensure() keeps a chunk's own blocks
|
||||
* beside the window behind its first query, and only the sequence's NEXT ensure() recycles
|
||||
* them -- so a prefill waiting a step for its next chunk would sit on a whole chunk of window
|
||||
* blocks while other sequences prefill, and eight of them exhaust the pool (measured on
|
||||
* Gemma 4: "the KV pool cannot hold 12480 tokens" with eight 16K prompts). Called by the
|
||||
* scheduler when it advances n_computed: keep_from is the new n_computed, the first query any
|
||||
* later step can run. */
|
||||
void trim_window(uint64_t seq, int64_t keep_from);
|
||||
|
||||
/* Adopt blocks a prefix-cache hit found. `n_tokens` must be a whole multiple of the group's
|
||||
* block size: a partial block is never shared, because the next token written into it would
|
||||
@@ -462,8 +490,35 @@ public:
|
||||
* and the restore has to precede the step that consumes it, and both are ordered by the
|
||||
* stream rather than by waiting. One pitched copy a stateful group between the card and the
|
||||
* store, at the link's rate. RAD_E_INVAL on a bad slot or an unknown sequence. */
|
||||
int checkpoint_save(const int32_t* state_slots, int n_slots, int32_t ck_slot, RadStream s);
|
||||
int checkpoint_restore(const int32_t* state_slots, int n_slots, int32_t ck_slot, RadStream s);
|
||||
int checkpoint_save(const int32_t* state_slots, int n_slots, int32_t ck_slot, RadStream s,
|
||||
const std::vector<int32_t>* win = nullptr);
|
||||
int checkpoint_restore(const int32_t* state_slots, int n_slots, int32_t ck_slot, RadStream s,
|
||||
const std::vector<int32_t>* win = nullptr);
|
||||
|
||||
/* ---------------- window snapshots (the sliding-window half of a prefix hit) ----------------
|
||||
* A WINDOW group keeps only the blocks its window can still read, so no block list from the
|
||||
* prefix cache describes it. What a later prompt that extends a cached prefix at position P
|
||||
* needs from it is exactly the window behind P: blocks [lo, P/B) with
|
||||
* lo = max(0, P/B - (window_blocks - 1)) -- the floor recycle_window keeps for a query at P.
|
||||
* A checkpoint slot therefore carries, after the linear state, window_blocks pages a WINDOW
|
||||
* group (every layer, layer-major rows), and a hit at a checkpoint restores them into fresh
|
||||
* blocks seeded at that floor.
|
||||
*
|
||||
* has_window_snapshot(): this rank's slot carries a window section. window_rows() names, from
|
||||
* the LEADER's table, the block ids [lo, P/B) of every non-zero snapshot group (win_snap) in
|
||||
* plans() order, each group padded with -1 to window_blocks -- one vector every rank addresses
|
||||
* with its own pool, because followers keep no sequence tables. False when the sequence does
|
||||
* not hold that range (it is gone, or its floor moved past lo). seed_window() gives a sequence
|
||||
* with an empty table in each snapshot group the blocks [lo, P/B) a restore will fill, before
|
||||
* the ensure that extends it; any other WINDOW group starts at the floor that ensure sets. */
|
||||
bool has_window_snapshot() const { return window_ck_bytes_ > 0; }
|
||||
bool window_rows(uint64_t seq, int64_t pos, std::vector<int32_t>* out) const;
|
||||
int seed_window(uint64_t seq, int64_t pos);
|
||||
/* The floor and end (block indices) of the window a query at `pos` reads in a group. */
|
||||
static int64_t window_lo(const KVGroupPlan& p, int64_t pos) {
|
||||
const int64_t b = pos / p.block_size - (p.window_blocks - 1);
|
||||
return b > 0 ? b : 0;
|
||||
}
|
||||
|
||||
/* Byte address of a state slot, for the slot-mapping builder. Null when the pool has no
|
||||
* host-visible base (a device pool), which is the normal case -- the offset is what the step
|
||||
@@ -486,7 +541,7 @@ private:
|
||||
|
||||
/* One traversal serving both checkpoint directions; see checkpoint_save. */
|
||||
int checkpoint_copy(const int32_t* state_slots, int n_slots, int32_t ck_slot, bool save,
|
||||
RadStream s);
|
||||
RadStream s, const std::vector<int32_t>* win);
|
||||
|
||||
struct Seq {
|
||||
uint64_t id = 0;
|
||||
@@ -509,6 +564,8 @@ private:
|
||||
void drop_state(int32_t g, int32_t s);
|
||||
Seq* find(uint64_t seq);
|
||||
const Seq* find(uint64_t seq) const;
|
||||
/* Recycle a WINDOW group's blocks no query at or past `keep_from` can read. */
|
||||
void recycle_window(Seq* s, int64_t keep_from);
|
||||
|
||||
std::vector<KVGroupPlan> plans_;
|
||||
std::vector<std::vector<int32_t>> free_blocks_; /* per group */
|
||||
@@ -524,6 +581,7 @@ private:
|
||||
HostArena* ck_store_ = nullptr; /* set_checkpoint_store */
|
||||
int64_t ck_rank_off_ = 0;
|
||||
int64_t checkpoint_bytes_ = 0;
|
||||
int64_t window_ck_bytes_ = 0; /* the window section of checkpoint_bytes_ */
|
||||
std::vector<StateClear> clears_; /* grabbed slots the engine must zero */
|
||||
void* pool_base_ = nullptr;
|
||||
BundleComparison bundling_;
|
||||
|
||||
@@ -158,6 +158,9 @@ int PrefixCache::configure(const Config& cfg, KVManager* kv, int64_t checkpoint_
|
||||
}
|
||||
|
||||
interval_ = checkpoint_interval;
|
||||
/* A WINDOW SNAPSHOT is state in the same sense: a hit is reusable at a checkpoint only, where
|
||||
* the slot carries the window behind it (KVManager::has_window_snapshot). */
|
||||
if (kv->has_window_snapshot() && interval_ > 0) has_linear_ = true;
|
||||
if (has_linear_) {
|
||||
if (interval_ <= 0) {
|
||||
RAD_ERR("checkpoint_interval is %lld but the model has linear-attention state. A "
|
||||
|
||||
@@ -320,6 +320,9 @@ struct KVGroupInfo {
|
||||
int64_t bytes_per_state = 0; /* linear/conv: per sequence */
|
||||
std::vector<int> layers;
|
||||
bool zero = false; /* rad_kv_group_zero: declared for position, nothing carved */
|
||||
/* Bound only at meta.n_layers and above: the drafter's own cache, which no trunk layer reads.
|
||||
* Set at declare (Builder::finish_kv_groups). */
|
||||
bool drafter = false;
|
||||
};
|
||||
|
||||
/* A RAD_KV_CONV GROUP'S WINDOW, IN ENTRIES: conv_width - 1 of history and one more for every
|
||||
@@ -362,6 +365,12 @@ public:
|
||||
* RadDrafterDecl::name points into the plugin's own storage. */
|
||||
RadDrafterDecl drafter{};
|
||||
std::string drafter_name;
|
||||
/* A SERIAL HEAD WITH NO CACHE OF ITS OWN (rad_drafter_shared_kv): it reads the trunk's K and V
|
||||
* and writes none, so the driver owes it no history and runs every round at the committed
|
||||
* position. `drafter_pos_offset` is where those rows sit for the rotary, 0 or 1 past it. Both
|
||||
* are false and 0 for every drafter that did not ask, which is every one that predates it. */
|
||||
bool drafter_shared_kv = false;
|
||||
int32_t drafter_pos_offset = 0;
|
||||
|
||||
/* THE MEDIA ENCODER THIS PLUGIN DECLARED (rad_declare_encoder). `modalities == 0` when it
|
||||
* declared none, which is every text-only program and every deployment that asked for no
|
||||
|
||||
@@ -94,6 +94,13 @@ struct AdvanceArgs {
|
||||
* the host's position keeps the host's three components, which is what a media token needs. */
|
||||
int64_t rope_off = -1;
|
||||
int32_t rope_pitch = 0;
|
||||
/* A SERIAL HEAD WITH NO CACHE OF ITS OWN (rad_drafter_shared_kv), read by ADV_HIST and
|
||||
* ADV_ROUND alone: its history pass is one row a sequence at the committed position, and every
|
||||
* round sits there too, its context ending at that position. `rot_shift` is where those rows
|
||||
* sit for the rotary, 0 or 1 past the committed position. Zero for every other head, whose
|
||||
* passes advance exactly as they always did. */
|
||||
int32_t shared_kv = 0;
|
||||
int32_t rot_shift = 0;
|
||||
};
|
||||
|
||||
/* Issue one advance on `s`. The rows are independent, so the card runs them in parallel. */
|
||||
|
||||
@@ -109,6 +109,22 @@ RAD_ADV_FN void adv_row(const AdvanceArgs& a, int i) {
|
||||
return;
|
||||
}
|
||||
case ADV_HIST: {
|
||||
if (a.shared_kv) {
|
||||
/* A HEAD THAT READS THE TRUNK'S CACHE AND KEEPS NONE (rad_drafter_shared_kv). There is
|
||||
* no history to fill, so the pass is round 1 alone and its one row is the last one of
|
||||
* the run below: the committed position, the trunk's row there, the token the trunk
|
||||
* chose after it. Its context is the committed positions and NOT the verify step's
|
||||
* whole run -- the cache past the committed position holds the K and V of the drafts
|
||||
* this verify rejected. The host staged the run's first trunk row; the card adds the
|
||||
* drafts it accepted. */
|
||||
int32_t* out = adv_i32(a, a.out_off);
|
||||
tok[k] = a.src[rout + S.acc];
|
||||
adv_pos(a, pos, k, S.head + a.rot_shift);
|
||||
out[k] += S.acc;
|
||||
ctx[i] = S.head;
|
||||
adv_groups(a, i, k, S.head, 1);
|
||||
return;
|
||||
}
|
||||
/* `aux` positions the host already knew the tokens of, then the verify step's own
|
||||
* positions up to the last one it committed, each with the token committed after it --
|
||||
* the sampler's pick there, since the drafts before it agreed with it. The pass has a
|
||||
@@ -133,12 +149,14 @@ RAD_ADV_FN void adv_row(const AdvanceArgs& a, int i) {
|
||||
}
|
||||
case ADV_ROUND: {
|
||||
/* Round 2 onward: round 1 is the history pass's last row (ADV_HIST above), so every
|
||||
* round embeds the proposal of the round before it. */
|
||||
const int32_t base = S.head + a.round - 1;
|
||||
* round embeds the proposal of the round before it. A head with no cache of its own does
|
||||
* not step forward: it stays at the committed position over the committed context, and
|
||||
* what it proposed reaches the next round through its own hidden state. */
|
||||
const int32_t base = a.shared_kv ? S.head : S.head + a.round - 1;
|
||||
const int32_t t = a.src[(int64_t)i * a.src_pitch];
|
||||
S.tok[a.round - 1] = t;
|
||||
tok[k] = t;
|
||||
adv_pos(a, pos, k, base);
|
||||
adv_pos(a, pos, k, a.shared_kv ? base + a.rot_shift : base);
|
||||
ctx[i] = base;
|
||||
adv_groups(a, i, k, base, 1);
|
||||
return;
|
||||
|
||||
@@ -185,8 +185,12 @@ void BatchBuilder::size_set(Set& s, const std::vector<KVGroupInfo>& groups) {
|
||||
s.groups[gi].block_size = e.block_size;
|
||||
int64_t mb = 1;
|
||||
if (e.paged) {
|
||||
int64_t span = (e.kind == RAD_KV_WINDOW && e.window > 0 && e.window < max_ctx_)
|
||||
? e.window : max_ctx_;
|
||||
/* A WINDOW row holds the window behind the step's first query AND the step's own
|
||||
* tokens (KVManager::ensure keeps both), so it is sized for a whole chunk past the
|
||||
* window -- plus the speculative lookahead, which a verify row carries on top. */
|
||||
const int64_t wspan = e.window + max_tok_ + 2 * ((int64_t)std::max(cfg_.n_spec, 0) + 1);
|
||||
int64_t span = (e.kind == RAD_KV_WINDOW && e.window > 0 && wspan < max_ctx_)
|
||||
? wspan : max_ctx_;
|
||||
mb = (span + e.block_size - 1) / e.block_size + 1;
|
||||
}
|
||||
s.groups[gi].max_blocks = mb;
|
||||
|
||||
+14
-5
@@ -47,12 +47,16 @@ int chunk_geometry_resolve(const Program& prog, const Config& cfg, ChunkGeometry
|
||||
* the same block size -- libr4d's is 16 for all of them -- but a hybrid model with a
|
||||
* sliding-window group served by a different kernel is exactly the case §7.2 is written for,
|
||||
* and lcm is the answer that is right for both. */
|
||||
bool has_linear = false;
|
||||
bool has_linear = false, has_window = false;
|
||||
for (const KVGroupInfo& kg : prog.kv_groups) {
|
||||
if (kg.decl.kind == RAD_KV_FULL || kg.decl.kind == RAD_KV_WINDOW) {
|
||||
if (kg.block_size > 0) {
|
||||
g.attn_block = lcm64(g.attn_block, kg.block_size);
|
||||
note(g.why, "attn_block", kg.block_size, kg.name.c_str());
|
||||
/* A drafter's window is recomputed by draft refill; only the trunk's needs a
|
||||
* snapshot for a prefix hit to resume. */
|
||||
if (kg.decl.kind == RAD_KV_WINDOW && !kg.layers.empty() && !kg.drafter)
|
||||
has_window = true;
|
||||
}
|
||||
} else {
|
||||
has_linear = true;
|
||||
@@ -123,11 +127,14 @@ int chunk_geometry_resolve(const Program& prog, const Config& cfg, ChunkGeometry
|
||||
* because down can reach zero and because a longer interval costs retention, not correctness.
|
||||
*
|
||||
* No linear state means no checkpoints: the interval is a property of a state kind that this
|
||||
* model does not have, and pretending otherwise would split chunks for nothing. */
|
||||
if (has_linear && cfg.checkpoint_interval > 0)
|
||||
* model does not have, and pretending otherwise would split chunks for nothing. The one
|
||||
* exception is a trunk window under a prefix cache, which snapshots the window behind a
|
||||
* prompt's tail (window_ckpt) and does not split chunks for it. */
|
||||
if ((has_linear || (has_window && cfg.prefix_cache)) && cfg.checkpoint_interval > 0)
|
||||
g.checkpoint_interval = align_up(cfg.checkpoint_interval, g.quantum);
|
||||
else
|
||||
g.checkpoint_interval = 0;
|
||||
g.window_ckpt = !has_linear && g.checkpoint_interval > 0;
|
||||
|
||||
/* One full quantum has to fit in one step. Below that, every chunk is short, no chunk ever
|
||||
* ends on a boundary, and the checkpoint lands wherever the step happened to end -- which is
|
||||
@@ -150,8 +157,10 @@ int chunk_geometry_resolve(const Program& prog, const Config& cfg, ChunkGeometry
|
||||
* always written, and that clamp comes FIRST. Printing only the budget would hide it -- every
|
||||
* budget above the interval runs the same chunk length, so a sweep over them reads as
|
||||
* "prefill is flat against the chunk" when nothing about the chunk changed. The clamp itself
|
||||
* is correct; a budget that silently does nothing is what has to be visible. */
|
||||
const int64_t eff = (g.checkpoint_interval > 0 && g.checkpoint_interval < cfg.max_tok)
|
||||
* is correct; a budget that silently does nothing is what has to be visible. A window
|
||||
* snapshot is taken at the prompt's tail and splits nothing. */
|
||||
const int64_t eff = (g.checkpoint_interval > 0 && !g.window_ckpt &&
|
||||
g.checkpoint_interval < cfg.max_tok)
|
||||
? g.checkpoint_interval : cfg.max_tok;
|
||||
RAD_INFO("chunk geometry: quantum %lld (attn block %lld, state chunk %lld), checkpoint "
|
||||
"interval %lld, max_tok %lld -> prefill chunks of at most %lld%s",
|
||||
|
||||
@@ -48,6 +48,12 @@ struct ChunkGeometry {
|
||||
/* Every contributor by name, for the startup line and for the refusal. Built once. */
|
||||
std::string why;
|
||||
|
||||
/* NO LINEAR STATE, A SLIDING WINDOW: the checkpoint snapshots the window behind a prompt's
|
||||
* tail (KVManager::has_window_snapshot) and nothing else. Chunks are not split at the
|
||||
* interval -- a window snapshot in the middle of a prompt buys a later hit nothing its tail
|
||||
* does not -- and the interval is only the shortest prompt worth a snapshot. */
|
||||
bool window_ckpt = false;
|
||||
|
||||
bool checkpoints() const { return checkpoint_interval > 0; }
|
||||
};
|
||||
|
||||
|
||||
@@ -46,6 +46,20 @@ struct IKVManager {
|
||||
* free list is empty, which is a scheduling signal and not an error: the caller preempts a
|
||||
* victim and retries. */
|
||||
virtual int ensure(uint64_t seq, int64_t n_tokens) = 0;
|
||||
/* The same, for a step whose first query sits at `keep_from` (the request's n_computed): a
|
||||
* WINDOW group then keeps every block that query can still read, however long the step is.
|
||||
* See KVManager::ensure. The default is for a manager with no windowed group. */
|
||||
virtual int ensure_from(uint64_t seq, int64_t n_tokens, int64_t keep_from) {
|
||||
(void)keep_from;
|
||||
return ensure(seq, n_tokens);
|
||||
}
|
||||
/* A committed step: a WINDOW group gives back what no later query can read. A no-op for a
|
||||
* manager with no windowed group. See KVManager::trim_window. */
|
||||
virtual void trim_window(uint64_t seq, int64_t keep_from) { (void)seq; (void)keep_from; }
|
||||
/* The window snapshot of a prefix hit (KVManager::has_window_snapshot / seed_window). The
|
||||
* defaults are a manager with none: no hit on a windowed trunk is ever resumed. */
|
||||
virtual bool has_window_snapshot() const { return false; }
|
||||
virtual int seed_window(uint64_t seq, int64_t pos) { (void)seq; (void)pos; return -1; }
|
||||
|
||||
/* Adopt blocks a prefix-cache hit found. `n_tokens` must be a whole multiple of the group's
|
||||
* block size -- a partial block is never shared, because the next token written into it would
|
||||
@@ -282,6 +296,10 @@ struct KVBinding final : IKVManager {
|
||||
bool has_sequence(uint64_t s) const override { return m->has_sequence(s); }
|
||||
void free_sequence(uint64_t s) override { m->free_sequence(s); }
|
||||
int ensure(uint64_t s, int64_t n) override { return m->ensure(s, n); }
|
||||
int ensure_from(uint64_t s, int64_t n, int64_t k) override { return m->ensure(s, n, k); }
|
||||
void trim_window(uint64_t s, int64_t k) override { m->trim_window(s, k); }
|
||||
bool has_window_snapshot() const override { return m->has_window_snapshot(); }
|
||||
int seed_window(uint64_t s, int64_t p) override { return m->seed_window(s, p); }
|
||||
int adopt(uint64_t s, int32_t g, const std::vector<int32_t>& b, int64_t n) override {
|
||||
return m->adopt(s, g, b, n);
|
||||
}
|
||||
|
||||
+104
-13
@@ -87,6 +87,21 @@ int Scheduler::init(Program& prog, const Config& cfg, IKVManager* kv, IPrefixCac
|
||||
n_paged, pc->cached_groups().size(),
|
||||
hit_holes_draft_ ? "LEAVES a hole in a drafter's own KV" : "leaves no hole");
|
||||
}
|
||||
/* THE TRUNK'S SHARE of that question: a paged group a TRUNK layer reads (a bound layer below
|
||||
* the trunk's layer count — a drafter borrows from base_layer and above) that the cache does
|
||||
* not index. Its hole is not repairable by recomputing the tail; see scheduler.h. */
|
||||
hit_holes_trunk_ = false;
|
||||
for (size_t i = 0; i < prog.kv_groups.size(); ++i) {
|
||||
if (kv->block_tokens((int32_t)i) <= 0) continue;
|
||||
bool trunk = false;
|
||||
for (int l : prog.kv_groups[i].layers) if (l < prog.meta.n_layers) { trunk = true; break; }
|
||||
if (!trunk) continue;
|
||||
const std::vector<int32_t>& cg = pc->cached_groups();
|
||||
if (std::find(cg.begin(), cg.end(), (int32_t)i) == cg.end()) { hit_holes_trunk_ = true; break; }
|
||||
}
|
||||
if (hit_holes_trunk_ && cfg.prefix_cache)
|
||||
RAD_INFO("prefix cache: a trunk layer's windowed group is not prefix-cached -- a hit "
|
||||
"resumes from a window snapshot (a checkpoint slot) or re-prefills");
|
||||
draft_refill_ = 0;
|
||||
if (cfg.n_spec > 0 && prog.drafter.kind == RAD_DRAFT_BLOCK && prog.drafter.window > 0 &&
|
||||
hit_holes_draft_) {
|
||||
@@ -95,6 +110,14 @@ int Scheduler::init(Program& prog, const Config& cfg, IKVManager* kv, IPrefixCac
|
||||
"drafter's window is recomputed", (long long)draft_refill_);
|
||||
}
|
||||
|
||||
serial_shared_ = cfg.n_spec > 0 && prog.drafter.kind == RAD_DRAFT_SERIAL &&
|
||||
prog.drafter_shared_kv;
|
||||
serial_rot_shift_ = serial_shared_ ? prog.drafter_pos_offset : 0;
|
||||
if (serial_shared_)
|
||||
RAD_INFO("serial drafter: reads the trunk's cache and keeps none -- no history pass, one "
|
||||
"row a drafting sequence, every round at the committed position%s",
|
||||
serial_rot_shift_ ? " (rotated one past it)" : "");
|
||||
|
||||
DraftController::Params dp;
|
||||
dp.max_depth = cfg.n_spec;
|
||||
/* THE ADAPTIVE WINDOW IS THE SERIAL DRAFTER'S POLICY (draft.h): it prices a draft as one more
|
||||
@@ -726,6 +749,7 @@ int64_t Scheduler::plan_chunk(int64_t n_computed, int64_t n_target, int64_t budg
|
||||
if (geo_.checkpoints()) {
|
||||
const int64_t I = geo_.checkpoint_interval;
|
||||
int64_t next = ((n_computed / I) + 1) * I; /* strictly after n_computed */
|
||||
if (geo_.window_ckpt) next = INT64_MAX; /* a window snapshot: the tail only */
|
||||
if (n_computed + want > next) want = next - n_computed;
|
||||
if (n_computed + want == next) {
|
||||
if (checkpoint_pos) *checkpoint_pos = next;
|
||||
@@ -778,6 +802,7 @@ int64_t Scheduler::plan_chunk(int64_t n_computed, int64_t n_target, int64_t budg
|
||||
bool Scheduler::last_checkpoint(int64_t pos, int64_t target) const {
|
||||
if (!geo_.checkpoints()) return false;
|
||||
const int64_t I = geo_.checkpoint_interval;
|
||||
if (geo_.window_ckpt) { const int64_t t = tail_checkpoint(target); return t > 0 && t <= pos; }
|
||||
if ((pos / I + 1) * I <= target) return false;
|
||||
return tail_checkpoint(target) <= pos;
|
||||
}
|
||||
@@ -789,6 +814,15 @@ int64_t Scheduler::tail_checkpoint(int64_t target) const {
|
||||
const int64_t I = geo_.checkpoint_interval, Q = geo_.quantum;
|
||||
if (I <= 0 || Q <= 0) return -1;
|
||||
const int64_t tail = target / Q * Q;
|
||||
/* A WINDOW SNAPSHOT is taken at the tail of any prompt of an interval or more. */
|
||||
/* A block short of the end: the next turn re-renders the last few tokens (a generation
|
||||
* prompt it replaces with the reply), and a snapshot past where the two renderings part is
|
||||
* one no hit can reach -- measured: every prompt whose length left fewer than ~8 tokens in
|
||||
* its last block missed. */
|
||||
if (geo_.window_ckpt) {
|
||||
const int64_t t = (target - std::max<int64_t>(Q, 16)) / Q * Q;
|
||||
return t >= I ? t : -1;
|
||||
}
|
||||
return tail > I && tail - tail / I * I >= std::max<int64_t>(Q, I / 4) ? tail : -1;
|
||||
}
|
||||
|
||||
@@ -864,7 +898,7 @@ int64_t Scheduler::busy_cap(int64_t n_computed, int64_t n_target, int64_t budget
|
||||
cap = std::max(cap, floor);
|
||||
const int64_t remaining = n_target - n_computed;
|
||||
int64_t span = remaining; /* where this run of chunks must end */
|
||||
if (geo_.checkpoints()) {
|
||||
if (geo_.checkpoints() && !geo_.window_ckpt) {
|
||||
const int64_t I = geo_.checkpoint_interval;
|
||||
span = std::min(span, ((n_computed / I) + 1) * I - n_computed);
|
||||
}
|
||||
@@ -978,6 +1012,36 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget, int64_t reserve) {
|
||||
* snapshot to resume from -- that is every recurrent layer continuing from whatever the
|
||||
* slot last held, and it reads as fluent text rather than as a failure. */
|
||||
if (reuse > 0 && has_linear_state_ && h.checkpoint_slot < 0) reuse = 0;
|
||||
/* A WINDOW SNAPSHOT COVERS THE TRUNK'S WINDOWED GROUPS -- at the checkpoint and nowhere
|
||||
* else. The lookup clamped the hit to it (PrefixCache: a window counts as state there),
|
||||
* so a hit with a slot is exactly at a snapshot; one without is no hit. */
|
||||
const bool win_hit = geo_.window_ckpt && kv_->has_window_snapshot() && reuse > 0 &&
|
||||
h.checkpoint_slot >= 0 && reuse == h.n_linear_tokens;
|
||||
|
||||
/* THE WINDOWED-GROUP CLAMP — a prefix hit on a model whose OWN (trunk) KV includes a
|
||||
* paged group the cache does not index. prefix.cpp skips RAD_KV_WINDOW groups — their
|
||||
* blocks below the window are recycled, so no block list describes them; the comment
|
||||
* there says a hit "costs the sequences ... a windowed layer whose cache starts where
|
||||
* the hit ended" — this is that cost in KV corruption. The adopted blocks cover the
|
||||
* cached groups ONLY, while `used = ctx_len + n_tokens` (batch.cpp) makes every
|
||||
* windowed trunk layer read the positions below ctx_len that this sequence NEVER WROTE
|
||||
* — and grab_block's min-heap (kv.cpp) hands this sequence the very blocks the most
|
||||
* recent tenant wrote. The model then attends to the PREVIOUS REQUEST'S KV as its own
|
||||
* prefix: fluent text carrying the last request's CONTENT. Zero the reuse; the whole
|
||||
* prompt re-prefills, which is what a window snapshot (below) exists to avoid -- seconds
|
||||
* to minutes of first-token time on a long agent turn.
|
||||
*
|
||||
* NOT the drafter's hole. A drafter's own group (bound at base_layer and above — see
|
||||
* scheduler.h) is repaired by draft refill, which CAPS the hit so the recompute covers
|
||||
* the drafter's window while the trunk reuses the rest; zeroing here would delete that
|
||||
* design. The trunk's hole, which no tail-recompute can fix, is this clamp's own. */
|
||||
if (reuse > 0 && hit_holes_trunk_ && !win_hit) {
|
||||
reuse = 0;
|
||||
RAD_DEBUG("admit %llu: prefix hit %lld zeroed -- a trunk paged group is not "
|
||||
"prefix-cached (windowed) and no window snapshot covers it; re-prefilling",
|
||||
(unsigned long long)r.id,
|
||||
(long long)h.n_attn_tokens);
|
||||
}
|
||||
|
||||
/* Claim the cached blocks. Without this the hit is only an accounting entry: the sequence
|
||||
* would skip computing those tokens and then attend to blocks it does not own. adopt()
|
||||
@@ -998,11 +1062,18 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget, int64_t reserve) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
/* The windowed groups start at the floor of the window behind the hit, in fresh
|
||||
* blocks the entry's restore fills from the snapshot. */
|
||||
if (reuse > 0 && win_hit && kv_->seed_window(r.id, reuse) < 0) {
|
||||
kv_->preempt(r.id);
|
||||
reuse = 0;
|
||||
}
|
||||
}
|
||||
|
||||
r.n_computed = reuse;
|
||||
r.n_cached = reuse;
|
||||
s.ckpt_src = (reuse > 0 && reuse == h.n_linear_tokens) ? h.checkpoint_slot : -1;
|
||||
s.ckpt_src = (reuse > 0 && reuse == h.n_linear_tokens &&
|
||||
(has_linear_state_ || win_hit)) ? h.checkpoint_slot : -1;
|
||||
s.hit_attn = h.n_attn_tokens;
|
||||
}
|
||||
|
||||
@@ -1026,7 +1097,7 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget, int64_t reserve) {
|
||||
/* THE CACHE GIVES WAY TO A NEW REQUEST as it does to a running one: with nothing running,
|
||||
* no other path would ever take blocks back from it, and the request would wait for good. */
|
||||
int rounds = 0;
|
||||
while (kv_->ensure(r.id, r.n_computed + want) < 0) {
|
||||
while (kv_->ensure_from(r.id, r.n_computed + want, r.n_computed) < 0) {
|
||||
if (++rounds > 256 || !cfg_.prefix_cache || pc_->evict(256) <= 0) {
|
||||
rc = RAD_E_NOMEM;
|
||||
break;
|
||||
@@ -1217,7 +1288,7 @@ const RadBatch* Scheduler::step() {
|
||||
static const int kMaxEvictRounds = 256;
|
||||
int evict_rounds = 0;
|
||||
bool failed = false;
|
||||
while (kv_->ensure(r.id, r.n_computed + want) < 0) {
|
||||
while (kv_->ensure_from(r.id, r.n_computed + want, r.n_computed) < 0) {
|
||||
/* THE CACHE GIVES ITS BLOCKS BACK BEFORE A RUNNING REQUEST DOES. Everything the prefix
|
||||
* cache holds is a saving on work that has already been done once; everything a
|
||||
* running request holds is work in flight. Evicting first is therefore strictly the
|
||||
@@ -1429,7 +1500,7 @@ const RadBatch* Scheduler::step() {
|
||||
int64_t ckpt = -1;
|
||||
const int64_t grown = e.ckpt_slot < 0 && limit > had
|
||||
? plan_chunk(r.n_computed, s.seq_len(), limit, &ckpt, r.checkpoint_at) : had;
|
||||
if (grown > had && kv_->ensure(r.id, r.n_computed + grown) >= 0) {
|
||||
if (grown > had && kv_->ensure_from(r.id, r.n_computed + grown, r.n_computed) >= 0) {
|
||||
e.n_tokens = (int32_t)grown;
|
||||
e.produces_token = (r.n_computed + grown >= s.seq_len());
|
||||
if (ckpt > 0) {
|
||||
@@ -1681,7 +1752,7 @@ const RadBatch* Scheduler::step_next_locked() {
|
||||
const int32_t d = s.draft_next;
|
||||
const int64_t want = 1 + d;
|
||||
if (ctx_limit_ > 0 && ctx_up + want > ctx_limit_) return nullptr;
|
||||
if (kv_->ensure(r.id, ctx_up + want) < 0) return nullptr;
|
||||
if (kv_->ensure_from(r.id, ctx_up + want, r.n_computed) < 0) return nullptr;
|
||||
|
||||
StepEntry n;
|
||||
n.req = &r;
|
||||
@@ -1822,6 +1893,10 @@ int Scheduler::commit(const StepResult& res) {
|
||||
|
||||
if (e.is_prefill) {
|
||||
r.n_computed += e.n_tokens;
|
||||
/* The chunk is committed: a window group gives its blocks below the window back now,
|
||||
* not at this sequence's next ensure(), which may be steps away while others
|
||||
* prefill. */
|
||||
kv_->trim_window(r.id, r.n_computed);
|
||||
step_prefill_tok_ += e.n_tokens;
|
||||
server::sink_prompt_progress(r.sink, r.n_computed, (int32_t)r.prompt.size(),
|
||||
r.n_cached);
|
||||
@@ -2158,7 +2233,8 @@ int Scheduler::serial_begin(int* rounds, SerialRow* out, int max) {
|
||||
* unwritten in the head's layer for good. The same goes for a row too near the end of the
|
||||
* context for its rounds, whose last positions do not exist. */
|
||||
if (can_draft && ctx_limit_ > 0 && head_max + *rounds > ctx_limit_) can_draft = false;
|
||||
if (can_draft && kv_->ensure(r.id, head_max + *rounds) < 0) can_draft = false;
|
||||
if (can_draft && kv_->ensure_from(r.id, head_max + *rounds, r.n_computed) < 0)
|
||||
can_draft = false;
|
||||
|
||||
/* THE HISTORY THIS STEP OWES, in two parts. Before the verified positions, the positions
|
||||
* the step computed whose next token the host holds -- a prefill chunk's prompt -- from
|
||||
@@ -2179,9 +2255,19 @@ int Scheduler::serial_begin(int* rounds, SerialRow* out, int max) {
|
||||
const int64_t owed_end = e.produces_token ? vstart : (int64_t)e.ctx_len + e.n_tokens;
|
||||
int64_t hs = s.draft_filled > e.ctx_len ? s.draft_filled : (int64_t)e.ctx_len;
|
||||
if (hs > owed_end) hs = owed_end;
|
||||
const int64_t lead = owed_end - hs;
|
||||
int64_t lead = owed_end - hs;
|
||||
const int64_t verified = e.produces_token ? e.n_spec + 1 : 0;
|
||||
const int64_t hist_n = lead + verified;
|
||||
int64_t hist_n = lead + verified;
|
||||
|
||||
/* A HEAD WITH NO CACHE OF ITS OWN IS OWED NO HISTORY (rad_drafter_shared_kv). Its one row
|
||||
* is round 1's -- the committed position, whichever of the verified ones the card says it
|
||||
* is -- and a sequence that does not draft has nothing to run at all. */
|
||||
if (serial_shared_) {
|
||||
if (!can_draft) continue;
|
||||
hs = vstart;
|
||||
lead = 0;
|
||||
hist_n = 1;
|
||||
}
|
||||
|
||||
if (!can_draft && hist_n <= 0) continue; /* nothing owed and nothing to draft */
|
||||
|
||||
@@ -2191,7 +2277,9 @@ int Scheduler::serial_begin(int* rounds, SerialRow* out, int max) {
|
||||
m.card = e.card;
|
||||
m.hist_row = (int32_t)(base + (hs - e.ctx_len));
|
||||
m.hist_n = (int32_t)hist_n;
|
||||
m.hist_pos = hs;
|
||||
/* The shared head's one row sits wherever the card's acceptance puts it; the host stages
|
||||
* the furthest that can be, as it does for every round. */
|
||||
m.hist_pos = serial_shared_ ? head_max : hs;
|
||||
m.dev = e.produces_token;
|
||||
m.dev_tok = (int32_t)(base + (vstart - e.ctx_len));
|
||||
m.dev_out = e.dev_out;
|
||||
@@ -2250,8 +2338,10 @@ const RadBatch* Scheduler::serial_batch(int round, int step) {
|
||||
e.card = m.card;
|
||||
e.n_tokens = round == 0 ? m.hist_n : 1;
|
||||
/* A round's position is the card's; the host stages the furthest it can be, which is what
|
||||
* every host-side ceiling reads. The history's are known here exactly. */
|
||||
e.ctx_len = (int32_t)(round == 0 ? m.hist_pos : m.base_pos + (round - 1));
|
||||
* every host-side ceiling reads. The history's are known here exactly. A head with no
|
||||
* cache of its own does not step forward, so neither does its ceiling. */
|
||||
e.ctx_len = (int32_t)(round == 0 ? m.hist_pos
|
||||
: m.base_pos + (serial_shared_ ? 0 : round - 1));
|
||||
e.n_spec = 0;
|
||||
/* One-based and constant: a head pass commits exactly the tokens it was handed. The head
|
||||
* issues no linear-state op, so nothing reads it; it is set rather than left at a value
|
||||
@@ -2409,7 +2499,8 @@ int Scheduler::block_begin(int block, int depth, int window, int32_t mask, Block
|
||||
/* The query block writes positions n_computed .. n_computed + block - 1, and none of them
|
||||
* may be at or past the end of the context. */
|
||||
const bool ok_ctx = ctx_limit_ <= 0 || r.n_computed + block <= ctx_limit_;
|
||||
const bool ok_kv = ok_room && ok_ctx && kv_->ensure(r.id, r.n_computed + block) >= 0;
|
||||
const bool ok_kv = ok_room && ok_ctx &&
|
||||
kv_->ensure_from(r.id, r.n_computed + block, r.n_computed) >= 0;
|
||||
static const bool dbg = [] { const char* v = std::getenv("RADIANCE_DEBUG_DRAFT");
|
||||
return v && *v && *v != '0'; }();
|
||||
if (dbg) {
|
||||
|
||||
+26
-2
@@ -191,8 +191,14 @@ public:
|
||||
|
||||
/* The batch the last build produced for one rank; see BatchBuilder::batch_for. */
|
||||
const RadBatch* batch_for(int rank) const { return builder_.batch_for(rank); }
|
||||
/* The advance's view of that build on one rank; see BatchBuilder::advance_args. */
|
||||
AdvanceArgs advance_args(int rank) const { return builder_.advance_args(rank); }
|
||||
/* The advance's view of that build on one rank; see BatchBuilder::advance_args. It carries
|
||||
* the serial head's shape as well, which only the draft passes' modes read. */
|
||||
AdvanceArgs advance_args(int rank) const {
|
||||
AdvanceArgs a = builder_.advance_args(rank);
|
||||
a.shared_kv = serial_shared_ ? 1 : 0;
|
||||
a.rot_shift = serial_rot_shift_;
|
||||
return a;
|
||||
}
|
||||
void fini();
|
||||
|
||||
/* ---------------------------------------------------------- off the step path */
|
||||
@@ -505,6 +511,18 @@ private:
|
||||
* also skips on a block-size mismatch. A bound like this lives in exactly one place; a second
|
||||
* copy is free to drift out of step with the first. */
|
||||
bool hit_holes_draft_ = true;
|
||||
/* DOES A HIT HOLE THE TRUNK ITSELF? hit_holes_draft_ is the drafter's guard, and draft_refill_
|
||||
* repairs a drafter hole by recomputing the prompt's TAIL. A TRUNK group the cache does not
|
||||
* index admits no such repair: the adopted blocks cover the cached groups only, while the
|
||||
* windowed trunk layers read the positions below ctx_len this sequence never wrote — the KV of
|
||||
* whoever held these blocks last. So a trunk hole refuses the hit outright.
|
||||
*
|
||||
* THE TRUNK IS WHICH GROUPS? The one a drafter borrows is bound at `base_layer` and above —
|
||||
* the drafter's layers run after the trunk's (rad_bind_layer_kv at the drafter declare), so a
|
||||
* group with a bound layer below meta.n_layers belongs to the trunk and a hit must cover it;
|
||||
* a drafter's own group is the refill's business, not this clamp's. Read off the Program,
|
||||
* which carries both the bindings and the trunk's layer count. */
|
||||
bool hit_holes_trunk_ = false;
|
||||
/* DRAFT REFILL. Where a hit leaves a hole in a WINDOWED block drafter's cache, the drafter is
|
||||
* declined until its window has slid past the hole, which on the follow-up turn of a chat --
|
||||
* the turn a prefix hit is for -- is most or all of the reply. So the hit is ended one window
|
||||
@@ -514,6 +532,12 @@ private:
|
||||
* that point would give back more than two windows is kept whole. The drafter's window, or 0
|
||||
* where no hit can leave such a hole. */
|
||||
int64_t draft_refill_ = 0;
|
||||
/* A SERIAL HEAD WITH NO CACHE OF ITS OWN (rad_drafter_shared_kv), off the Program at init. It
|
||||
* owes no history, so serial_begin gives it one row a drafting sequence and none to a sequence
|
||||
* that does not draft, and its rounds stay at the committed position (advance.h). False and 0
|
||||
* for every other drafter, whose passes are staged exactly as before. */
|
||||
bool serial_shared_ = false;
|
||||
int32_t serial_rot_shift_ = 0;
|
||||
BatchBuilder builder_;
|
||||
DraftController draft_;
|
||||
|
||||
|
||||
+203
-32
@@ -13,6 +13,7 @@
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <cstddef>
|
||||
#include <cstring>
|
||||
#include <functional>
|
||||
@@ -45,6 +46,75 @@ bool starts_with(const std::string& s, const std::string& p) {
|
||||
|
||||
std::string show(const std::string& s) { return nlohmann::json(s).dump(); }
|
||||
|
||||
int refuse(std::string* why, const std::string& s) {
|
||||
if (why) *why = s;
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
/* A byte that begins a bare word or a JSON value, or is the object's own punctuation. */
|
||||
bool object_byte(unsigned char c) {
|
||||
return c == 0 || std::isalnum(c) || is_ws(c) || std::strchr("-+._'\"{}[],:", (int)c) != nullptr;
|
||||
}
|
||||
|
||||
/* An argument object, as the streaming parser reads it (chatparse.cpp). Where a key or a value
|
||||
* may begin, it tells three literals apart by their first bytes: a dialect string's opener, and
|
||||
* the call's close and end, which a reply that leaves its object unclosed writes there. None may
|
||||
* begin another. A bare word ends at the object's punctuation or at the call's close; one
|
||||
* automaton finds both in the order they start only when the close holds none of it. */
|
||||
int object_check(const ChatFormat& f, std::string* why) {
|
||||
const std::string& so = f.object_string_open;
|
||||
const std::string& sc = f.object_string_close;
|
||||
if (so.empty() != sc.empty())
|
||||
return refuse(why, "object_string_open and object_string_close are set together or not "
|
||||
"at all");
|
||||
if (!so.empty()) {
|
||||
if (trim_ws(so) != so || trim_ws(sc) != sc)
|
||||
return refuse(why, "an object string delimiter may not begin or end with "
|
||||
"whitespace");
|
||||
if (object_byte((unsigned char)so[0]))
|
||||
return refuse(why, "object_string_open " + show(so) + " begins with a byte that also "
|
||||
"begins a bare word, a JSON value or the object's punctuation");
|
||||
}
|
||||
std::vector<std::string> lits;
|
||||
if (!so.empty()) lits.push_back(so);
|
||||
const std::string cc = trim_ws(f.call_close), ce = trim_ws(f.call_end);
|
||||
for (const std::string* s : { &cc, &ce }) {
|
||||
if (s->empty()) continue;
|
||||
for (char c : *s)
|
||||
if (std::strchr(",:{}[]\"", c))
|
||||
return refuse(why, "the call's close " + show(*s) + " holds " +
|
||||
show(std::string(1, c)) + ", which is the argument object's "
|
||||
"punctuation");
|
||||
if (std::find(lits.begin(), lits.end(), *s) == lits.end()) lits.push_back(*s);
|
||||
else if (!so.empty() && *s == so)
|
||||
return refuse(why, show(*s) + " both opens an object string and closes the call");
|
||||
}
|
||||
for (size_t i = 0; i < lits.size(); ++i)
|
||||
for (size_t j = 0; j < lits.size(); ++j)
|
||||
if (i != j && (starts_with(lits[i], lits[j]) || occurs_inside(lits[j], lits[i])))
|
||||
return refuse(why, show(lits[j]) + " and " + show(lits[i]) + " cannot be told "
|
||||
"apart inside an argument object");
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* Content is scanned for a later reasoning block's opener and for a stray close beside the call
|
||||
* openers, in one automaton, which reports them in the order they start only when none occurs
|
||||
* inside another or begins it. */
|
||||
int reasoning_anywhere_check(const ChatFormat& f, std::string* why) {
|
||||
if (!f.reasoning_anywhere) return RAD_OK;
|
||||
std::vector<std::string> d = { trim_ws(f.reasoning_open), trim_ws(f.reasoning_close) };
|
||||
if (f.has_tools()) {
|
||||
if (!f.call_open.empty()) d.push_back(trim_ws(f.call_open));
|
||||
d.push_back(f.name_prefix);
|
||||
}
|
||||
for (size_t i = 0; i < d.size(); ++i)
|
||||
for (size_t j = 0; j < d.size(); ++j)
|
||||
if (i != j && (starts_with(d[i], d[j]) || occurs_inside(d[j], d[i])))
|
||||
return refuse(why, show(d[j]) + " and " + show(d[i]) + " cannot be told apart in "
|
||||
"content, which a reasoning block may open anywhere in");
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
/* ================================================================== validity */
|
||||
@@ -61,16 +131,24 @@ int chat_format_check(const ChatFormat& f, std::string* why) {
|
||||
return no("reasoning_close is only whitespace");
|
||||
if ((uint32_t)f.reasoning_in_prompt > (uint32_t)ChatThink::Never)
|
||||
return no("reasoning_in_prompt is not a RAD_CHAT_THINK_* value");
|
||||
if ((uint32_t)f.args_form > (uint32_t)ChatArgs::Object)
|
||||
return no("args_form is not a RAD_CHAT_ARGS_* value");
|
||||
/* A block that opens later in the reply is found by its opener, in content. */
|
||||
if (f.reasoning_anywhere && (!f.has_reasoning() || trim_ws(f.reasoning_open).empty()))
|
||||
return no("reasoning_anywhere needs a reasoning block with an opener");
|
||||
|
||||
if (!f.has_tools()) {
|
||||
for (const std::string* s : { &f.section_open, &f.section_close, &f.call_separator,
|
||||
&f.call_open, &f.call_close, &f.name_suffix, &f.call_end,
|
||||
&f.arg_prefix, &f.arg_name_suffix, &f.arg_value_prefix,
|
||||
&f.arg_value_suffix })
|
||||
&f.arg_value_suffix, &f.object_string_open,
|
||||
&f.object_string_close })
|
||||
if (!s->empty()) return no("tool-call delimiters are set but name_prefix is empty");
|
||||
if (f.object_args() || f.object_bare_keys)
|
||||
return no("an argument object is described but name_prefix is empty");
|
||||
if (!f.reasoning_breaks.empty()) return no("reasoning_breaks without tool calls");
|
||||
if (!f.triggers.empty()) return no("grammar triggers without tool calls");
|
||||
return RAD_OK;
|
||||
return reasoning_anywhere_check(f, why);
|
||||
}
|
||||
|
||||
if (!f.section_open.empty() || !f.section_close.empty())
|
||||
@@ -81,22 +159,43 @@ int chat_format_check(const ChatFormat& f, std::string* why) {
|
||||
") is not read by the streaming parser; tagged calls separate on whitespace");
|
||||
if (f.call_open.empty() && !f.call_close.empty())
|
||||
return no("call_close without call_open");
|
||||
if (f.name_suffix.empty() || trim_ws(f.name_suffix).empty())
|
||||
return no("name_suffix must end the function name with something besides whitespace");
|
||||
if (is_ws((unsigned char)f.name_suffix[0]))
|
||||
return no("name_suffix " + show(f.name_suffix) + " may not begin with whitespace");
|
||||
if (f.call_end.empty()) return no("call_end is empty: a call must close with its own tag");
|
||||
if (f.arg_prefix.empty()) return no("arg_prefix is empty");
|
||||
if (f.arg_value_suffix.empty()) return no("arg_value_suffix is empty");
|
||||
if (f.arg_name_suffix.empty() && f.arg_value_prefix.empty())
|
||||
return no("nothing ends an argument name: arg_name_suffix and arg_value_prefix are empty");
|
||||
if (!f.arg_name_suffix.empty() && !f.arg_value_prefix.empty())
|
||||
return no("arg_name_suffix and arg_value_prefix are both set; the streaming parser reads "
|
||||
"one delimiter between an argument's name and its value");
|
||||
if (f.string_value != ChatValue::Raw && f.string_value != ChatValue::Cdata)
|
||||
return no("string_value must be RAD_CHAT_VALUE_RAW or RAD_CHAT_VALUE_CDATA");
|
||||
if ((uint32_t)f.other_value > (uint32_t)ChatValue::Json)
|
||||
return no("other_value is not a RAD_CHAT_VALUE_* value");
|
||||
const bool object = f.object_args();
|
||||
/* An object's own `{` may be what ends the name; anything else needs its suffix. */
|
||||
if (!object || !f.name_suffix.empty()) {
|
||||
if (f.name_suffix.empty() || trim_ws(f.name_suffix).empty())
|
||||
return no("name_suffix must end the function name with something besides whitespace");
|
||||
if (is_ws((unsigned char)f.name_suffix[0]))
|
||||
return no("name_suffix " + show(f.name_suffix) + " may not begin with whitespace");
|
||||
}
|
||||
if (!object) {
|
||||
if (f.call_end.empty()) return no("call_end is empty: a call must close with its own tag");
|
||||
if (f.arg_prefix.empty()) return no("arg_prefix is empty");
|
||||
if (f.arg_value_suffix.empty()) return no("arg_value_suffix is empty");
|
||||
if (f.arg_name_suffix.empty() && f.arg_value_prefix.empty())
|
||||
return no("nothing ends an argument name: arg_name_suffix and arg_value_prefix are "
|
||||
"empty");
|
||||
if (!f.arg_name_suffix.empty() && !f.arg_value_prefix.empty())
|
||||
return no("arg_name_suffix and arg_value_prefix are both set; the streaming parser "
|
||||
"reads one delimiter between an argument's name and its value");
|
||||
if (f.string_value != ChatValue::Raw && f.string_value != ChatValue::Cdata)
|
||||
return no("string_value must be RAD_CHAT_VALUE_RAW or RAD_CHAT_VALUE_CDATA");
|
||||
if ((uint32_t)f.other_value > (uint32_t)ChatValue::Json)
|
||||
return no("other_value is not a RAD_CHAT_VALUE_* value");
|
||||
if (!f.object_string_open.empty() || !f.object_string_close.empty() ||
|
||||
f.object_bare_keys)
|
||||
return no("the object_* fields describe an argument object, and args_form is "
|
||||
"RAD_CHAT_ARGS_TAGGED");
|
||||
} else {
|
||||
for (const std::string* s : { &f.arg_prefix, &f.arg_name_suffix, &f.arg_value_prefix,
|
||||
&f.arg_value_suffix })
|
||||
if (!s->empty())
|
||||
return no("the arg_* fields describe tagged arguments, and args_form is "
|
||||
"RAD_CHAT_ARGS_OBJECT");
|
||||
if (!f.call_end.empty() && trim_ws(f.call_end).empty())
|
||||
return no("call_end is only whitespace");
|
||||
const int st = object_check(f, why);
|
||||
if (st < 0) return st;
|
||||
}
|
||||
|
||||
/* A wrapped format's content is scanned for the wrapper's core and for name_prefix alone,
|
||||
* which opens a call written without its wrapper; the two must not be confusable. */
|
||||
@@ -127,16 +226,19 @@ int chat_format_check(const ChatFormat& f, std::string* why) {
|
||||
return no("reasoning break " + show(b) + " overlaps reasoning_close " +
|
||||
show(close));
|
||||
}
|
||||
/* Inside a call the next tag is an argument or the close, and the close is recognised by its
|
||||
* core as well: the whitespace around it is optional when a reply leaves the format. */
|
||||
const std::string end = trim_ws(f.call_end);
|
||||
if (end.empty()) return no("call_end is only whitespace");
|
||||
for (const std::string* e : { &f.call_end, &end })
|
||||
if (starts_with(f.arg_prefix, *e) || starts_with(*e, f.arg_prefix) ||
|
||||
occurs_inside(f.arg_prefix, *e) || occurs_inside(*e, f.arg_prefix))
|
||||
return no("arg_prefix " + show(f.arg_prefix) + " and call_end " + show(f.call_end) +
|
||||
" cannot be told apart");
|
||||
return RAD_OK;
|
||||
if (!object) {
|
||||
/* Inside a call the next tag is an argument or the close, and the close is recognised by
|
||||
* its core as well: the whitespace around it is optional when a reply leaves the
|
||||
* format. */
|
||||
const std::string end = trim_ws(f.call_end);
|
||||
if (end.empty()) return no("call_end is only whitespace");
|
||||
for (const std::string* e : { &f.call_end, &end })
|
||||
if (starts_with(f.arg_prefix, *e) || starts_with(*e, f.arg_prefix) ||
|
||||
occurs_inside(f.arg_prefix, *e) || occurs_inside(*e, f.arg_prefix))
|
||||
return no("arg_prefix " + show(f.arg_prefix) + " and call_end " +
|
||||
show(f.call_end) + " cannot be told apart");
|
||||
}
|
||||
return reasoning_anywhere_check(f, why);
|
||||
}
|
||||
|
||||
/* ================================================================== the plugin's declaration */
|
||||
@@ -183,6 +285,11 @@ int chat_format_from_abi(const RadChatFormat* in, ChatFormat* out, std::string*
|
||||
f.other_value = (ChatValue)c.other_value;
|
||||
f.value_newlines = c.value_newlines != 0;
|
||||
list(c.triggers, c.n_triggers, &f.triggers);
|
||||
f.args_form = (ChatArgs)c.args_form;
|
||||
f.object_string_open = s(c.object_string_open);
|
||||
f.object_string_close = s(c.object_string_close);
|
||||
f.object_bare_keys = c.object_bare_keys != 0;
|
||||
f.reasoning_anywhere = c.reasoning_anywhere != 0;
|
||||
*out = std::move(f);
|
||||
return RAD_OK;
|
||||
}
|
||||
@@ -286,13 +393,23 @@ int chat_format_from_template(const std::string& jinja, const std::string& bos,
|
||||
std::string chat_format_describe(const ChatFormat& f) {
|
||||
std::string s = f.name + ":";
|
||||
if (f.has_reasoning())
|
||||
s += " reasoning " + show(f.reasoning_open) + ".." + show(f.reasoning_close);
|
||||
s += " reasoning " + show(f.reasoning_open) + ".." + show(f.reasoning_close) +
|
||||
(f.reasoning_anywhere ? " anywhere" : "");
|
||||
else
|
||||
s += " no reasoning";
|
||||
if (f.has_tools()) {
|
||||
if (f.has_tools() && f.object_args()) {
|
||||
s += "; calls " + show(f.call_open) + show(f.name_prefix) + "NAME" + show(f.name_suffix) +
|
||||
" {OBJECT";
|
||||
if (!f.object_string_open.empty())
|
||||
s += ", strings " + show(f.object_string_open) + ".." + show(f.object_string_close);
|
||||
if (f.object_bare_keys) s += ", bare keys";
|
||||
s += "} " + show(f.call_end) + show(f.call_close);
|
||||
} else if (f.has_tools()) {
|
||||
s += "; calls " + show(f.call_open) + show(f.name_prefix) + "NAME" + show(f.name_suffix) +
|
||||
" " + show(f.arg_prefix) + "ARG" + show(f.arg_name_suffix) + show(f.arg_value_prefix) +
|
||||
"VALUE" + show(f.arg_value_suffix) + " " + show(f.call_end) + show(f.call_close);
|
||||
}
|
||||
if (f.has_tools()) {
|
||||
if (!f.triggers.empty()) {
|
||||
s += "; grammar on";
|
||||
for (const std::string& t : f.triggers) s += " " + show(t);
|
||||
@@ -310,7 +427,8 @@ std::vector<std::string> chat_format_markers(const ChatFormat& f) {
|
||||
for (const std::string* s : { &f.reasoning_open, &f.reasoning_close, &f.section_open,
|
||||
&f.section_close, &f.call_open, &f.call_close, &f.name_prefix,
|
||||
&f.name_suffix, &f.call_end, &f.arg_prefix, &f.arg_name_suffix,
|
||||
&f.arg_value_prefix, &f.arg_value_suffix }) {
|
||||
&f.arg_value_prefix, &f.arg_value_suffix,
|
||||
&f.object_string_open, &f.object_string_close }) {
|
||||
const std::string t = trim_ws(*s);
|
||||
if (!t.empty() && std::find(out.begin(), out.end(), t) == out.end()) out.push_back(t);
|
||||
}
|
||||
@@ -538,6 +656,46 @@ void add_json_rules(const common_grammar_builder& b) {
|
||||
"json-null");
|
||||
}
|
||||
|
||||
/* THE ARGUMENT OBJECT of the object family, in its dialect: JSON, or strings between the
|
||||
* declared delimiters and keys written bare. As llama.cpp's own Gemma 4 grammar does, it fixes
|
||||
* the syntax and leaves the values to the model: a tool's schema says what JSON a value must be,
|
||||
* and the dialect is not JSON, so the schema converter has nothing to say about it. Whitespace
|
||||
* goes where the dialect's writers put it -- after a separator and inside the brackets -- and
|
||||
* nowhere else. */
|
||||
void add_object_rules(const common_grammar_builder& b, const ChatFormat& f) {
|
||||
const std::string& so = f.object_string_open;
|
||||
if (!so.empty())
|
||||
b.add_rule("obj-string", gbnf_format_literal(so) + " " +
|
||||
until_pattern({ f.object_string_close }) + " " +
|
||||
gbnf_format_literal(f.object_string_close));
|
||||
else
|
||||
b.add_rule("obj-string", "\"\\\"\" ( [^\"\\\\] | \"\\\\\" ( [\"\\\\/ bfnrt] | \"u\" "
|
||||
"[0-9a-fA-F]{4} ) )* \"\\\"\"");
|
||||
b.add_rule("obj-number", "\"-\"? (\"0\" | [1-9] [0-9]*) (\".\" [0-9]+)? ([eE] [+-]? [0-9]+)?");
|
||||
/* A dialect with strings of its own still gets a value in Python's quotes, `'...'`, which
|
||||
* is how Gemma 4 writes arguments it was handed as JSON (measured). Refused, the model
|
||||
* takes the next token the grammar allows -- a `-` -- and every such string becomes a
|
||||
* number; the parser reads the quoted text verbatim but for an escaped quote. */
|
||||
const char* sq = so.empty() ? "" : " | obj-sqstring";
|
||||
if (!so.empty()) b.add_rule("obj-sqstring", "\"'\" ( [^'\\\\] | \"\\\\\" [^\\x00] )* \"'\"");
|
||||
b.add_rule("obj-value", std::string("obj-object | obj-array | obj-string") + sq +
|
||||
" | obj-number | \"true\" | \"false\" | \"null\"");
|
||||
b.add_rule("obj-array", "\"[\" space (\"]\" | obj-value (\",\" space obj-value)* space "
|
||||
"\"]\")");
|
||||
if (f.object_bare_keys) {
|
||||
/* A bare key: no whitespace, no punctuation, and not the string opener's first byte. */
|
||||
std::string cls = "[^ \\t\\n\\r:,{}\\[\\]\"";
|
||||
if (!so.empty()) cls += class_char((unsigned char)so[0]);
|
||||
cls += "]+";
|
||||
b.add_rule("obj-key", cls + " | obj-string");
|
||||
} else {
|
||||
b.add_rule("obj-key", "obj-string");
|
||||
}
|
||||
b.add_rule("obj-member", "obj-key \":\" space obj-value");
|
||||
b.add_rule("obj-object", "\"{\" space (\"}\" | obj-member (\",\" space obj-member)* space "
|
||||
"\"}\")");
|
||||
}
|
||||
|
||||
G optspace(const std::string& tag) {
|
||||
size_t a = 0, b = tag.size();
|
||||
while (a < b && is_ws((unsigned char)tag[a])) ++a;
|
||||
@@ -644,6 +802,18 @@ int chat_format_grammar(const ChatFormat& f, const ChatGrammarRequest& req, Chat
|
||||
const auto& fn = tool.at("function");
|
||||
const std::string name = fn.at("name");
|
||||
if (!req.only_tool.empty() && name != req.only_tool) continue;
|
||||
if (f.object_args()) {
|
||||
/* The name, then the object; the object's own closing brace may be all
|
||||
* that ends the call. */
|
||||
G open = wrap(seq({ lit(f.name_prefix), wrap(lit(name)), lit(f.name_suffix) }));
|
||||
G func = f.call_end.empty()
|
||||
? seq({ open, rule_ref("obj-object") })
|
||||
: seq({ open, rule_ref("obj-object"), space(),
|
||||
wrap(lit(f.call_end)) });
|
||||
b.add_rule(rule_name("tool-" + name), render(func));
|
||||
choices.push_back(rule_ref(rule_name("tool-" + name)));
|
||||
continue;
|
||||
}
|
||||
auto params = fn.contains("parameters") ? fn.at("parameters") : ojson::object();
|
||||
const auto properties = params.contains("properties") ? params.at("properties")
|
||||
: ojson::object();
|
||||
@@ -704,7 +874,8 @@ int chat_format_grammar(const ChatFormat& f, const ChatGrammarRequest& req, Chat
|
||||
if (choices.empty() && !req.only_tool.empty())
|
||||
throw std::invalid_argument("no tool named \"" + req.only_tool + "\" to call");
|
||||
if (typed) add_json_rules(b);
|
||||
if (!choices.empty()) b.add_rule("until-suffix", until_pattern({ f.arg_value_suffix }));
|
||||
if (!choices.empty() && f.object_args()) add_object_rules(b, f);
|
||||
else if (!choices.empty()) b.add_rule("until-suffix", until_pattern({ f.arg_value_suffix }));
|
||||
|
||||
G choice = alt(choices);
|
||||
G calls;
|
||||
|
||||
+38
-6
@@ -32,10 +32,21 @@
|
||||
* the raw text (optionally CDATA-wrapped), any other type is JSON, and text that does not parse as
|
||||
* JSON is taken raw -- a model writing into an XML tag writes Python as often as JSON.
|
||||
*
|
||||
* The analyser also recognises formats outside this family (a JSON object per call, JSON
|
||||
* arguments inside a tag, call ids). For those chat_format_from_template keeps the reasoning split
|
||||
* and names why tool calls are refused, and a model that needs one gets it by adding the shape to
|
||||
* the parser, not by a fallback. */
|
||||
* THE OBJECT FAMILY writes a call as its name and one object holding the arguments
|
||||
* (ChatArgs::Object):
|
||||
*
|
||||
* Gemma 4 <|tool_call>call:NAME{key:<|"|>text<|"|>,n:3}<tool_call|>
|
||||
*
|
||||
* The object is JSON or a dialect of it -- strings between two declared delimiters with their
|
||||
* text verbatim, keys written bare -- and the arguments a client receives are that object in
|
||||
* JSON. Here the values carry their own types, so no schema is consulted to read them; a bare
|
||||
* word that is no JSON literal or number is read as a string, as a typed argument that is not
|
||||
* JSON is in the tagged family.
|
||||
*
|
||||
* The analyser also recognises formats outside these families (a JSON object per call with its
|
||||
* name inside it, call ids). For those chat_format_from_template keeps the reasoning split and
|
||||
* names why tool calls are refused, and a model that needs one gets it by adding the shape to the
|
||||
* parser, not by a fallback. */
|
||||
#pragma once
|
||||
#include "rad_internal.h"
|
||||
|
||||
@@ -68,6 +79,12 @@ enum class ChatThink : uint32_t {
|
||||
Never = 2, /* the model opens its own block, if any */
|
||||
};
|
||||
|
||||
/* How a call's arguments are written. The numbering is the ABI's (RAD_CHAT_ARGS_*). */
|
||||
enum class ChatArgs : uint32_t {
|
||||
Tagged = 0, /* each argument in its own tags: arg_prefix NAME .. VALUE arg_value_suffix */
|
||||
Object = 1, /* one object after the name: `{` key `:` value, ... `}` */
|
||||
};
|
||||
|
||||
struct ChatFormat {
|
||||
std::string name; /* for logs: "plugin:<arch>" or "template" */
|
||||
|
||||
@@ -83,6 +100,10 @@ struct ChatFormat {
|
||||
* Must name the call opener (`call_open`) when non-empty. */
|
||||
std::vector<std::string> reasoning_breaks;
|
||||
ChatThink reasoning_in_prompt = ChatThink::FromPrompt;
|
||||
/* A block may also open later in the reply -- after the answer, between calls -- and is read
|
||||
* as reasoning there; a close with no block open is dropped. Gemma 4 writes an empty block
|
||||
* after its answer now and then, and a lone close. Needs `reasoning_open`. */
|
||||
bool reasoning_anywhere = false;
|
||||
|
||||
/* ------------------------------------------------------------------ tool calls
|
||||
* `name_prefix` is what opens a call (after `call_open`, when there is one). Empty means the
|
||||
@@ -94,8 +115,18 @@ struct ChatFormat {
|
||||
/* Around EACH call: "<tool_call>\n", "</tool_call>". When set, a call written without it --
|
||||
* name_prefix alone -- is still read as a call, leniently (chatparse.h). */
|
||||
std::string call_open, call_close;
|
||||
std::string name_prefix, name_suffix; /* "<function=", ">\n" */
|
||||
std::string call_end; /* "</function>\n" */
|
||||
/* "<function=", ">\n". In the object family name_suffix may be empty: the name then ends
|
||||
* where the object begins, at its `{`. */
|
||||
std::string name_prefix, name_suffix;
|
||||
std::string call_end; /* "</function>\n"; may be empty for an object */
|
||||
|
||||
/* How the arguments are written. Object: the arg_* fields below are empty, and these three
|
||||
* describe the object's dialect -- a string delimiter besides JSON's `"`, between which the
|
||||
* text is verbatim ("<|\"|>" twice for Gemma 4; empty for JSON strings only), and whether a
|
||||
* key may be written bare. */
|
||||
ChatArgs args_form = ChatArgs::Tagged;
|
||||
std::string object_string_open, object_string_close;
|
||||
bool object_bare_keys = false;
|
||||
|
||||
std::string arg_prefix; /* "<parameter=" */
|
||||
std::string arg_name_suffix; /* ">\n" (MiniCPM: empty, the value prefix ends it) */
|
||||
@@ -115,6 +146,7 @@ struct ChatFormat {
|
||||
|
||||
bool has_reasoning() const { return !reasoning_close.empty(); }
|
||||
bool has_tools() const { return !name_prefix.empty(); }
|
||||
bool object_args() const { return args_form == ChatArgs::Object; }
|
||||
};
|
||||
|
||||
/* Can the streaming parser run this format? RAD_OK, or RAD_E_UNSUPPORTED with *why naming the
|
||||
|
||||
+748
-15
@@ -744,6 +744,30 @@ struct ReplyFormat::Impl {
|
||||
std::string cc_core;
|
||||
Dfa think, think_breaks, text, arg_name, value, junk, arg_name_loose, value_loose;
|
||||
size_t longest = 0; /* the longest delimiter */
|
||||
|
||||
/* THE OBJECT FAMILY. `object`: a call's arguments are one object; `ns_object`: the object's
|
||||
* own `{` is what ends the name (name_suffix empty), and ns_core is "{". */
|
||||
bool object = false, ns_object = false;
|
||||
/* Where a key or a value may begin, besides the object's punctuation: the dialect string's
|
||||
* opener, and the call's close and end -- a reply that leaves its object unclosed writes them
|
||||
* there. Read anchored, by their first bytes (chat_format_check keeps them apart). */
|
||||
enum : uint8_t { LitString, LitClose, LitEnd };
|
||||
std::vector<std::string> obj_lits;
|
||||
std::vector<uint8_t> obj_lit_kind;
|
||||
/* A dialect string runs to its close. A bare value ends at `,` `}` `]` and a bare key at `:`
|
||||
* `,` `}` -- patterns 0..2 -- or at the call's close or end, which follow at the indices
|
||||
* below (-1: none). */
|
||||
Dfa obj_str, obj_bare, obj_key;
|
||||
/* A value the model opened with a plain `"` -- or `'` (obj_sqstr) -- in a dialect that has
|
||||
* strings of its own: read as that dialect's strings are, verbatim, to a quote the object's
|
||||
* syntax goes on after. Patterns: the quote, the escaped quote, the dialect's string close,
|
||||
* the call's close (if any). */
|
||||
Dfa obj_qstr, obj_sqstr;
|
||||
int bare_cc = -1, bare_ce = -1, key_cc = -1, key_ce = -1;
|
||||
|
||||
/* REASONING ANYWHERE: content is scanned for a later block's opener and a stray close too,
|
||||
* after the call openers (text_think) or alone when the request has no calls (think_only). */
|
||||
Dfa text_think, think_only;
|
||||
};
|
||||
|
||||
ReplyFormat::ReplyFormat() : impl_(std::make_unique<Impl>()) {}
|
||||
@@ -773,6 +797,12 @@ int ReplyFormat::compile(const ChatFormat& f, std::shared_ptr<const ReplyFormat>
|
||||
if (f.call_open.empty()) m.openers = { f.name_prefix };
|
||||
else m.openers = { m.co_core, f.name_prefix };
|
||||
m.name_end = f.arg_name_suffix.empty() ? f.arg_value_prefix : f.arg_name_suffix;
|
||||
m.object = f.has_tools() && f.object_args();
|
||||
if (m.object && f.name_suffix.empty()) {
|
||||
m.ns_object = true;
|
||||
m.ns_core = "{";
|
||||
m.ns_trail.clear();
|
||||
}
|
||||
|
||||
if (f.has_reasoning()) {
|
||||
m.think.build({ m.close_core });
|
||||
@@ -780,7 +810,50 @@ int ReplyFormat::compile(const ChatFormat& f, std::shared_ptr<const ReplyFormat>
|
||||
for (const std::string& s : f.reasoning_breaks) b.push_back(s);
|
||||
m.think_breaks.build(b);
|
||||
}
|
||||
if (f.has_tools()) {
|
||||
if (f.reasoning_anywhere && f.has_reasoning()) {
|
||||
std::vector<std::string> t;
|
||||
if (f.has_tools()) t = m.openers;
|
||||
t.push_back(m.open_core);
|
||||
t.push_back(m.close_core);
|
||||
m.text_think.build(t);
|
||||
m.think_only.build({ m.open_core, m.close_core });
|
||||
}
|
||||
if (m.object) {
|
||||
m.text.build(m.openers);
|
||||
std::string trail;
|
||||
split_ws(f.call_close, &m.cc_core, &trail);
|
||||
std::vector<std::string> bare{ ",", "}", "]" }, key{ ":", ",", "}" };
|
||||
if (!f.object_string_open.empty()) {
|
||||
m.obj_lits.push_back(f.object_string_open);
|
||||
m.obj_lit_kind.push_back(Impl::LitString);
|
||||
/* The call's close inside a string: where a model left the string unclosed. */
|
||||
std::vector<std::string> sp{ f.object_string_close };
|
||||
std::vector<std::string> qp{ "\"", "\\\"", f.object_string_close };
|
||||
std::vector<std::string> sq{ "'", "\\'", f.object_string_close };
|
||||
if (!m.cc_core.empty()) {
|
||||
sp.push_back(m.cc_core);
|
||||
qp.push_back(m.cc_core);
|
||||
sq.push_back(m.cc_core);
|
||||
}
|
||||
m.obj_str.build(sp);
|
||||
m.obj_qstr.build(qp);
|
||||
m.obj_sqstr.build(sq);
|
||||
}
|
||||
if (!m.cc_core.empty()) {
|
||||
m.obj_lits.push_back(m.cc_core);
|
||||
m.obj_lit_kind.push_back(Impl::LitClose);
|
||||
m.bare_cc = (int)bare.size(); bare.push_back(m.cc_core);
|
||||
m.key_cc = (int)key.size(); key.push_back(m.cc_core);
|
||||
}
|
||||
if (!m.end_core.empty() && m.end_core != m.cc_core) {
|
||||
m.obj_lits.push_back(m.end_core);
|
||||
m.obj_lit_kind.push_back(Impl::LitEnd);
|
||||
m.bare_ce = (int)bare.size(); bare.push_back(m.end_core);
|
||||
m.key_ce = (int)key.size(); key.push_back(m.end_core);
|
||||
}
|
||||
m.obj_bare.build(bare);
|
||||
m.obj_key.build(key);
|
||||
} else if (f.has_tools()) {
|
||||
m.text.build(m.openers);
|
||||
m.arg_name.build({ m.name_end });
|
||||
m.value.build({ f.arg_value_suffix });
|
||||
@@ -800,7 +873,8 @@ int ReplyFormat::compile(const ChatFormat& f, std::shared_ptr<const ReplyFormat>
|
||||
const std::string* const delims[] = { &f.reasoning_open, &f.reasoning_close, &f.call_open,
|
||||
&f.call_close, &f.name_prefix, &f.name_suffix,
|
||||
&f.call_end, &f.arg_prefix, &m.name_end,
|
||||
&f.arg_value_suffix };
|
||||
&f.arg_value_suffix, &f.object_string_open,
|
||||
&f.object_string_close };
|
||||
for (const std::string* s : delims) m.longest = std::max(m.longest, s->size());
|
||||
for (const std::string& s : f.reasoning_breaks) m.longest = std::max(m.longest, s.size());
|
||||
*out = std::move(r);
|
||||
@@ -831,6 +905,9 @@ struct ReplyParser::Impl {
|
||||
bool calls = false; /* the request sent tools and the format has calls */
|
||||
bool breaks = false; /* an unclosed reasoning block ends at a call */
|
||||
bool pure = false; /* no reasoning, calls or document: every byte is content */
|
||||
/* A reasoning block may open later in the reply too (ChatFormat::reasoning_anywhere), and
|
||||
* this request extracts reasoning. */
|
||||
bool anywhere = false;
|
||||
std::vector<Tool> tools;
|
||||
std::unordered_map<std::string, size_t> by_name;
|
||||
std::vector<std::string> terminators;
|
||||
@@ -897,9 +974,10 @@ static int bind_tools(const ReplyFormat::Impl& F, const ojson& tools, ReplyParse
|
||||
optional.push_back(pname);
|
||||
}
|
||||
/* A name the argument's own delimiter could end early would be read as a
|
||||
* different name. */
|
||||
* different name. An object's keys are delimited by its own punctuation, and
|
||||
* one that holds it is written as a string. */
|
||||
const std::string probe = pname + F.name_end;
|
||||
if (probe.find(F.name_end) != pname.size()) {
|
||||
if (!F.object && probe.find(F.name_end) != pname.size()) {
|
||||
*why = "parameter '" + pname + "' of tool '" + t.name + "' contains '" +
|
||||
F.name_end + "', which this model's tool-call format uses to end an "
|
||||
"argument name";
|
||||
@@ -909,7 +987,8 @@ static int bind_tools(const ReplyFormat::Impl& F, const ojson& tools, ReplyParse
|
||||
}
|
||||
t.arms.insert(t.arms.end(), optional.begin(), optional.end());
|
||||
if (t.name.find(F.ns_core) != std::string::npos ||
|
||||
(t.name + F.f.name_suffix).find(F.f.name_suffix) != t.name.size()) {
|
||||
(!F.ns_object &&
|
||||
(t.name + F.f.name_suffix).find(F.f.name_suffix) != t.name.size())) {
|
||||
*why = "tool '" + t.name + "' has a name containing '" + F.ns_core +
|
||||
"', which this model's tool-call format uses to end a function name";
|
||||
return RAD_E_INVAL;
|
||||
@@ -949,6 +1028,8 @@ int ReplyParser::create(std::shared_ptr<const ReplyFormat> fmt, const ReplyOptio
|
||||
P.calls = want_calls && !opt.response_format;
|
||||
P.breaks = want_calls && F.f.has_reasoning() && !F.f.reasoning_breaks.empty();
|
||||
P.pure = !F.f.has_reasoning() && !want_calls && !opt.response_format;
|
||||
P.anywhere = F.f.reasoning_anywhere && F.f.has_reasoning() && opt.extract_reasoning &&
|
||||
!opt.response_format;
|
||||
|
||||
if (F.f.has_reasoning()) {
|
||||
switch (F.f.reasoning_in_prompt) {
|
||||
@@ -1004,6 +1085,19 @@ enum class St : uint8_t {
|
||||
RfClose, /* "```" */
|
||||
RfEnd, /* after the closing fence */
|
||||
RfRaw, /* a reply that is not the document it was asked for: content */
|
||||
ObjStart, /* after a name_suffix: whitespace, then the argument object's `{` */
|
||||
ObjKey, /* where a key may begin, or the object's `}` */
|
||||
ObjKeyBare, /* a bare key, to its `:` */
|
||||
ObjColon, /* after a quoted key: whitespace, then `:` */
|
||||
ObjValue, /* where a value may begin, or an empty array's `]` */
|
||||
ObjLit, /* the dialect's string opener, or the call's close or end, being matched */
|
||||
ObjStr, /* a dialect string, to its close */
|
||||
ObjQStr, /* a value opened with a plain quote in a dialect with strings of its own */
|
||||
ObjQLook, /* after a plain quote there: does the object's syntax go on? */
|
||||
ObjJStr, /* a JSON string, to its quote */
|
||||
ObjBare, /* a bare value: a number, a literal, or a word read as a string */
|
||||
ObjAfter, /* after a value: whitespace, then `,` or a closing bracket */
|
||||
ObjEnd, /* after the object: whitespace, then call_end */
|
||||
};
|
||||
|
||||
/* A function name the grammar does not know is still read as a call, up to this long. */
|
||||
@@ -1018,8 +1112,20 @@ struct ReplyStream::Impl {
|
||||
explicit Impl(const ReplyParser::Impl& p) : P(p), F(p.fmt->impl()) {
|
||||
content.init(P.terminators.empty() ? nullptr : &P.terms, &P.terminators);
|
||||
st = P.pure ? St::Text : St::LeadWs;
|
||||
if (P.anywhere) {
|
||||
text_dfa = P.calls ? &F.text_think : &F.think_only;
|
||||
n_open = P.calls ? F.openers.size() : 0;
|
||||
} else if (P.calls) {
|
||||
text_dfa = &F.text;
|
||||
n_open = F.openers.size();
|
||||
}
|
||||
}
|
||||
|
||||
/* What content is scanned with: the call openers when calls are on, then -- reasoning
|
||||
* anywhere -- a later block's opener and a stray close. Null: content is every byte. */
|
||||
const Dfa* text_dfa = nullptr;
|
||||
size_t n_open = 0;
|
||||
|
||||
ReplyMessage msg;
|
||||
ContentOut content;
|
||||
bool think_text = false; /* the reasoning has had a non-blank byte */
|
||||
@@ -1062,6 +1168,28 @@ struct ReplyStream::Impl {
|
||||
size_t vs_pos = 0;
|
||||
bool fenced = false;
|
||||
|
||||
/* THE ARGUMENT OBJECT being read: its open brackets, whether a key (rather than a value) is
|
||||
* being read, a separator read but not yet written -- it is written only once the next
|
||||
* member shows the object goes on, so a trailing one never reaches the JSON -- whether the
|
||||
* container was just opened, and whether a key's `:` went out with no value yet. */
|
||||
std::vector<char> ostack;
|
||||
bool okey = false, ocomma = false, ofirst = false, vpending = false;
|
||||
/* A bare value's first bytes, to tell at its end whether it was a JSON number or literal --
|
||||
* which the grammar admits -- or a word read as a string, which it does not. */
|
||||
std::string bare_txt;
|
||||
/* A JSON string's escape being read -- the backslash, and a "u" escape's four hex digits,
|
||||
* in vheld -- and a high surrogate's escape, held until the low one shows it is a pair. */
|
||||
std::string jhi;
|
||||
/* INSIDE A STRING: its trailing run of whitespace, closing brackets and quotes, held -- the
|
||||
* brackets are the object's own if the call's close follows (srun) -- the quotes and
|
||||
* backticks it has written (nq, nb), the bytes after a plain quote while they decide what it
|
||||
* was (qtail), and how a plain-quoted value writes its quotes: 0 not yet seen, 1 as \" (one
|
||||
* is unescaped), 2 as they are. */
|
||||
std::string srun, qtail;
|
||||
size_t nq = 0, nb = 0, ns = 0;
|
||||
uint8_t qmode = 0;
|
||||
char qc = '"';
|
||||
|
||||
/* published offsets, for the deltas */
|
||||
size_t sent_r = 0, sent_c = 0, sent_a = 0;
|
||||
int cur = -1; /* the channel last published: 0 r, 1 c, 2 args */
|
||||
@@ -1202,7 +1330,7 @@ struct ReplyStream::Impl {
|
||||
|
||||
bool declared_prefix(std::string_view n) const {
|
||||
for (const Tool& t : P.tools) {
|
||||
const std::string full = t.name + F.f.name_suffix;
|
||||
const std::string full = t.name + (F.ns_object ? F.ns_core : F.f.name_suffix);
|
||||
if (full.size() >= n.size() && full.compare(0, n.size(), n) == 0) return true;
|
||||
}
|
||||
return false;
|
||||
@@ -1283,14 +1411,307 @@ struct ReplyStream::Impl {
|
||||
cur = -1;
|
||||
event(ReplyEvent::CallBegin, (uint32_t)msg.calls.size() - 1, msg.calls.back().name);
|
||||
depth = 0; in_str = false; esc = false;
|
||||
args_out("{");
|
||||
argc = 0;
|
||||
++calls;
|
||||
att.clear();
|
||||
post_call = false;
|
||||
if (F.object) {
|
||||
/* The arguments are the object's, and its `{` is written now: a reply that ends
|
||||
* here is a call with no arguments yet, as in the tagged family. */
|
||||
obj_out("{");
|
||||
ostack.assign(1, '{');
|
||||
okey = ocomma = vpending = false;
|
||||
ofirst = true;
|
||||
jhi.clear();
|
||||
st = F.ns_object ? St::ObjKey : St::ObjStart;
|
||||
return;
|
||||
}
|
||||
args_out("{");
|
||||
st = St::Body;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ the argument object
|
||||
*
|
||||
* The object of the object family, read as it streams and written as JSON as it is read:
|
||||
* brackets and separators as they come, a key as soon as its `:` shows it is one, a string
|
||||
* as its bytes arrive, and a bare value as the tagged family writes a typed one (ValueOut,
|
||||
* Raw): held while it could still be a literal or a number, else a string. What the dialect
|
||||
* spells otherwise -- its string delimiters, its bare keys -- is respelled; what leaves it
|
||||
* -- a missing separator, a trailing one, a bracket of the wrong kind, an object the call's
|
||||
* close cuts off -- is repaired locally and said so (strict). The arguments a closed call
|
||||
* reports are JSON whatever was written. */
|
||||
|
||||
void obj_out(std::string_view s) {
|
||||
if (s.empty()) return;
|
||||
touch(2);
|
||||
msg.calls.back().arguments.append(s.data(), s.size());
|
||||
}
|
||||
void obj_flush() { if (!scratch.empty()) { obj_out(scratch); scratch.clear(); } }
|
||||
|
||||
/* A member or an element begins: the separator before it, if one was read, goes out now. */
|
||||
void obj_sep() {
|
||||
if (ocomma) { obj_out(","); ocomma = false; }
|
||||
ofirst = false;
|
||||
}
|
||||
|
||||
/* The outermost bracket closed: what follows the object. */
|
||||
void obj_done() {
|
||||
if (!F.end_core.empty()) { lpos = 0; lhold.clear(); st = St::ObjEnd; }
|
||||
else end_call();
|
||||
}
|
||||
|
||||
/* A closing bracket where a key, a value or a separator may stand. A separator before it is
|
||||
* dropped, and a bracket of the other kind closes the open container all the same. */
|
||||
void obj_close_bracket(char c) {
|
||||
if (ocomma) { lenient(); ocomma = false; }
|
||||
const char top = ostack.back();
|
||||
if ((top == '{') != (c == '}')) lenient();
|
||||
if (vpending) { lenient(); obj_out("null"); vpending = false; }
|
||||
ostack.pop_back();
|
||||
ofirst = false;
|
||||
obj_out(top == '{' ? "}" : "]");
|
||||
if (ostack.empty()) obj_done();
|
||||
else st = St::ObjAfter;
|
||||
}
|
||||
|
||||
/* The punctuation after a value. */
|
||||
void obj_struct(char c) {
|
||||
if (c != ',') { obj_close_bracket(c); return; }
|
||||
if (ocomma) lenient(); /* `,,`: one separator */
|
||||
ocomma = true;
|
||||
ofirst = false;
|
||||
okey = ostack.back() == '{';
|
||||
st = okey ? St::ObjKey : St::ObjValue;
|
||||
}
|
||||
|
||||
bool obj_lit_start(unsigned char c) const {
|
||||
for (const std::string& l : F.obj_lits)
|
||||
if ((unsigned char)l[0] == c) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
/* Bytes that open no string and close no call: a bare key or a bare value. */
|
||||
void obj_bare_begin() {
|
||||
ds = 0;
|
||||
hold.clear();
|
||||
if (okey) {
|
||||
if (!F.f.object_bare_keys) lenient();
|
||||
name.clear();
|
||||
st = St::ObjKeyBare;
|
||||
return;
|
||||
}
|
||||
obj_sep();
|
||||
vpending = false;
|
||||
bare_txt.clear();
|
||||
val.begin(ValueOut::Raw, /*cdata=*/false, /*lead=*/false, /*trail=*/false, scratch);
|
||||
obj_flush();
|
||||
st = St::ObjBare;
|
||||
}
|
||||
|
||||
static constexpr size_t kBareKeep = 64; /* longer than any number a model writes */
|
||||
|
||||
/* A bare value ended: one that is no JSON number or literal was read by the recovery rule. */
|
||||
void bare_done() {
|
||||
std::string_view v(bare_txt);
|
||||
while (!v.empty() && is_ws((unsigned char)v.back())) v.remove_suffix(1);
|
||||
const bool json = bare_txt.size() < kBareKeep && !v.empty() &&
|
||||
(v == "true" || v == "false" || v == "null" ||
|
||||
((v[0] == '-' || (v[0] >= '0' && v[0] <= '9')) &&
|
||||
nlohmann::json::accept(v)));
|
||||
if (!json) lenient();
|
||||
}
|
||||
|
||||
/* A JSON string, which is the dialect's own only when it declares no string delimiters. */
|
||||
void json_string_begin() {
|
||||
if (!F.f.object_string_open.empty()) lenient();
|
||||
obj_out("\"");
|
||||
vheld.clear();
|
||||
st = St::ObjJStr;
|
||||
}
|
||||
|
||||
/* One of the anchored literals matched where a key or a value may begin. */
|
||||
void obj_lit_done(uint8_t kind) {
|
||||
if (kind == ReplyFormat::Impl::LitString) {
|
||||
obj_sep();
|
||||
if (!okey) vpending = false;
|
||||
obj_out("\"");
|
||||
ds = 0;
|
||||
hold.clear();
|
||||
str_begin();
|
||||
st = St::ObjStr;
|
||||
return;
|
||||
}
|
||||
/* The call's close or end where the object wanted more: the reply left the object
|
||||
* unclosed, and the call ends here with it closed. */
|
||||
lenient();
|
||||
ocomma = false;
|
||||
if (kind == ReplyFormat::Impl::LitClose) end_call_at_close();
|
||||
else end_core_done();
|
||||
}
|
||||
|
||||
/* A JSON string's text goes out as it is, its escapes checked: one JSON has not is the
|
||||
* backslash and the letter as text, a raw control character is escaped, and a surrogate
|
||||
* escape that is not half of a pair is U+FFFD -- a client's JSON parser refuses all three. */
|
||||
void jstr_char(const char* q, size_t n) {
|
||||
if (n == 0) return;
|
||||
if (!jhi.empty()) { lenient(); jhi.clear(); obj_out("\\ufffd"); }
|
||||
touch(2);
|
||||
json_escape_into(msg.calls.back().arguments, q, n);
|
||||
}
|
||||
|
||||
void jstr_escape_done(const std::string& e) {
|
||||
/* e: a complete two-character escape, or a "u" escape with its four digits. */
|
||||
if (e.size() == 6) {
|
||||
const unsigned long cp = std::strtoul(e.c_str() + 2, nullptr, 16);
|
||||
if (cp >= 0xD800 && cp <= 0xDBFF) {
|
||||
if (!jhi.empty()) { lenient(); obj_out("\\ufffd"); }
|
||||
jhi = e;
|
||||
return;
|
||||
}
|
||||
if (cp >= 0xDC00 && cp <= 0xDFFF) {
|
||||
if (jhi.empty()) { lenient(); obj_out("\\ufffd"); return; }
|
||||
obj_out(jhi + e);
|
||||
jhi.clear();
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (!jhi.empty()) { lenient(); jhi.clear(); obj_out("\\ufffd"); }
|
||||
obj_out(e);
|
||||
}
|
||||
|
||||
static constexpr size_t kRunKeep = 16; /* the closers a string's end may hold back */
|
||||
static constexpr size_t kLookKeep = 32; /* what deciding a close may read ahead */
|
||||
|
||||
static bool run_byte(char c) {
|
||||
return c == '}' || c == ']' || c == '"' || c == '`' || c == '\'' || is_ws((unsigned char)c);
|
||||
}
|
||||
|
||||
void str_begin() { srun.clear(); nq = nb = ns = 0; }
|
||||
void str_emit(const char* q, size_t n) {
|
||||
if (n == 0) return;
|
||||
nq += (size_t)std::count(q, q + n, '"');
|
||||
nb += (size_t)std::count(q, q + n, '`');
|
||||
ns += (size_t)std::count(q, q + n, '\'');
|
||||
touch(2);
|
||||
json_escape_into(msg.calls.back().arguments, q, n);
|
||||
}
|
||||
void str_flush() { str_emit(srun.data(), srun.size()); srun.clear(); }
|
||||
|
||||
/* A string's text: all of it goes out but a trailing run of whitespace and closers. */
|
||||
void str_text(const char* q, size_t n) {
|
||||
size_t k = n;
|
||||
while (k > 0 && run_byte(q[k - 1])) --k;
|
||||
if (k > 0) { str_flush(); str_emit(q, k); }
|
||||
srun.append(q + k, n - k);
|
||||
if (srun.size() > kRunKeep) {
|
||||
const size_t out = srun.size() - kRunKeep;
|
||||
str_emit(srun.data(), out);
|
||||
srun.erase(0, out);
|
||||
}
|
||||
}
|
||||
|
||||
/* Where the held run stops being text: the closers after it close every open bracket of the
|
||||
* object, innermost first, as the model writes them before the call's close -- read from the
|
||||
* end, the last closes the outermost. npos: they do not. */
|
||||
size_t run_cut() const {
|
||||
size_t i = srun.size(), k = 0;
|
||||
while (i > 0 && k < ostack.size()) {
|
||||
const char c = srun[i - 1];
|
||||
if (is_ws((unsigned char)c)) { --i; continue; }
|
||||
if (c != (ostack[k] == '{' ? '}' : ']')) break;
|
||||
--i;
|
||||
++k;
|
||||
}
|
||||
return k == ostack.size() && k > 0 ? i : std::string::npos;
|
||||
}
|
||||
|
||||
static bool starts(std::string_view a, std::string_view b) {
|
||||
return a.size() >= b.size() && a.compare(0, b.size(), b) == 0;
|
||||
}
|
||||
|
||||
/* The call's close in a string whose held run closes the whole object: the model left the
|
||||
* string open (measured: the close delimiter at p=0.86, `}` at p=0.08), and this is where
|
||||
* the call ends -- as vLLM's and HF's Gemma 4 parsers end it, at the first `}<tool_call|>`.
|
||||
* The closers are the object's. A quote or backtick just before them that leaves the string
|
||||
* with an odd count of its kind was the string's close, written in the wrong spelling. */
|
||||
void cut_begin() {
|
||||
const size_t cut = run_cut();
|
||||
if (cut == std::string::npos) { str_flush(); str_emit(F.cc_core.data(), F.cc_core.size()); return; }
|
||||
lenient();
|
||||
size_t keep = cut;
|
||||
if (keep > 0 && (srun[keep - 1] == '"' || srun[keep - 1] == '`' || srun[keep - 1] == '\'')) {
|
||||
const char c = srun[keep - 1];
|
||||
const size_t n = (c == '"' ? nq : c == '`' ? nb : ns) +
|
||||
(size_t)std::count(srun.begin(), srun.begin() + (long)keep, c);
|
||||
if (n % 2 == 1) --keep;
|
||||
}
|
||||
str_emit(srun.data(), keep);
|
||||
srun.clear();
|
||||
if (!jhi.empty()) jhi.clear();
|
||||
obj_out(okey ? "\":null" : "\"");
|
||||
vpending = false;
|
||||
ocomma = false;
|
||||
/* As after a call's close of its own: a repeated close goes with it. */
|
||||
end_call();
|
||||
}
|
||||
|
||||
/* After a plain quote in a plain-quoted value: 0 not yet known, 1 it closed the value -- the
|
||||
* object goes on with a member, an element, its closers and the call's close -- 2 it was
|
||||
* text. */
|
||||
int q_verdict() const {
|
||||
const std::string& q = qtail;
|
||||
if (q.size() > kLookKeep) return 2;
|
||||
const size_t n = q.size();
|
||||
size_t i = 0, top = ostack.size();
|
||||
auto ws = [&] { while (i < n && is_ws((unsigned char)q[i])) ++i; };
|
||||
ws();
|
||||
while (i < n && top > 0 && q[i] == (ostack[top - 1] == '{' ? '}' : ']')) { --top; ++i; ws(); }
|
||||
if (i == n) return 0;
|
||||
const std::string& so = F.f.object_string_open;
|
||||
std::string_view r(q.data() + i, n - i);
|
||||
if (!F.cc_core.empty()) {
|
||||
if (starts(r, F.cc_core)) return 1;
|
||||
if (starts(F.cc_core, r)) return 0;
|
||||
}
|
||||
if (top == 0 || q[i] != ',') return 2;
|
||||
++i;
|
||||
ws();
|
||||
if (i == n) return 0;
|
||||
r = std::string_view(q.data() + i, n - i);
|
||||
const unsigned char c = (unsigned char)q[i];
|
||||
if (starts(r, so)) return 1;
|
||||
if (starts(so, r)) return 0;
|
||||
if (ostack[top - 1] == '{') {
|
||||
if (!(std::isalpha(c) || c == '_')) return 2;
|
||||
while (i < n && (std::isalnum((unsigned char)q[i]) || q[i] == '_')) ++i;
|
||||
ws();
|
||||
if (i == n) return 0;
|
||||
return q[i] == ':' ? 1 : 2;
|
||||
}
|
||||
return (c == '"' || c == '\'' || c == '{' || c == '[' || c == '-' || std::isdigit(c)) ? 1 : 2;
|
||||
}
|
||||
|
||||
void q_done(bool closed) {
|
||||
std::string again;
|
||||
again.swap(qtail);
|
||||
if (closed) {
|
||||
str_flush();
|
||||
obj_string_done();
|
||||
} else {
|
||||
if (qmode == 0) qmode = 2;
|
||||
str_text(&qc, 1);
|
||||
st = St::ObjQStr;
|
||||
}
|
||||
read_again(again);
|
||||
}
|
||||
|
||||
/* A string or a key closed. */
|
||||
void obj_string_done() {
|
||||
if (!jhi.empty()) { lenient(); jhi.clear(); obj_out("\\ufffd"); }
|
||||
obj_out("\"");
|
||||
st = okey ? St::ObjColon : St::ObjAfter;
|
||||
}
|
||||
|
||||
/* The core of call_end has matched. The whitespace the format writes after it is part of the
|
||||
* tag, so the call closes when that has arrived too -- a reply that ends in between leaves the
|
||||
* call open, as the grammar does -- and a reply that goes straight on without it has closed
|
||||
@@ -1306,8 +1727,18 @@ struct ReplyStream::Impl {
|
||||
* match, so no quote is ever pending here; a raw value that left a string open is passed
|
||||
* through as the model wrote it. */
|
||||
void end_call() {
|
||||
std::string close((size_t)std::max(depth, 0), '}');
|
||||
args_out(close);
|
||||
if (F.object) {
|
||||
/* What the object left open is closed, so the arguments are JSON: a key whose value
|
||||
* never came is null, and each bracket gets its partner. */
|
||||
std::string close = vpending ? "null" : "";
|
||||
vpending = false;
|
||||
for (auto it = ostack.rbegin(); it != ostack.rend(); ++it) close += *it == '{' ? '}' : ']';
|
||||
ostack.clear();
|
||||
obj_out(close);
|
||||
} else {
|
||||
std::string close((size_t)std::max(depth, 0), '}');
|
||||
args_out(close);
|
||||
}
|
||||
publish(2, true);
|
||||
msg.calls.back().closed = true;
|
||||
event(ReplyEvent::CallEnd, (uint32_t)msg.calls.size() - 1, {});
|
||||
@@ -1499,14 +1930,22 @@ struct ReplyStream::Impl {
|
||||
return p;
|
||||
|
||||
case St::Text:
|
||||
if (!P.calls) {
|
||||
if (!text_dfa) {
|
||||
text_out(p, (size_t)(e - p));
|
||||
return e;
|
||||
}
|
||||
p = scan(F.text, p, e, &hit, [this](const char* q, size_t n) { text_out(q, n); });
|
||||
if (hit >= 0) {
|
||||
p = scan(*text_dfa, p, e, &hit, [this](const char* q, size_t n) { text_out(q, n); });
|
||||
if (hit < 0) return p;
|
||||
if ((size_t)hit < n_open) {
|
||||
att_at = here(p) - F.openers[(size_t)hit].size();
|
||||
begin_text_attempt(hit);
|
||||
} else if ((size_t)hit == n_open) {
|
||||
/* A reasoning block opens again, later in the reply. */
|
||||
trail = 0;
|
||||
st = St::ThinkOpenWs;
|
||||
} else {
|
||||
/* Its close with no block open: not part of the answer. */
|
||||
lenient();
|
||||
}
|
||||
return p;
|
||||
|
||||
@@ -1558,12 +1997,18 @@ struct ReplyStream::Impl {
|
||||
lpos = 0;
|
||||
lhold.clear();
|
||||
tag_end = att.size();
|
||||
if (loose) st = St::OpenPeek;
|
||||
if (loose && F.object) {
|
||||
/* A call written without its wrapper, in the object family: a declared
|
||||
* tool's name and the object's opening are what make it one. */
|
||||
if (tool < 0) { fail_attempt(); return p + 1; }
|
||||
begin_call(false);
|
||||
} else if (loose) st = St::OpenPeek;
|
||||
else if (F.ns_trail.empty()) begin_call(true);
|
||||
else st = St::OpenTail;
|
||||
return p + 1;
|
||||
}
|
||||
if (name.size() > kMaxLooseName || (c == '<' && !declared_prefix(name))) {
|
||||
if (name.size() > kMaxLooseName || (c == '<' && !declared_prefix(name)) ||
|
||||
(loose && F.object && !declared_prefix(name))) {
|
||||
fail_attempt();
|
||||
return p + 1;
|
||||
}
|
||||
@@ -1775,6 +2220,279 @@ struct ReplyStream::Impl {
|
||||
if (p < e) { post_call = true; ds = 0; hold.clear(); st = St::Text; }
|
||||
return p;
|
||||
|
||||
case St::ObjStart:
|
||||
while (p < e && is_ws((unsigned char)*p)) ++p;
|
||||
if (p == e) return p;
|
||||
if (*p == '{') { ofirst = true; okey = true; st = St::ObjKey; return p + 1; }
|
||||
/* No object after the name: the call takes none, and what stands there instead is
|
||||
* read as what follows a call. */
|
||||
lenient();
|
||||
obj_done();
|
||||
return p;
|
||||
|
||||
case St::ObjKey: {
|
||||
while (p < e && is_ws((unsigned char)*p)) ++p;
|
||||
if (p == e) return p;
|
||||
const char c = *p;
|
||||
okey = true;
|
||||
if (c == '}' || c == ']') { obj_close_bracket(c); return p + 1; }
|
||||
if (c == ',') { lenient(); return p + 1; } /* an empty member */
|
||||
if (c == '"') {
|
||||
obj_sep();
|
||||
json_string_begin();
|
||||
return p + 1;
|
||||
}
|
||||
if (obj_lit_start((unsigned char)c)) { lhold.clear(); st = St::ObjLit; return p; }
|
||||
obj_bare_begin();
|
||||
return p;
|
||||
}
|
||||
|
||||
case St::ObjKeyBare:
|
||||
p = scan(F.obj_key, p, e, &hit, [this](const char* q, size_t n) { name.append(q, n); });
|
||||
if (hit < 0) return p;
|
||||
if (hit <= 2) {
|
||||
std::string_view k(name);
|
||||
while (!k.empty() && is_ws((unsigned char)k.back())) k.remove_suffix(1);
|
||||
if (k.empty()) lenient();
|
||||
obj_sep();
|
||||
std::string out = json_quote(k);
|
||||
name.clear();
|
||||
if (hit == 0) {
|
||||
obj_out(out + ":");
|
||||
vpending = true;
|
||||
okey = false;
|
||||
st = St::ObjValue;
|
||||
return p;
|
||||
}
|
||||
/* A key with no value: it is null. */
|
||||
lenient();
|
||||
obj_out(out + ":null");
|
||||
obj_struct(hit == 1 ? ',' : '}');
|
||||
return p;
|
||||
}
|
||||
/* The call's close or end inside a key: the key had no value, and goes. */
|
||||
name.clear();
|
||||
lenient();
|
||||
ocomma = false;
|
||||
if (hit == F.key_cc) end_call_at_close();
|
||||
else end_core_done();
|
||||
return p;
|
||||
|
||||
case St::ObjColon:
|
||||
while (p < e && is_ws((unsigned char)*p)) ++p;
|
||||
if (p == e) return p;
|
||||
vpending = true;
|
||||
okey = false;
|
||||
st = St::ObjValue;
|
||||
if (*p == ':') { obj_out(":"); return p + 1; }
|
||||
lenient();
|
||||
obj_out(":");
|
||||
return p;
|
||||
|
||||
case St::ObjValue: {
|
||||
while (p < e && is_ws((unsigned char)*p)) ++p;
|
||||
if (p == e) return p;
|
||||
const char c = *p;
|
||||
const bool in_array = ostack.back() == '[';
|
||||
okey = false;
|
||||
if (c == '{' || c == '[') {
|
||||
obj_sep();
|
||||
vpending = false;
|
||||
obj_out(c == '{' ? "{" : "[");
|
||||
ostack.push_back(c);
|
||||
ofirst = true;
|
||||
okey = c == '{';
|
||||
st = c == '{' ? St::ObjKey : St::ObjValue;
|
||||
return p + 1;
|
||||
}
|
||||
if (c == ']' && in_array && ofirst) { obj_close_bracket(c); return p + 1; }
|
||||
if (c == '}' || c == ']' || c == ',') {
|
||||
/* No value where one was due: a member's is null, and an array's gap is no
|
||||
* element. */
|
||||
lenient();
|
||||
if (!in_array) {
|
||||
obj_out("null");
|
||||
vpending = false;
|
||||
st = St::ObjAfter;
|
||||
return p;
|
||||
}
|
||||
if (c == ',') return p + 1;
|
||||
obj_close_bracket(c);
|
||||
return p + 1;
|
||||
}
|
||||
if ((c == '"' || c == '\'') && !F.f.object_string_open.empty()) {
|
||||
/* Measured on Gemma 4: such a quote -- `"`, or `'` as Python and JavaScript
|
||||
* write strings -- is followed by the text verbatim, or with only its quotes
|
||||
* escaped, never JSON's other escapes. */
|
||||
obj_sep();
|
||||
vpending = false;
|
||||
lenient();
|
||||
obj_out("\"");
|
||||
qc = c;
|
||||
qmode = 0;
|
||||
str_begin();
|
||||
st = St::ObjQStr;
|
||||
return p + 1;
|
||||
}
|
||||
if (c == '"') {
|
||||
obj_sep();
|
||||
vpending = false;
|
||||
json_string_begin();
|
||||
return p + 1;
|
||||
}
|
||||
if (obj_lit_start((unsigned char)c)) { lhold.clear(); st = St::ObjLit; return p; }
|
||||
obj_bare_begin();
|
||||
return p;
|
||||
}
|
||||
|
||||
case St::ObjLit: {
|
||||
const char c = *p;
|
||||
lhold.push_back(c);
|
||||
bool part = false;
|
||||
for (size_t i = 0; i < F.obj_lits.size(); ++i) {
|
||||
const std::string& l = F.obj_lits[i];
|
||||
if (lhold.size() > l.size() || l.compare(0, lhold.size(), lhold) != 0) continue;
|
||||
if (lhold.size() < l.size()) { part = true; continue; }
|
||||
lhold.clear();
|
||||
obj_lit_done(F.obj_lit_kind[i]);
|
||||
return p + 1;
|
||||
}
|
||||
if (part) return p + 1;
|
||||
/* None of them: the bytes begin a bare key or value. */
|
||||
std::string again;
|
||||
again.swap(lhold);
|
||||
obj_bare_begin();
|
||||
read_again(again);
|
||||
return p + 1;
|
||||
}
|
||||
|
||||
case St::ObjStr:
|
||||
p = scan(F.obj_str, p, e, &hit, [this](const char* q, size_t n) { str_text(q, n); });
|
||||
if (hit < 0) return p;
|
||||
if (hit == 0) { str_flush(); obj_string_done(); }
|
||||
else cut_begin();
|
||||
return p;
|
||||
|
||||
case St::ObjQStr:
|
||||
p = scan(qc == '"' ? F.obj_qstr : F.obj_sqstr, p, e, &hit,
|
||||
[this](const char* q, size_t n) { str_text(q, n); });
|
||||
if (hit < 0) return p;
|
||||
if (hit == 0) { qtail.clear(); st = St::ObjQLook; }
|
||||
else if (hit == 1) {
|
||||
if (qmode == 0) qmode = 1;
|
||||
const char esc[2] = { '\\', qc };
|
||||
if (qmode == 1) str_text(&qc, 1);
|
||||
else str_text(esc, 2);
|
||||
} else if (hit == 2) { lenient(); str_flush(); obj_string_done(); }
|
||||
else cut_begin();
|
||||
return p;
|
||||
|
||||
case St::ObjQLook: {
|
||||
qtail.push_back(*p);
|
||||
const int v = q_verdict();
|
||||
if (v) q_done(v == 1);
|
||||
return p + 1;
|
||||
}
|
||||
|
||||
case St::ObjJStr: {
|
||||
const char* run = p;
|
||||
while (p < e) {
|
||||
const unsigned char c = (unsigned char)*p;
|
||||
if (vheld.size() == 1) { /* after the backslash */
|
||||
if (c && std::strchr("\"\\/bfnrt", (int)c)) {
|
||||
vheld.push_back((char)c);
|
||||
jstr_escape_done(vheld);
|
||||
vheld.clear();
|
||||
run = ++p;
|
||||
continue;
|
||||
}
|
||||
if (c == 'u') { vheld.push_back('u'); run = ++p; continue; }
|
||||
/* No JSON escape: the backslash is text, and what follows it is read as
|
||||
* the string's next byte. */
|
||||
lenient();
|
||||
vheld.clear();
|
||||
jstr_char("\\", 1);
|
||||
run = p;
|
||||
continue;
|
||||
}
|
||||
if (!vheld.empty()) { /* a "u" escape's digits */
|
||||
if (std::isxdigit(c)) {
|
||||
vheld.push_back((char)c);
|
||||
if (vheld.size() == 6) { jstr_escape_done(vheld); vheld.clear(); }
|
||||
run = ++p;
|
||||
continue;
|
||||
}
|
||||
lenient();
|
||||
const std::string text = vheld;
|
||||
vheld.clear();
|
||||
jstr_char(text.data(), text.size());
|
||||
run = p;
|
||||
continue;
|
||||
}
|
||||
if (c != '"' && c != '\\') { ++p; continue; }
|
||||
jstr_char(run, (size_t)(p - run));
|
||||
++p;
|
||||
if (c == '"') { obj_string_done(); return p; }
|
||||
vheld.assign(1, '\\');
|
||||
run = p;
|
||||
}
|
||||
jstr_char(run, (size_t)(p - run));
|
||||
return p;
|
||||
}
|
||||
|
||||
case St::ObjBare:
|
||||
p = scan(F.obj_bare, p, e, &hit, [this](const char* q, size_t n) {
|
||||
if (bare_txt.size() < kBareKeep)
|
||||
bare_txt.append(q, std::min(n, kBareKeep - bare_txt.size()));
|
||||
val.add(q, n, scratch);
|
||||
obj_flush();
|
||||
});
|
||||
if (hit < 0) return p;
|
||||
val.finish(false, scratch);
|
||||
obj_flush();
|
||||
bare_done();
|
||||
if (hit <= 2) { obj_struct(",}]"[hit]); return p; }
|
||||
lenient();
|
||||
if (hit == F.bare_cc) end_call_at_close();
|
||||
else end_core_done();
|
||||
return p;
|
||||
|
||||
case St::ObjAfter: {
|
||||
while (p < e && is_ws((unsigned char)*p)) ++p;
|
||||
if (p == e) return p;
|
||||
const char c = *p;
|
||||
if (c == ',' || c == '}' || c == ']') { obj_struct(c); return p + 1; }
|
||||
/* A key or a value with no separator before it: one is supplied. */
|
||||
lenient();
|
||||
ocomma = true;
|
||||
ofirst = false;
|
||||
okey = ostack.back() == '{';
|
||||
st = okey ? St::ObjKey : St::ObjValue;
|
||||
return p;
|
||||
}
|
||||
|
||||
case St::ObjEnd: {
|
||||
if (lpos == 0) {
|
||||
while (p < e && is_ws((unsigned char)*p)) ++p;
|
||||
if (p == e) return p;
|
||||
}
|
||||
const char c = *p;
|
||||
if (c == F.end_core[lpos]) {
|
||||
lhold.push_back(c);
|
||||
if (++lpos == F.end_core.size()) { lhold.clear(); lpos = 0; end_core_done(); }
|
||||
return p + 1;
|
||||
}
|
||||
/* The object is not followed by the call's end: the call ends with it all the same,
|
||||
* and what stands there is read as what follows a call. */
|
||||
lenient();
|
||||
std::string again;
|
||||
again.swap(lhold);
|
||||
lpos = 0;
|
||||
end_call();
|
||||
read_again(again);
|
||||
return p;
|
||||
}
|
||||
|
||||
case St::RfWs:
|
||||
while (p < e && is_ws((unsigned char)*p)) ++p;
|
||||
if (p < e) {
|
||||
@@ -1962,6 +2680,14 @@ struct ReplyStream::Impl {
|
||||
}
|
||||
|
||||
void finish_all() {
|
||||
/* The reply ended while a close was being decided: it was one. */
|
||||
while (st == St::ObjQLook) {
|
||||
q_done(true);
|
||||
std::string again = std::move(refeed);
|
||||
refeed.clear();
|
||||
run(again, fed >= again.size() ? fed - again.size() : 0);
|
||||
}
|
||||
if (st == St::ObjStr || st == St::ObjQStr) str_flush();
|
||||
while (in_loose_attempt()) {
|
||||
fail_attempt();
|
||||
std::string again = std::move(refeed);
|
||||
@@ -1998,6 +2724,11 @@ struct ReplyStream::Impl {
|
||||
case St::ValJsonEnd:
|
||||
json_value_done(std::string_view(vheld).substr(0, vheld.size() - vs_pos));
|
||||
break;
|
||||
case St::ObjBare:
|
||||
/* A bare value the reply was cut off inside: as it arrived. The call is open. */
|
||||
val.finish(true, scratch);
|
||||
obj_flush();
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
@@ -2066,7 +2797,9 @@ ReplyHeld ReplyStream::held() const {
|
||||
(m.msg.reasoning.size() - m.sent_r) + (m.msg.content.size() - m.sent_c) +
|
||||
(m.msg.calls.empty() ? 0 : m.msg.calls.back().arguments.size() - m.sent_a);
|
||||
h.space = m.content.held_space() + m.think_pend.size();
|
||||
h.structure = m.att.size() + m.name.size() + m.vheld.size() + m.val.held_container();
|
||||
h.delimiter += m.srun.size() + m.qtail.size();
|
||||
h.structure = m.att.size() + m.name.size() + m.vheld.size() + m.val.held_container() +
|
||||
m.jhi.size();
|
||||
return h;
|
||||
}
|
||||
|
||||
|
||||
@@ -623,6 +623,22 @@ int Vocab::load(VocabBuild b) {
|
||||
RAD_INFO("vocab: end-of-generation also on %s (a control token the container declares "
|
||||
"neither as eos nor eot; without this a turn ending on it runs on)",
|
||||
added.c_str());
|
||||
|
||||
/* AND WHAT THE CHECKPOINT ITSELF NAMES. generation_config.json's eos_token_id is the
|
||||
* model's own list of tokens a generation ends on, and the one that is not a guess:
|
||||
* Gemma 4 names <|tool_response> there beside <eos> and <turn|>, because after its calls
|
||||
* the model writes it and waits for the response -- a turn that runs past it answers
|
||||
* its own call. Every id in range is honoured, as transformers honours them. */
|
||||
std::string named;
|
||||
for (int32_t id : b_.eos_ids) {
|
||||
if (id < 0 || id >= (int32_t)b_.tokens.size()) continue;
|
||||
if (std::find(eog_.begin(), eog_.end(), id) != eog_.end()) continue;
|
||||
eog_.push_back(id);
|
||||
named += (named.empty() ? "" : " ") + b_.tokens[id] + "=" + std::to_string(id);
|
||||
}
|
||||
if (!named.empty())
|
||||
RAD_INFO("vocab: end-of-generation also on %s (named by the checkpoint's "
|
||||
"generation_config.json)", named.c_str());
|
||||
}
|
||||
|
||||
/* The encoder: the chain compiled and the tables flattened. A pattern the regex compiler
|
||||
|
||||
@@ -86,6 +86,11 @@ struct VocabBuild {
|
||||
|
||||
/* Diagnostics only: what rad-convert thought it was reading. Not baked. */
|
||||
std::string source;
|
||||
|
||||
/* The ids the checkpoint's generation_config.json names as eos_token_id, which the container
|
||||
* carries as metadata (`generation.eos_token_id`) rather than in the vocabulary section. The
|
||||
* engine fills it from there before load(); not baked. */
|
||||
std::vector<int32_t> eos_ids;
|
||||
};
|
||||
|
||||
/* ================================================================== the loaded vocab */
|
||||
|
||||
Reference in new issue
Block a user