From ce62f5058fb6ff574099e680bf2925bce6fcd924 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 5 Oct 2026 10:04:09 +0200 Subject: [PATCH 01/48] ple: a table-driven PLE format (enum, row bytes and a dequant per type) PleTable had one bool per format (q5_0, fp8) and an if-chain in decode(), open() and format(). Now one list, ple_formats(), holds one entry per table type: its GGUF type name, the bytes of a 160-value row, whether it carries a scale and its dequantizer. open(), format(), the row size, the error string and the row buffers all read it, so the next formats (Q8_0, Q5_1, Q4_0, BF16) are one entry each. No behaviour change: IQ4_NL, Q5_0 and FP8 decode with the same functions, and the "not IQ4_NL, Q5_0 or FP8 (I8)" error text is built from the list and reads the same. ple_reader_test --selftest now writes a PLE-only GGUF for every format in the list and checks both readers (direct and mapped) against the format's own dequantizer, for single rows and a 16-row token gather. --- include/strata/kernels/ngram.hpp | 27 +++++++- src/kernels/ngram.cpp | 76 +++++++++++++++------- src/ngram/ple_reader_test.cpp | 106 +++++++++++++++++++++++++++++++ 3 files changed, 185 insertions(+), 24 deletions(-) diff --git a/include/strata/kernels/ngram.hpp b/include/strata/kernels/ngram.hpp index a321ea70f9..6cd1d8551f 100644 --- a/include/strata/kernels/ngram.hpp +++ b/include/strata/kernels/ngram.hpp @@ -46,7 +46,32 @@ inline constexpr float NG_RMS_EPS = 1e-6f; inline constexpr uint64_t PLE_TABLE_ROWS = 320001536ull; inline constexpr int PLE_ROW_BYTES = (PLE_HEAD_DIM / 32) * 18; // 90: an IQ4_NL row inline constexpr int PLE_ROW_BYTES_FP8 = PLE_HEAD_DIM; // 160: an F8_E4M3 row, one byte a value -inline constexpr int PLE_ROW_BYTES_MAX = PLE_ROW_BYTES_FP8; +inline constexpr int PLE_ROW_BYTES_MAX = PLE_ROW_BYTES_FP8; // the widest row any format in `ple_formats()` has + +/// THE FORMATS OF THE TABLE, ONE ROW EACH. A table type is one entry here (its GGUF type name, the bytes of one +/// 160-value row, how to turn a row into floats) and nothing else: `PleTable::open`, `format()`, the reader's row size, +/// the error string and the buffers' size all read this list, so a new format cannot be in one switch and missing from +/// another. A row is always `PLE_HEAD_DIM` = 160 values = 5 blocks of 32 for the block formats. +enum class PleFormat : uint8_t { IQ4_NL, Q5_0, F8_E4M3 }; + +struct PleFormatInfo { + PleFormat id; + const char* name; ///< what `PleTable::format()` returns + const char* gguf_type; ///< `TensorInfo::type_name()` of the table tensor ("I8" for F8_E4M3: GGUF has no FP8 type) + uint32_t row_bytes; ///< bytes of one 160-value row in the file + bool needs_scale; ///< the table has one scale in the GGUF metadata (`strata.ple.scale`), F8_E4M3 only + void (*dequant)(const uint8_t* row, float scale, float* out160); +}; + +/// Every format, in the order of `PleFormat`; `ple_format_count()` entries. +const PleFormatInfo* ple_formats(); +int ple_format_count(); +const PleFormatInfo& ple_format_info(PleFormat f); +/// The format whose table tensor has this GGUF type name, or nullptr. F8_E4M3's name is "I8"; the caller checks the +/// `strata.ple.format` marker and the scale. +const PleFormatInfo* ple_format_for_type(const char* gguf_type_name); +/// "IQ4_NL, Q5_0 or FP8 (I8)": the formats for an error message, built from the list. +std::string ple_format_list(); /// The artifact's own hash constants, transcribed from `docs/gguf-dump-shard1.txt`: /// diff --git a/src/kernels/ngram.cpp b/src/kernels/ngram.cpp index 7292dd963b..3728207b2f 100644 --- a/src/kernels/ngram.cpp +++ b/src/kernels/ngram.cpp @@ -135,11 +135,48 @@ void fp8_e4m3_dequant_row(const uint8_t* row, float scale, float* out160) { } // --------------------------------------------------------------------------------------------------- +// THE FORMAT TABLE (see PleFormatInfo). One entry per table type; the block formats decode 5 blocks of 32. +namespace { +template +void dequant_blocks(const uint8_t* row, float /*scale*/, float* out160) { + for (int b = 0; b < PLE_HEAD_DIM / 32; ++b) Block(row + (size_t) b * BlockBytes, out160 + b * 32); +} +void dequant_iq4_nl(const uint8_t* row, float, float* out160) { iq4nl_dequant_row(row, out160); } +void dequant_fp8(const uint8_t* row, float scale, float* out160) { fp8_e4m3_dequant_row(row, scale, out160); } + +const PleFormatInfo kPleFormats[] = { + {PleFormat::IQ4_NL, "IQ4_NL", "IQ4_NL", PLE_ROW_BYTES, false, dequant_iq4_nl}, + {PleFormat::Q5_0, "Q5_0", "Q5_0", (PLE_HEAD_DIM / 32) * 22, false, dequant_blocks}, + {PleFormat::F8_E4M3, "F8_E4M3", "I8", PLE_ROW_BYTES_FP8, true, dequant_fp8}, +}; +constexpr int kPleFormatCount = (int) (sizeof kPleFormats / sizeof kPleFormats[0]); +} // namespace + +const PleFormatInfo* ple_formats() { return kPleFormats; } +int ple_format_count() { return kPleFormatCount; } +const PleFormatInfo& ple_format_info(PleFormat f) { return kPleFormats[(int) f]; } +const PleFormatInfo* ple_format_for_type(const char* gguf_type_name) { + for (const PleFormatInfo& f : kPleFormats) + if (std::strcmp(f.gguf_type, gguf_type_name) == 0) return &f; + return nullptr; +} +std::string ple_format_list() { + std::string out; + for (int i = 0; i < kPleFormatCount; ++i) { + const PleFormatInfo& f = kPleFormats[i]; + if (i > 0) out += i + 1 == kPleFormatCount ? " or " : ", "; + out += std::strcmp(f.gguf_type, "I8") == 0 ? "FP8 (I8)" : f.name; + } + return out; +} + +static_assert(PLE_ROW_BYTES_MAX >= PLE_ROW_BYTES && PLE_ROW_BYTES_MAX >= PLE_ROW_BYTES_FP8, "row buffers too small"); + struct PleTable::Impl { GgufFile* file = nullptr; const uint8_t* data = nullptr; uint64_t n_rows = 0; - bool q5_0 = false; // #296: Q5_0 rows (110 B), the mapped reader only + const PleFormatInfo* fmt = &ple_format_info(PleFormat::IQ4_NL); // the table's format (#296: Q5_0 is one of them) mutable uint64_t bytes_read = 0; // Direct mode (plan v0.3 P2): the mapping above is released after the header parse and every row comes // from an unbuffered SSD read into `raw`. @@ -155,15 +192,9 @@ struct PleTable::Impl { strata::ngram::PleReader::Ticket prefetch_tickets[kMaxPrefetch] = {}; uint32_t prefetch_keys[kMaxPrefetch][PLE_N_HEADS] = {}; uint8_t prefetch_raw[kMaxPrefetch][PLE_N_HEADS * PLE_ROW_BYTES_MAX] = {}; - bool fp8 = false; // F8_E4M3 rows (tools/ple_fp8_pack.py); else IQ4_NL float scale = 1.0f; // the FP8 table's one scale uint32_t rb = PLE_ROW_BYTES; // bytes per row - void decode(const uint8_t* row, float* out160) const { - if (fp8) fp8_e4m3_dequant_row(row, scale, out160); - else if (q5_0) - for (int b = 0; b < PLE_HEAD_DIM / 32; ++b) strata::dequantize_q5_0(row + (size_t) b * 22, out160 + b * 32); - else iq4nl_dequant_row(row, out160); - } + void decode(const uint8_t* row, float* out160) const { fmt->dequant(row, scale, out160); } }; PleTable::PleTable() : impl_(new Impl) {} @@ -193,12 +224,16 @@ bool PleTable::open(const std::string& gguf_path, std::string& err, const PleIoO close(); return false; } - // IQ4_NL (ISTA-DASLab's shard 2, the original's own GGUF), Q5_0 (#296: OrcaRouter's GGUF), or the FP8 table as - // shipped: I8 bytes marked strata.ple.format = f8_e4m3 with strata.ple.scale (tools/ple_fp8_pack.py) - impl_->fp8 = false; - impl_->q5_0 = std::strcmp(t->type_name(), "Q5_0") == 0; - impl_->rb = impl_->q5_0 ? (PLE_HEAD_DIM / 32) * 22 : PLE_ROW_BYTES; - if (std::strcmp(t->type_name(), "I8") == 0) { + // The table's type is looked up in the format list (ple_formats()): IQ4_NL (ISTA-DASLab's shard 2, the original's + // own GGUF), Q5_0 (#296: OrcaRouter's GGUF), or the FP8 table as shipped: I8 bytes marked strata.ple.format = + // f8_e4m3 with strata.ple.scale (tools/ple_fp8_pack.py) + const PleFormatInfo* fmt = ple_format_for_type(t->type_name()); + if (fmt == nullptr) { + err = std::string("per_layer_token_embd.weight is ") + t->type_name() + ", not " + ple_format_list(); + close(); + return false; + } + if (fmt->needs_scale) { const MetaValue* f = impl_->file->get("strata.ple.format"); const MetaValue* s = impl_->file->get("strata.ple.scale"); if (f == nullptr || f->s != "f8_e4m3" || s == nullptr || !(s->num() > 0.0)) { @@ -206,14 +241,10 @@ bool PleTable::open(const std::string& gguf_path, std::string& err, const PleIoO close(); return false; } - impl_->fp8 = true; impl_->scale = (float) s->num(); - impl_->rb = PLE_ROW_BYTES_FP8; - } else if (!impl_->q5_0 && std::strcmp(t->type_name(), "IQ4_NL") != 0) { - err = std::string("per_layer_token_embd.weight is ") + t->type_name() + ", not IQ4_NL, Q5_0 or FP8 (I8)"; - close(); - return false; } + impl_->fmt = fmt; + impl_->rb = fmt->row_bytes; // PleReader's row_bytes has been a runtime parameter since the FP8 table (160 B rows) needed it; Q5_0's // 110 B rows go through the exact same generic path (ple_reader_test --selftest covers both 90 and 110 B // rows: straddling, caching, in-flight tickets, keep-alive). This refusal was stale. @@ -323,13 +354,12 @@ void PleTable::close() { impl_->data = nullptr; impl_->n_rows = 0; impl_->rb = PLE_ROW_BYTES; - impl_->q5_0 = false; - impl_->fp8 = false; + impl_->fmt = &ple_format_info(PleFormat::IQ4_NL); } bool PleTable::is_open() const { return impl_->data != nullptr || impl_->reader.is_open(); } bool PleTable::locked() const { return impl_->locked; } -const char* PleTable::format() const { return impl_->fp8 ? "F8_E4M3" : impl_->q5_0 ? "Q5_0" : "IQ4_NL"; } +const char* PleTable::format() const { return impl_->fmt->name; } PleIo PleTable::mode() const { return impl_->mode; } uint64_t PleTable::rows() const { return impl_->n_rows; } uint64_t PleTable::bytes_read() const { return impl_->bytes_read; } diff --git a/src/ngram/ple_reader_test.cpp b/src/ngram/ple_reader_test.cpp index 87270fdc62..db94691942 100644 --- a/src/ngram/ple_reader_test.cpp +++ b/src/ngram/ple_reader_test.cpp @@ -75,6 +75,110 @@ bool check_rows(ng::PleReader& rd, const std::vector& rows, uint32_t n return true; } +/// EVERY FORMAT OF THE TABLE, END TO END (table-driven: one entry in `k::ple_formats()` is one run here). A minimal +/// PLE-only GGUF holds `rows` rows of that format's row size, each filled with bytes that encode the row, and both I/O +/// modes must return exactly what the format's own dequantizer makes of those bytes - so the row width, the offset +/// and the type lookup all have to be right for every format, not only for IQ4_NL. +uint32_t gguf_type_id(const char* name) { + static const struct { const char* name; uint32_t id; } ids[] = { + {"IQ4_NL", 20}, {"Q4_0", 2}, {"Q4_1", 3}, {"Q5_0", 6}, {"Q5_1", 7}, {"Q8_0", 8}, {"BF16", 30}, {"F8_E4M3", 24}}; + for (const auto& e : ids) + if (std::strcmp(e.name, name) == 0) return e.id; + return 0xFFFFFFFFu; +} + +std::string write_format_table(const std::string& dir, const k::PleFormatInfo& f, uint32_t rows) { + const std::string path = dir + "/ple_format_selftest.gguf"; + std::ofstream out(path, std::ios::binary); + if (!out) { std::fprintf(stderr, "cannot write %s\n", path.c_str()); return {}; } + const auto le = [](auto value, int bytes) { + std::string s((size_t) bytes, '\0'); + for (int i = 0; i < bytes; ++i) s[(size_t) i] = (char) ((value >> (8 * i)) & 0xff); + return s; + }; + const auto str = [&](const char* s) { return le((uint64_t) std::strlen(s), 8) + std::string(s); }; + const uint64_t n_kv = f.needs_scale ? 3 : 1; + std::string head = "GGUF" + le(3u, 4) + le(1ull, 8) + le(n_kv, 8); + head += str("general.architecture") + le(8u, 4) + str("strata-ple"); + if (f.needs_scale) { + const float scale = 0.75f; + uint32_t sb; + std::memcpy(&sb, &scale, 4); + head += str("strata.ple.format") + le(8u, 4) + str("f8_e4m3"); + head += str("strata.ple.scale") + le(6u, 4) + le(sb, 4); // 6 = FLOAT32 + } + head += str("per_layer_token_embd.weight") + le(2u, 4); + head += le((uint64_t) k::PLE_HEAD_DIM, 8) + le((uint64_t) rows, 8); + head += le(gguf_type_id(f.name), 4) + le(0ull, 8); + while (head.size() % 32) head += '\0'; + out.write(head.data(), (std::streamsize) head.size()); + std::vector r(f.row_bytes); + for (uint32_t i = 0; i < rows; ++i) { + expected_row(i, f.row_bytes, r.data()); + out.write((const char*) r.data(), (std::streamsize) f.row_bytes); + } + out.close(); + return out ? path : std::string(); +} + +void format_round_trip(const std::string& dir, const k::PleFormatInfo& f, uint32_t rows) { + CHECK(gguf_type_id(f.name) != 0xFFFFFFFFu, "%s: no GGUF type id in this test", f.name); + CHECK(f.row_bytes > 0 && f.row_bytes <= (uint32_t) k::PLE_ROW_BYTES_MAX, "%s: row_bytes %u out of range", f.name, f.row_bytes); + const std::string path = write_format_table(dir, f, rows); + if (path.empty()) { CHECK(false, "%s: no table was written", f.name); return; } + std::mt19937 rng(13); + std::vector want(rows); + for (uint32_t i = 0; i < rows; ++i) want[i] = rng() % rows; + want[0] = 0; + want[1] = rows - 1; + for (k::PleIo mode : {k::PleIo::Direct, k::PleIo::Mmap}) { + const char* name = mode == k::PleIo::Direct ? "direct" : "mmap"; + k::PleTable t; + std::string err; + k::PleIoOptions io; + io.mode = mode; + io.max_inflight = 8; + io.cache_rows = 0; + CHECK(t.open(path, err, io), "%s: open in %s mode: %s", f.name, name, err.c_str()); + if (g_fail) break; + CHECK(std::strcmp(t.format(), f.name) == 0, "%s: format() says \"%s\"", f.name, t.format()); + CHECK(t.rows() == rows, "%s: rows %llu, not %u", f.name, (unsigned long long) t.rows(), rows); + std::vector raw(f.row_bytes); + float got[k::PLE_HEAD_DIM], ref[k::PLE_HEAD_DIM]; + for (uint32_t r : want) { + t.read_row(r, got); + expected_row(r, f.row_bytes, raw.data()); + f.dequant(raw.data(), f.needs_scale ? 0.75f : 1.0f, ref); + if (std::memcmp(got, ref, sizeof got) != 0) { + CHECK(false, "%s: %s: row %u differs from the format's own dequantizer", f.name, name, r); + break; + } + } + // the 16-row path a token takes, one batch + float tok[16 * k::PLE_HEAD_DIM]; + uint32_t rows16[16]; + for (int h = 0; h < 16; ++h) rows16[h] = want[(size_t) h + 2]; + t.gather(rows16, tok); + for (int h = 0; h < 16; ++h) { + expected_row(rows16[h], f.row_bytes, raw.data()); + f.dequant(raw.data(), f.needs_scale ? 0.75f : 1.0f, ref); + CHECK(std::memcmp(tok + (size_t) h * k::PLE_HEAD_DIM, ref, sizeof ref) == 0, "%s: %s: gather head %d differs", f.name, name, h); + } + } + std::filesystem::remove(path); +} + +void all_formats_round_trip(const std::string& dir) { + CHECK(k::ple_format_count() > 0, "no formats"); + for (int i = 0; i < k::ple_format_count(); ++i) { + const k::PleFormatInfo& f = k::ple_formats()[i]; + CHECK((int) f.id == i, "%s: the table is not in PleFormat order", f.name); + CHECK(k::ple_format_for_type(f.gguf_type) == &f, "%s: type lookup", f.name); + format_round_trip(dir, f, 2000); + } + CHECK(k::ple_format_for_type("Q6_K") == nullptr, "Q6_K must not be a PLE format"); +} + // row_bytes: ng::ROW_BYTES (90, IQ4_NL) is the production default; 110 (#296, OrcaRouter's Q5_0 PLE rows) is // run too, through the exact same generic row_bytes path -- nothing here is IQ4_NL-specific, so a second row // size run here is the correctness evidence for lifting ngram.cpp's "Q5_0 PLE requires --ple-io mmap" refusal. @@ -288,6 +392,8 @@ int main(int argc, char** argv) { if (self) { // ng::ROW_BYTES (90, IQ4_NL, production default) and 110 (#296, OrcaRouter's Q5_0 PLE rows) through the // same generic row_bytes path -- see the comment on selftest(). + all_formats_round_trip(dir); // every format of k::ple_formats(), both readers, vs its dequantizer + if (g_fail != 0) return 1; const int r90 = selftest(dir, ng::ROW_BYTES); const int r110 = selftest(dir, 110); return r90 != 0 ? r90 : r110; From 74945954fe792a4a0c1bfa9120fd2d4959a2c62f Mon Sep 17 00:00:00 2001 From: Anon Date: Mon, 5 Oct 2026 10:09:29 +0200 Subject: [PATCH 02/48] ple: read Q8_0 and Q5_1 n-gram tables (#651) Ordinary GGUFs ship per_layer_token_embd.weight in other formats than IQ4_NL: Unsloth's UD-Q6_K_XL and Swift-1.5 Q4_K_L as Q8_0 (170-byte rows, ~54 GB), a Q5_K_M finetune as Q5_1 (120-byte rows). The engine refused both at start. - dequantize_q5_1 in strata/artifact/dequant.hpp (ggml's dequantize_row_q5_1: unsigned 5-bit codes times d plus the block minimum m); Q8_0 rows use the existing dequantize_q8_0 - two entries in the PLE format list (the table-driven commit before this one): Q5_1 and Q8_0, on both readers; PLE_ROW_BYTES_MAX grows to 170 - tests: dequant_q5_1_test (synthetic blocks against ggml, no model, no GPU), dequant_bf16_test knows Q5_1, ple_q5_parity takes Q5_0, Q5_1 or Q8_0 tables and checks both the mapped and the direct reader Ported onto the format table by the maintainer from anon761's PR #651 (the --ple-io ram fault-in is the next commit). Quality of the Q8_0 table: ksanislo measured 0.53% error against the BF16 table, FP8 2.66%, IQ4_NL 7.59%. Co-authored-by: ksanislo --- CMakeLists.txt | 6 +++ include/strata/artifact/dequant.hpp | 16 ++++++ include/strata/kernels/ngram.hpp | 6 ++- src/kernels/dequant_bf16_test.cpp | 1 + src/kernels/ngram.cpp | 3 ++ src/kernels/ple_q5_parity.cpp | 75 ++++++++++++++++++++--------- src/ngram/ple_reader_test.cpp | 5 ++ tests/core/dequant_q5_1_test.cpp | 40 +++++++++++++++ 8 files changed, 126 insertions(+), 26 deletions(-) create mode 100644 tests/core/dequant_q5_1_test.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 4b34aebaf7..ae36e40e9e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1030,6 +1030,12 @@ if(STRATA_NATIVE_EXPERTS) endif() target_link_libraries(strata_kernels_cpu PUBLIC ggml-cpu ggml-base) target_compile_definitions(strata_kernels_cpu PUBLIC STRATA_NATIVE_EXPERTS=1) + if(STRATA_BUILD_TESTS) + # the Q5_1 block dequantizer (a Q5_1 PLE table) against ggml's, synthetic blocks: no model, no GPU + add_executable(dequant_q5_1_test tests/core/dequant_q5_1_test.cpp) + target_link_libraries(dequant_q5_1_test PRIVATE strata_artifact ggml-base) + add_test(NAME dequant_q5_1_test COMMAND dequant_q5_1_test) + endif() # the router lookahead's dot on each rung this CPU has (AVX2, the older CPUs' AVX1) against a double reference add_executable(router_dot_parity src/kernels/cpu/router_dot_parity.cpp) target_link_libraries(router_dot_parity PRIVATE strata_kernels_cpu) diff --git a/include/strata/artifact/dequant.hpp b/include/strata/artifact/dequant.hpp index d5a314ce2d..b177c8ec0a 100644 --- a/include/strata/artifact/dequant.hpp +++ b/include/strata/artifact/dequant.hpp @@ -109,6 +109,22 @@ inline void dequantize_q5_0(const uint8_t* block, float* out) { out[j + 16] = (float)(x1 - 16) * d; } } +// ---- Q5_1: 32 elements from a 24-byte block: fp16 d, fp16 m, then Q5_0's qh[4] and qs[16]. The 5-bit codes are +// unsigned and the block's minimum m is added instead of Q5_0's fixed -16 offset (dequantize_row_q5_1). +inline void dequantize_q5_1(const uint8_t* block, float* out) { + const float d = fp16_to_fp32(read_u16(block)); + const float m = fp16_to_fp32(read_u16(block + 2)); + const uint8_t* qh = block + 4; + const uint8_t* qs = block + 8; + const uint32_t h = + (uint32_t)qh[0] | ((uint32_t)qh[1] << 8) | ((uint32_t)qh[2] << 16) | ((uint32_t)qh[3] << 24); + for (int j = 0; j < 16; ++j) { + const int x0 = (int)(qs[j] & 0x0F) | (int)(((h >> j) & 1u) << 4); + const int x1 = (int)(qs[j] >> 4) | (int)(((h >> (j + 16)) & 1u) << 4); + out[j] = (float)x0 * d + m; + out[j + 16] = (float)x1 * d + m; + } +} // ---- IQ4_NL: 32 elements from an 18-byte block. Non-linear 4-bit codebook, NOT a linear grid, so // the table must be exact. Copied verbatim from ggml-common.h `kvalues_iq4nl` at 3cf03257: // -127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113 diff --git a/include/strata/kernels/ngram.hpp b/include/strata/kernels/ngram.hpp index 6cd1d8551f..c0c8585846 100644 --- a/include/strata/kernels/ngram.hpp +++ b/include/strata/kernels/ngram.hpp @@ -46,13 +46,15 @@ inline constexpr float NG_RMS_EPS = 1e-6f; inline constexpr uint64_t PLE_TABLE_ROWS = 320001536ull; inline constexpr int PLE_ROW_BYTES = (PLE_HEAD_DIM / 32) * 18; // 90: an IQ4_NL row inline constexpr int PLE_ROW_BYTES_FP8 = PLE_HEAD_DIM; // 160: an F8_E4M3 row, one byte a value -inline constexpr int PLE_ROW_BYTES_MAX = PLE_ROW_BYTES_FP8; // the widest row any format in `ple_formats()` has +inline constexpr int PLE_ROW_BYTES_Q5_1 = (PLE_HEAD_DIM / 32) * 24; // 120: a Q5_1 row (a Q5_K_M finetune) +inline constexpr int PLE_ROW_BYTES_Q8_0 = (PLE_HEAD_DIM / 32) * 34; // 170: a Q8_0 row (UD-Q6_K_XL, Swift-1.5 Q4_K_L) +inline constexpr int PLE_ROW_BYTES_MAX = PLE_ROW_BYTES_Q8_0; // the widest row any format in `ple_formats()` has /// THE FORMATS OF THE TABLE, ONE ROW EACH. A table type is one entry here (its GGUF type name, the bytes of one /// 160-value row, how to turn a row into floats) and nothing else: `PleTable::open`, `format()`, the reader's row size, /// the error string and the buffers' size all read this list, so a new format cannot be in one switch and missing from /// another. A row is always `PLE_HEAD_DIM` = 160 values = 5 blocks of 32 for the block formats. -enum class PleFormat : uint8_t { IQ4_NL, Q5_0, F8_E4M3 }; +enum class PleFormat : uint8_t { IQ4_NL, Q5_0, F8_E4M3, Q5_1, Q8_0 }; struct PleFormatInfo { PleFormat id; diff --git a/src/kernels/dequant_bf16_test.cpp b/src/kernels/dequant_bf16_test.cpp index 80d3d53e68..28a75ba1b4 100644 --- a/src/kernels/dequant_bf16_test.cpp +++ b/src/kernels/dequant_bf16_test.cpp @@ -25,6 +25,7 @@ bool cpu_block(int type, const uint8_t* b, float* out) { switch (type) { case 2: dequantize_q4_0(b, out); return true; case 6: dequantize_q5_0(b, out); return true; + case 7: dequantize_q5_1(b, out); return true; case 8: dequantize_q8_0(b, out); return true; case 11: dequantize_q3_K(b, out); return true; case 12: dequantize_q4_K(b, out); return true; diff --git a/src/kernels/ngram.cpp b/src/kernels/ngram.cpp index 3728207b2f..8a705639fd 100644 --- a/src/kernels/ngram.cpp +++ b/src/kernels/ngram.cpp @@ -148,6 +148,9 @@ const PleFormatInfo kPleFormats[] = { {PleFormat::IQ4_NL, "IQ4_NL", "IQ4_NL", PLE_ROW_BYTES, false, dequant_iq4_nl}, {PleFormat::Q5_0, "Q5_0", "Q5_0", (PLE_HEAD_DIM / 32) * 22, false, dequant_blocks}, {PleFormat::F8_E4M3, "F8_E4M3", "I8", PLE_ROW_BYTES_FP8, true, dequant_fp8}, + // Ordinary GGUFs ship the table in other types: Unsloth's UD-Q6_K_XL and Swift-1.5 Q4_K_L as Q8_0, a Q5_K_M finetune as Q5_1 + {PleFormat::Q5_1, "Q5_1", "Q5_1", PLE_ROW_BYTES_Q5_1, false, dequant_blocks}, + {PleFormat::Q8_0, "Q8_0", "Q8_0", PLE_ROW_BYTES_Q8_0, false, dequant_blocks}, }; constexpr int kPleFormatCount = (int) (sizeof kPleFormats / sizeof kPleFormats[0]); } // namespace diff --git a/src/kernels/ple_q5_parity.cpp b/src/kernels/ple_q5_parity.cpp index cd387a8e45..29dc47e9c6 100644 --- a/src/kernels/ple_q5_parity.cpp +++ b/src/kernels/ple_q5_parity.cpp @@ -1,4 +1,5 @@ -// Real-artifact Q5_0 PLE rows against ggml's reference dequantizer. +// Real-artifact Q5_0 / Q5_1 / Q8_0 PLE rows against ggml's reference dequantizer, through both readers (the mapped +// one and the direct SSD reader). #define NOMINMAX #include "strata/artifact/gguf_reader.hpp" #include "strata/kernels/ngram.hpp" @@ -10,33 +11,28 @@ #include #include -int main(int argc, char** argv) { - if (argc != 2) { - std::fprintf(stderr, "usage: ple_q5_parity \n"); - return 2; - } - strata::GgufFile gguf(argv[1]); - const auto* tensor = gguf.find("per_layer_token_embd.weight"); - if (!tensor || tensor->type != 6 || tensor->shape.size() != 2 || tensor->shape[0] != 160) { - std::fprintf(stderr, "expected Q5_0 PLE [160, N]\n"); - return 2; - } +namespace { + +// Largest absolute difference between the table's rows and ggml's dequantization of the same bytes, single rows +// and one 16-row batch; -1 when the table cannot be opened or read. +double check(const char* path, strata::kernels::PleIo mode, const uint8_t* bytes, size_t row_bytes, + const ggml_type_traits* traits, std::string& format, size_t& n_rows) { strata::kernels::PleIoOptions options; - options.mode = strata::kernels::PleIo::Mmap; + options.mode = mode; strata::kernels::PleTable table; std::string err; - if (!table.open(argv[1], err, options)) { - std::fprintf(stderr, "%s\n", err.c_str()); - return 1; + if (!table.open(path, err, options)) { + std::fprintf(stderr, "open: %s\n", err.c_str()); + return -1.0; } - const auto* traits = ggml_get_type_traits(GGML_TYPE_Q5_0); - const uint8_t* bytes = gguf.tensor_data(*tensor); + format = table.format(); + n_rows = (size_t) table.rows(); const uint32_t probes[] = {0, 1, 12345, 20000003, (uint32_t) (table.rows() - 1)}; double max_abs = 0.0; for (uint32_t row : probes) { float got[160], want[160]; table.read_row(row, got); - traits->to_float(bytes + (size_t) row * 110, want, 160); + traits->to_float(bytes + (size_t) row * row_bytes, want, 160); for (int i = 0; i < 160; ++i) max_abs = std::max(max_abs, (double) std::fabs(got[i] - want[i])); } @@ -45,15 +41,46 @@ int main(int argc, char** argv) { float batch[16 * 160]; if (!table.issue(rows) || !table.collect(batch, err)) { std::fprintf(stderr, "collect: %s\n", err.c_str()); - return 1; + return -1.0; } for (int h = 0; h < 16; ++h) { float want[160]; - traits->to_float(bytes + (size_t) rows[h] * 110, want, 160); + traits->to_float(bytes + (size_t) rows[h] * row_bytes, want, 160); for (int i = 0; i < 160; ++i) max_abs = std::max(max_abs, (double) std::fabs(batch[h * 160 + i] - want[i])); } - std::printf("Q5_0 PLE: %zu rows, max_abs %.3e %s\n", (size_t) table.rows(), max_abs, - max_abs <= 1e-6 ? "PASS" : "FAIL"); - return max_abs <= 1e-6 ? 0 : 1; + return max_abs; +} + +} // namespace + +int main(int argc, char** argv) { + if (argc != 2) { + std::fprintf(stderr, "usage: ple_q5_parity \n"); + return 2; + } + strata::GgufFile gguf(argv[1]); + const auto* tensor = gguf.find("per_layer_token_embd.weight"); + // Q5_0 (#296: OrcaRouter's Q4_K_S), Q5_1 (a Q5_K_M GGUF), Q8_0 (UD-Q6_K_XL, Swift-1.5 Q4_K_L): 5 blocks of + // 32 per row + if (!tensor || (tensor->type != GGML_TYPE_Q5_0 && tensor->type != GGML_TYPE_Q5_1 && tensor->type != GGML_TYPE_Q8_0) || + tensor->shape.size() != 2 || tensor->shape[0] != 160) { + std::fprintf(stderr, "expected a Q5_0, Q5_1 or Q8_0 PLE [160, N]\n"); + return 2; + } + const auto type = (ggml_type) tensor->type; + const size_t row_bytes = type == GGML_TYPE_Q5_0 ? 110 : type == GGML_TYPE_Q5_1 ? 120 : 170; + const auto* traits = ggml_get_type_traits(type); + const uint8_t* bytes = gguf.tensor_data(*tensor); + bool ok = true; + for (auto mode : {strata::kernels::PleIo::Mmap, strata::kernels::PleIo::Direct}) { + std::string format; + size_t n_rows = 0; + const double max_abs = check(argv[1], mode, bytes, row_bytes, traits, format, n_rows); + const bool pass = max_abs >= 0.0 && max_abs <= 1e-6; + std::printf("%s PLE, %s reader: %zu rows, max_abs %.3e %s\n", format.c_str(), + mode == strata::kernels::PleIo::Mmap ? "mapped" : "direct", n_rows, max_abs, pass ? "PASS" : "FAIL"); + ok = ok && pass; + } + return ok ? 0 : 1; } diff --git a/src/ngram/ple_reader_test.cpp b/src/ngram/ple_reader_test.cpp index db94691942..6baaf1eeb4 100644 --- a/src/ngram/ple_reader_test.cpp +++ b/src/ngram/ple_reader_test.cpp @@ -177,6 +177,11 @@ void all_formats_round_trip(const std::string& dir) { format_round_trip(dir, f, 2000); } CHECK(k::ple_format_for_type("Q6_K") == nullptr, "Q6_K must not be a PLE format"); + if (g_fail == 0) { + std::printf("ple formats, both readers vs their dequantizers:"); + for (int i = 0; i < k::ple_format_count(); ++i) std::printf(" %s", k::ple_formats()[i].name); + std::printf(": OK\n"); + } } // row_bytes: ng::ROW_BYTES (90, IQ4_NL) is the production default; 110 (#296, OrcaRouter's Q5_0 PLE rows) is diff --git a/tests/core/dequant_q5_1_test.cpp b/tests/core/dequant_q5_1_test.cpp new file mode 100644 index 0000000000..6cd17f7661 --- /dev/null +++ b/tests/core/dequant_q5_1_test.cpp @@ -0,0 +1,40 @@ +// dequantize_q5_1 (strata/artifact/dequant.hpp: the PLE table of a Q5_1 GGUF) against ggml's dequantize_row_q5_1, +// on synthetic blocks: random codes, high bits and scales, plus the edge codes 0 and 31 and a negative minimum. +// No model, no GPU. +#include "strata/artifact/dequant.hpp" +#include "ggml.h" + +#include +#include +#include +#include +#include +#include + +int main() { + constexpr int kBlocks = 4096; + constexpr int kBlockBytes = 24; + std::mt19937 rng(20261002); + std::uniform_int_distribution byte(0, 255); + std::uniform_real_distribution scale(-0.05f, 0.05f); + std::vector blocks((size_t) kBlocks * kBlockBytes); + for (int b = 0; b < kBlocks; ++b) { + uint8_t* blk = blocks.data() + (size_t) b * kBlockBytes; + const ggml_fp16_t d = ggml_fp32_to_fp16(scale(rng)); + const ggml_fp16_t m = ggml_fp32_to_fp16(b == 1 ? -1.5f : scale(rng) * 20.0f); + std::memcpy(blk, &d, 2); + std::memcpy(blk + 2, &m, 2); + for (int i = 4; i < kBlockBytes; ++i) blk[i] = (uint8_t) byte(rng); + if (b == 0) std::memset(blk + 4, 0x00, 20); // every code 0: the value is m + if (b == 1) std::memset(blk + 4, 0xFF, 20); // every code 31 (all high bits set) + } + const auto* traits = ggml_get_type_traits(GGML_TYPE_Q5_1); + std::vector want((size_t) kBlocks * 32), got((size_t) kBlocks * 32); + traits->to_float(blocks.data(), want.data(), (int64_t) want.size()); + for (int b = 0; b < kBlocks; ++b) strata::dequantize_q5_1(blocks.data() + (size_t) b * kBlockBytes, got.data() + b * 32); + double max_abs = 0.0; + for (size_t i = 0; i < want.size(); ++i) max_abs = std::fmax(max_abs, std::fabs((double) got[i] - want[i])); + const bool ok = max_abs <= 1e-6; + std::printf("Q5_1 dequant: %d blocks, max_abs %.3e %s\n", kBlocks, max_abs, ok ? "PASS" : "FAIL"); + return ok ? 0 : 1; +} From e79b8fc14382375d20a566a770d881c6f9399112 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 5 Oct 2026 10:11:10 +0200 Subject: [PATCH 03/48] ple: check the table's size arithmetic before using it (#865) PleTable::open compared rows x row_bytes against the file after the 64-bit product could already have wrapped, and mapped the tensor before checking it fits. Now: refuse a row count that overflows rows x row_bytes and a data section that starts past the end of the file, check offset and size without an addition that can wrap (offset > have, need > have - offset), require a single-tensor shard to start at offset 0 and fill the file, and map the table only after all of that. close() also resets the FP8 scale and the byte counter. ple_reader_test --selftest writes tables that claim one row too many, one too few and a wrapping row count, for every format, and checks both readers refuse each with a message and stay closed. Checks taken from CC-David-CC's #865 (its opt-in Q8_0 table is #651's; the direct reader reads Q8_0, so the experimental switch and the mapped-only limit are not needed). Co-authored-by: CC-David-CC --- src/kernels/ngram.cpp | 15 +++++++++++++-- src/ngram/ple_reader_test.cpp | 34 ++++++++++++++++++++++++++++++++-- 2 files changed, 45 insertions(+), 4 deletions(-) diff --git a/src/kernels/ngram.cpp b/src/kernels/ngram.cpp index 8a705639fd..0e404d9731 100644 --- a/src/kernels/ngram.cpp +++ b/src/kernels/ngram.cpp @@ -11,6 +11,7 @@ #include #include #include +#include #if !defined(_WIN32) #include #endif @@ -252,7 +253,6 @@ bool PleTable::open(const std::string& gguf_path, std::string& err, const PleIoO // 110 B rows go through the exact same generic path (ple_reader_test --selftest covers both 90 and 110 B // rows: straddling, caching, in-flight tickets, keep-alive). This refusal was stale. impl_->n_rows = t->shape[1]; - impl_->data = impl_->file->tensor_data(*t); // THE CHECK THAT MAKES THE OFFSET FALSIFIABLE. The manifest's `shard2_tensor.offset` is 0, but that is // the offset within the GGUF's DATA SECTION: the file's first 192 bytes are a header, and reading at 0 @@ -262,10 +262,18 @@ bool PleTable::open(const std::string& gguf_path, std::string& err, const PleIoO // assumed. A wrong data offset would leave a different remainder. // A shard may hold other tensors too (Swift 1.5's shard 1 holds layers 0-12 and the table): the table must // then fit inside the file at its own offset; alone in its shard (the original's shard 2) it fills it exactly. + // The size arithmetic is checked before it is used (#865): a header that claims enough rows to wrap the 64-bit + // product, or a data section that starts past the end of the file, must be refused, not compared after wrapping. + if (impl_->n_rows > std::numeric_limits::max() / impl_->rb || + impl_->file->data_start() > impl_->file->file_size()) { + err = "PLE table size overflow or invalid data offset in " + gguf_path; + close(); + return false; + } const uint64_t need = impl_->n_rows * (uint64_t) impl_->rb; const uint64_t have = impl_->file->file_size() - impl_->file->data_start(); const bool alone = impl_->file->tensors().size() == 1; - if (alone ? need != have : t->offset + need > have) { + if (t->offset > have || need > have - t->offset || (alone && (t->offset != 0 || need != have))) { char buf[256]; std::snprintf(buf, sizeof buf, "PLE table size mismatch: %llu rows x %d B = %llu at offset %llu, but the file holds %llu from " @@ -277,6 +285,7 @@ bool PleTable::open(const std::string& gguf_path, std::string& err, const PleIoO close(); return false; } + impl_->data = impl_->file->tensor_data(*t); // only a table that fits the file is mapped if (io.mode == PleIo::Direct) { // The parse above is the validated source of the offset; the mapping itself is not kept, so no page of // the table can enter this process's working set or the file cache through it. @@ -358,6 +367,8 @@ void PleTable::close() { impl_->n_rows = 0; impl_->rb = PLE_ROW_BYTES; impl_->fmt = &ple_format_info(PleFormat::IQ4_NL); + impl_->scale = 1.0f; + impl_->bytes_read = 0; } bool PleTable::is_open() const { return impl_->data != nullptr || impl_->reader.is_open(); } diff --git a/src/ngram/ple_reader_test.cpp b/src/ngram/ple_reader_test.cpp index 6baaf1eeb4..28baeea02b 100644 --- a/src/ngram/ple_reader_test.cpp +++ b/src/ngram/ple_reader_test.cpp @@ -87,7 +87,8 @@ uint32_t gguf_type_id(const char* name) { return 0xFFFFFFFFu; } -std::string write_format_table(const std::string& dir, const k::PleFormatInfo& f, uint32_t rows) { +// `claimed_rows` is the row count the header states; `rows` rows are actually written (equal unless a test lies) +std::string write_format_table(const std::string& dir, const k::PleFormatInfo& f, uint32_t rows, uint64_t claimed_rows = 0) { const std::string path = dir + "/ple_format_selftest.gguf"; std::ofstream out(path, std::ios::binary); if (!out) { std::fprintf(stderr, "cannot write %s\n", path.c_str()); return {}; } @@ -108,7 +109,7 @@ std::string write_format_table(const std::string& dir, const k::PleFormatInfo& f head += str("strata.ple.scale") + le(6u, 4) + le(sb, 4); // 6 = FLOAT32 } head += str("per_layer_token_embd.weight") + le(2u, 4); - head += le((uint64_t) k::PLE_HEAD_DIM, 8) + le((uint64_t) rows, 8); + head += le((uint64_t) k::PLE_HEAD_DIM, 8) + le(claimed_rows != 0 ? claimed_rows : (uint64_t) rows, 8); head += le(gguf_type_id(f.name), 4) + le(0ull, 8); while (head.size() % 32) head += '\0'; out.write(head.data(), (std::streamsize) head.size()); @@ -168,7 +169,36 @@ void format_round_trip(const std::string& dir, const k::PleFormatInfo& f, uint32 std::filesystem::remove(path); } +/// A table whose header does not match the file is refused with a message, never read past its end (#865): one row +/// short, one row long (a single-tensor shard must be filled exactly), and a row count that wraps the 64-bit size. +void bad_sizes_are_refused(const std::string& dir) { + for (int i = 0; i < k::ple_format_count(); ++i) { + const k::PleFormatInfo& f = k::ple_formats()[i]; + struct { const char* what; uint32_t rows; uint64_t claimed; } cases[] = { + {"claims one row more than the file holds", 500, 501}, + {"claims one row less than the file holds", 500, 499}, + {"claims a row count that wraps 2^64", 8, (uint64_t) 0x4000000000000000ull / 3 * 2}, + }; + for (const auto& c : cases) { + const std::string path = write_format_table(dir, f, c.rows, c.claimed); + if (path.empty()) { CHECK(false, "%s: no table was written", f.name); continue; } + for (k::PleIo mode : {k::PleIo::Direct, k::PleIo::Mmap}) { + k::PleTable t; + std::string err; + k::PleIoOptions io; + io.mode = mode; + io.cache_rows = 0; + CHECK(!t.open(path, err, io), "%s: a table that %s was accepted", f.name, c.what); + CHECK(!err.empty(), "%s: refused without a message (%s)", f.name, c.what); + CHECK(!t.is_open(), "%s: left open after refusing (%s)", f.name, c.what); + } + std::filesystem::remove(path); + } + } +} + void all_formats_round_trip(const std::string& dir) { + bad_sizes_are_refused(dir); CHECK(k::ple_format_count() > 0, "no formats"); for (int i = 0; i < k::ple_format_count(); ++i) { const k::PleFormatInfo& f = k::ple_formats()[i]; From 626a89bc1ea0243c1def228e2b11ad21ffa8522f Mon Sep 17 00:00:00 2001 From: Anon Date: Mon, 5 Oct 2026 10:12:34 +0200 Subject: [PATCH 04/48] ple: --ple-io ram faults the table in on up to 16 threads before mlock (#651) mlock alone brings a cold file in one page at a time from one thread, ~0.47 GiB/s (about two minutes for a 54 GB Q8_0 table); 16 threads reach ~2 GiB/s on anon761's machine. The pages are then resident and mlock only pins them. When mlock fails, the pages stay faulted in (the message says they may be reclaimed) instead of being touched again one by one. ple_reader_test gets --make-table PATH FORMAT (a big synthetic table, with --rows) and --ram-time PATH (open mapped and locked, print the seconds) to time it cold. Ported by the maintainer from anon761's PR #651. Co-authored-by: ksanislo --- src/kernels/ngram.cpp | 29 ++++++++++++++++++++++++----- src/ngram/ple_reader_test.cpp | 29 +++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+), 5 deletions(-) diff --git a/src/kernels/ngram.cpp b/src/kernels/ngram.cpp index 0e404d9731..2d338a6406 100644 --- a/src/kernels/ngram.cpp +++ b/src/kernels/ngram.cpp @@ -15,6 +15,9 @@ #if !defined(_WIN32) #include #endif +#include +#include +#include #include #include @@ -308,14 +311,30 @@ bool PleTable::open(const std::string& gguf_path, std::string& err, const PleIoO const uintptr_t a0 = (uintptr_t) impl_->data & ~(uintptr_t) (page - 1); const uintptr_t a1 = (uintptr_t) impl_->data + (uintptr_t) need; madvise((void*) a0, a1 - a0, MADV_WILLNEED); + // Fault the table in with several threads first: mlock (and a single toucher) brings it in one page at a time + // from one thread, ~0.5 GB/s from a cold file - 106 s for a 54 GB Q8_0 table. The pages are then resident + // and mlock only pins them. + { + constexpr uintptr_t kPiece = 64ull << 20; + const uintptr_t pieces = (a1 - a0 + kPiece - 1) / kPiece; + const unsigned threads = std::max(1u, std::min(16u, std::thread::hardware_concurrency())); + std::atomic next{0}; + auto touch = [&] { + volatile uint8_t sink = 0; + for (uintptr_t i; (i = next.fetch_add(1)) < pieces;) + for (uintptr_t p = a0 + i * kPiece, e = std::min(a1, p + kPiece); p < e; p += page) + sink = sink + *(const volatile uint8_t*) p; + (void) sink; + }; + std::vector pool; + for (unsigned t = 0; t < threads; ++t) pool.emplace_back(touch); + for (auto& t : pool) t.join(); + } if (mlock((const void*) a0, a1 - a0) == 0) { impl_->locked = true; } else { - std::fprintf(stderr, "strata: PLE table mlock failed (%s; raise `ulimit -l`): touching its pages instead\n", - std::strerror(errno)); - volatile uint8_t sink = 0; - for (uintptr_t p = a0; p < a1; p += page) sink = sink + *(const volatile uint8_t*) p; - (void) sink; + std::fprintf(stderr, "strata: PLE table mlock failed (%s; raise `ulimit -l`): its pages stay faulted in " + "but may be reclaimed\n", std::strerror(errno)); } #endif } diff --git a/src/ngram/ple_reader_test.cpp b/src/ngram/ple_reader_test.cpp index 28baeea02b..e9086d5143 100644 --- a/src/ngram/ple_reader_test.cpp +++ b/src/ngram/ple_reader_test.cpp @@ -411,9 +411,12 @@ int main(int argc, char** argv) { bool direct_only = false; bool sync_submit = false; bool self = false; + std::string make_path, make_fmt, ram_path; // --make-table PATH FORMAT (uses --rows), --ram-time PATH for (int i = 1; i < argc; ++i) { const std::string a = argv[i]; if (a == "--selftest") self = true; + else if (a == "--make-table" && i + 2 < argc) { make_path = argv[i + 1]; make_fmt = argv[i + 2]; i += 2; } + else if (a == "--ram-time" && i + 1 < argc) ram_path = argv[++i]; else if (a == "--dir" && i + 1 < argc) dir = argv[++i]; else if (a == "--gguf" && i + 1 < argc) gguf = argv[++i]; else if (a == "--rows" && i + 1 < argc) rows = std::atoi(argv[++i]); @@ -433,6 +436,32 @@ int main(int argc, char** argv) { const int r110 = selftest(dir, 110); return r90 != 0 ? r90 : r110; } + if (!make_path.empty()) { // a big synthetic table, for timing --ple-io ram's fault-in + for (int i = 0; i < k::ple_format_count(); ++i) { + const k::PleFormatInfo& f = k::ple_formats()[i]; + if (make_fmt != f.name) continue; + const std::string tmp = write_format_table(std::filesystem::path(make_path).parent_path().string(), f, (uint32_t) rows); + if (tmp.empty()) return 1; + std::filesystem::rename(tmp, make_path); + std::printf("wrote %s: %s, %d rows, %.2f GiB\n", make_path.c_str(), f.name, rows, + (double) rows * f.row_bytes / (1024.0 * 1024.0 * 1024.0)); + return 0; + } + std::fprintf(stderr, "unknown format %s\n", make_fmt.c_str()); + return 2; + } + if (!ram_path.empty()) { // open mapped and locked (--ple-io ram): the seconds it takes + k::PleTable t; + k::PleIoOptions io; + io.mode = k::PleIo::Mmap; + io.lock = true; + std::string err; + const double t0 = now_us(); + const bool ok = t.open(ram_path, err, io); + std::printf("ram open: %s, format %s, locked %d, %.2f s\n", ok ? "ok" : err.c_str(), ok ? t.format() : "-", ok && t.locked(), + (now_us() - t0) / 1e6); + return ok ? 0 : 1; + } if (!gguf.empty()) return real(gguf, rows, tokens, inflight, direct_first, direct_only, sync_submit); std::fprintf(stderr, "nothing to do\n"); return 2; From 16bdc7073d417458382e0f27cb01ed158bc0c3a8 Mon Sep 17 00:00:00 2001 From: saikiran-rs Date: Mon, 5 Oct 2026 10:18:09 +0200 Subject: [PATCH 05/48] native experts: Q4_0 and Q4_1 GPU kernels, Q4_0 PLE table A plain llama-quantize Q4_0 file of this model (bartowski's Qwen3.8-Flash-Next-Q4_0 and Swift-1.5 Q4_0: gate/up Q4_0, down Q4_0 on 42 layers and Q4_1 on 6, a Q4_0 PLE table and token embedding) was refused at start: no GPU kernels for Q4_0/Q4_1 experts, and the PLE reader took only IQ4_NL, Q5_0 and FP8. Follows #222 (Q4 to Q6 quantizations). - Q4_0: Fmt<2> with the codes centred before dp4a (q - 8 as signed bytes), the exact integer form ggml-cpu's q4_0 x q8_0 dot uses, rather than llama.cpp's CUDA chain (uncentred codes minus 8 x the q8_1 float sum): on a real Q4_0 expert the CUDA chain measured 1.4e-2 relative error against the float product, the centred form 5.3e-3. - Q4_1: Fmt<3>, the Q5_1 chain without the fifth bit and the same min-term choice. - dq_q4_0 / dq_q4_1 for the prompt path's dequant fallback; row bytes, is_iq and the GU/D/MMVQ format lists. - PLE: Q4_0 rows (90 B, as IQ4_NL) through the same reader: one entry in the PLE format list (ple_format_test and ple_reader_test cover it). - docs/UNSLOTH_Q4.md: a Q4_0 section with the measured run. native_expert_parity --synthetic (now in the CMake matrix): q4_0/q4_0 CPU 1.29e-2, GPU 1.29e-2, CPU-GPU 1.1e-7; q4_0/q4_1 CPU-GPU 3.2e-4; GPU dequant bit-exact against to_float. The existing pairs are unchanged. On bartowski's file (revision 928589f), layers 0 and 5 (Q4_1 down) and 20 and 47: CPU and GPU 1.1-1.3e-2, CPU-GPU 1.1e-7 (Q4_0 down) and 5e-4 to 1.1e-3 (Q4_1 down). Served on one RTX 3060 (all experts in RAM, 131K context): 24,461-token prompt 787 tok/s read, 24.0 tok/s out; 67,934 tokens 737 / 26.4, the hidden fact found. Ported onto the format table by the maintainer (the PLE part of the PR is the Q4_0 table entry). --- CMakeLists.txt | 4 +- docs/UNSLOTH_Q4.md | 37 ++++++++++++-- include/strata/kernels/ngram.hpp | 2 +- src/kernels/cuda/iq_kernels.cu | 82 ++++++++++++++++++++++++++++++-- src/kernels/ngram.cpp | 2 + 5 files changed, 117 insertions(+), 10 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index ae36e40e9e..c7b44c3e8c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1166,7 +1166,9 @@ if(STRATA_NATIVE_EXPERTS) # kernel for it before; q5_0/q5_0 (both roles Q5_0) is left out of this list since stacking the same # lower-precision format on both roles pushes the GPU path over this test's 3% threshold (quantization # noise, not a kernel bug -- see the PR). - foreach(_pair q4_K/q5_1 q4_K/q8_0 q5_K/q8_0 q8_0/q8_0 q4_K/q5_0 q5_0/q8_0) + # q4_0/q4_0 and q4_0/q4_1: a plain llama-quantize Q4_0 file (bartowski's Qwen3.8-Flash-Next-Q4_0: gate/up Q4_0, + # down Q4_0 on 42 layers and Q4_1 on 6) + foreach(_pair q4_K/q5_1 q4_K/q8_0 q5_K/q8_0 q8_0/q8_0 q4_K/q5_0 q5_0/q8_0 q4_0/q4_0 q4_0/q4_1) string(REPLACE "/" "_" _name "${_pair}") add_test(NAME native_expert_parity_${_name} COMMAND native_expert_parity --synthetic ${_pair}) set_tests_properties(native_expert_parity_${_name} PROPERTIES TIMEOUT 120) diff --git a/docs/UNSLOTH_Q4.md b/docs/UNSLOTH_Q4.md index e275dec7cc..9e2601019c 100644 --- a/docs/UNSLOTH_Q4.md +++ b/docs/UNSLOTH_Q4.md @@ -248,13 +248,44 @@ the pack rounds the file's Q8_0 hyper-connection projections to BF16, and on the perplexity 6-9% above llama.cpp's on the same file (teacher-forced, short context). Reading the Q8_0 values instead closes most of that gap; it is measured on AMD only and not in this release. +## Q4_0 files + +A plain `llama-quantize` Q4_0 file of this model runs the same way: pack shard 1 with `--compat-bf16` as above and +point `--native` at it. Tested: +[bartowski/Qwen3.8-Flash-Next-GGUF, `Qwen3.8-Flash-Next-Q4_0`, revision `928589f`](https://huggingface.co/bartowski/Qwen3.8-Flash-Next-GGUF/tree/928589fdb66c6ff07f22ac561e3fbce76553548f/Qwen3.8-Flash-Next-Q4_0) +(3 shards, 100.6 GB). Its routed experts are Q4_0 for gate/up and for down, except down in layers 0-5, which is Q4_1; +the PLE table and the token embedding are Q4_0. The pack serves 302 tensors from the GGUF as stored and converts 362 +(168 exact, 194 rounded to BF16, largest absolute error 0.0156; 1.23 GiB). + +The Q4_0 expert kernels centre the codes (q - 8) before the integer dot product, as ggml-cpu's Q4_0 x Q8_0 dot does, +instead of llama.cpp's CUDA form (uncentred codes, minus 8 x the Q8_1 block sum in float); Q4_1 follows the Q5_1 +kernel without the fifth bit. `native_expert_parity` on this file (layers 0 and 5: Q4_0/Q4_1, layers 20 and 47: +Q4_0/Q4_0): relative error against the float product 1.1-1.3e-2 on the CPU and the GPU alike, CPU vs GPU 1.1e-7 for +Q4_0/Q4_0 and 5e-4 to 1.1e-3 with Q4_1 down. + +Measured on one RTX 3060 12 GB (PCIe 3.0 x16), Xeon E5-2696 v4, 121 GiB DDR4-2400, Linux, CUDA 12.4; every expert in +RAM, `--max-context 131072 --kv int8 --kv-resident 20480`, expert cache `auto` (1,960 slots, 5.06 GiB), prompt chunk +`auto` (6,144 tokens); greedy, `reasoning_effort` medium, one request at a time: + +| Prompt | Prompt read | Output | +| --- | --- | --- | +| 63 tokens (prose) | - | 25.4 tok/s | +| 111 tokens (code) | - | 28.0 tok/s | +| 24,461 tokens | 787 tok/s | 24.0 tok/s | +| 67,934 tokens (a fact hidden in the middle: found) | 737 tok/s | 26.4 tok/s | + +A coding prompt was answered correctly. Not measured: agreement with llama.cpp on this file (as +[above](#quality-against-llamacpp-on-the-same-file) for UD-Q4_K_XL), AMD, Windows, and bartowski's Swift-1.5 Q4_0, +whose header shows the same formats. + ## Scope and validation -- UD-Q4_K_XL and UD-IQ4_XS at revision `38bb39e` are targeted. Other Unsloth quantizations use formats this engine may - not have kernels for; the engine checks every layer's formats at start and refuses an unsupported one by name. +- UD-Q4_K_XL and UD-IQ4_XS at revision `38bb39e` are targeted, and plain Q4_0 files ([above](#q4_0-files)). Other + quantizations use formats this engine may not have kernels for; the engine checks every layer's formats at start + and refuses an unsupported one by name. - Tests: the packer's synthetic 4-shard and conversion tests (`.venv/bin/python -m unittest discover -s tools -p test_iq_pack.py`); CTests `gguf_split_test`, `expert_layout_test`, `native_expert_parity_*` (the three real expert - format pairs against ggml-cpu, the Q5_1 min term, Q8_0 rows), `prefill_mmq_kquant_test` (with `-DSTRATA_MMQ_KQUANTS=ON`: the + format pairs against ggml-cpu, the Q5_1 min term, Q8_0 rows, Q4_0/Q4_0 and Q4_0/Q4_1), `prefill_mmq_kquant_test` (with `-DSTRATA_MMQ_KQUANTS=ON`: the prompt path's MMQ products for Q4_K / Q5_K / Q5_1 / Q8_0 against ggml's dequantized weights); the in-place mode against `experts.bin` on the Coder (identical tokens and logits). - Real runs: greedy answers to a coding prompt (correct) at every budget and setting above, identical across them; diff --git a/include/strata/kernels/ngram.hpp b/include/strata/kernels/ngram.hpp index c0c8585846..da7373896d 100644 --- a/include/strata/kernels/ngram.hpp +++ b/include/strata/kernels/ngram.hpp @@ -54,7 +54,7 @@ inline constexpr int PLE_ROW_BYTES_MAX = PLE_ROW_BYTES_Q8_0; // the /// 160-value row, how to turn a row into floats) and nothing else: `PleTable::open`, `format()`, the reader's row size, /// the error string and the buffers' size all read this list, so a new format cannot be in one switch and missing from /// another. A row is always `PLE_HEAD_DIM` = 160 values = 5 blocks of 32 for the block formats. -enum class PleFormat : uint8_t { IQ4_NL, Q5_0, F8_E4M3, Q5_1, Q8_0 }; +enum class PleFormat : uint8_t { IQ4_NL, Q5_0, F8_E4M3, Q5_1, Q8_0, Q4_0 }; struct PleFormatInfo { PleFormat id; diff --git a/src/kernels/cuda/iq_kernels.cu b/src/kernels/cuda/iq_kernels.cu index 4b662ab065..53bf360bc5 100644 --- a/src/kernels/cuda/iq_kernels.cu +++ b/src/kernels/cuda/iq_kernels.cu @@ -310,7 +310,7 @@ __device__ __forceinline__ float vec_dot_iq4_xs_q8_1(const void* __restrict__ vb // Q4_K / Q5_K gate/up and Q5_1 / Q8_0 down: llama.cpp's vec_dot_*_q8_1 (vecdotq.cuh, VDR 2 each), transcribed; the // Q5_1 min term is the one departure (below). Via eddoursul/Strata 8029fa9 (iq_dot.cuh) and #255 (Q8_0, // gopinath87607), which agree with llama.cpp and with each other. -constexpr int VDR_Q4_K = 2, VDR_Q5_K = 2, VDR_Q5_1 = 2, VDR_Q5_0 = 2, VDR_Q8_0 = 2; +constexpr int VDR_Q4_K = 2, VDR_Q5_K = 2, VDR_Q5_1 = 2, VDR_Q5_0 = 2, VDR_Q4_1 = 2, VDR_Q4_0 = 2, VDR_Q8_0 = 2; __device__ __forceinline__ float vec_dot_q4_K_q8_1_impl_vmmq(const int* __restrict__ v, const int* __restrict__ u, const uint8_t* __restrict__ sc, const uint8_t* __restrict__ m, @@ -450,6 +450,46 @@ __device__ __forceinline__ float vec_dot_q5_0_q8_1(const void* __restrict__ vbq, const float s8 = __high2float(bq8_1->ds); return d5 * (sumi * d8 - (16.0f * VDR_Q5_0 / QI5_0) * s8); } +// Q4_0 (plain llama-quantize Q4_0 files, e.g. bartowski's: gate/up and most down projections): the codes are centred +// (q - 8 as signed bytes) before the dot, the exact integer form ggml-cpu's q4_0 x q8_0 dot uses, rather than +// llama.cpp's CUDA chain (uncentred codes minus 8 x the q8_1 block's float sum `ds.y`). On a real Q4_0 expert +// (2560 x 640) the CUDA chain measured 1.4e-2 relative error against the float product, the centred form 5.3e-3; +// with the CUDA chain native_expert_parity failed its 3e-2 limit on two layers of a Q4_0 Flash-Next file. The +// centring is the same idea as the Q5_1 min term above: the offset is applied to the activations' own int8 codes. +__device__ __forceinline__ int q4_0_centred(const int v) { + const int b = v ^ 0x08080808; // per byte: 0..15 -> (q - 8) as a 4-bit two's complement value + return b | ((b & 0x08080808) * 0x1E); // sign-extend each nibble into its byte (0x08 * 0x1E = 0xF0) +} +__device__ __forceinline__ float vec_dot_q4_0_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1, + const int& kbx, const int& iqs) { + const block_q4_0* bq4 = (const block_q4_0*) vbq + kbx; + int sumi = 0; +#pragma unroll + for (int i = 0; i < VDR_Q4_0; ++i) { + const int v = get_int_b2(bq4->qs, iqs + i); + sumi = ggml_cuda_dp4a(q4_0_centred((v >> 0) & 0x0F0F0F0F), get_int_b4(bq8_1->qs, iqs + i), sumi); + sumi = ggml_cuda_dp4a(q4_0_centred((v >> 4) & 0x0F0F0F0F), get_int_b4(bq8_1->qs, iqs + i + QI4_0), sumi); + } + return __half2float(bq4->d) * __low2float(bq8_1->ds) * sumi; +} +// Q4_1 (llama-quantize puts it on a few down projections of its Q4_0 files): the Q5_1 chain above without the fifth +// bit, the same min-term choice (the activations' own int8 codes): sumi * (d4 * d8) + sumu * (m4 * d8). +__device__ __forceinline__ float vec_dot_q4_1_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1, + const int& kbx, const int& iqs) { + const block_q4_1* bq4_1 = (const block_q4_1*) vbq + kbx; + int sumi = 0, sumu = 0; +#pragma unroll + for (int i = 0; i < VDR_Q4_1; ++i) { + const int v = get_int_b4(bq4_1->qs, iqs + i); + const int u0 = get_int_b4(bq8_1->qs, iqs + i), u1 = get_int_b4(bq8_1->qs, iqs + i + QI4_1); + sumi = ggml_cuda_dp4a((v >> 0) & 0x0F0F0F0F, u0, sumi); + sumi = ggml_cuda_dp4a((v >> 4) & 0x0F0F0F0F, u1, sumi); + sumu = ggml_cuda_dp4a(0x01010101, u1, ggml_cuda_dp4a(0x01010101, u0, sumu)); + } + const float2 dm4 = __half22float2(bq4_1->dm); + const float d8 = __low2float(bq8_1->ds); + return sumi * (dm4.x * d8) + sumu * (dm4.y * d8); +} __device__ __forceinline__ float vec_dot_q5_1_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1, const int& kbx, const int& iqs) { const block_q5_1* bq5_1 = (const block_q5_1*) vbq + kbx; @@ -515,6 +555,10 @@ template<> struct Fmt<13> { static constexpr int qk = 256, ipb = QI5_K / VDR_Q5_ __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_q5_K_q8_1(v, y, kbx, iqs); } }; template<> struct Fmt<7> { static constexpr int qk = 32, ipb = QI5_1 / VDR_Q5_1, step = VDR_Q5_1; __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_q5_1_q8_1(v, y, kbx, iqs); } }; +template<> struct Fmt<2> { static constexpr int qk = 32, ipb = QI4_0 / VDR_Q4_0, step = VDR_Q4_0; + __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_q4_0_q8_1(v, y, kbx, iqs); } }; +template<> struct Fmt<3> { static constexpr int qk = 32, ipb = QI4_1 / VDR_Q4_1, step = VDR_Q4_1; + __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_q4_1_q8_1(v, y, kbx, iqs); } }; template<> struct Fmt<6> { static constexpr int qk = 32, ipb = QI5_0 / VDR_Q5_0, step = VDR_Q5_0; __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_q5_0_q8_1(v, y, kbx, iqs); } }; template<> struct Fmt<8> { static constexpr int qk = 32, ipb = QI8_0 / VDR_Q8_0, step = VDR_Q8_0; @@ -522,9 +566,9 @@ template<> struct Fmt<8> { static constexpr int qk = 32, ipb = QI8_0 / VDR_Q8_0, // The formats of each role, one list each so a type cannot be in one switch and missing from another. Every // entry is a kernel template for each CUDA architecture of the build, hence two lists rather than one. -#define STRATA_GU_FMTS(X) X(16) X(17) X(18) X(21) X(22) X(23) X(29) X(42) X(12) X(13) X(6) X(8) -#define STRATA_D_FMTS(X) X(20) X(23) X(42) X(7) X(6) X(8) -#define STRATA_MMVQ_FMTS(X) X(16) X(17) X(18) X(20) X(21) X(22) X(23) X(29) X(42) X(12) X(13) X(7) X(6) X(8) +#define STRATA_GU_FMTS(X) X(16) X(17) X(18) X(21) X(22) X(23) X(29) X(42) X(12) X(13) X(6) X(2) X(3) X(8) +#define STRATA_D_FMTS(X) X(20) X(23) X(42) X(7) X(6) X(2) X(3) X(8) +#define STRATA_MMVQ_FMTS(X) X(16) X(17) X(18) X(20) X(21) X(22) X(23) X(29) X(42) X(12) X(13) X(7) X(6) X(2) X(3) X(8) __device__ __forceinline__ float warp_sum(float v) { #pragma unroll @@ -1606,6 +1650,30 @@ __device__ void dq_q5_0(const void* vx, int64_t ibs, dst_t* yy, int tid) { } } template +__device__ void dq_q4_0(const void* vx, int64_t ibs, dst_t* yy, int tid) { + const block_q4_0* x = (const block_q4_0*) vx + ibs * (QK_K / QK4_0); + const int ib = tid % 8, il = tid / 8; + const float d = __half2float(x[ib].d); + dst_t* y = yy + 32 * ib; + for (int j = 0; j < 4; ++j) { + const int iqs = 4 * il + j; // llama.cpp's dequantize_q4_0 for value pairs iqs, iqs + 16 + y[iqs] = cvt(((float) (x[ib].qs[iqs] & 0xf) - 8.0f) * d); + y[iqs + 16] = cvt(((float) (x[ib].qs[iqs] >> 4) - 8.0f) * d); + } +} +template +__device__ void dq_q4_1(const void* vx, int64_t ibs, dst_t* yy, int tid) { + const block_q4_1* x = (const block_q4_1*) vx + ibs * (QK_K / QK4_1); + const int ib = tid % 8, il = tid / 8; + const float2 dm = __half22float2(x[ib].dm); + dst_t* y = yy + 32 * ib; + for (int j = 0; j < 4; ++j) { + const int iqs = 4 * il + j; // llama.cpp's dequantize_q4_1 for value pairs iqs, iqs + 16 + y[iqs] = cvt((float) (x[ib].qs[iqs] & 0xf) * dm.x + dm.y); + y[iqs + 16] = cvt((float) (x[ib].qs[iqs] >> 4) * dm.x + dm.y); + } +} +template __device__ void dq_q5_1(const void* vx, int64_t ibs, dst_t* yy, int tid) { const block_q5_1* x = (const block_q5_1*) vx + ibs * (QK_K / QK5_1); const int ib = tid % 8, il = tid / 8; @@ -1656,6 +1724,8 @@ __device__ __forceinline__ void dq_dispatch(int ty, const void* vx, int64_t ibs, case 13: dq_q5_k(vx, ibs, y, tid); break; case 7: dq_q5_1(vx, ibs, y, tid); break; case 6: dq_q5_0(vx, ibs, y, tid); break; + case 2: dq_q4_0(vx, ibs, y, tid); break; + case 3: dq_q4_1(vx, ibs, y, tid); break; case 8: dq_q8_0(vx, ibs, y, tid); break; case 30: dq_bf16(vx, ibs, y, tid); break; default: break; @@ -1680,7 +1750,7 @@ __global__ void dequant_gu_kernel(int ty, const void* __restrict__ gate, const v // the types dq_dispatch dequantizes bool is_iq(int t) { return t == 16 || t == 17 || t == 18 || t == 20 || t == 21 || t == 22 || t == 23 || t == 29 || t == 42 || t == 11 || - t == 12 || t == 13 || t == 7 || t == 6 || t == 8; + t == 12 || t == 13 || t == 7 || t == 6 || t == 2 || t == 3 || t == 8; } // values per block of the types the grouped expert kernels take (0 = none) int gu_qk(int t) { @@ -1793,6 +1863,8 @@ size_t iq_row_bytes(int t, int64_t n) noexcept { case 13: return (size_t) (n / 256) * sizeof(block_q5_K); case 7: return (size_t) (n / 32) * sizeof(block_q5_1); case 6: return (size_t) (n / 32) * sizeof(block_q5_0); + case 2: return (size_t) (n / 32) * sizeof(block_q4_0); + case 3: return (size_t) (n / 32) * sizeof(block_q4_1); case 8: return (size_t) (n / 32) * sizeof(block_q8_0); case 30: return (size_t) n * 2; // BF16: the token embedding only (iq_embed_rows, iq_dequant_f32) default: return 0; diff --git a/src/kernels/ngram.cpp b/src/kernels/ngram.cpp index 2d338a6406..259bfe88da 100644 --- a/src/kernels/ngram.cpp +++ b/src/kernels/ngram.cpp @@ -155,6 +155,8 @@ const PleFormatInfo kPleFormats[] = { // Ordinary GGUFs ship the table in other types: Unsloth's UD-Q6_K_XL and Swift-1.5 Q4_K_L as Q8_0, a Q5_K_M finetune as Q5_1 {PleFormat::Q5_1, "Q5_1", "Q5_1", PLE_ROW_BYTES_Q5_1, false, dequant_blocks}, {PleFormat::Q8_0, "Q8_0", "Q8_0", PLE_ROW_BYTES_Q8_0, false, dequant_blocks}, + // Q4_0 (plain llama-quantize Q4_0 files, #599): 90-byte rows like IQ4_NL (18-byte blocks), a linear 4-bit grid + {PleFormat::Q4_0, "Q4_0", "Q4_0", PLE_ROW_BYTES, false, dequant_blocks}, }; constexpr int kPleFormatCount = (int) (sizeof kPleFormats / sizeof kPleFormats[0]); } // namespace From cb87a62e82906ff6d6b6623545acd4334903a986 Mon Sep 17 00:00:00 2001 From: Constantin Date: Mon, 5 Oct 2026 10:19:27 +0200 Subject: [PATCH 06/48] ple: read the n-gram table at full BF16 precision (#586) The full checkpoint stores the table as BF16 (320-byte rows, 102.4 GB), the source of record; the engine gets it as IQ4_NL (about 8% off per row) or FP8. A bfloat16 is the top half of a float32, so widening is a shift: exact for every value, no rounding and no scale. One entry in the PLE format list (type BF16, self-describing: no scale, no metadata) and bf16_dequant_row; the direct reader takes the 320-byte row like any other width, and PLE_ROW_BYTES_MAX is 320. ple_reader_test checks the widening is exact over the patterns a lossy path breaks on (subnormals, +-inf, both NaNs); the generic every-format test covers a synthetic BF16 GGUF through both readers. Not in this commit: the PR's rename of tools/ple_fp8_pack.py (nothing needs it) and any setup option. Whether a table format other than IQ4_NL is worth offering is a quality question (see the measurement in the 0.1.40 notes). Ported by the maintainer from constantindjonkam's PR #586. --- include/strata/kernels/ngram.hpp | 14 +++++++++++--- src/kernels/ngram.cpp | 17 +++++++++++++++++ src/ngram/ple_reader_test.cpp | 25 +++++++++++++++++++++++++ 3 files changed, 53 insertions(+), 3 deletions(-) diff --git a/include/strata/kernels/ngram.hpp b/include/strata/kernels/ngram.hpp index da7373896d..8429147602 100644 --- a/include/strata/kernels/ngram.hpp +++ b/include/strata/kernels/ngram.hpp @@ -48,13 +48,14 @@ inline constexpr int PLE_ROW_BYTES = (PLE_HEAD_DIM / 32) * 18; // 90: inline constexpr int PLE_ROW_BYTES_FP8 = PLE_HEAD_DIM; // 160: an F8_E4M3 row, one byte a value inline constexpr int PLE_ROW_BYTES_Q5_1 = (PLE_HEAD_DIM / 32) * 24; // 120: a Q5_1 row (a Q5_K_M finetune) inline constexpr int PLE_ROW_BYTES_Q8_0 = (PLE_HEAD_DIM / 32) * 34; // 170: a Q8_0 row (UD-Q6_K_XL, Swift-1.5 Q4_K_L) -inline constexpr int PLE_ROW_BYTES_MAX = PLE_ROW_BYTES_Q8_0; // the widest row any format in `ple_formats()` has +inline constexpr int PLE_ROW_BYTES_BF16 = PLE_HEAD_DIM * 2; // 320: a BF16 row, two bytes a value +inline constexpr int PLE_ROW_BYTES_MAX = PLE_ROW_BYTES_BF16; // the widest row any format in `ple_formats()` has /// THE FORMATS OF THE TABLE, ONE ROW EACH. A table type is one entry here (its GGUF type name, the bytes of one /// 160-value row, how to turn a row into floats) and nothing else: `PleTable::open`, `format()`, the reader's row size, /// the error string and the buffers' size all read this list, so a new format cannot be in one switch and missing from /// another. A row is always `PLE_HEAD_DIM` = 160 values = 5 blocks of 32 for the block formats. -enum class PleFormat : uint8_t { IQ4_NL, Q5_0, F8_E4M3, Q5_1, Q8_0, Q4_0 }; +enum class PleFormat : uint8_t { IQ4_NL, Q5_0, F8_E4M3, Q5_1, Q8_0, Q4_0, BF16 }; struct PleFormatInfo { PleFormat id; @@ -130,6 +131,12 @@ void iq4nl_dequant_row(const uint8_t* row, float* out160); /// `weight_scale`), kept byte for byte by tools/ple_fp8_pack.py; IQ4_NL is 8% off it per row. void fp8_e4m3_dequant_row(const uint8_t* row, float scale, float* out160); +/// One BF16 row -> 160 floats, EXACTLY: bfloat16 is the top half of a float32, so this is a shift and a copy with no +/// rounding anywhere. It is the other published form of this same table - the full checkpoint stores +/// `...ngram_embedding.shard_k` as BF16 (2 B a value, 102.4 GB), the source of record rather than a re-quantization. +/// There is no scale, because BF16 values are the values. +void bf16_dequant_row(const uint8_t* row, float* out160); + /// How the table's rows are read (plan v0.3 P2). `Direct` is the default: unbuffered 4 KiB reads from the SSD, /// so the table never occupies RAM or the OS file cache. `Mmap` is the earlier memory-mapped path, kept as the /// A/B arm; it returns the same bytes. @@ -142,7 +149,8 @@ enum class PleIo { Direct, Mmap }; struct PleIoOptions { PleIo mode = PleIo::Direct; uint32_t max_inflight = 256; ///< outstanding SSD reads (decode needs 16; a prompt chunk saturates the SSD at 256) - uint64_t cache_rows = 1u << 20; ///< bounded row cache: 1,048,576 rows x 90 B ~ 95 MB; 0 disables + uint64_t cache_rows = 1u << 20; ///< bounded row cache, in ROWS: 1,048,576 x 90 B ~ 95 MB (IQ4_NL), ~160 MB (FP8), + ///< ~335 MB (BF16); 0 disables bool io_thread = true; ///< reads submitted by a worker thread, not the caller /// Mmap mode only (`--ple-io ram`): lock the whole mapped table in RAM at open, so no SSD read ever sits on /// the prompt or token path. Needs RAM for the full table. POSIX only (mlock); `locked()` reports the outcome. diff --git a/src/kernels/ngram.cpp b/src/kernels/ngram.cpp index 259bfe88da..406213c30f 100644 --- a/src/kernels/ngram.cpp +++ b/src/kernels/ngram.cpp @@ -138,6 +138,19 @@ void fp8_e4m3_dequant_row(const uint8_t* row, float scale, float* out160) { for (int j = 0; j < PLE_HEAD_DIM; ++j) out160[j] = kFp8.v[row[j]] * scale; } +void bf16_dequant_row(const uint8_t* row, float* out160) { + // bfloat16 IS the top 16 bits of a float32, so widening is exact for every value, normal or not - no rounding, + // no clamp, no scale. Bytes are assembled little-endian explicitly rather than reinterpreted, so this is the + // same on a big-endian host. + for (int j = 0; j < PLE_HEAD_DIM; ++j) { + const uint32_t bits = (uint32_t) row[2 * j] | ((uint32_t) row[2 * j + 1] << 8); + const uint32_t wide = bits << 16; + float v; + std::memcpy(&v, &wide, sizeof v); + out160[j] = v; + } +} + // --------------------------------------------------------------------------------------------------- // THE FORMAT TABLE (see PleFormatInfo). One entry per table type; the block formats decode 5 blocks of 32. namespace { @@ -147,6 +160,7 @@ void dequant_blocks(const uint8_t* row, float /*scale*/, float* out160) { } void dequant_iq4_nl(const uint8_t* row, float, float* out160) { iq4nl_dequant_row(row, out160); } void dequant_fp8(const uint8_t* row, float scale, float* out160) { fp8_e4m3_dequant_row(row, scale, out160); } +void dequant_bf16(const uint8_t* row, float, float* out160) { bf16_dequant_row(row, out160); } const PleFormatInfo kPleFormats[] = { {PleFormat::IQ4_NL, "IQ4_NL", "IQ4_NL", PLE_ROW_BYTES, false, dequant_iq4_nl}, @@ -157,6 +171,9 @@ const PleFormatInfo kPleFormats[] = { {PleFormat::Q8_0, "Q8_0", "Q8_0", PLE_ROW_BYTES_Q8_0, false, dequant_blocks}, // Q4_0 (plain llama-quantize Q4_0 files, #599): 90-byte rows like IQ4_NL (18-byte blocks), a linear 4-bit grid {PleFormat::Q4_0, "Q4_0", "Q4_0", PLE_ROW_BYTES, false, dequant_blocks}, + // BF16 (#586): the checkpoint's own table at full precision, 320-byte rows; self-describing, so no scale and no + // metadata to trust (tools/ple_fp8_pack.py writes the FP8 form of the same table) + {PleFormat::BF16, "BF16", "BF16", PLE_ROW_BYTES_BF16, false, dequant_bf16}, }; constexpr int kPleFormatCount = (int) (sizeof kPleFormats / sizeof kPleFormats[0]); } // namespace diff --git a/src/ngram/ple_reader_test.cpp b/src/ngram/ple_reader_test.cpp index e9086d5143..9208470837 100644 --- a/src/ngram/ple_reader_test.cpp +++ b/src/ngram/ple_reader_test.cpp @@ -75,6 +75,30 @@ bool check_rows(ng::PleReader& rd, const std::vector& rows, uint32_t n return true; } +/// THE BF16 TABLE, and the claim it rests on. A bfloat16 is literally the top half of a float32, so widening +/// one is a shift: exact for every value, normal or not, with no rounding to hide behind. These patterns are +/// the ones a lossy path would break on - the subnormals and the NaN/inf encodings a saturating cast to FP8 +/// would collapse - so a table that came back through the FP8 route would not reproduce all of them. +void bf16_widening_is_exact() { + const uint16_t bits[] = {0x0000, 0x8000, 0x3f80, 0xbf80, 0x7f7f, 0xff7f, // 0, -0, 1, -1, max, -max + 0x0001, 0x8001, 0x007f, 0x7f80, 0xff80, // smallest subnormals, +-inf + 0x7fc0, 0x7f81, 0x4049, 0xc249, 0x3c75}; // NaN, signalling NaN, 3.14, -3.14 + for (uint16_t b : bits) { + uint8_t row[2 * k::PLE_HEAD_DIM]; + std::memset(row, 0, sizeof row); + row[0] = (uint8_t) b; // little-endian: the low byte first + row[1] = (uint8_t) (b >> 8); + float out[k::PLE_HEAD_DIM]; + k::bf16_dequant_row(row, out); + uint32_t want = (uint32_t) b << 16, got; + std::memcpy(&got, &out[0], sizeof got); + CHECK(got == want, "bf16 0x%04x widened to 0x%08x, not 0x%08x", b, got, want); + bool tail_zero = true; // one element under test must not have shifted the rest + for (int j = 1; j < k::PLE_HEAD_DIM; ++j) tail_zero = tail_zero && out[j] == 0.0f; + CHECK(tail_zero, "bf16 0x%04x: the rest of the row is not zero", b); + } +} + /// EVERY FORMAT OF THE TABLE, END TO END (table-driven: one entry in `k::ple_formats()` is one run here). A minimal /// PLE-only GGUF holds `rows` rows of that format's row size, each filled with bytes that encode the row, and both I/O /// modes must return exactly what the format's own dequantizer makes of those bytes - so the row width, the offset @@ -198,6 +222,7 @@ void bad_sizes_are_refused(const std::string& dir) { } void all_formats_round_trip(const std::string& dir) { + bf16_widening_is_exact(); // BF16's own claim: a shift, exact for every pattern bad_sizes_are_refused(dir); CHECK(k::ple_format_count() > 0, "no formats"); for (int i = 0; i < k::ple_format_count(); ++i) { From 9661ecb8822e1ee71ba9c6aeda1daa2fe65eaead Mon Sep 17 00:00:00 2001 From: sarashin Date: Sun, 4 Oct 2026 23:37:13 +0900 Subject: [PATCH 07/48] sycl: follow #626 (ThreadAffinity) and #559 (NativeDense::load layer range) so v0.1.39 compiles The sycl port went in as 5ffcce4 ("sycl: port 0.1.39"). Two engine-side changes were merged into the release branch after it (4f5e6c8, f5410ae) and nothing in sycl/ was updated for them, so the v0.1.39 tag does not compile: - #626 (5a8b292) made the thread affinity a value: pin_current_thread() returns strata::kernels::cpu::ThreadAffinity and restore_thread_affinity() takes it. sycl/include/strata/core/session.hpp still stored a `long long` (no conversion exists, and it did not include the header that names the type); sycl/src/core/session.cpp still assigned the returned struct to it and passed the `long long` back. - #559 (9461f5e) added the two layer-range arguments to NativeDense::load. The sycl out-of-line definition was still the 4-argument one and no longer matched the declaration in include/strata/core/native_dense.hpp. Both are fixed by mirroring the CUDA sources: the same member type, the same `outside()` predicate, and the same place it is applied in the tensor loop. `pinned` now follows CUDA as well: it is pinned_core.valid, so a pin that failed is not "restored". Nothing changes when the pin succeeds. No caller passes layer_lo/layer_hi yet, so `outside()` is never true today: this restores the build and does not change what the engine computes. Measured here: Arch Linux, Intel oneAPI DPC++ 2026.0.0 + oneMKL 2026.0, SPIR-V (JIT), cmake -S sycl -B build-sycl -G Ninja -DCMAKE_C_COMPILER=icx -DCMAKE_CXX_COMPILER=icpx, then `cmake --build build-sycl --target strata -- -k 0` -> 0 errors, links. The two errors are a type and a declaration mismatch, so the compiler version does not matter. Not built here: the other targets (kernel parity tests, benches) and the AOT path. Not run on an Arc in this change. --- sycl/include/strata/core/session.hpp | 3 ++- sycl/src/core/native_dense.cpp | 9 +++++++-- sycl/src/core/session.cpp | 4 ++-- 3 files changed, 11 insertions(+), 5 deletions(-) diff --git a/sycl/include/strata/core/session.hpp b/sycl/include/strata/core/session.hpp index af9cbfc777..3bb6e9d41a 100644 --- a/sycl/include/strata/core/session.hpp +++ b/sycl/include/strata/core/session.hpp @@ -18,6 +18,7 @@ #include #include "strata/core/hit_hook.hpp" #include "strata/core/layer.hpp" +#include "strata/kernels/cpu/pool.hpp" #include #include @@ -375,7 +376,7 @@ struct SessionLoopScratch { float* y_miss = nullptr; ///< pinned host staging for the pool's answer, `parts_bytes` long size_t parts_bytes = 0; dpct::event_ptr probe = nullptr; - long long pinned_core = -1; ///< the affinity to restore, or -1 if the host was never pinned + strata::kernels::cpu::ThreadAffinity pinned_core{}; ///< affinity to restore, or invalid if the host was not pinned bool pinned = false; /// Allocates the buffers and pins the host thread. Call ONCE, at session setup. diff --git a/sycl/src/core/native_dense.cpp b/sycl/src/core/native_dense.cpp index 4007db4b86..af95caaff5 100644 --- a/sycl/src/core/native_dense.cpp +++ b/sycl/src/core/native_dense.cpp @@ -86,7 +86,12 @@ NativeDense::~NativeDense() { bool NativeDense::load(const std::vector &shards, WeightTable &table, std::string &err, - bool include_ple_key) try { + bool include_ple_key, int64_t layer_lo, int64_t layer_hi) try { + auto outside = [&](const std::string &name) { // a blk.. tensor of another stage's layers + if (layer_hi < 0 || name.rfind("blk.", 0) != 0) return false; + const long l = std::strtol(name.c_str() + 4, nullptr, 10); + return l < layer_lo || l >= layer_hi; + }; if (scratch_ || !weights_.empty()) { err = "native dense: already loaded"; return false; } if (shards.empty()) { err = "native dense: at least one GGUF shard is required"; return false; } try { @@ -155,7 +160,7 @@ bool NativeDense::load(const std::vector &shards, } } for (const auto& tensor : gguf.tensors()) { - if (!eligible(tensor, include_ple_key)) continue; + if (!eligible(tensor, include_ple_key) || outside(tensor.name)) continue; if (!in_range(tensor.name) && tensor.name.find("ple") == std::string::npos) continue; if (!seen.insert(tensor.name).second) { err = "native dense: duplicate tensor " + tensor.name; return false; diff --git a/sycl/src/core/session.cpp b/sycl/src/core/session.cpp index 2c75bde594..3085404938 100644 --- a/sycl/src/core/session.cpp +++ b/sycl/src/core/session.cpp @@ -784,7 +784,7 @@ bool SessionLoopScratch::init(size_t parts_bytes_in, std::string &err) try { const std::vector cores = strata::kernels::cpu::physical_cores(false); if (!cores.empty()) { pinned_core = strata::kernels::cpu::pin_current_thread(cores[0]); - pinned = true; + pinned = pinned_core.valid; } return true; } @@ -800,7 +800,7 @@ void SessionLoopScratch::free() { if (pinned) { strata::kernels::cpu::restore_thread_affinity(pinned_core); pinned = false; - pinned_core = -1; + pinned_core = {}; } if (probe != nullptr) { dpct::destroy_event(probe); probe = nullptr; } if (y_miss != nullptr) { From a5682fea1667c87b9a6b9ad0b2cd69dd9898fbaf Mon Sep 17 00:00:00 2001 From: LocalXPU <337401568+LocalXPU@users.noreply.github.com> Date: Sun, 4 Oct 2026 19:28:45 -0500 Subject: [PATCH 08/48] sycl: keep cudaStreamQuery's answer in the per-layer ring waits The migration turned `q = cudaStreamQuery(cs)` into `DPCT_CHECK_ERROR(cs->ext_oneapi_empty())`. That macro yields 0 whenever the call does not throw, whatever the queue holds. The guard `q != 1 && *seq < want` (verify.cpp, session.cpp) therefore fired on any ring that took more than 2 ms and reported "never rang (graph finished)" while the graph was still running. With every expert resident the host does not wait per layer (STRATA_VERIFY_NO_HOST), so the path measured on the B70 never reached it. With host-mirrored experts the first layer whose GPU time passes 2 ms does: layer 15 of the Coder on one Arc Pro B60, every time. q is now 0 when the queue is empty and 1 while it is running, as the guard and the trace comment ("1 = still running") expect. fixups.py gets the same rewrite (entry 8), so a fresh dpct run of session.cpp produces it too. Measured on one Arc Pro B60 (4,042 of 12,288 Coder IQ1_M experts mirrored in RAM, 128 greedy tokens, AOT bmg-g21): before, exit 1 at layer 15 in 5 of 5 tries; after, exit 0 in 7 of 7 runs, at 11.2-11.9 tok/s with coherent text. --- sycl/src/core/session.cpp | 5 ++++- sycl/src/core/verify.cpp | 6 ++++-- sycl/tools/fixups.py | 4 ++++ 3 files changed, 12 insertions(+), 3 deletions(-) diff --git a/sycl/src/core/session.cpp b/sycl/src/core/session.cpp index 3085404938..e3bc116761 100644 --- a/sycl/src/core/session.cpp +++ b/sycl/src/core/session.cpp @@ -1367,7 +1367,10 @@ bool session_run_token(const ModelGeometry &g, int64_t pos, int32_t pos_base, // A slow ring: flush the submission queue once more, and notice a fault or a finished graph. last_flush = now; ++tg.flushes; - const dpct::err0 q = DPCT_CHECK_ERROR((cs->ext_oneapi_empty())); + // SYCL port fix: cudaStreamQuery's answer (0 finished, 1 still running) was lost in the migration + // (DPCT_CHECK_ERROR of ext_oneapi_empty() is always 0), so ANY wait over 2 ms was reported as + // "graph finished". Layers whose GPU time exceeds 2 ms (host-mirrored experts read over PCIe) failed that way. + const dpct::err0 q = cs->ext_oneapi_empty() ? 0 : 1; if (q != 1 && *seq < want) { err = "session_run_token: layer " + std::to_string(l) + " never rang (" + diff --git a/sycl/src/core/verify.cpp b/sycl/src/core/verify.cpp index 038f4d43a0..27aa6fb40b 100644 --- a/sycl/src/core/verify.cpp +++ b/sycl/src/core/verify.cpp @@ -1376,8 +1376,10 @@ bool Verifier::run(int T, const int32_t *tokens, int64_t pos0, PoolMultiFn pool, const auto now = Clock::now(); if (now - last_flush > std::chrono::microseconds(2000)) { last_flush = now; - const dpct::err0 q = - DPCT_CHECK_ERROR(((cs_)->ext_oneapi_empty())); + // SYCL port fix: cudaStreamQuery's answer (0 finished, 1 still running) was lost in the migration + // (DPCT_CHECK_ERROR of ext_oneapi_empty() is always 0), so ANY wait over 2 ms was reported as + // "graph finished". Layers whose GPU time exceeds 2 ms (host-mirrored experts read over PCIe) failed that way. + const dpct::err0 q = cs_->ext_oneapi_empty() ? 0 : 1; if (q != 1 && *seq < want) { trace_ev("NEVER-RANG", k, l, (int64_t) q); trace_dump(stderr); diff --git a/sycl/tools/fixups.py b/sycl/tools/fixups.py index b07d6a0e86..26d942c907 100644 --- a/sycl/tools/fixups.py +++ b/sycl/tools/fixups.py @@ -53,6 +53,10 @@ for rel in all_sources(): edit(rel, sub(r"__nanosleep\(\d+\);", "/* spin (no __nanosleep on SYCL) */;")) # 7. `__fadd_rn(a, b ? c : d)` lost its parentheses. edit(rel, sub(r"= (\w+) \+ (\w+) \? (\w+\[\w+\]) : 0\.0f;", r"= \1 + (\2 ? \3 : 0.0f);")) + # 8. cudaStreamQuery(s): dpct writes `DPCT_CHECK_ERROR(s->ext_oneapi_empty())`, which is 0 whenever the call does not + # throw, so the ring waits' `q != 1` guard (1 = still running) was always true and any wait over 2 ms "never rang". + edit(rel, sub(r"(const dpct::err0 q =)\s*DPCT_CHECK_ERROR\(\(+(\w+)\)*->ext_oneapi_empty\(\)\)+;", + r"\1 \2->ext_oneapi_empty() ? 0 : 1;")) # 2b. every `(dpct::queue_ptr) stream` cast goes through strata::q_of(), which maps CUDA's null stream to the # default in-order queue instead of dereferencing a null sycl::queue* (include/strata/sycl_queue.hpp). From 7cd96e3eefd4f6ec2dcbaa2722459820d2948b0b Mon Sep 17 00:00:00 2001 From: LocalXPU <337401568+LocalXPU@users.noreply.github.com> Date: Sun, 4 Oct 2026 19:30:38 -0500 Subject: [PATCH 09/48] docs, setup: Arc Pro B60 rows, B60 notes, PCI id e211 INTEL_ARC.md: "What has been run" rows for 2x and 1x Arc Pro B60, plus notes for the card: PCI id 8086:e211 (bmg-g21), setvars.sh stopping at OCL_ICD_FILENAMES under `set -u`, running natively without Docker, and the layer-split startup warning that counts the other card's layers. sycl/setup_intel.py: the B60 table entry was e221, which the kernel's xe id list files under the BMG-G31 cards (0xE220-0xE223). Both Arc Pro B60 cards measured here are 8086:e211, so setup named them "Intel GPU e211 (xe)" with a guessed VRAM size. e211 is added; e221 stays, since there is no card here to say it is wrong. tools/test_setup_sycl.py checks the table. COMMUNITY_BENCHMARKS.md and bench/results/2026-10-04-community-2x-arc-pro-b60/: the report, in the template's format, with the server configs, engine logs and per-request timings. --- .../README.md | 70 +++++++++++++++++++ .../data/B2.run.txt | 54 ++++++++++++++ .../data/bench.py | 41 +++++++++++ .../data/c2-fib1.json | 1 + .../data/c2-long.txt | 8 +++ .../data/c2-long2.txt | 26 +++++++ .../data/c2-short.txt | 35 ++++++++++ .../data/coder2.engine.txt | 66 +++++++++++++++++ .../data/coder2.json | 47 +++++++++++++ .../data/i2-long.txt | 8 +++ .../data/i2-long2.txt | 23 ++++++ .../data/i2-short.txt | 27 +++++++ .../data/iq2b.engine.txt | 69 ++++++++++++++++++ .../data/iq2b.json | 47 +++++++++++++ docs/COMMUNITY_BENCHMARKS.md | 3 + docs/INTEL_ARC.md | 16 +++++ sycl/setup_intel.py | 3 +- tools/test_setup_sycl.py | 21 ++++++ 18 files changed, 564 insertions(+), 1 deletion(-) create mode 100644 bench/results/2026-10-04-community-2x-arc-pro-b60/README.md create mode 100644 bench/results/2026-10-04-community-2x-arc-pro-b60/data/B2.run.txt create mode 100644 bench/results/2026-10-04-community-2x-arc-pro-b60/data/bench.py create mode 100644 bench/results/2026-10-04-community-2x-arc-pro-b60/data/c2-fib1.json create mode 100644 bench/results/2026-10-04-community-2x-arc-pro-b60/data/c2-long.txt create mode 100644 bench/results/2026-10-04-community-2x-arc-pro-b60/data/c2-long2.txt create mode 100644 bench/results/2026-10-04-community-2x-arc-pro-b60/data/c2-short.txt create mode 100644 bench/results/2026-10-04-community-2x-arc-pro-b60/data/coder2.engine.txt create mode 100644 bench/results/2026-10-04-community-2x-arc-pro-b60/data/coder2.json create mode 100644 bench/results/2026-10-04-community-2x-arc-pro-b60/data/i2-long.txt create mode 100644 bench/results/2026-10-04-community-2x-arc-pro-b60/data/i2-long2.txt create mode 100644 bench/results/2026-10-04-community-2x-arc-pro-b60/data/i2-short.txt create mode 100644 bench/results/2026-10-04-community-2x-arc-pro-b60/data/iq2b.engine.txt create mode 100644 bench/results/2026-10-04-community-2x-arc-pro-b60/data/iq2b.json diff --git a/bench/results/2026-10-04-community-2x-arc-pro-b60/README.md b/bench/results/2026-10-04-community-2x-arc-pro-b60/README.md new file mode 100644 index 0000000000..1c57d1cd00 --- /dev/null +++ b/bench/results/2026-10-04-community-2x-arc-pro-b60/README.md @@ -0,0 +1,70 @@ +# Community benchmark on 2x Intel Arc Pro B60 + +Measured on 2026-10-04 by LocalXPU. This is the SYCL port (`sycl/`) on two Arc Pro B60 cards, one request at a time, at an 8,192-token context. It is a short test: two prompt sizes, 2 to 3 requests each. It is not a 4K/32K/128K sweep. + +## Hardware and software + +- 2x Intel Arc Pro B60 24 GB (`8086:e211`, 456 GB/s each), PCIe 3.0 x8 per card; Ryzen 5 5600; 62 GB DDR4; storage type not recorded +- Ubuntu 24.04, kernel 6.17 (`xe` driver), Level Zero V2, compute runtime NEO 26.09.37435.12, oneAPI DPC++ 2026.1.1, oneMKL 2026.1.0 +- Strata `6f32ec0` plus two `sycl/` fixes (the build fix for #559/#626 and the `cudaStreamQuery` fix in the ring wait); engine reports `0.1.39-sycl`; AOT `-DSTRATA_SYCL_AOT=bmg-g21`; source build, no Docker +- Nothing else ran on the GPUs. The kernel log was watched for `xe` resets during every run: none. + +## Model and configuration + +- Coder IQ1_M (`Qwen3.8-Flash-Next-GSQ-RCO-IQ1_M`, shard hashes checked against the Hugging Face LFS ids), `--layer-split 24` +- Flash-Next IQ2_XS (`Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS`), `--layer-split 25` +- Packs from `tools/iq_pack.py`, MTP layer from `tools/mtp_fetch.py` / `mtp_pack.py` / `mtp_rt.py`, profiles from `data/` +- Context 8,192; KV int8; `--spec 4 --spec-min-p 0.5`; greedy (`temperature 0`), `enable_thinking: false`; no vision + +`data/coder2.json` and `data/iq2b.json` are the exact server configs (engine arguments and environment); the engine's startup and stage lines are in `data/coder2.engine.txt`, `data/iq2b.engine.txt` and, for the one-card run, `data/B2.run.txt`. Served with +`sycl/serve/server_intel.py --engine strata --config --port 8085`. + +## Method + +Requests went through `/v1/chat/completions`, one at a time. Prompt and decode speed are the server's own `timings` object +(`prompt_per_second`, `predicted_per_second`), per request; `bench.py` prints them (copy in `data/`, raw output in `data/c2-*.txt`, `data/i2-*.txt`). +Model loading is not included. Three prompts: + +- short: "Write a Python function that returns the n-th Fibonacci number" (23 prompt tokens cold, 7 fresh after the cached prefix) +- 2K code: about 2,000 tokens of the repository's `tools/*.py` plus "write a binary search tree class" (1,922 prompt tokens, none reused); the second turn reuses the first +- 2K prose: about 2,100 tokens of source plus "say what this code is for" (2,129 prompt tokens, none reused); the repeat reuses 2,122 of them + +## Results + +All experts were resident in VRAM on both cards in both runs (engine line `layer split: 100% of the experts resident`), so `STRATA_VERIFY_NO_HOST=1` was set. + +| Configuration | Prompt tokens (fresh) | Reused | Generated | Requests | Prompt tok/s | Decode tok/s | Drafts accepted | +| --- | ---: | ---: | ---: | ---: | --- | --- | --- | +| Coder IQ1_M, short | 23 / 7 | 0 / 16 | 159 | 3 | 50.4 cold, 74-80 | 52.8 first, 56.6 and 56.6 | 112/138, 114/133 | +| Coder IQ1_M, 2K code | 1,922 | 0 | 256 | 1 | 425.3 | 57.2 | 186/208 | +| Coder IQ1_M, 2K code, next turn | 21 | 2,178 | 256 | 1 | 61.4 | 71.4 | 209/212 | +| Coder IQ1_M, 2K prose | 2,129 | 0 | 128 | 1 | 427.9 | 40.1 | 70/98 | +| Coder IQ1_M, 2K prose, repeat | 7 | 2,122 | 128 | 1 | 78.1 | 41.3 | 70/98 | +| IQ2_XS, short | 23 / 7 | 0 / 16 | 112 | 2 | 50.4 cold, 81.7 | 58.6 and 61.3 | 84/88, 84/89 | +| IQ2_XS, 2K code | 1,922 | 0 | 256 | 1 | 445.1 | 55.5 | 183/213 | +| IQ2_XS, 2K code, next turn | 284 | 1,915 | 256 | 1 | 177.0 | 72.5 | 211/217 | +| IQ2_XS, 2K prose | 2,129 | 0 | 104 | 1 | 436.4 | 38.8 | 56/87 | +| IQ2_XS, 2K prose, repeat | 7 | 2,122 | 104 | 1 | 79.3 | 40.0 | 56/87 | + +The two prose rows are slower because fewer drafts were accepted (71% and 64%), not because of the context: the 256-token code reply at the same context ran 57.2 and 55.5. +Time to first token was not measured separately. + +One card, Coder IQ1_M, 4,042 of 12,288 experts mirrored in pinned RAM (`STRATA_MIRROR_MIB=8192`, `ONEAPI_DEVICE_SELECTOR=level_zero:0`), +by-hand `--tokens` run, 11-token prompt, 128 greedy tokens: **11.9 tok/s** (11.2 to 11.9 over five builds that differ only in experiments), coherent Python. +Without the ring-wait fix this configuration stopped at layer 15 with `never rang (graph finished)` in 5 of 5 tries. +The engine's stage table shows `wait for rings` at 186.8 ms per round, about 3.9 ms per layer. It drops to 72.9 ms and 25.1 tok/s with `kSpinMax` 2,000 in +`sycl/include/strata/sycl_doorbell.hpp`, which suggests the GPU does not see the host's flag stores during the spin kernel and waits out the bound. That change +risks proceeding before a slow host answers, so it is not part of this report. + +Memory after load (`xpu-smi`, MiB, card 0 / card 1): Coder 14,592 / 17,456; IQ2_XS 20,246 / 20,573. The tightest card kept 3.7 GB free of the 24 GB with `--vram-reserve-mib 1536`. + +## Correctness and limitations + +- Both models, `/v1/chat/completions`: a Fibonacci function executed against the first ten values and `fn(50) == 12586269025`; a Euclid `gcd` executed on four pairs; a palindrome check (IQ2_XS); `sum(i*i for i in range(1,11))` answered `385`. All passed. +- A three-turn conversation (a name and a number, then arithmetic on it, then a lambda using both) was answered correctly by both models, and the conversation cache reused 41 and 74 tokens. +- No NaN, garbage or repetition loop in any output. +- Not done: the 19-token chat-templated prompt from the docs (no token-for-token comparison with the reference text), streaming, the Anthropic route, tool calls, contexts above 2.2K, `--layer-split auto`, a run with `STRATA_VERIFY_NO_HOST=1` and experts outside VRAM. +- Kernel tests (`ctest`, one B60): 21 of 25 pass; `iq_parity` passes for all 10 formats once its fixtures exist; `ple_parity` needs the Q2_0 shard; `s2_expert_grouped_parity` fails 4 bitwise comparisons while its host-reference check is within tolerance; `conversation_snapshot_test` aborts with `munmap_chunk(): invalid pointer`. +- One `xe` GT reset on card 0, during the first `iq_parity` run (it did not finish in 300 s and was killed by a timeout; the same binary then passed in under 90 s). The card recovered without a reboot. + +Paths in `data/` were shortened: `` is the directory with the models, packs and MTP layer, `` the Strata source tree. diff --git a/bench/results/2026-10-04-community-2x-arc-pro-b60/data/B2.run.txt b/bench/results/2026-10-04-community-2x-arc-pro-b60/data/B2.run.txt new file mode 100644 index 0000000000..aa646dd248 --- /dev/null +++ b/bench/results/2026-10-04-community-2x-arc-pro-b60/data/B2.run.txt @@ -0,0 +1,54 @@ +IDS=7734,264,12654,709,421,4523,279,307,7324,76938,1324 +strata generate: PCIe probe: 7.0 GB/s host->device (best of 7.0 7.0 7.0 7.0) -> pcie_frac 0.19 (default 0.55) +strata generate: this CPU has no AVX-512: the expert kernels run on AVX-2 (multi-token for the i-quant gate/up rows) +strata generate: native pack: /packs/coder-iq1_m experts (largest blob 2.66 MB), token embedding IQ4_XS in mapped host memory (322 MiB) +strata generate: 1406 MiB of weights loaded from /packs/coder-iq1_m (302 canonical tensors skipped: served natively) +strata generate: 300 native projection matrices, 2018.88 MiB of weights +strata generate: the SSD is kept awake while rows are read: one page of the table after 100 ms without a read, until 60 s after the last request (STRATA_SSD_KEEPALIVE=0 turns it off) +strata generate: profile data/expert-profile-coder.bin: 12288 ranked pairs, built for 12288 slots +strata generate: PLE on, table 320001536 rows of /models/coder-iq1_m/Qwen3.8-Flash-Next-GSQ-RCO-IQ1_M-00002-of-00002.gguf +strata mtp: draft layer loaded, 802 MiB of VRAM (experts 675, dense 111), files read in 0.45 s (1746 MiB/s) +strata generate: experimental native Q5_K head, 521472000 bytes +strata generate: GPU 0: Intel(R) Arc(TM) Pro B60 Graphics, compute capability 20.1 +strata generate: WARNING: this engine was compiled with CUDA 12.8 headers but loaded a CUDA 0.2 runtime (libcudart): GPU properties can read wrong and some kernels go unused. Rebuild it against one toolkit (cmake -DCUDAToolkit_ROOT=, with its libcudart.so present) (#542) +strata generate: experts streamed from the GGUF on demand (--stream-experts): no host arena; every expert must fit the VRAM cache +strata generate: expert cache auto: 18.90 GiB free, 1536 MiB reserved (+218 MiB for the draft head) -> 6331 slots +strata generate: expert cache 8246 slots, 15.70 GiB of VRAM; policy is +strata generate: the GPU computes the experts in the cache; it rounds differently from the CPU, + so a reply can differ slightly from a run without the cache (same quality: + bench/results/2026-09-27-cache-parity). + PROFILE, ranked by routing frequency, no eviction. +strata generate: profile fill: 15.70 GiB in 2.5 s (6.79 GB/s, pipelined) +strata generate: pre-filled 8246 of 8246 slots from the profile; slot 0 verified +strata generate: 4042 of 4042 experts missing from VRAM mirrored in pinned host memory (7.72 GiB, 1.3 s); the GPU reads them over PCIe +strata generate: R4 hit path ON - resident experts are computed on the GPU +strata generate: 5 expert-pool workers + the host thread +strata generate: session is up (engine 0.1.39-sycl) +strata generate: sampling greedy +strata generate: token graph hit path: 8246 resident experts, decided on the device +strata generate: prompt path allocates its own buffers (no cache slots to borrow) +strata mtp: draft head over 106299 tokens (212.9 MiB) +strata generate: prefill 10 tokens in 1 chunks, 563.9 ms (17.7 tok/s); experts streamed 354 (354 by DMA, host 5.2 ms), resident 1689; PLE 2.7 ms +strata verify: window up to 6 tokens, 74.0 MiB of device buffers +strata verify: captured the 1-token window (upload , sync ) +strata verify: captured the 2-token window (upload , sync ) +strata verify: captured the 3-token window (upload , sync ) +strata verify: captured the 4-token window (upload , sync ) +strata verify: captured the 5-token window (upload , sync ) +strata verify: captured the 6-token window (upload , sync ) +strata generate: window and draft graphs captured in 125 ms +speculation 50 rounds of 6, drafts accepted 81 of 98 (0.827), 2.62 tokens per round +window sizes T1:11 T2:8 T3:3 T4:28 T5:0 T6:0 (min draft probability 0.50) +suffix drafts 3 windows, drafts accepted 8 of 9 +accepted per round 0:14 1:10 2:7 3:19 4:0 5:0 +verify window wait for rings 186.845 pool 10.966 host 1.142 commit 9.963 ms/round; CPU experts 2.50 distinct / 3.33 routed per layer +pool multi gate/up 6.183 quantize 0.025 down 2.868 ms/round; 27.1 GB/s over the rows phases; CPU pool call 10.958 ms/round +dispatch plan 0.100 activation quantize 0.254 jobs 1.514 run 9.080 ms/round +adaptive tier 1069 experts swapped into the VRAM tier (every 4 rounds, 0.839 ms/round) +pcie experts 0.21 distinct experts per layer read over PCIe (share 49/256 of the misses) +mtp 10.095 ms/round drafting (49 rounds), MTP prompt 6.8 ms, 1015 MiB of VRAM +prompt : 7734 264 12654 709 421 4523 279 307 7324 76938 1324 +output : 1608 48575 13 271 727 15336 1393 1590 198 262 413 307 2564 220 16 25 198 285 460 307 198 262 460 15336 1393 12 16 8 478 15336 1393 12 17 8 271 760 709 3294 369 264 4145 29812 7873 314 279 76938 8240 13 4213 11 424 369 524 10727 364 3349 2663 314 307 1521 424 95272 3205 942 279 1788 2663 5081 2942 13 1946 7042 14588 11 567 628 958 20781 1954 310 3436 8334 16100 2663 13 248046 198 248045 846 198 7734 264 12654 709 421 4523 279 307 7324 76938 1324 1608 48575 248046 198 248045 74455 198 248068 198 760 1156 6587 264 12654 709 421 4523 279 307 7324 76938 1324 1608 48575 13 1061 369 +decode 128 tokens in 10735.2 ms -> 11.92 tok/s +prefill 10 tokens in 563.9 ms -> 17.73 tok/s (time to first token 809.0 ms) +EXIT=0 diff --git a/bench/results/2026-10-04-community-2x-arc-pro-b60/data/bench.py b/bench/results/2026-10-04-community-2x-arc-pro-b60/data/bench.py new file mode 100644 index 0000000000..41b46ad7d5 --- /dev/null +++ b/bench/results/2026-10-04-community-2x-arc-pro-b60/data/bench.py @@ -0,0 +1,41 @@ +import json,sys,re,urllib.request,time,glob +URL="http://127.0.0.1:8085/v1/chat/completions" +def ask(msgs,max_tokens=256): + body={"messages":msgs,"max_tokens":max_tokens,"temperature":0,"chat_template_kwargs":{"enable_thinking":False}} + t=time.time() + r=urllib.request.urlopen(urllib.request.Request(URL,json.dumps(body).encode(),{"content-type":"application/json"}),timeout=900) + d=json.load(r); d["wall"]=time.time()-t + return d +def show(tag,d): + tm=d["timings"];u=d["usage"] + print(f"[{tag}] prompt_n={tm['prompt_n']} cache_n={tm['cache_n']} prompt {tm['prompt_per_second']:.1f} tok/s | decode {tm['predicted_n']} tok {tm['predicted_per_second']:.1f} tok/s | drafts {tm.get('draft_n_accepted')}/{tm.get('draft_n')} | wall {d['wall']:.1f}s | finish {d['choices'][0]['finish_reason']}") +def code(text): + m=re.search(r"```python\n(.*?)```",text,re.S); return m.group(1) if m else text +def run_tests(src,tests): + g={} + try: + exec(src,g); exec(tests,g); return "PASS" + except Exception as e: return f"FAIL {e!r}" +mode=sys.argv[1] +if mode=="short": + for i in range(2): + d=ask([{"role":"user","content":"Write a Python function that returns the n-th Fibonacci number"}],256); show(f"fib run{i}",d) + print(d["choices"][0]["message"]["content"]) + print("fib tests:",run_tests(code(d["choices"][0]["message"]["content"]),"fn=[v for k,v in list(globals().items()) if callable(v) and not k.startswith('_') and k!='exec'][-1]\nassert [fn(i) for i in range(10)]==[0,1,1,2,3,5,8,13,21,34]; assert fn(50)==12586269025")) + d=ask([{"role":"user","content":"Write a Python function gcd(a, b) that returns the greatest common divisor using Euclid's algorithm. Only the code."}],200); show("gcd",d) + c=d["choices"][0]["message"]["content"]; print(c) + print("gcd tests:",run_tests(code(c),"assert gcd(48,18)==6; assert gcd(17,5)==1; assert gcd(0,9)==9; assert gcd(270,192)==6")) + d=ask([{"role":"user","content":"What is the output of this Python code? print(sum(i*i for i in range(1,11))) Answer with just the number."}],20); show("known",d); print(d["choices"][0]["message"]["content"], "(expected 385)") +if mode=="long": + src="".join(open(f).read() for f in sorted(glob.glob("/tools/*.py"))[:6])[:int(sys.argv[2])] + msgs=[{"role":"user","content":"Here is some Python source:\n\n"+src+"\n\nIn one paragraph, say what this code is for, then write a short Python function that reverses a string."}] + for i in range(2): + d=ask(msgs,256); show(f"long run{i}",d) + print(d["choices"][0]["message"]["content"][:1200]) +if mode=="long2": + fs=sorted(glob.glob("/tools/*.py")) + src="".join(open(f).read() for f in fs[6:12])[:7000] + msgs=[{"role":"user","content":"Here is some Python source:\n\n"+src+"\n\nWrite a Python implementation of a binary search tree class with insert, search, delete and in-order traversal methods, with docstrings."}] + d=ask(msgs,256); show("long2 BST",d) + d2=ask(msgs+[{"role":"assistant","content":d["choices"][0]["message"]["content"]},{"role":"user","content":"Now add a height() method."}],256); show("long2 turn2",d2) + print(d["choices"][0]["message"]["content"][:600]) diff --git a/bench/results/2026-10-04-community-2x-arc-pro-b60/data/c2-fib1.json b/bench/results/2026-10-04-community-2x-arc-pro-b60/data/c2-fib1.json new file mode 100644 index 0000000000..8b6e53d22f --- /dev/null +++ b/bench/results/2026-10-04-community-2x-arc-pro-b60/data/c2-fib1.json @@ -0,0 +1 @@ +{"id": "chatcmpl-9a1c5ae9d2084c8f9b34ac8c", "object": "chat.completion", "created": 1791157128, "model": "coder-iq1_m", "choices": [{"index": 0, "message": {"role": "assistant", "content": "```python\ndef fibonacci(n: int) -> int:\n \"\"\"Return the n-th Fibonacci number (0-indexed).\n \n fibonacci(0) = 0\n fibonacci(1) = 1\n fibonacci(2) = 1\n fibonacci(3) = 2\n ...\n \"\"\"\n if n < 0:\n raise ValueError(\"n must be a non-negative integer\")\n if n == 0:\n return 0\n if n == 1:\n return 1\n \n a, b = 0, 1\n for _ in range(2, n + 1):\n a, b = b, a + b\n return b\n```"}, "finish_reason": "stop"}], "usage": {"prompt_tokens": 23, "completion_tokens": 159, "total_tokens": 182, "prompt_tokens_details": {"cached_tokens": 0}}, "timings": {"cache_n": 0, "prompt_n": 23, "prompt_ms": 456.3, "prompt_per_token_ms": 19.839, "prompt_per_second": 50.4, "predicted_n": 159, "predicted_ms": 3009.9, "predicted_per_token_ms": 18.93, "predicted_per_second": 52.8, "draft_n": 138, "draft_n_accepted": 112}} \ No newline at end of file diff --git a/bench/results/2026-10-04-community-2x-arc-pro-b60/data/c2-long.txt b/bench/results/2026-10-04-community-2x-arc-pro-b60/data/c2-long.txt new file mode 100644 index 0000000000..679f45b186 --- /dev/null +++ b/bench/results/2026-10-04-community-2x-arc-pro-b60/data/c2-long.txt @@ -0,0 +1,8 @@ +[long run0] prompt_n=2129 cache_n=0 prompt 427.9 tok/s | decode 128 tok 40.1 tok/s | drafts 70/98 | wall 8.2s | finish stop +[long run1] prompt_n=7 cache_n=2122 prompt 78.1 tok/s | decode 128 tok 41.3 tok/s | drafts 70/98 | wall 3.2s | finish stop +This code is a comprehensive integration test script for a batched inference engine (likely named "Strata") that verifies the correctness of multi-slot decoding, specifically ensuring that tokens generated in parallel slots match those generated in solo mode, even when long prompts are interleaved with other decoding operations or when requests are continued from checkpoints. The script sets up various scenarios involving different prompt lengths, slot assignments, and continuation logic to validate that the engine's internal state management, expert caching, and token generation remain consistent across different execution paths. + +```python +def reverse_string(s: str) -> str: + return s[::-1] +``` diff --git a/bench/results/2026-10-04-community-2x-arc-pro-b60/data/c2-long2.txt b/bench/results/2026-10-04-community-2x-arc-pro-b60/data/c2-long2.txt new file mode 100644 index 0000000000..590511513b --- /dev/null +++ b/bench/results/2026-10-04-community-2x-arc-pro-b60/data/c2-long2.txt @@ -0,0 +1,26 @@ +[long2 BST] prompt_n=1922 cache_n=0 prompt 425.3 tok/s | decode 256 tok 57.2 tok/s | drafts 186/208 | wall 9.0s | finish length +[long2 turn2] prompt_n=21 cache_n=2178 prompt 61.4 tok/s | decode 256 tok 71.4 tok/s | drafts 209/212 | wall 3.9s | finish length +```python +class BinarySearchTree: + """A binary search tree implementation with insert, search, delete, and in-order traversal.""" + + def __init__(self): + """Initialize an empty binary search tree.""" + self.root = None + + def insert(self, value): + """Insert a value into the binary search tree. + + Args: + value: The value to insert into the tree. + + Returns: + None + """ + if self.root is None: + self.root = _Node(value) + return + + current = self.root + while True: + if value < curr diff --git a/bench/results/2026-10-04-community-2x-arc-pro-b60/data/c2-short.txt b/bench/results/2026-10-04-community-2x-arc-pro-b60/data/c2-short.txt new file mode 100644 index 0000000000..4bf19ec8db --- /dev/null +++ b/bench/results/2026-10-04-community-2x-arc-pro-b60/data/c2-short.txt @@ -0,0 +1,35 @@ +[fib run0] prompt_n=7 cache_n=16 prompt 74.3 tok/s | decode 159 tok 56.6 tok/s | drafts 114/133 | wall 2.9s | finish stop +[fib run1] prompt_n=7 cache_n=16 prompt 80.1 tok/s | decode 159 tok 56.6 tok/s | drafts 114/133 | wall 2.9s | finish stop +```python +def fibonacci(n: int) -> int: + """Return the n-th Fibonacci number (0-indexed). + + fibonacci(0) = 0 + fibonacci(1) = 1 + fibonacci(2) = 1 + fibonacci(3) = 2 + ... + """ + if n < 0: + raise ValueError("n must be a non-negative integer") + if n == 0: + return 0 + if n == 1: + return 1 + + a, b = 0, 1 + for _ in range(2, n + 1): + a, b = b, a + b + return b +``` +fib tests: PASS +[gcd] prompt_n=37 cache_n=0 prompt 71.7 tok/s | decode 32 tok 60.8 tok/s | drafts 23/24 | wall 1.0s | finish stop +```python +def gcd(a, b): + while b: + a, b = b, a % b + return a +``` +gcd tests: PASS +[known] prompt_n=42 cache_n=0 prompt 69.5 tok/s | decode 4 tok 25.1 tok/s | drafts 4/6 | wall 0.8s | finish stop +385 (expected 385) diff --git a/bench/results/2026-10-04-community-2x-arc-pro-b60/data/coder2.engine.txt b/bench/results/2026-10-04-community-2x-arc-pro-b60/data/coder2.engine.txt new file mode 100644 index 0000000000..a8651328d7 --- /dev/null +++ b/bench/results/2026-10-04-community-2x-arc-pro-b60/data/coder2.engine.txt @@ -0,0 +1,66 @@ +strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split 24) +strata generate: PCIe probe: 7.0 GB/s host->device (best of 7.0 7.0 7.0 7.0) -> pcie_frac 0.19 (default 0.55) +strata generate: this CPU has no AVX-512: the expert kernels run on AVX-2 (multi-token for the i-quant gate/up rows) +strata generate: native pack: /packs/coder-iq1_m experts (largest blob 2.66 MB), token embedding IQ4_XS in mapped host memory (322 MiB) +strata generate: layer split: CUDA0 loads the dense weights of layers 0-23 only +strata generate: 741 MiB of weights loaded from /packs/coder-iq1_m (686 canonical tensors skipped: served natively) +strata generate: 150 native projection matrices, 988.19 MiB of weights +strata generate: the SSD is kept awake while rows are read: one page of the table after 100 ms without a read, until 60 s after the last request (STRATA_SSD_KEEPALIVE=0 turns it off) +strata generate: layer split: CUDA1 loads the dense weights of layers 24-47 only +strata generate: layer split: CUDA1 PCIe probe 7.0 GB/s (best of 7.0 7.0 7.0 7.0) -> pcie_frac 0.19 +strata generate: layer split: CUDA1 holds its weights; 22.04 GiB free (its session follows the split search) +strata generate: profile data/expert-profile-coder.bin: 12288 ranked pairs, built for 12288 slots +strata generate: PLE on, table 320001536 rows of /models/coder-iq1_m/Qwen3.8-Flash-Next-GSQ-RCO-IQ1_M-00002-of-00002.gguf +strata generate: layer split: CUDA1 holds its weights, session [24, 48) and the head; 21.43 GiB free +strata mtp: draft layer loaded, 802 MiB of VRAM (experts 675, dense 111), files read in 0.44 s (1769 MiB/s) +strata generate: GPU 0: Intel(R) Arc(TM) Pro B60 Graphics, compute capability 20.1 +strata generate: WARNING: this engine was compiled with CUDA 12.8 headers but loaded a CUDA 0.2 runtime (libcudart): GPU properties can read wrong and some kernels go unused. Rebuild it against one toolkit (cmake -DCUDAToolkit_ROOT=, with its libcudart.so present) (#542) +strata generate: experts streamed from the GGUF on demand (--stream-experts): no host arena; every expert must fit the VRAM cache +strata generate: expert cache auto: 21.95 GiB free, 1536 MiB reserved (+0 MiB for the draft head) -> 6144 slots +strata generate: expert cache 6144 slots, 11.07 GiB of VRAM; policy is +strata generate: the GPU computes the experts in the cache; it rounds differently from the CPU, + so a reply can differ slightly from a run without the cache (same quality: + bench/results/2026-09-27-cache-parity). + PROFILE, ranked by routing frequency, no eviction. +strata generate: profile fill: 11.07 GiB in 1.9 s (6.27 GB/s, pipelined) +strata generate: pre-filled 6144 of 6144 slots from the profile; slot 0 verified +strata generate: 3024 of 6144 experts missing from VRAM mirrored in pinned host memory (6.00 GiB, 1.0 s); the GPU reads them over PCIe +strata generate: WARNING: 3120 experts are neither in VRAM nor mirrored; with STRATA_VERIFY_NO_HOST the device plan cannot run them and their layers' windows fall back slowly - raise STRATA_MIRROR_MIB or the free RAM, or lower --max-context +strata generate: layer split, CUDA1: 20.65 GiB free of 23.91, room for experts 17.33 GiB +strata generate: layer split: CUDA1 runs layers 24-47, expert cache 6144 slots (12.35 GiB), 6144 of its 6144 profiled pairs; slot 0 verified +strata generate: layer split: CUDA0 runs layers 0-23 +strata generate: R4 hit path ON - resident experts are computed on the GPU +strata generate: 5 expert-pool workers + the host thread +strata generate: session is up (engine 0.1.39-sycl) +strata generate: token graph hit path: 12288 resident experts, decided on the device +strata serve: layer split: 100% of the experts resident, the prompt path's streamed ring 96 slots +strata serve: the prompt path allocates its own buffers (too few cache slots to borrow) +strata verify: window up to 6 tokens, 74.0 MiB of device buffers +strata serve: layer split: layers 0-23 (CUDA0), 24-47 (CUDA1), one hand-off per window +strata verify: window up to 6 tokens, 74.0 MiB of device buffers +strata mtp: draft head over 106299 tokens (212.9 MiB) +strata serve: 9890 MiB of VRAM free with everything loaded +strata verify: captured the 6-token window (upload , sync ) +strata verify: captured the 6-token window (upload , sync ) +strata verify: captured the 4-token window (upload , sync ) +strata verify: captured the 4-token window (upload , sync ) +strata verify: captured the 1-token window (upload , sync ) +strata verify: captured the 1-token window (upload , sync ) +strata verify: captured the 2-token window (upload , sync ) +strata verify: captured the 2-token window (upload , sync ) +strata serve: prompt 23 tokens = 0 reused + 23 read in 456 ms (50.4 tok/s), 159 generated in 3010 ms (52.8 tok/s), drafts accepted 112 of 138, 1 checkpoints +strata serve: suffix drafts: 1 windows, 1 of 5 drafts accepted +strata serve: prompt 23 tokens = 16 reused + 7 read in 94 ms (74.3 tok/s), 159 generated in 2810 ms (56.6 tok/s), drafts accepted 114 of 133, 1 checkpoints +strata serve: prompt 23 tokens = 16 reused + 7 read in 87 ms (80.1 tok/s), 159 generated in 2808 ms (56.6 tok/s), drafts accepted 114 of 133, 1 checkpoints +strata serve: prompt 37 tokens = 0 reused + 37 read in 516 ms (71.7 tok/s), 32 generated in 526 ms (60.8 tok/s), drafts accepted 23 of 24, 1 checkpoints +strata verify: captured the 5-token window (upload , sync ) +strata verify: captured the 5-token window (upload , sync ) +strata serve: prompt 42 tokens = 0 reused + 42 read in 604 ms (69.5 tok/s), 4 generated in 160 ms (25.1 tok/s), drafts accepted 4 of 6, 1 checkpoints +strata verify: captured the 3-token window (upload , sync ) +strata verify: captured the 3-token window (upload , sync ) +strata serve: prompt 2129 tokens = 0 reused + 2129 read in 4975 ms (427.9 tok/s), 128 generated in 3189 ms (40.1 tok/s), drafts accepted 70 of 98, 1 checkpoints +strata serve: prompt 2129 tokens = 2122 reused + 7 read in 90 ms (78.1 tok/s), 128 generated in 3101 ms (41.3 tok/s), drafts accepted 70 of 98, 1 checkpoints +strata serve: prompt 1922 tokens = 0 reused + 1922 read in 4519 ms (425.3 tok/s), 256 generated in 4475 ms (57.2 tok/s), drafts accepted 186 of 208, 1 checkpoints +strata serve: suffix drafts: 1 windows, 2 of 5 drafts accepted +strata serve: prompt 2199 tokens = 2178 reused + 21 read in 342 ms (61.4 tok/s), 256 generated in 3587 ms (71.4 tok/s), drafts accepted 209 of 212, 2 checkpoints +strata serve: suffix drafts: 37 windows, 185 of 185 drafts accepted diff --git a/bench/results/2026-10-04-community-2x-arc-pro-b60/data/coder2.json b/bench/results/2026-10-04-community-2x-arc-pro-b60/data/coder2.json new file mode 100644 index 0000000000..dec1a68c1e --- /dev/null +++ b/bench/results/2026-10-04-community-2x-arc-pro-b60/data/coder2.json @@ -0,0 +1,47 @@ +{ + "engine": "strata", + "exe": "/strata-native.sh", + "cwd": "", + "tokenizer": "/packs/coder-iq1_m/tokenizer", + "model_name": "coder-iq1_m", + "backend": "sycl", + "log": "/logs/w2/coder2.engine.log", + "args": [ + "--pack", + "/packs/coder-iq1_m", + "--native", + "/models/coder-iq1_m/Qwen3.8-Flash-Next-GSQ-RCO-IQ1_M-00001-of-00002.gguf", + "--ple-gguf", + "/models/coder-iq1_m/Qwen3.8-Flash-Next-GSQ-RCO-IQ1_M-00002-of-00002.gguf", + "--expert-profile", + "data/expert-profile-coder.bin", + "--expert-cache", + "auto", + "--stream-experts", + "--prefill", + "auto", + "--spec", + "4", + "--spec-min-p", + "0.5", + "--mtp", + "/mtp/rt", + "--max-context", + "8192", + "--kv", + "int8", + "--vram-reserve-mib", + "1536", + "--no-prefill-borrow", + "--layer-split", + "24" + ], + "env": { + "ONEAPI_DEVICE_SELECTOR": "level_zero:0,1", + "SYCL_CACHE_PERSISTENT": "0", + "STRATA_MIRROR_MIB": "6144", + "STRATA_VERIFY_DEVICE_PLAN": "1", + "STRATA_STAGE_TRIM": "1", + "STRATA_VERIFY_NO_HOST": "1" + } +} \ No newline at end of file diff --git a/bench/results/2026-10-04-community-2x-arc-pro-b60/data/i2-long.txt b/bench/results/2026-10-04-community-2x-arc-pro-b60/data/i2-long.txt new file mode 100644 index 0000000000..c9aedcee38 --- /dev/null +++ b/bench/results/2026-10-04-community-2x-arc-pro-b60/data/i2-long.txt @@ -0,0 +1,8 @@ +[long run0] prompt_n=2129 cache_n=0 prompt 436.4 tok/s | decode 104 tok 38.8 tok/s | drafts 56/87 | wall 7.6s | finish stop +[long run1] prompt_n=7 cache_n=2122 prompt 79.3 tok/s | decode 104 tok 40.0 tok/s | drafts 56/87 | wall 2.7s | finish stop +This code serves as a comprehensive test harness for a batch inference engine, specifically designed to verify that token generation remains consistent when multiple prompts are processed concurrently in separate slots. It compares the output tokens from parallel execution against those from sequential "solo" runs to ensure that interleaving, checkpointing, and resource sharing (such as expert cache borrowing) do not introduce drift or errors in the model's responses. + +```python +def reverse_string(s: str) -> str: + return s[::-1] +``` diff --git a/bench/results/2026-10-04-community-2x-arc-pro-b60/data/i2-long2.txt b/bench/results/2026-10-04-community-2x-arc-pro-b60/data/i2-long2.txt new file mode 100644 index 0000000000..943b358ef4 --- /dev/null +++ b/bench/results/2026-10-04-community-2x-arc-pro-b60/data/i2-long2.txt @@ -0,0 +1,23 @@ +[long2 BST] prompt_n=1922 cache_n=0 prompt 445.1 tok/s | decode 256 tok 55.5 tok/s | drafts 183/213 | wall 9.0s | finish length +[long2 turn2] prompt_n=284 cache_n=1915 prompt 177.0 tok/s | decode 256 tok 72.5 tok/s | drafts 211/217 | wall 5.1s | finish length +```python +class BinarySearchTree: + """A binary search tree implementation with insert, search, delete, and in-order traversal.""" + + class Node: + """Internal node of the binary search tree.""" + + def __init__(self, value): + """Initialize a node with a value and no children.""" + self.value = value + self.left = None + self.right = None + + def __init__(self): + """Initialize an empty binary search tree.""" + self.root = None + + def insert(self, value): + """Insert a value into the binary search tree. + + Args: diff --git a/bench/results/2026-10-04-community-2x-arc-pro-b60/data/i2-short.txt b/bench/results/2026-10-04-community-2x-arc-pro-b60/data/i2-short.txt new file mode 100644 index 0000000000..e6c92f98d7 --- /dev/null +++ b/bench/results/2026-10-04-community-2x-arc-pro-b60/data/i2-short.txt @@ -0,0 +1,27 @@ +[fib run0] prompt_n=23 cache_n=0 prompt 50.4 tok/s | decode 112 tok 58.6 tok/s | drafts 84/88 | wall 2.4s | finish stop +[fib run1] prompt_n=7 cache_n=16 prompt 81.7 tok/s | decode 112 tok 61.3 tok/s | drafts 84/89 | wall 1.9s | finish stop +```python +def fibonacci(n): + """Return the n-th Fibonacci number (0-indexed).""" + if n < 0: + raise ValueError("n must be a non-negative integer") + if n == 0: + return 0 + if n == 1: + return 1 + a, b = 0, 1 + for _ in range(2, n + 1): + a, b = b, a + b + return b +``` +fib tests: PASS +[gcd] prompt_n=37 cache_n=0 prompt 73.3 tok/s | decode 32 tok 61.8 tok/s | drafts 23/24 | wall 1.0s | finish stop +```python +def gcd(a, b): + while b: + a, b = b, a % b + return a +``` +gcd tests: PASS +[known] prompt_n=42 cache_n=0 prompt 71.1 tok/s | decode 4 tok 25.4 tok/s | drafts 4/6 | wall 0.7s | finish stop +385 (expected 385) diff --git a/bench/results/2026-10-04-community-2x-arc-pro-b60/data/iq2b.engine.txt b/bench/results/2026-10-04-community-2x-arc-pro-b60/data/iq2b.engine.txt new file mode 100644 index 0000000000..6dcb24c0b7 --- /dev/null +++ b/bench/results/2026-10-04-community-2x-arc-pro-b60/data/iq2b.engine.txt @@ -0,0 +1,69 @@ +strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split 25) +strata generate: PCIe probe: 7.0 GB/s host->device (best of 7.0 7.0 7.0 7.0) -> pcie_frac 0.19 (default 0.55) +strata generate: this CPU has no AVX-512: the expert kernels run on AVX-2 (multi-token for the i-quant gate/up rows) +strata generate: native pack: /packs/qwen-iq2_xs experts (largest blob 1.51 MB), token embedding IQ4_XS in mapped host memory (322 MiB) +strata generate: layer split: CUDA0 loads the dense weights of layers 0-24 only +strata generate: 799 MiB of weights loaded from /packs/qwen-iq2_xs (670 canonical tensors skipped: served natively) +strata generate: 156 native projection matrices, 766.85 MiB of weights +strata generate: the SSD is kept awake while rows are read: one page of the table after 100 ms without a read, until 60 s after the last request (STRATA_SSD_KEEPALIVE=0 turns it off) +strata generate: layer split: CUDA1 loads the dense weights of layers 25-47 only +strata generate: layer split: CUDA1 PCIe probe 7.0 GB/s (best of 7.0 7.0 7.0 7.0) -> pcie_frac 0.19 +strata generate: layer split: CUDA1 holds its weights; 22.36 GiB free (its session follows the split search) +strata generate: profile data/expert-profile.bin: 24576 ranked pairs, built for 24576 slots +strata generate: PLE on, table 320001536 rows of /models/qwen-iq2_xs/Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf +strata generate: layer split: CUDA1 holds its weights, session [25, 48) and the head; 21.93 GiB free +strata mtp: draft layer loaded, 802 MiB of VRAM (experts 675, dense 111), files read in 0.75 s (1053 MiB/s) +strata generate: GPU 0: Intel(R) Arc(TM) Pro B60 Graphics, compute capability 20.1 +strata generate: WARNING: this engine was compiled with CUDA 12.8 headers but loaded a CUDA 0.2 runtime (libcudart): GPU properties can read wrong and some kernels go unused. Rebuild it against one toolkit (cmake -DCUDAToolkit_ROOT=, with its libcudart.so present) (#542) +strata generate: experts streamed from the GGUF on demand (--stream-experts): no host arena; every expert must fit the VRAM cache +strata generate: expert cache auto: 22.11 GiB free, 1536 MiB reserved (+0 MiB for the draft head) -> 12800 slots +strata generate: expert cache 12800 slots, 16.91 GiB of VRAM; policy is +strata generate: the GPU computes the experts in the cache; it rounds differently from the CPU, + so a reply can differ slightly from a run without the cache (same quality: + bench/results/2026-09-27-cache-parity). + PROFILE, ranked by routing frequency, no eviction. +strata generate: profile fill: 16.91 GiB in 3.8 s (4.81 GB/s, pipelined) +strata generate: pre-filled 12800 of 12800 slots from the profile; slot 0 verified +strata generate: 4473 of 11776 experts missing from VRAM mirrored in pinned host memory (6.00 GiB, 1.1 s); the GPU reads them over PCIe +strata generate: WARNING: 7303 experts are neither in VRAM nor mirrored; with STRATA_VERIFY_NO_HOST the device plan cannot run them and their layers' windows fall back slowly - raise STRATA_MIRROR_MIB or the free RAM, or lower --max-context +strata generate: layer split, CUDA1: 21.14 GiB free of 23.91, room for experts 17.93 GiB +strata generate: layer split: CUDA1 runs layers 25-47, expert cache 11776 slots (16.11 GiB), 11776 of its 11776 profiled pairs; slot 0 verified +strata generate: layer split: CUDA0 runs layers 0-24 +strata generate: R4 hit path ON - resident experts are computed on the GPU +strata generate: 5 expert-pool workers + the host thread +strata generate: session is up (engine 0.1.39-sycl) +strata generate: token graph hit path: 24576 resident experts, decided on the device +strata serve: layer split: 100% of the experts resident, the prompt path's streamed ring 96 slots +strata serve: the prompt path allocates its own buffers (too few cache slots to borrow) +strata verify: window up to 6 tokens, 56.4 MiB of device buffers +strata serve: layer split: layers 0-24 (CUDA0), 25-47 (CUDA1), one hand-off per window +strata verify: window up to 6 tokens, 56.4 MiB of device buffers +strata mtp: draft head over 106299 tokens (137.9 MiB) +strata serve: 4235 MiB of VRAM free with everything loaded +strata verify: captured the 6-token window (upload , sync ) +strata verify: captured the 6-token window (upload , sync ) +strata verify: captured the 4-token window (upload , sync ) +strata verify: captured the 4-token window (upload , sync ) +strata verify: captured the 1-token window (upload , sync ) +strata verify: captured the 1-token window (upload , sync ) +strata verify: captured the 3-token window (upload , sync ) +strata verify: captured the 3-token window (upload , sync ) +strata serve: prompt 23 tokens = 0 reused + 23 read in 456 ms (50.4 tok/s), 112 generated in 1910 ms (58.6 tok/s), drafts accepted 84 of 88, 1 checkpoints +strata serve: prompt 23 tokens = 16 reused + 7 read in 86 ms (81.7 tok/s), 112 generated in 1827 ms (61.3 tok/s), drafts accepted 84 of 89, 1 checkpoints +strata serve: suffix drafts: 1 windows, 1 of 3 drafts accepted +strata serve: prompt 37 tokens = 0 reused + 37 read in 505 ms (73.3 tok/s), 32 generated in 518 ms (61.8 tok/s), drafts accepted 23 of 24, 1 checkpoints +strata verify: captured the 5-token window (upload , sync ) +strata verify: captured the 5-token window (upload , sync ) +strata serve: prompt 42 tokens = 0 reused + 42 read in 591 ms (71.1 tok/s), 4 generated in 157 ms (25.4 tok/s), drafts accepted 4 of 6, 1 checkpoints +strata verify: captured the 2-token window (upload , sync ) +strata verify: captured the 2-token window (upload , sync ) +strata serve: prompt 2129 tokens = 0 reused + 2129 read in 4878 ms (436.4 tok/s), 104 generated in 2680 ms (38.8 tok/s), drafts accepted 56 of 87, 1 checkpoints +strata serve: prompt 2129 tokens = 2122 reused + 7 read in 88 ms (79.2 tok/s), 104 generated in 2602 ms (40.0 tok/s), drafts accepted 56 of 87, 1 checkpoints +strata serve: prompt 1922 tokens = 0 reused + 1922 read in 4318 ms (445.1 tok/s), 256 generated in 4616 ms (55.5 tok/s), drafts accepted 183 of 213, 1 checkpoints +strata serve: suffix drafts: 1 windows, 1 of 5 drafts accepted +strata serve: prompt 2199 tokens = 1915 reused + 284 read in 1604 ms (177.0 tok/s), 256 generated in 3532 ms (72.5 tok/s), drafts accepted 211 of 217, 2 checkpoints +strata serve: suffix drafts: 41 windows, 205 of 205 drafts accepted +strata serve: prompt 30 tokens = 0 reused + 30 read in 454 ms (66.1 tok/s), 11 generated in 255 ms (43.2 tok/s), drafts accepted 7 of 9, 1 checkpoints +strata serve: prompt 70 tokens = 41 reused + 29 read in 412 ms (70.3 tok/s), 3 generated in 97 ms (30.9 tok/s), drafts accepted 3 of 3, 2 checkpoints +strata serve: prompt 108 tokens = 74 reused + 34 read in 479 ms (70.9 tok/s), 14 generated in 307 ms (45.6 tok/s), drafts accepted 8 of 11, 3 checkpoints +strata serve: prompt 33 tokens = 0 reused + 33 read in 487 ms (67.8 tok/s), 39 generated in 813 ms (47.9 tok/s), drafts accepted 28 of 38, 1 checkpoints diff --git a/bench/results/2026-10-04-community-2x-arc-pro-b60/data/iq2b.json b/bench/results/2026-10-04-community-2x-arc-pro-b60/data/iq2b.json new file mode 100644 index 0000000000..ae1884edfe --- /dev/null +++ b/bench/results/2026-10-04-community-2x-arc-pro-b60/data/iq2b.json @@ -0,0 +1,47 @@ +{ + "engine": "strata", + "exe": "/strata-native.sh", + "cwd": "", + "tokenizer": "/packs/qwen-iq2_xs/tokenizer", + "model_name": "qwen3.8-flash-next-iq2_xs", + "backend": "sycl", + "log": "/logs/w2/iq2b.engine.log", + "args": [ + "--pack", + "/packs/qwen-iq2_xs", + "--native", + "/models/qwen-iq2_xs/Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00001-of-00002.gguf", + "--ple-gguf", + "/models/qwen-iq2_xs/Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf", + "--expert-profile", + "data/expert-profile.bin", + "--expert-cache", + "auto", + "--stream-experts", + "--prefill", + "auto", + "--spec", + "4", + "--spec-min-p", + "0.5", + "--mtp", + "/mtp/rt", + "--max-context", + "8192", + "--kv", + "int8", + "--vram-reserve-mib", + "1536", + "--no-prefill-borrow", + "--layer-split", + "25" + ], + "env": { + "ONEAPI_DEVICE_SELECTOR": "level_zero:0,1", + "SYCL_CACHE_PERSISTENT": "0", + "STRATA_MIRROR_MIB": "6144", + "STRATA_VERIFY_DEVICE_PLAN": "1", + "STRATA_STAGE_TRIM": "1", + "STRATA_VERIFY_NO_HOST": "1" + } +} \ No newline at end of file diff --git a/docs/COMMUNITY_BENCHMARKS.md b/docs/COMMUNITY_BENCHMARKS.md index e6903faf40..f4198f17c6 100644 --- a/docs/COMMUNITY_BENCHMARKS.md +++ b/docs/COMMUNITY_BENCHMARKS.md @@ -18,6 +18,9 @@ and their limits. Report what you actually measured and label estimates separate - [2026-10-03: 2x AMD Instinct MI50 16 GB (gfx906), Xeon E5-2666 v3, 32 GB RAM](../bench/results/2026-10-03-community-2x-mi50/README.md): the gfx906 build (#638) with #639 and #640, Coder IQ1_M, 131,072-token context, layer split across both cards; three runs each at 4,096, 32,768, and 128,000 prompt tokens, plus six recall checks. +- [2026-10-04: 2x Intel Arc Pro B60 24 GB, Ryzen 5 5600, 62 GB RAM](../bench/results/2026-10-04-community-2x-arc-pro-b60/README.md): + the SYCL port at `6f32ec0` with two fixes, Coder IQ1_M and Flash-Next IQ2_XS, 8,192-token context, layer split across both cards; + short prompts and 2K-token prompts, plus one run on a single B60. Intel's SYCL engine, no 4,096/32,768/128,000-token sweep. ## What to record diff --git a/docs/INTEL_ARC.md b/docs/INTEL_ARC.md index 7b6acfeb63..b08481fe33 100644 --- a/docs/INTEL_ARC.md +++ b/docs/INTEL_ARC.md @@ -19,12 +19,18 @@ There is **no ready-made Intel engine** in the release zips. You build it from s | Community | 2x Arc Pro B70, `--layer-split` | Flash-Next IQ3_XXS 66 tok/s decode, 394 tok/s prompt (with the `stage_room` fix that is now in 0.1.39) | #423 | | Community | Arc Pro B50 16 GB | Coder IQ1_M ~23 tok/s, IQ2_XS ~25-27 tok/s, up to 128K | #423 | | Community | Arc B580 12 GB, WSL2 | IQ2_XS ~21 tok/s, Coder ~15 tok/s; **device loss also seen** | #423 | +| Community | 2x Arc Pro B60 24 GB, `--layer-split` | Coder IQ1_M: 56.6 tok/s decode, 428 tok/s prompt (2,129 tokens); Flash-Next IQ2_XS: 58.6-61.3 tok/s decode, 436 tok/s prompt; all experts in VRAM; 8K context | [bench/results/2026-10-04-community-2x-arc-pro-b60](../bench/results/2026-10-04-community-2x-arc-pro-b60/README.md) | +| Community | one Arc Pro B60 24 GB | Coder IQ1_M with 4,042 of 12,288 experts mirrored in RAM: 11.9 tok/s decode (needs the ring-wait fix from the same report) | same | | Strata maintainers | no Arc | compile check and kernel tests on a CPU device only (below) | this release | The 0.1.39 port re-migrates 0.1.38's port onto the 0.1.39 engine sources (the #606 NaN fix, the #649 verify trace, the new prompt paths). It compiles and its kernel tests run, but **nobody has run the 0.1.39 port on an Arc yet**. The numbers in the table were measured on earlier versions. +The two B60 rows ran `6f32ec0` plus two small `sycl/` fixes (the compile fix and the ring-wait fix), AOT `bmg-g21`, on Ubuntu 24.04 with +`xe`, Level Zero V2, NEO 26.09.37435.12 and oneAPI 2026.1.1, without Docker. Host: Ryzen 5 5600, 62 GB RAM, PCIe 3.0 x8 per card. +Full flags, per-request timings and engine logs are in the report linked in the table. + ## What was tested here (0.1.39) - **Compiles:** Ubuntu 24.04 (WSL2), Intel oneAPI DPC++ 2026.1.1 + oneMKL 2026.1. The whole `sycl/` project @@ -108,6 +114,16 @@ Things that matter on an Arc (details in INTEL.md): - `SYCL_CACHE_PERSISTENT=0`: the persistent JIT cache crashed on Xe2 during the first compile. - Two cards: `ONEAPI_DEVICE_SELECTOR=level_zero:*` (the image pins `level_zero:0`; `strata-sycl.sh` now passes the variable through) and `--layer-split`. +- **Arc Pro B60:** the PCI id is `8086:e211` (`lspci -nn`, the kernel's `xe` id list files it with the BMG-G21 cards), `sycl-ls` prints + `Intel(R) Arc(TM) Pro B60 Graphics 20.1.0`, and `ocloc ids bmg-g21` prints 20.1.0, so `-DSTRATA_SYCL_AOT=bmg-g21` is the right target. + `setup_intel.py` knows `e211` (and still lists `e221`). On a `--layer-split` the startup line "N experts are neither in VRAM nor mirrored" + counts the other card's layers; the lines `100% of the experts resident` that follow are the ones to read. Set `STRATA_MIRROR_MIB=0` there, + or the pinned mirror is allocated and not used. +- **`setvars.sh` and `set -u`:** `source /opt/intel/oneapi/setvars.sh` in a shell with `set -u` stops at `OCL_ICD_FILENAMES: unbound variable` + (oneAPI 2026.1.1). Source it before `set -u`, or run `set +u` around it. +- **Without Docker:** `sycl/serve/strata-sycl.sh` needs Docker. Natively, `source setvars.sh`, export `SYCL_CACHE_PERSISTENT=0`, + `ZES_ENABLE_SYSMAN=1` and `STRATA_VERIFY_DEVICE_PLAN=1`, then run `build-sycl-aot/strata` or `sycl/serve/server_intel.py` with an `exe` that does this. + A normal user is not in the `render` group on Ubuntu, and then `sycl-ls` shows only the CPU device. - `STRATA_VERIFY_NO_HOST=1` (set by `strata-sycl.sh`) is only valid when every expert is in VRAM. On smaller cards that path is the one that has hung, and #667 found the likely reason: the GPU does not see the CPU's flag stores without a system fence. diff --git a/sycl/setup_intel.py b/sycl/setup_intel.py index 0b1e2f0589..9e615bc10b 100644 --- a/sycl/setup_intel.py +++ b/sycl/setup_intel.py @@ -41,7 +41,8 @@ MOUNT = Path(os.environ.get("STRATA_SYCL_ROOT") or ROOT.parent) # what strata- # Battlemage / Alchemist PCI device ids -> (name, VRAM GB). lspci's database lags new cards (an Arc Pro B70 reads # "Intel Corporation Device [8086:e223]"), so the sysfs id is the reliable signal and the name table is ours. -INTEL_ARC = {"e223": ("Arc Pro B70", 32.0), "e221": ("Arc Pro B60", 24.0), "e20b": ("Arc B580", 12.0), +INTEL_ARC = {"e223": ("Arc Pro B70", 32.0), "e221": ("Arc Pro B60", 24.0), "e211": ("Arc Pro B60", 24.0), + "e20b": ("Arc B580", 12.0), "e20c": ("Arc B570", 10.0), "e212": ("Arc B50", 16.0), "56a0": ("Arc A770", 16.0), "56a1": ("Arc A750", 8.0), "56a2": ("Arc A580", 8.0), "56a5": ("Arc A380", 6.0), "56a6": ("Arc A310", 4.0), "5690": ("Arc A770M", 16.0)} diff --git a/tools/test_setup_sycl.py b/tools/test_setup_sycl.py index 2ff02b64a3..49badcab2c 100644 --- a/tools/test_setup_sycl.py +++ b/tools/test_setup_sycl.py @@ -71,5 +71,26 @@ class CMakeOption(unittest.TestCase): self.assertIn("add_subdirectory(sycl)", src) +class IntelIds(unittest.TestCase): + """sycl/setup_intel.py names a card by its PCI device id. The Arc Pro B60s measured on 2x B60 (`lspci -nn` 8086:e211, + bmg-g21) must not fall through to "Intel GPU e211 (xe)" with a guessed VRAM size.""" + + @staticmethod + def table(): + import importlib.util + spec = importlib.util.spec_from_file_location("setup_intel", ROOT / "sycl" / "setup_intel.py") + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + return mod.INTEL_ARC + + def test_b60_e211_is_named_with_its_vram(self): + self.assertEqual(self.table()["e211"], ("Arc Pro B60", 24.0)) + + def test_the_ids_that_were_listed_before_are_kept(self): + t = self.table() + self.assertEqual(t["e223"][0], "Arc Pro B70") + self.assertEqual(t["e221"][0], "Arc Pro B60") + + if __name__ == "__main__": unittest.main() From b70c9cbbfe1135ee7b1e43e237bf8d801fe14735 Mon Sep 17 00:00:00 2001 From: LocalXPU <337401568+LocalXPU@users.noreply.github.com> Date: Sun, 4 Oct 2026 19:54:32 -0500 Subject: [PATCH 10/48] docs: the host has 64 GB of RAM (62 GiB usable), not 62 GB --- bench/results/2026-10-04-community-2x-arc-pro-b60/README.md | 2 +- docs/COMMUNITY_BENCHMARKS.md | 2 +- docs/INTEL_ARC.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/bench/results/2026-10-04-community-2x-arc-pro-b60/README.md b/bench/results/2026-10-04-community-2x-arc-pro-b60/README.md index 1c57d1cd00..2935e01697 100644 --- a/bench/results/2026-10-04-community-2x-arc-pro-b60/README.md +++ b/bench/results/2026-10-04-community-2x-arc-pro-b60/README.md @@ -4,7 +4,7 @@ Measured on 2026-10-04 by LocalXPU. This is the SYCL port (`sycl/`) on two Arc P ## Hardware and software -- 2x Intel Arc Pro B60 24 GB (`8086:e211`, 456 GB/s each), PCIe 3.0 x8 per card; Ryzen 5 5600; 62 GB DDR4; storage type not recorded +- 2x Intel Arc Pro B60 24 GB (`8086:e211`, 456 GB/s each), PCIe 3.0 x8 per card; Ryzen 5 5600; 64 GB DDR4; storage type not recorded - Ubuntu 24.04, kernel 6.17 (`xe` driver), Level Zero V2, compute runtime NEO 26.09.37435.12, oneAPI DPC++ 2026.1.1, oneMKL 2026.1.0 - Strata `6f32ec0` plus two `sycl/` fixes (the build fix for #559/#626 and the `cudaStreamQuery` fix in the ring wait); engine reports `0.1.39-sycl`; AOT `-DSTRATA_SYCL_AOT=bmg-g21`; source build, no Docker - Nothing else ran on the GPUs. The kernel log was watched for `xe` resets during every run: none. diff --git a/docs/COMMUNITY_BENCHMARKS.md b/docs/COMMUNITY_BENCHMARKS.md index f4198f17c6..adb9f736e1 100644 --- a/docs/COMMUNITY_BENCHMARKS.md +++ b/docs/COMMUNITY_BENCHMARKS.md @@ -18,7 +18,7 @@ and their limits. Report what you actually measured and label estimates separate - [2026-10-03: 2x AMD Instinct MI50 16 GB (gfx906), Xeon E5-2666 v3, 32 GB RAM](../bench/results/2026-10-03-community-2x-mi50/README.md): the gfx906 build (#638) with #639 and #640, Coder IQ1_M, 131,072-token context, layer split across both cards; three runs each at 4,096, 32,768, and 128,000 prompt tokens, plus six recall checks. -- [2026-10-04: 2x Intel Arc Pro B60 24 GB, Ryzen 5 5600, 62 GB RAM](../bench/results/2026-10-04-community-2x-arc-pro-b60/README.md): +- [2026-10-04: 2x Intel Arc Pro B60 24 GB, Ryzen 5 5600, 64 GB RAM](../bench/results/2026-10-04-community-2x-arc-pro-b60/README.md): the SYCL port at `6f32ec0` with two fixes, Coder IQ1_M and Flash-Next IQ2_XS, 8,192-token context, layer split across both cards; short prompts and 2K-token prompts, plus one run on a single B60. Intel's SYCL engine, no 4,096/32,768/128,000-token sweep. diff --git a/docs/INTEL_ARC.md b/docs/INTEL_ARC.md index b08481fe33..0a1b4f4e16 100644 --- a/docs/INTEL_ARC.md +++ b/docs/INTEL_ARC.md @@ -28,7 +28,7 @@ trace, the new prompt paths). It compiles and its kernel tests run, but **nobody yet**. The numbers in the table were measured on earlier versions. The two B60 rows ran `6f32ec0` plus two small `sycl/` fixes (the compile fix and the ring-wait fix), AOT `bmg-g21`, on Ubuntu 24.04 with -`xe`, Level Zero V2, NEO 26.09.37435.12 and oneAPI 2026.1.1, without Docker. Host: Ryzen 5 5600, 62 GB RAM, PCIe 3.0 x8 per card. +`xe`, Level Zero V2, NEO 26.09.37435.12 and oneAPI 2026.1.1, without Docker. Host: Ryzen 5 5600, 64 GB RAM, PCIe 3.0 x8 per card. Full flags, per-request timings and engine logs are in the report linked in the table. ## What was tested here (0.1.39) From 525017f443aa9b4c8e875baf59d1d24baa3984b8 Mon Sep 17 00:00:00 2001 From: LocalXPU <337401568+LocalXPU@users.noreply.github.com> Date: Sun, 4 Oct 2026 22:35:40 -0500 Subject: [PATCH 11/48] docs: e221 is also an Arc Pro B60 id (seen on another B60 pair) --- docs/INTEL_ARC.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/INTEL_ARC.md b/docs/INTEL_ARC.md index 0a1b4f4e16..bfaddde9fa 100644 --- a/docs/INTEL_ARC.md +++ b/docs/INTEL_ARC.md @@ -116,7 +116,7 @@ Things that matter on an Arc (details in INTEL.md): variable through) and `--layer-split`. - **Arc Pro B60:** the PCI id is `8086:e211` (`lspci -nn`, the kernel's `xe` id list files it with the BMG-G21 cards), `sycl-ls` prints `Intel(R) Arc(TM) Pro B60 Graphics 20.1.0`, and `ocloc ids bmg-g21` prints 20.1.0, so `-DSTRATA_SYCL_AOT=bmg-g21` is the right target. - `setup_intel.py` knows `e211` (and still lists `e221`). On a `--layer-split` the startup line "N experts are neither in VRAM nor mirrored" + `setup_intel.py` knows both B60 ids, `e211` and `e221` (both seen on B60 cards). On a `--layer-split` the startup line "N experts are neither in VRAM nor mirrored" counts the other card's layers; the lines `100% of the experts resident` that follow are the ones to read. Set `STRATA_MIRROR_MIB=0` there, or the pinned mirror is allocated and not used. - **`setvars.sh` and `set -u`:** `source /opt/intel/oneapi/setvars.sh` in a shell with `set -u` stops at `OCL_ICD_FILENAMES: unbound variable` From a5ada869aedcfae4c2714bcf1461a867f8eec622 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 5 Oct 2026 10:22:19 +0200 Subject: [PATCH 12/48] docs: INTEL_ARC says what ran on an Arc (#868 follow-up) The 0.1.39 paragraph said nobody had run the 0.1.39 port on an Arc. Two Arc Pro B60 reports (#867, #870) did, with the two sycl/ fixes now in 0.1.40 (#784 the compile fix, #866 the ring wait). Say that, and that an unpatched 0.1.39 port did not compile against its own engine sources. --- docs/INTEL_ARC.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/docs/INTEL_ARC.md b/docs/INTEL_ARC.md index bfaddde9fa..2f65b3bdec 100644 --- a/docs/INTEL_ARC.md +++ b/docs/INTEL_ARC.md @@ -24,8 +24,11 @@ There is **no ready-made Intel engine** in the release zips. You build it from s | Strata maintainers | no Arc | compile check and kernel tests on a CPU device only (below) | this release | The 0.1.39 port re-migrates 0.1.38's port onto the 0.1.39 engine sources (the #606 NaN fix, the #649 verify -trace, the new prompt paths). It compiles and its kernel tests run, but **nobody has run the 0.1.39 port on an Arc -yet**. The numbers in the table were measured on earlier versions. +trace, the new prompt paths). 0.1.39's `sycl/` did not compile against 0.1.39's own engine sources (#784: the +`ThreadAffinity` type of #626 and the layer range of `NativeDense::load` from #559), and its ring waits never saw a +slow layer as still running (#866, #867). Both are fixed in 0.1.40, and the two B60 reports below were measured with +exactly those two fixes on top of 0.1.39. **No one has run an unpatched 0.1.39 port on an Arc**, and the other rows were +measured on earlier versions. The two B60 rows ran `6f32ec0` plus two small `sycl/` fixes (the compile fix and the ring-wait fix), AOT `bmg-g21`, on Ubuntu 24.04 with `xe`, Level Zero V2, NEO 26.09.37435.12 and oneAPI 2026.1.1, without Docker. Host: Ryzen 5 5600, 64 GB RAM, PCIe 3.0 x8 per card. From bd50ff7a0a933e3597389f66979a7b3e3e4d1d22 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 5 Oct 2026 12:18:47 +0200 Subject: [PATCH 13/48] docs: the PLE table formats the engine reads, and how far each is from the BF16 table Row error on 4,000 random rows against the checkpoint's BF16 table (Q8_0 0.53%, FP8 2.64%, IQ4_NL 7.60%, matching the numbers reported in #651), and teacher-forced KL on the Q2_0 model with each table. --- docs/DETAILS.md | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/docs/DETAILS.md b/docs/DETAILS.md index d9484e6528..78390cefa3 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -1028,7 +1028,13 @@ the document, +0.4% on the chat. Details: `bench/results/2026-09-27-esp/`. - **RAM:** all 24,576 experts, pinned. The CPU computes the experts that are not on the GPU **in place**, at the same time as the GPU works on the cached ones (AVX-512 / AVX2 kernels, ggml's for the i-quants). - **SSD:** the 28.8 GB n-gram table, a few rows per token, read unbuffered past the OS cache (`--ple-io direct`, the - default, made for SSDs; on a rotational disk `--ple-io ram` keeps the table in RAM, #605). + default, made for SSDs; on a rotational disk `--ple-io ram` keeps the table in RAM, #605). The engine reads the table + in the format the GGUF has it: IQ4_NL (the default table), Q4_0, Q5_0, Q5_1, Q8_0, FP8 (E4M3 with a scale) or BF16. + Measured on 4,000 random rows against the checkpoint's own BF16 table, the mean per-row error is Q8_0 0.53%, FP8 2.64%, + Q5_1 3.78%, Q5_0 4.25%, IQ4_NL 7.60%, Q4_1 7.80%, Q4_0 8.55% (a Q8_0 table is 54 GB, an IQ4_NL one 28.8 GB). On the Q2_0 model, 700 teacher-forced tokens, the mean KL against the BF16 table is 0.0117 (Q5_0), 0.0121 (Q5_1), 0.0125 + (Q8_0), 0.0128 (FP8), 0.0140 (Q4_0) and 0.0146 (IQ4_NL), with the perplexity within 1% of BF16's either way: any change to the + table moves the 2-bit model by about 0.012, so the formats are hard to tell apart. Setup does not offer another table; + it only changes which GGUF the engine is given. - **Speculation:** the model's own MTP layer drafts up to 3 tokens; one pass over all 48 layers checks them. 2.4-3.2 tokens per pass on average. When the reply repeats the context (code edits, quoted text), **prompt lookup** (engine 0.1.7) drafts up to 5 tokens from the earlier copy, but only where its measured acceptance and cost say it pays: From 58dd26b9f26c5fd7892cec04721bb94d9ae9afce Mon Sep 17 00:00:00 2001 From: sergiywith Date: Sat, 3 Oct 2026 01:05:45 +0300 Subject: [PATCH 14/48] serve: image sources - network paths refused, URLs capped at 32 MiB and fetched outside the FIFO, no local files for other sites' pages Vision.load read whatever an image source named. A network path (\\host\share\x.png, //host/share/x.png, \\?\UNC\host\..., \??\UNC\host\..., file:////host/share/x.png) made Windows connect to that host and sign in with the user's NTLM credentials - os.path.isfile alone does it. Such paths are now refused before anything looks at them, and so is file://host/share/x.png (that names \\host\share; the old code read it as the relative path host/share/x.png). An http(s) image was read whole, with no cap, inside prepare()'s `with self.fifo`: a huge one filled the memory and a slow one held every other request for as long as urlopen waited (60 s per read). Now it is read up to 32 MiB (IMAGE_URL_MAX; a larger Content-Length is refused unread), downloaded before the FIFO is taken, and a URL that cannot be read is a 400 instead of a dropped connection. Other sites' pages: with no api_key (the default) _authorized() lets every request in, and /v1/chat/completions and /v1/messages read the body as JSON whatever its Content-Type; only /settings, /v1/load, /v1/unload and the MCP tools check the Content-Type and Origin (_own_page). So any web page open in the user's browser could POST a chat request as text/plain - a CORS "simple" request, no preflight - that names a file on this computer (or a network path) as an image, and the server read it. The page gets no answer to read (no CORS headers unless cors_origins lists it or "*"), but the read, and a network path's sign-in, happened. Reproduced over HTTP: answered 200, the file handed to the encoder. Now a request whose Origin is neither the server's own address nor in trusted_origins may send data: and http(s) images only; a file path or file:// URL is a 400 that says so. Clients that send no Origin (CLI tools, SDKs, agents), Strata's own page (it sends data: URLs) and trusted origins are unchanged. As for /settings and MCP, a DNS-rebinding page, whose Origin matches its Host header, still counts as the server's own. Tests: each network form is refused with os.path.isfile never called, and local files, file:// and data: URLs still load; the cap with and without a Content-Length, and a 404; the URL is downloaded with the FIFO free; a foreign-Origin text/plain request naming a file is a 400 on both APIs, while data: images and no-Origin, own-origin and trusted-origin requests are answered. --- serve/server.py | 77 +++++++++++++++++++---- serve/test_server.py | 145 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 210 insertions(+), 12 deletions(-) diff --git a/serve/server.py b/serve/server.py index bfc2a4f288..65dad2f8da 100644 --- a/serve/server.py +++ b/serve/server.py @@ -43,6 +43,7 @@ import threading import time import urllib.request import uuid +from http.client import HTTPException from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path from typing import Iterator, Protocol @@ -1264,6 +1265,17 @@ class StrataEngine: self.progress, self.last = None, {} +IMAGE_URL_MAX = 32 << 20 # an image URL is read up to this (the web app attaches pictures of up to 20 MB) + + +def network_path(path: str) -> bool: + r"""A path to another computer: \\host\share or //host/share (either slash), \\?\UNC\host\..., \\.\UNC\host\... + or the NT form \??\UNC\host\... Windows connects to that host at the first look at the path (os.path.isfile is + enough) and signs in with the user's NTLM credentials. \\?\ and \??\ name local files too; no client needs them.""" + p = path.replace("/", "\\") + return p.startswith("\\\\") or p.startswith("\\??\\") + + class Vision: """The resident image encoder: `strata-vision` (llama.cpp mtmd + the mmproj file) reads `ENC ` lines and writes each image's embeddings; results are cached by the image's hash, so a conversation that @@ -1315,14 +1327,35 @@ class Vision: if source.startswith("data:"): return base64.b64decode(source.split(",", 1)[1]) if source.startswith(("http://", "https://")): - req = urllib.request.Request(source, headers={"User-Agent": "strata"}) - with urllib.request.urlopen(req, timeout=60) as r: - return r.read() + return Vision.download(source) path = source[7:] if source.startswith("file://") else source + # refused before anything looks at the path: file://host/share/x.png is \\host\share\x.png ("file://C:/x.png", + # a drive, is a client's spelling of file:///C:/x.png) + host = re.split(r"[/\\]", path, maxsplit=1)[0] if source.startswith("file://") else "" + if network_path(path) or host and not re.fullmatch(r"[A-Za-z]:|localhost", host, re.IGNORECASE): + raise ValueError("an image file must be on this computer: network paths (\\\\host\\share, //host/share, " + "file://host/...) are not read") if path and os.path.isfile(path): return Path(path).read_bytes() raise ValueError("an image must be a data: URL, an http(s) URL or a local file path") + @staticmethod + def download(url: str) -> bytes: + """An image URL's bytes, at most IMAGE_URL_MAX of them: the whole response was read, so a huge or endless one + filled the memory. One that cannot be read is a ValueError (a 400 that says so), not a dropped connection.""" + too_big = f"the image URL's file is over {IMAGE_URL_MAX >> 20} MiB" + try: + with urllib.request.urlopen(urllib.request.Request(url, headers={"User-Agent": "strata"}), timeout=60) as r: + size = r.headers.get("Content-Length") or "" + if size.isdigit() and int(size) > IMAGE_URL_MAX: + raise ValueError(too_big) + data = r.read(IMAGE_URL_MAX + 1) + except (OSError, HTTPException) as e: + raise ValueError(f"the image URL could not be read: {e}") from None + if len(data) > IMAGE_URL_MAX: + raise ValueError(too_big) + return data + @staticmethod def normalize(data: bytes) -> bytes: """The formats strata-vision's decoder (stb_image) reads pass through; anything else is converted to PNG.""" @@ -1351,9 +1384,9 @@ class Vision: im.save(out, format="PNG") return out.getvalue() - def encode(self, source: str) -> tuple[Path, int]: - """-> (embeddings file, number of image tokens).""" - data = self.normalize(self.load(source)) + def encode(self, source: str | bytes) -> tuple[Path, int]: + """-> (embeddings file, number of image tokens). `source`: what load() reads, or the image's bytes.""" + data = self.normalize(source if isinstance(source, bytes) else self.load(source)) key = hashlib.sha256(data).hexdigest()[:32] with self.lock: if key in self.cache: @@ -2159,6 +2192,9 @@ class Service: "'vision'), so it cannot read images") pad = self.tok.encode(IMAGE_PAD, parse_special=True)[0] start = self.tok.encode(VISION_START, parse_special=True)[0] + # An image URL is downloaded first, outside the FIFO: under it, a slow server held every other request + # for as long as urlopen waited. + images = [Vision.download(src) if src.startswith(("http://", "https://")) else src for src in images] # Encode only while the engine is idle: the engine and the image encoder (a separate process) must not # run on the GPU at the same time - an encode during a running request left that request stuck at # "reading the prompt" with CPU and GPU busy, for good (reproduced). So encoding takes its turn in the @@ -3251,12 +3287,7 @@ def make_handler(svc: Service): if not self.headers.get("Content-Type", "").startswith("application/json"): self._json(415, {"error": {"message": "send application/json"}}) return False - # The Origin must be this server's own address (host and port), or an origin the config trusts - # (trusted_origins: the web app behind a reverse proxy or tunnel). Headers a proxy adds (X-Forwarded-*, - # CF-Ray, CF-Connecting-IP) prove nothing about the page that sent the request, so they open nothing. - origin = (self.headers.get("Origin") or "").rstrip("/") - if origin and origin.split("://", 1)[-1] != self.headers.get("Host", "") and \ - origin not in svc.trusted_origins: + if self._foreign_origin(): self._json(403, {"error": {"message": f"{what} only from Strata's own page (or an origin in the " f"config's trusted_origins)"}}) return False @@ -3299,6 +3330,26 @@ def make_handler(svc: Service): print(f"[strata] the Settings view changed {', '.join(changed)} in {Path(svc.config_path).name} " f"(the earlier file: {bak.name}); used from the next start", flush=True) self._json(200, {**runconfig.view(new, svc.config_path), "changed": changed}) + def _foreign_origin(self) -> bool: + """A web page of another origin sent this. The Origin must be this server's own address (host and port), + or an origin the config trusts (trusted_origins: the web app behind a reverse proxy or tunnel); no Origin + is a client that is no browser. Headers a proxy adds (X-Forwarded-*, CF-Ray, CF-Connecting-IP) prove + nothing about the page that sent the request, so they open nothing.""" + origin = (self.headers.get("Origin") or "").rstrip("/") + return bool(origin) and origin.split("://", 1)[-1] != self.headers.get("Host", "") and \ + origin not in svc.trusted_origins + + def _no_local_images(self, messages): + """A web page of another origin must not have a file on this computer read as an image. Without an + api_key, _foreign_page refuses such a page unless cors_origins lets it in - and a page cors_origins lets + in (["*"]: every page) could name any file and, CORS allowing, read what the model says about it. data: + and http(s) images are the page's own to send; files come from Strata's own page, a trusted origin or a + client that is no browser. ValueError (a 400).""" + if self._foreign_origin() and any(not src.startswith(("data:", "http://", "https://")) + for src in images_of(messages)): + raise ValueError("a web page of another origin cannot have a file on this computer read as an " + "image: send it as a data: URL (or add the page's origin to the config's " + "trusted_origins)") def _settings(self): # They change what every client gets, so only the app's own page may set them @@ -3366,6 +3417,7 @@ def make_handler(svc: Service): def _openai(self, req): req = svc.with_shared(req, "openai") messages, tools, kw = openai_to_messages(req) + self._no_local_images(messages) messages, validator = prepare_format(req.get("response_format"), messages) if validator is not None and (tools or req.get("strata_mcp")): raise ValueError("structured response_format with tools/MCP is not supported") @@ -3551,6 +3603,7 @@ def make_handler(svc: Service): svc.load() req = svc.with_shared(req, "anthropic") messages, tools, kw = anthropic_to_messages(req, svc.anthropic_think_unasked) + self._no_local_images(messages) max_new = int(req.get("max_tokens") or 0) # 0/-1: the rest of the context svc.reasoning_budget(req) # a bad value is a 400 before anything is sent ids, thinking, max_new = svc.prepare(messages, tools, kw, max_new) diff --git a/serve/test_server.py b/serve/test_server.py index 0ffe2f6c97..34ef69e0b4 100644 --- a/serve/test_server.py +++ b/serve/test_server.py @@ -2681,5 +2681,150 @@ class LostStep(unittest.TestCase): self.run_mode("stop", stream=False) +class ImageSources(unittest.TestCase): + """What an image source may name: never a network path (Windows signs in to the host at the first look), a URL up + to IMAGE_URL_MAX and downloaded outside the request FIFO, a file on this computer not for a page of another site.""" + + NETWORK = [r"\\host\share\x.png", "//host/share/x.png", r"\\?\UNC\host\share\x.png", r"\\.\UNC\host\share\x.png", + r"\??\UNC\host\share\x.png", r"/\host\share\x.png", "file://host/share/x.png", + "file:////host/share/x.png", r"file://\\host\share\x.png"] + + class Vision(ImageMarkers.FakeVision): + def __init__(self, d): + super().__init__(d) + self.got = [] + + def encode(self, source): + self.got.append(source) + return super().encode(source) + + def test_network_paths_are_refused_before_any_look(self): + from serve.server import Vision + with mock.patch("os.path.isfile") as isfile, mock.patch.object(Path, "read_bytes") as read: + for src in self.NETWORK: + with self.subTest(src=src), self.assertRaisesRegex(ValueError, "network paths"): + Vision.load(src) + isfile.assert_not_called() + read.assert_not_called() + with tempfile.TemporaryDirectory() as d: # files on this computer load as before + f = Path(d) / "x.png" + f.write_bytes(b"\x89PNG\r\n\x1a\n") + for src in (str(f), "file://" + str(f), "data:image/png;base64,iVBORw0KGgo="): + with self.subTest(src=src): + self.assertEqual(Vision.load(src), b"\x89PNG\r\n\x1a\n") + + def test_a_url_is_read_up_to_the_cap(self): + import http.server + import serve.server as server + + class Files(http.server.BaseHTTPRequestHandler): + def log_message(self, *args): + pass + + def do_GET(self): + body = {"/small": b"x" * 100, "/big": b"x" * 5000}.get(urllib.parse.urlsplit(self.path).path) + if body is None: + self.send_error(404) + return + self.send_response(200) + if "length" in self.path: # else the body ends when the connection does + self.send_header("Content-Length", str(len(body))) + self.end_headers() + try: + self.wfile.write(body) + except OSError: # the reader stopped at the cap + pass + + httpd = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Files) + threading.Thread(target=httpd.serve_forever, daemon=True).start() + base = f"http://127.0.0.1:{httpd.server_address[1]}" + try: + with mock.patch.object(server, "IMAGE_URL_MAX", 1000): + for q in ("", "?length"): + with self.subTest(q=q): + self.assertEqual(server.Vision.load(base + "/small" + q), b"x" * 100) + with self.assertRaisesRegex(ValueError, "is over"): + server.Vision.load(base + "/big" + q) + with self.assertRaisesRegex(ValueError, "could not be read: HTTP Error 404"): + server.Vision.load(base + "/missing") + finally: + httpd.shutdown() + httpd.server_close() + + def test_a_url_is_downloaded_outside_the_fifo(self): + import serve.server as server + tok = ByteTokenizer() + with tempfile.TemporaryDirectory() as d: + vision = self.Vision(d) + svc = Service(MockEngine(tok, "ok", max_context=CTX), tok, ChatTemplate(ROOT / "serve/chat_template.jinja"), + vision=vision) + held = [] + + def download(url): + held.append(svc.fifo.locked()) + return b"the picture" + + msgs = [{"role": "user", "content": [{"type": "image", "source": "https://example.com/x.png"}, + {"type": "image", "source": "x.png"}]}] + with mock.patch.object(server.Vision, "download", side_effect=download): + svc.prepare(msgs, None, {}) + self.assertEqual(held, [False]) # not while every other request waits + self.assertEqual(vision.got, [b"the picture", "x.png"]) + svc.embeddings.path.unlink(missing_ok=True) + + def test_a_page_of_another_site_cannot_name_a_file(self): + tok = ByteTokenizer() + with tempfile.TemporaryDirectory() as d: + vision = self.Vision(d) + svc = Service(MockEngine(tok, "\n\nok", max_context=CTX), tok, + ChatTemplate(ROOT / "serve/chat_template.jinja"), vision=vision) + httpd = serve(svc, port=0) + host = f"127.0.0.1:{httpd.server_address[1]}" + + def post(path, src, headers): + image = {"type": "image_url", "image_url": {"url": src}} if path.endswith("completions") else \ + {"type": "image", "source": {"type": "url", "url": src}} + body = {"model": "m", "max_tokens": 8, "messages": [{"role": "user", "content": [ + {"type": "text", "text": "what is it?"}, image]}]} + req = urllib.request.Request(f"http://{host}{path}", data=json.dumps(body).encode(), headers=headers) + try: + with urllib.request.urlopen(req, timeout=30) as r: + return r.status, json.loads(r.read()) + except urllib.error.HTTPError as e: + with e: + return e.code, json.loads(e.read()) + + try: + f = str(Path(d) / "secret.png") + # a page on any site, no api_key (the default): text/plain needs no CORS preflight - 0.1.38 refuses + # such a page outright (403) + page = {"Content-Type": "text/plain;charset=UTF-8", "Origin": "https://evil.example"} + status, b = post("/v1/chat/completions", f, page) + self.assertEqual(status, 403, b) + # a page cors_origins lets in (here every page) may send JSON, and still cannot name a file + svc.cors_origins = ["*"] + page = {"Content-Type": "application/json", "Origin": "https://evil.example"} + for path in ("/v1/chat/completions", "/v1/messages"): + for src in (f, "file://" + f): + with self.subTest(path=path, src=src): + status, b = post(path, src, page) + self.assertEqual(status, 400, b) + self.assertIn("another origin", b["error"]["message"]) + self.assertEqual(vision.got, []) # nothing was read + svc.trusted_origins = ["https://app.example"] + data = "data:image/png;base64,iVBORw0KGgo=" + for src, headers in ((data, page), # the page's own picture + (f, {"Content-Type": "application/json"}), # curl, SDKs, agents + (f, {"Content-Type": "application/json", "Origin": "http://" + host}), + (f, {"Content-Type": "application/json", "Origin": "https://app.example"})): + with self.subTest(src=src[:20], headers=headers): + status, b = post("/v1/chat/completions", src, headers) + self.assertEqual(status, 200, b) + self.assertEqual(vision.got, [data, f, f, f]) + finally: + httpd.shutdown() + httpd.server_close() + + if __name__ == "__main__": unittest.main() From 264e81265bd43c8f0f86bc6a7ce4c1cb94f5cd81 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 5 Oct 2026 10:10:14 +0200 Subject: [PATCH 15/48] serve: /v1/responses refuses a file image from another origin (#553); a bad data: URL or unreadable file is a 400 (from #582) --- serve/server.py | 14 ++++++++++++-- serve/test_responses.py | 16 ++++++++++++++++ serve/test_server.py | 12 ++++++++++++ 3 files changed, 40 insertions(+), 2 deletions(-) diff --git a/serve/server.py b/serve/server.py index 65dad2f8da..327c5ece0a 100644 --- a/serve/server.py +++ b/serve/server.py @@ -1325,7 +1325,10 @@ class Vision: @staticmethod def load(source: str) -> bytes: if source.startswith("data:"): - return base64.b64decode(source.split(",", 1)[1]) + try: + return base64.b64decode(source.split(",", 1)[1]) + except (IndexError, ValueError) as e: # no comma, or not base64 + raise ValueError(f"the image's data: URL could not be read ({e})") from None if source.startswith(("http://", "https://")): return Vision.download(source) path = source[7:] if source.startswith("file://") else source @@ -1336,7 +1339,10 @@ class Vision: raise ValueError("an image file must be on this computer: network paths (\\\\host\\share, //host/share, " "file://host/...) are not read") if path and os.path.isfile(path): - return Path(path).read_bytes() + try: + return Path(path).read_bytes() + except OSError as e: + raise ValueError(f"the image could not be read from {path} ({e})") from None raise ValueError("an image must be a data: URL, an http(s) URL or a local file path") @staticmethod @@ -3559,6 +3565,10 @@ def make_handler(svc: Service): messages = responses_api.input_messages(req) tools, names, skipped = responses_api.request_tools(req) kw = responses_api.template_kwargs(req, svc.shared) + try: + self._no_local_images(messages) # as on the chat route: no file read for a foreign page + except ValueError as e: + raise ResponsesError(str(e), "input") from None try: messages, validator = prepare_format(responses_api.text_format(req), messages) except ValueError as e: diff --git a/serve/test_responses.py b/serve/test_responses.py index 2bae986966..2878cb6c9d 100644 --- a/serve/test_responses.py +++ b/serve/test_responses.py @@ -264,6 +264,22 @@ class OverHttp(Server): code, r = self.post({"model": "m", "input": "hi"}, headers={"Origin": "https://evil.example.com"}) self.assertEqual(code, 403) + def test_a_foreign_page_cannot_name_a_file_as_an_image(self): + """#553: the chat routes refuse a file image from another origin; so does /v1/responses.""" + def body(src): + return {"model": "m", "input": [{"role": "user", "content": [ + {"type": "input_text", "text": "what is it?"}, {"type": "input_image", "image_url": src}]}]} + self.svc.cors_origins = ["*"] # a page cors_origins lets in may send JSON, not name a file + for src in (r"\\host\share\x.png", "/etc/passwd", "file:///C:/x.png"): + with self.subTest(src=src): + code, r = self.post(body(src), headers={"Origin": "https://evil.example.com"}) + self.assertEqual(code, 400, r) + self.assertIn("another origin", r["error"]["message"]) + # data: and http(s) are the page's own to send: not refused by this check (no vision here, so a 400 of another kind) + for src in ("data:image/png;base64,iVBORw0KGgo=", "https://example.com/x.png"): + code, r = self.post(body(src), headers={"Origin": "https://evil.example.com"}) + self.assertNotIn("another origin", json.dumps(r)) + def test_json_schema_text_format(self): self.engine.scripts = [self.tok.encode("\n\n{\"n\": 3}<|im_end|>", parse_special=True)] self.engine.script = self.engine.scripts[0] diff --git a/serve/test_server.py b/serve/test_server.py index 34ef69e0b4..c2241ba28f 100644 --- a/serve/test_server.py +++ b/serve/test_server.py @@ -2713,6 +2713,18 @@ class ImageSources(unittest.TestCase): with self.subTest(src=src): self.assertEqual(Vision.load(src), b"\x89PNG\r\n\x1a\n") + def test_unreadable_sources_are_a_value_error(self): + """From #582: a bad data: URL or an unreadable file is a 400, not a dropped connection.""" + from serve.server import Vision + for src in ("data:image/png", "data:image/png;base64,abcde"): + with self.subTest(src=src), self.assertRaisesRegex(ValueError, "data: URL could not be read"): + Vision.load(src) + with tempfile.TemporaryDirectory() as d: + f = Path(d) / "x.png" + f.write_bytes(b"x") + with mock.patch.object(Path, "read_bytes", side_effect=PermissionError("denied")), self.assertRaisesRegex(ValueError, "could not be read from"): + Vision.load(str(f)) + def test_a_url_is_read_up_to_the_cap(self): import http.server import serve.server as server From 0b30051cb1ca4e47186c66209d362025a60197cb Mon Sep 17 00:00:00 2001 From: Strata Contributor Date: Sun, 4 Oct 2026 18:21:14 +0800 Subject: [PATCH 16/48] serve: invalidate the engine after fatal verification timeouts Maintainer: fatal lines checked before batch routing, 'an earlier window never finished' is fatal, alive() check in generate_batched, tests run on Windows (#748). --- serve/server.py | 22 +++++++ serve/test_fatal_recovery.py | 116 +++++++++++++++++++++++++++++++++++ 2 files changed, 138 insertions(+) create mode 100644 serve/test_fatal_recovery.py diff --git a/serve/server.py b/serve/server.py index 327c5ece0a..fc3b45d400 100644 --- a/serve/server.py +++ b/serve/server.py @@ -389,6 +389,12 @@ def btrace(*a): EOS_IDS = {248044, 248046} # <|endoftext|>, <|im_end|>: the engine's default --eos-ids +# The engine's own words for a verifier that cannot go on (its GPU waits were released, or an earlier window never +# finished, #267): the process may stay alive and even print DONE, but it must not take another request. +FATAL_PREFIXES = ("ERR verify: timed out at layer ", "ERR verify batch: timed out at layer ", + "ERR verify: an earlier window never finished", "ERR verify batch: an earlier window never finished") + + class StrataEngine: """The resident engine: `strata --serve` reads `GEN ` lines and streams `T ` lines, then `DONE ...`. Requests are serialized by the service's FIFO, so one pipe is enough. @@ -519,6 +525,18 @@ class StrataEngine: proc, lines = self.proc, self.lines # this process's: a restart replaces both (#344) slot_q = self.slot_q for line in proc.stdout: + # checked before batch routing: a fatal line is never a slot's own + if line.startswith(FATAL_PREFIXES): + # release_gpu_waits invalidates the verifier, even if the native + # process stays alive and prints DONE afterwards. + if self.proc is proc: + self.silent_note = "Unrecoverable native verification failure: " + line[4:].strip() + self.ended = True + try: + proc.terminate() + except OSError: + pass + break # publish EOF, never the trailing DONE if line.startswith(("BT ", "BDONE ")) and slot_q: # --batch: a batch slot's own lines try: slot_q[int(line.split()[1])].put(line) @@ -876,6 +894,8 @@ class StrataEngine: with a much shorter prompt (#656: `BYIELD `; the part read waits in a slot and the read goes on after). A consumer that stops early leaves the engine in step: the solo request is STOPped and read to its DONE, an admission to its BADM, a slot is BSTOPped and freed at its BDONE.""" + if not self.alive(): + raise EngineDied("the engine is unavailable; this request was not sent") self.progress = None keys = self.sampling_keys(sampling or {}) out: list[int] = [] @@ -1116,6 +1136,8 @@ class StrataEngine: """Yields token ids, and None as a heartbeat every 10 s while the engine is quiet (reading a long prompt): the HTTP layer turns it into an SSE comment, which keeps clients' watchdogs calm and notices a client that has gone. A consumer that stops early (or `cancel`) makes the engine STOP, so it does not run to max_new.""" + if not self.alive(): + raise EngineDied("the engine is unavailable; this request was not sent") if getattr(self, "batch", 0): yield from self.generate_batched(ids, max_new, sampling, cancel, embeddings) return diff --git a/serve/test_fatal_recovery.py b/serve/test_fatal_recovery.py new file mode 100644 index 0000000000..bdd378bc2f --- /dev/null +++ b/serve/test_fatal_recovery.py @@ -0,0 +1,116 @@ +"""Real pipe/process protocol regression for a native ERR that leaves its process alive.""" +import os +from pathlib import Path +import sys +import tempfile +import threading +import time +import unittest +import json +import urllib.request +from serve.server import StrataEngine, Service, ChatTemplate, EngineDied, serve +from serve.test_server import ByteTokenizer + +FAKE=r''' +import sys +from pathlib import Path +state=Path(sys.argv[sys.argv.index('--state')+1]) +mode=sys.argv[sys.argv.index('--mode')+1] +print('READY 4096 stop',flush=True) +for line in sys.stdin: + if line.startswith('QUIT'):break + if line.startswith(('GEN','BGEN')): + if not state.exists(): + state.write_text('first request was attempted') + if mode=='invalid':print('ERR prompt exceeds context',flush=True) + else: + kind='verify batch' if mode=='batch' else 'verify' + print(f'ERR {kind}: timed out at layer 18; its GPU waits were released and the GPU finished (#267)',flush=True) + print('DONE 0 1 0 1 error',flush=True) + continue + print('T 90\nDONE 1 1 0 1 stop',flush=True) +''' + +class FatalRecovery(unittest.TestCase): + def setUp(self): + self.tmp=tempfile.TemporaryDirectory();self.addCleanup(self.tmp.cleanup) + self.root=Path(self.tmp.name);py=self.root/'native.py' + if os.name=='nt': # no shebangs on Windows: a .cmd runs the same fake engine + py.write_text(FAKE);self.script=self.root/'native.cmd' + self.script.write_text(f'@"{sys.executable}" "{py}" %*\r\n') + else: + self.script=py;py.write_text('#!'+sys.executable+'\n'+FAKE);py.chmod(0o700) + def engine(self,mode='fatal'): + e=StrataEngine(str(self.script),['--state',str(self.root/'state'),'--mode',mode]) + self.addCleanup(e.close);return e + def service(self,e): + return Service(e,ByteTokenizer(),ChatTemplate(Path(__file__).parent/'chat_template.jinja')) + def wait_dead(self,e): + end=time.monotonic()+2 + while e.alive() and time.monotonic() Date: Mon, 5 Oct 2026 10:19:08 +0200 Subject: [PATCH 17/48] serve: a tool call inside the reasoning counts only for a declared tool (#804, strict form of #787) With tools declared, a in the reasoning is held whole; a declared name becomes a tool call, anything else (undeclared name, malformed, unfinished, cut by ) stays reasoning text. finish() never makes a call from it. Without tools the parser is byte-identical. Tests: parser (split tags, undeclared, no tools, unfinished), OpenAI and Anthropic finish reasons, Anthropic block order. Co-authored-by: kossum --- serve/frontend.py | 39 +++++++++- serve/server.py | 6 +- serve/test_reasoning_tools.py | 137 ++++++++++++++++++++++++++++++++++ 3 files changed, 176 insertions(+), 6 deletions(-) create mode 100644 serve/test_reasoning_tools.py diff --git a/serve/frontend.py b/serve/frontend.py index 02a1d2f9bc..34374109c2 100644 --- a/serve/frontend.py +++ b/serve/frontend.py @@ -601,10 +601,42 @@ class OutputParser: self.buf += delta out: list[Event] = [] while True: - if self.state == "reasoning": + if self.state == "rcall": + # #804: a `` inside the reasoning, with tools declared. It is held whole (never streamed + # as a call) until it ends: a declared name is then a tool call, anything else stays reasoning text. + body = self.buf[len(CALL_START):] + end, think = call_end(body), body.find(THINK_END) + if end >= 0 and (think < 0 or think >= end): + call = None + try: + name = body[:end].strip()[len("", 1)[0] + if name in self.schemas: + call = parse_tool_call(body[:end], self.schemas.get(name)) + except ValueError: + pass + if call is not None: + out.append(Event("tool_call", call=call)) + else: + out.append(Event("reasoning", self.buf[:len(CALL_START) + end + len(CALL_END)])) + self.buf = body[end + len(CALL_END):] + self.state = "reasoning" + elif think >= 0: # the thinking ended inside it: it never was a call + out.append(Event("reasoning", self.buf[:len(CALL_START) + think])) + self.buf = body[think:] + self.state = "reasoning" + else: + return out + elif self.state == "reasoning": i = self.buf.find(THINK_END) + tool = self.buf.find(CALL_START) if self.schemas else -1 + if tool >= 0 and (i < 0 or tool < i): + if tool: + out.append(Event("reasoning", self.buf[:tool])) + self.buf = self.buf[tool:] + self.state = "rcall" + continue if i < 0: - keep = self._hold(self.buf, (THINK_END,)) + keep = self._hold(self.buf, (THINK_END, CALL_START) if self.schemas else (THINK_END,)) if len(self.buf) > keep: out.append(Event("reasoning", self.buf[:len(self.buf) - keep])) self.buf = self.buf[len(self.buf) - keep:] @@ -669,7 +701,8 @@ class OutputParser: self._reset_scan() return out if self.buf: - kind = {"reasoning": "reasoning", "content": "content"}.get(self.state, "content") + # an unfinished call inside the reasoning (#804) is reasoning text, never a call + kind = {"reasoning": "reasoning", "rcall": "reasoning", "content": "content"}.get(self.state, "content") text = self.buf if self.state != "call" else CALL_START + self.buf out.append(Event(kind, text)) self.buf = "" diff --git a/serve/server.py b/serve/server.py index fc3b45d400..1048e91259 100644 --- a/serve/server.py +++ b/serve/server.py @@ -2381,7 +2381,7 @@ class Service: break raw_ids.append(t) seg.append(t) - thinking_n += parser.state == "reasoning" + thinking_n += parser.state in ("reasoning", "rcall") run_len = run_len + 1 if t == run_tok else 1 run_tok = t if self.repeat_stop_tokens and run_len >= self.repeat_stop_tokens: @@ -2433,7 +2433,7 @@ class Service: for t in extra: n += 1 raw_ids.append(t) - thinking_n += parser.state == "reasoning" + thinking_n += parser.state in ("reasoning", "rcall") evs = parser.feed(detok.push(t)) self._note(n, evs, st, rate) for ev in evs: @@ -2507,7 +2507,7 @@ class Service: hit_msg += f" (+{pcie_share*100:.1f}% of the routed experts over PCIe)" print(f"[strata] done: {n} tokens in {el:.0f} s ({rate:.1f} tok/s) " f"({finish}, cancel={cancel.is_set()}){hit_msg}", flush=True) - if finish == "length" and parser.state == "reasoning": # #530 + if finish == "length" and parser.state in ("reasoning", "rcall"): # #530 print("[strata] the reply reached max tokens while still thinking, so it has no " "answer: a thinking budget (reasoning_budget_tokens, in the request or in " "strata-.json for every request) leaves room to answer", flush=True) diff --git a/serve/test_reasoning_tools.py b/serve/test_reasoning_tools.py new file mode 100644 index 0000000000..a75adcd1d7 --- /dev/null +++ b/serve/test_reasoning_tools.py @@ -0,0 +1,137 @@ +"""serve/test_reasoning_tools.py - #804 (strict form of PR #787): a tool call the model writes inside its reasoning. + +A call inside the reasoning counts only when tools are declared and the name is one of them; anything else stays +reasoning text. Without tools the parser is byte-identical to before. + + python -m unittest serve.test_reasoning_tools -v +""" +from __future__ import annotations + +import json +import sys +import unittest +import urllib.request +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from serve.frontend import ChatTemplate, OutputParser # noqa: E402 +from serve.server import ByteTokenizer, MockEngine, Service, serve # noqa: E402 +from serve.test_server import CTX, UnfinishedToolCall # noqa: E402 + +ROOT = Path(__file__).resolve().parents[1] +CALL = "\n\n\n120\n\n\nfile.txt\n\n\n" +OTHER = CALL.replace("read_file", "not_declared") +TOOLS = [{"name": "read_file", "parameters": {"properties": {"limit": {"type": "integer"}, "path": {"type": "string"}}}}] + + +def run(text, width, tools=TOOLS, thinking=True, stream_tools=True): + p = OutputParser(thinking=thinking, tools=tools, stream_tools=stream_tools) + evs = [] + for i in range(0, len(text), width): + evs += p.feed(text[i:i + width]) + return evs + p.finish() + + +def joined(evs, kind): + return "".join(e.text for e in evs if e.kind == kind) + + +class Parser(unittest.TestCase): + def test_a_declared_call_in_the_reasoning_is_a_call(self): + text = "before " + CALL + " after\n\nanswer" + for width in (1, 2, 7, 100_000): + with self.subTest(width=width): + evs = run(text, width) + calls = [e.call for e in evs if e.kind == "tool_call"] + self.assertEqual([(c.name, c.arguments) for c in calls], + [("read_file", {"limit": 120, "path": "file.txt"})]) + self.assertEqual(joined(evs, "reasoning"), "before after") + self.assertEqual(joined(evs, "content"), "answer") + self.assertFalse([e for e in evs if e.kind in ("tool_start", "tool_args")]) # never streamed + + def test_an_undeclared_name_stays_reasoning(self): + text = "see " + OTHER + " done\n\nanswer" + for width in (1, 5, 100_000): + with self.subTest(width=width): + evs = run(text, width) + self.assertFalse([e for e in evs if e.kind == "tool_call"]) + self.assertEqual(joined(evs, "reasoning"), "see " + OTHER + " done") + self.assertEqual(joined(evs, "content"), "answer") + + def test_no_tools_declared_is_unchanged(self): + text = "before " + CALL + " after\n\nanswer" + for tools in (None, []): + for width in (1, 7, 100_000): + with self.subTest(tools=tools, width=width): + evs = run(text, width, tools=tools) + self.assertFalse([e for e in evs if e.kind == "tool_call"]) + self.assertEqual(joined(evs, "reasoning"), "before " + CALL + " after") + self.assertEqual(joined(evs, "content"), "answer") + + def test_an_unfinished_call_is_never_a_call(self): + for text in ("before\n\n", + "before\n\n\nfile.txt\n\n"): + for width in (1, 100_000): + with self.subTest(text=text[-20:], width=width): + evs = run(text, width) + self.assertFalse([e for e in evs if e.kind == "tool_call"]) + self.assertEqual(joined(evs, "reasoning"), text) + + def test_the_thinking_ending_inside_a_call_makes_it_text(self): + text = "a\n\nhmm\n\nthe answer" + for width in (1, 100_000): + with self.subTest(width=width): + evs = run(text, width) + self.assertFalse([e for e in evs if e.kind == "tool_call"]) + self.assertEqual(joined(evs, "reasoning"), "a\n\nhmm") + self.assertEqual(joined(evs, "content"), "the answer") + + def test_a_call_in_the_answer_is_unchanged(self): + text = "think\n\nok " + CALL + for width in (1, 100_000): + evs = run(text, width) + self.assertEqual(len([e for e in evs if e.kind == "tool_call"]), 1) + self.assertEqual(joined(evs, "reasoning"), "think") + + def test_a_partial_tag_is_held(self): + p = OutputParser(thinking=True, tools=TOOLS) + evs = p.feed("hello "), "reasoning"), " More thought.\n\ndone" + a = helper.answers(script) + self.assertEqual((a["openai", False][0], [json.loads(x) for x in a["openai", False][1]]), + ("tool_calls", [{"path": "file.txt"}])) + self.assertEqual(a["anthropic", False], ("tool_use", [{"path": "file.txt"}])) + # the order of the Anthropic stream's blocks: thinking, the call, more thinking, the answer + tok = ByteTokenizer() + svc = Service(MockEngine(tok, script, max_context=CTX), tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) + httpd = serve(svc, port=0) + try: + body = {"model": "x", "max_tokens": 500, "stream": True, "messages": [{"role": "user", "content": "hi"}], + "tools": [{"name": "write", "input_schema": {"type": "object", "properties": helper.PROPS}}]} + req = urllib.request.Request(f"http://127.0.0.1:{httpd.server_address[1]}/v1/messages", + data=json.dumps(body).encode(), headers={"Content-Type": "application/json", + "anthropic-version": "2023-06-01"}) + with urllib.request.urlopen(req, timeout=30) as r: + raw = r.read().decode() + evs = [json.loads(line[6:]) for line in raw.splitlines() if line.startswith("data: {")] + order = [e["content_block"]["type"] for e in evs if e["type"] == "content_block_start"] + self.assertEqual(order, ["thinking", "tool_use", "thinking", "text"]) + tool = [e["delta"]["partial_json"] for e in evs if e["type"] == "content_block_delta" + and e["delta"]["type"] == "input_json_delta"] + self.assertEqual(json.loads("".join(tool)), {"path": "file.txt"}) + finally: + httpd.shutdown() + httpd.server_close() + + +if __name__ == "__main__": + unittest.main() From ffbc39f4fb2eb6de793313a7d3fa03f1f9803748 Mon Sep 17 00:00:00 2001 From: Arthur031221 Date: Mon, 5 Oct 2026 12:25:03 +0800 Subject: [PATCH 18/48] serve: skip completed empty assistant turns in chat history Filter earlier assistant messages with no text, images or tool calls before rendering the prompt. Keep the final message. Co-authored-by: jramirez-uab <238218748+jramirez-uab@users.noreply.github.com> Signed-off-by: Arthur031221 --- serve/frontend.py | 5 +++ serve/test_frontend.py | 81 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 86 insertions(+) create mode 100644 serve/test_frontend.py diff --git a/serve/frontend.py b/serve/frontend.py index 34374109c2..0733e8e8be 100644 --- a/serve/frontend.py +++ b/serve/frontend.py @@ -49,6 +49,11 @@ class ChatTemplate: def render(self, messages: list[dict], tools: list[dict] | None = None, add_generation_prompt: bool = True, **kwargs) -> str: + # Do not use completed empty assistant turns as examples for the next reply. Keep the final message. + messages = [m for i, m in enumerate(messages) + if i == len(messages) - 1 or not (isinstance(m, dict) and m.get("role") == "assistant" + and not _text_of(m.get("content")).strip() + and not _has_image(m.get("content")) and not m.get("tool_calls"))] return self.template.render(messages=messages, tools=tools, add_generation_prompt=add_generation_prompt, **kwargs) diff --git a/serve/test_frontend.py b/serve/test_frontend.py new file mode 100644 index 0000000000..8591538267 --- /dev/null +++ b/serve/test_frontend.py @@ -0,0 +1,81 @@ +"""Chat history normalization before rendering the model's prompt.""" +import copy +from pathlib import Path +import unittest + +from serve.frontend import ChatTemplate, anthropic_to_messages, openai_to_messages +from serve.server import ByteTokenizer, MockEngine, Service + + +class EmptyAssistantHistory(unittest.TestCase): + def setUp(self): + self.template = ChatTemplate(Path(__file__).with_name("chat_template.jinja")) + tok = ByteTokenizer() + self.service = Service(MockEngine(tok, "ok"), tok, self.template) + + def test_openai_empty_replies_are_not_rendered(self): + for content in (None, "", " \n\t", [], [{"type": "text", "text": ""}]): + for preserve in (True, False): + with self.subTest(content=content, preserve_thinking=preserve): + history = [] + for _ in range(3): + history.extend([{"role": "user", "content": "haz un ls"}, + {"role": "assistant", "content": content, + "reasoning_content": "Let me run ls."}]) + history.append({"role": "user", "content": "haz un ls"}) + messages, tools, kwargs = openai_to_messages({"messages": history}) + kwargs["preserve_thinking"] = preserve + clean = [m for m in messages if m["role"] == "user"] + self.assertEqual(self.service.encode_prompt(messages, tools, kwargs), + self.service.encode_prompt(clean, tools, kwargs)) + + def test_anthropic_thinking_only_replies_are_not_rendered(self): + messages, tools, kwargs = anthropic_to_messages({"messages": [ + {"role": "user", "content": "haz un ls"}, + {"role": "assistant", "content": [{"type": "thinking", "thinking": "Let me run ls."}]}, + {"role": "user", "content": "haz un ls"}, + ]}) + self.assertEqual(self.service.encode_prompt(messages, tools, kwargs), + self.service.encode_prompt([messages[0], messages[2]], tools, kwargs)) + + def test_text_and_tool_calls_are_kept(self): + messages, tools, kwargs = openai_to_messages({"messages": [ + {"role": "user", "content": "haz un ls"}, + {"role": "assistant", "content": [{"type": "text", "text": "Running ls."}]}, + {"role": "assistant", "content": None, "tool_calls": [ + {"type": "function", "function": {"name": "run", "arguments": '{"command":"ls"}'}}, + ]}, + {"role": "tool", "content": "file.txt"}, + {"role": "user", "content": "thanks"}, + ]}) + before = copy.deepcopy(messages) + prompt = self.template.render(messages, tools=tools, **kwargs) + self.assertIn("Running ls.", prompt) + self.assertIn("", prompt) + self.assertIn("file.txt", prompt) + self.assertEqual(messages, before) + + def test_image_only_assistant_turn_is_kept(self): + messages, tools, kwargs = openai_to_messages({"messages": [ + {"role": "user", "content": "describe the image"}, + {"role": "assistant", "content": [{"type": "image_url", "image_url": "image.png"}]}, + {"role": "user", "content": "thanks"}, + ]}) + self.assertIn("<|vision_start|><|image_pad|><|vision_end|>", + self.template.render(messages, tools=tools, **kwargs)) + + def test_final_empty_assistant_turn_is_kept(self): + prompt = self.template.render([{"role": "user", "content": "hi"}, + {"role": "assistant", "content": ""}], add_generation_prompt=False) + self.assertIn("<|im_start|>assistant\n", prompt) + + def test_empty_user_and_tool_turns_are_kept(self): + prompt = self.template.render([{"role": "user", "content": ""}, + {"role": "tool", "content": ""}, + {"role": "user", "content": "hi"}]) + self.assertEqual(prompt.count("<|im_start|>user\n"), 3) + self.assertIn("\n\n", prompt) + + +if __name__ == "__main__": + unittest.main() From 9cd3d00b6d0331de4f2e71cdc1ac2519ccd998c1 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 5 Oct 2026 10:19:37 +0200 Subject: [PATCH 19/48] serve: STRATA_KEEP_EMPTY_TURNS=1 restores rendering of empty assistant turns (#843) #886 skips them by default (recommended on; the owner can flip it). Only prompts that carry an empty assistant turn change. --- serve/frontend.py | 4 +++- serve/test_frontend.py | 13 +++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/serve/frontend.py b/serve/frontend.py index 0733e8e8be..643962832d 100644 --- a/serve/frontend.py +++ b/serve/frontend.py @@ -16,6 +16,7 @@ and the formats change often; the engine boundary is token ids in, text deltas o from __future__ import annotations import json +import os import re import uuid from dataclasses import dataclass, field @@ -50,8 +51,9 @@ class ChatTemplate: def render(self, messages: list[dict], tools: list[dict] | None = None, add_generation_prompt: bool = True, **kwargs) -> str: # Do not use completed empty assistant turns as examples for the next reply. Keep the final message. + # (#843. STRATA_KEEP_EMPTY_TURNS=1 renders them as before.) messages = [m for i, m in enumerate(messages) - if i == len(messages) - 1 or not (isinstance(m, dict) and m.get("role") == "assistant" + if i == len(messages) - 1 or os.environ.get("STRATA_KEEP_EMPTY_TURNS") == "1" or not (isinstance(m, dict) and m.get("role") == "assistant" and not _text_of(m.get("content")).strip() and not _has_image(m.get("content")) and not m.get("tool_calls"))] return self.template.render(messages=messages, tools=tools, add_generation_prompt=add_generation_prompt, diff --git a/serve/test_frontend.py b/serve/test_frontend.py index 8591538267..714dee270a 100644 --- a/serve/test_frontend.py +++ b/serve/test_frontend.py @@ -79,3 +79,16 @@ class EmptyAssistantHistory(unittest.TestCase): if __name__ == "__main__": unittest.main() + + +class EmptyTurnsSwitch(unittest.TestCase): + def test_keep_empty_turns_restores_the_old_prompt(self): + import os + from unittest import mock + template = ChatTemplate(Path(__file__).with_name("chat_template.jinja")) + msgs = [{"role": "user", "content": "a"}, {"role": "assistant", "content": ""}, + {"role": "user", "content": "b"}] + clean = template.render([msgs[0], msgs[2]]) + self.assertEqual(template.render(msgs), clean) + with mock.patch.dict(os.environ, {"STRATA_KEEP_EMPTY_TURNS": "1"}): + self.assertNotEqual(template.render(msgs), clean) From d398d7c33f61d1966704674a85c4057e1e346080 Mon Sep 17 00:00:00 2001 From: Pravesh Khatana Date: Fri, 2 Oct 2026 21:22:14 +0530 Subject: [PATCH 20/48] fix(serve): safely handle malformed or partial tool call arguments in history Maintainer: one frontend.tool_arguments helper for both frontends, bad JSON, a list or a number is kept as {"arguments": raw}; tests (#510) --- serve/frontend.py | 24 +++++++++++++++++++----- serve/server.py | 1 + serve/test_server.py | 36 ++++++++++++++++++++++++++++++++++++ 3 files changed, 56 insertions(+), 5 deletions(-) diff --git a/serve/frontend.py b/serve/frontend.py index 643962832d..4d2310ce29 100644 --- a/serve/frontend.py +++ b/serve/frontend.py @@ -264,6 +264,23 @@ def _tool_list(value, wrapper: str | None) -> list[dict]: return tools +def tool_arguments(raw) -> dict: + """A call's arguments from a client's history -> the mapping the template renders (both APIs). A JSON object + (as text or already parsed) is used as it is; empty is {}; anything else (cut-off or malformed JSON, a list, a + number) is kept as text under "arguments" instead of refusing the whole conversation (#510).""" + if raw is None or (isinstance(raw, str) and not raw.strip()): + return {} + if isinstance(raw, dict): + return raw + if isinstance(raw, str): + try: + value = json.loads(raw) + except ValueError: + return {"arguments": raw} + return value if isinstance(value, dict) else {"arguments": raw} + return {"arguments": json.dumps(raw, ensure_ascii=False)} + + def openai_to_messages(req: dict) -> tuple[list[dict], list[dict] | None, dict]: """OpenAI Chat Completions -> (template messages, template tools, template kwargs).""" messages = [] @@ -280,10 +297,7 @@ def openai_to_messages(req: dict) -> tuple[list[dict], list[dict] | None, dict]: fn = c.get("function", c) if not isinstance(fn, dict): raise ValueError("tool_calls must be a list of objects (each with a \"function\" object)") - args = fn.get("arguments") - if isinstance(args, str): # the template requires a mapping, not a JSON string - args = json.loads(args) if args.strip() else {} - calls.append({"function": {"name": fn.get("name"), "arguments": args or {}}}) + calls.append({"function": {"name": fn.get("name"), "arguments": tool_arguments(fn.get("arguments"))}}) out["tool_calls"] = calls messages.append(out) tools = [t.get("function", t) if t.get("type") == "function" else t @@ -326,7 +340,7 @@ def anthropic_to_messages(req: dict, think_unasked: bool = True) -> tuple[list[d elif kind == "thinking": reasoning.append(block.get("thinking", "")) elif kind == "tool_use": - calls.append({"function": {"name": block.get("name"), "arguments": block.get("input") or {}}}) + calls.append({"function": {"name": block.get("name"), "arguments": tool_arguments(block.get("input"))}}) elif kind == "tool_result": messages.append({"role": "tool", "content": _text_of(block.get("content"))}) if text or calls or reasoning: diff --git a/serve/server.py b/serve/server.py index 1048e91259..838068bd3a 100644 --- a/serve/server.py +++ b/serve/server.py @@ -3232,6 +3232,7 @@ def make_handler(svc: Service): else: self._json(404, {"error": {"message": "not found"}}) except ValueError as e: + print(f"[strata] 400 invalid request: {e}", flush=True) if path == "/v1/responses": self._json(400, responses_error_body(str(e))) else: diff --git a/serve/test_server.py b/serve/test_server.py index c2241ba28f..e5c9e2c003 100644 --- a/serve/test_server.py +++ b/serve/test_server.py @@ -766,6 +766,42 @@ class ClientShapes(unittest.TestCase): with self.subTest(calls=calls), self.assertRaisesRegex(ValueError, "tool_calls must be a list of objects"): openai_to_messages({"messages": [{"role": "assistant", "content": "", "tool_calls": calls}]}) + def test_tool_call_malformed_arguments_fallback(self): + from serve.frontend import openai_to_messages + bad_call = [{"id": "c1", "type": "function", "function": {"name": "f", "arguments": "{malformed_json"}}] + msgs, tools, kwargs = openai_to_messages({"messages": [{"role": "user", "content": "u"}, + {"role": "assistant", "content": "", "tool_calls": bad_call}]}) + self.assertEqual(msgs[1]["tool_calls"], [{"function": {"name": "f", "arguments": {"arguments": "{malformed_json"}}}]) + tpl = ChatTemplate(ROOT / "serve/chat_template.jinja") + rendered = tpl.render(msgs, tools=tools, **kwargs) + self.assertIn("", rendered) + self.assertIn("\n{malformed_json", rendered) + + +class ToolArguments(unittest.TestCase): + """#510: one helper for both frontends; a history whose arguments are not a JSON object is kept, not a 500.""" + + def test_helper(self): + from serve.frontend import tool_arguments + for raw, want in ((None, {}), ("", {}), (" ", {}), ({"a": 1}, {"a": 1}), ('{"a": 1}', {"a": 1}), + ("{cut", {"arguments": "{cut"}), ("[1, 2]", {"arguments": "[1, 2]"}), + ("5", {"arguments": "5"}), ([1, 2], {"arguments": "[1, 2]"}), (7, {"arguments": "7"})): + with self.subTest(raw=raw): + self.assertEqual(tool_arguments(raw), want) + + def test_both_frontends_render_it(self): + from serve.frontend import anthropic_to_messages, openai_to_messages + for bad in ("{cut", "[1]", "3"): + with self.subTest(bad=bad): + m = openai_to_messages({"messages": [{"role": "user", "content": "u"}, {"role": "assistant", "content": "", + "tool_calls": [{"id": "c", "type": "function", "function": {"name": "f", "arguments": bad}}]}]})[0] + self.assertEqual(m[1]["tool_calls"][0]["function"]["arguments"], {"arguments": bad}) + for bad in ([1], 3, "{cut"): + with self.subTest(anthropic=bad): + m = anthropic_to_messages({"messages": [{"role": "user", "content": "u"}, {"role": "assistant", "content": [ + {"type": "tool_use", "id": "t", "name": "f", "input": bad}]}]})[0] + self.assertIn("arguments", m[1]["tool_calls"][0]["function"]["arguments"]) + class SamplingKeys(unittest.TestCase): """The GEN line's sampling keys: top_k 0 ("off") or wider than the engine's 64 get the widest list, 64 (they used From e7c2edb8573cdea1ac842efbb650130e089895f8 Mon Sep 17 00:00:00 2001 From: Zuraiz Anjum Date: Fri, 2 Oct 2026 05:33:27 +0500 Subject: [PATCH 21/48] serve: honor stop and stop_sequences, cut the answer before the stop string and stop the engine there --- docs/DETAILS.md | 4 +- serve/server.py | 113 +++++++++++++++++++++++++++++++++++--- serve/test_server.py | 127 +++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 236 insertions(+), 8 deletions(-) diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 78390cefa3..a1aa466b56 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -686,7 +686,9 @@ persisted across restarts. **Current limits (v1):** one request at a time unless `"parallel": N` is set (opt-in batch slots, up to N requests decoded together: [BATCHING.md](BATCHING.md)), and one conversation cached at a time (switching between two chats re-reads the other one unless the opt-in cache above is enabled, or each conversation keeps its own batch slot); images only when set up with them (below); no video. **Temperature / top_p / top_k / min_p / -seed** are honored per request (OpenAI and Anthropic fields); with the default adaptive expert tier a sampled result +seed** are honored per request (OpenAI and Anthropic fields), and so are stop strings (OpenAI `stop`, a string or up +to 4; Anthropic `stop_sequences`): the answer ends before the first one, which is not sent, and the engine stops +there (`finish_reason` "stop"; `stop_reason` "stop_sequence" with `stop_sequence` set to the one found); with the default adaptive expert tier a sampled result is not reproducible run to run - for seed-reproducible output add `--adapt-every 100000` (static residency) to the engine arguments. The run config's optional `sampling` block sets the defaults for requests that leave the fields out (`"sampling": {"temperature": 1.0, "top_p": 0.95, "top_k": 20}`); a request's own fields always win, and with no diff --git a/serve/server.py b/serve/server.py index 838068bd3a..496f6f8053 100644 --- a/serve/server.py +++ b/serve/server.py @@ -1713,6 +1713,63 @@ class Detokenizer: return delta +OPENAI_MAX_STOP = 4 # OpenAI's limit on `stop` + + +def stop_strings(req: dict) -> list[str]: + """The request's stop strings: OpenAI's `stop` (a string or a list of up to 4) or Anthropic's `stop_sequences` + (a list). Empty strings are left out. A bad value is a ValueError, so a 400 before anything is generated.""" + req = req or {} + if req.get("stop") is not None: + stop = req["stop"] + stop = [stop] if isinstance(stop, str) else stop + if not isinstance(stop, list) or not all(isinstance(x, str) for x in stop): + raise ValueError("stop must be a string or a list of strings") + if len(stop) > OPENAI_MAX_STOP: + raise ValueError(f"stop takes at most {OPENAI_MAX_STOP} strings") + elif req.get("stop_sequences") is not None: + stop = req["stop_sequences"] + if not isinstance(stop, list) or not all(isinstance(x, str) for x in stop): + raise ValueError("stop_sequences must be a list of strings") + else: + return [] + return [x for x in stop if x] + + +class StopMatcher: + """Cuts the answer's text at the first stop string. Text that could still be the start of a stop string is held + back (only that tail, never more), so a stop string split across tokens or chunks is still found and never sent.""" + + def __init__(self, stops: list[str]): + self.stops, self.held, self.hit = stops, "", None + + def push(self, text: str) -> str: + """-> the text that is safe to send now; after a match, self.hit is the stop string and nothing more comes.""" + if self.hit is not None: + return "" + buf = self.held + text + first = None + for s in self.stops: + i = buf.find(s) + if i >= 0 and (first is None or i < first[0]): + first = (i, s) + if first is not None: + self.held, self.hit = "", first[1] + return buf[:first[0]] + keep = 0 # the longest end of buf that a stop string starts with + for s in self.stops: + for k in range(min(len(s) - 1, len(buf)), keep, -1): + if buf.endswith(s[:k]): + keep = k + break + self.held = buf[len(buf) - keep:] if keep else "" + return buf[:len(buf) - keep] + + def flush(self) -> str: + held, self.held = self.held, "" + return held + + class Service: def __init__(self, engine: Engine, tokenizer, template: ChatTemplate, model_name: str = "qwen3.8-flash-next", vision: Vision | None = None, sampling_defaults: dict | None = None, @@ -2321,6 +2378,27 @@ class Service: detok, n, finish = Detokenizer(self.tok), 0, "length" run_tok, run_len, repeated = None, 0, False # #606: the current run of one repeated token thinking_n = 0 # tokens written while thinking (Responses' reasoning_tokens) + stop_list = stop_strings(sampling) + stops = StopMatcher(stop_list) if stop_list else None + + def cut(evs): + """The events with the answer's text cut at a stop string (OpenAI stop, Anthropic stop_sequences).""" + if stops is None: + return evs + out = [] + for ev in evs: + if stops.hit is not None: + break # nothing after the stop string is sent + if ev.kind == "content": + text = stops.push(ev.text or "") + if text: + out.append(Event("content", text)) + continue + held = stops.flush() # a stop string does not run across a tool call or thinking + if held: + out.append(Event("content", held)) + out.append(ev) + return out timings, before = None, None # this request's timings; the engine's `last` before it raw_ids = [] # every generated id (STRATA_DEBUG: dump raw model text) emb = getattr(self.embeddings, "path", None) @@ -2387,11 +2465,14 @@ class Service: if self.repeat_stop_tokens and run_len >= self.repeat_stop_tokens: repeated = True # #606: a degenerate output, not an answer: end it here break - evs = parser.feed(detok.push(t)) + evs = cut(parser.feed(detok.push(t))) self._note(n, evs, st, rate) last_print = self._progress(last_print, st=st) for ev in evs: yield "event", ev + if stops is not None and stops.hit is not None: + finish = "stop" # gen.close() below STOPs the engine, as for a stop token + break if budget and parser.state == "reasoning": thought += 1 # at a clean point: no tag held back, no character split across tokens @@ -2434,10 +2515,13 @@ class Service: n += 1 raw_ids.append(t) thinking_n += parser.state in ("reasoning", "rcall") - evs = parser.feed(detok.push(t)) + evs = cut(parser.feed(detok.push(t))) self._note(n, evs, st, rate) for ev in evs: yield "event", ev + if stops is not None and stops.hit is not None: + finish = "stop" + break prompt = prompt + seg + extra if cancel.is_set(): finish = "cancel" @@ -2527,10 +2611,15 @@ class Service: finally: if emb: Path(emb).unlink(missing_ok=True) - for ev in parser.finish(): + for ev in cut(parser.finish()): yield "event", ev - yield "done", {"finish": finish, "completion_tokens": n, "reused": (timings or {}).get("cache_n", 0), - "timings": timings, "reasoning_tokens": thinking_n} + if stops is not None and stops.hit is None and stops.held: + yield "event", Event("content", stops.flush()) # the held tail was not a stop string after all + done = {"finish": finish, "completion_tokens": n, "reused": (timings or {}).get("cache_n", 0), + "timings": timings, "reasoning_tokens": thinking_n} + if stops is not None and stops.hit is not None: + done["stop_sequence"] = stops.hit + yield "done", done def prompt_tokens_seen(prompt_tokens: int, last: dict) -> int: @@ -2848,12 +2937,14 @@ def anthropic_events(svc: Service, req: dict, ids, thinking, tools, max_new, can else: if open_kind is not None: yield close() - stop = "tool_use" if used_tool and streamed <= finished and x["finish"] == "stop" else \ + stop = "stop_sequence" if x.get("stop_sequence") is not None else \ + "tool_use" if used_tool and streamed <= finished and x["finish"] == "stop" else \ {"stop": "end_turn", "length": "max_tokens", "cancel": "end_turn"}[x["finish"]] # the final counts, Anthropic's way: input_tokens leaves out what the conversation cache already held, # which is cache_read_input_tokens (message_start could only say the whole prompt) reused = min(x.get("reused") or 0, len(ids)) - yield "message_delta", {"type": "message_delta", "delta": {"stop_reason": stop, "stop_sequence": None}, + yield "message_delta", {"type": "message_delta", "delta": {"stop_reason": stop, + "stop_sequence": x.get("stop_sequence")}, "usage": {"input_tokens": len(ids) - reused, "cache_read_input_tokens": reused, "output_tokens": x["completion_tokens"]}} yield "message_stop", {"type": "message_stop"} @@ -2885,6 +2976,7 @@ def anthropic_collect(events) -> dict: blocks.pop() elif name == "message_delta": msg["stop_reason"] = e["delta"]["stop_reason"] + msg["stop_sequence"] = e["delta"].get("stop_sequence") msg["usage"].update(e["usage"]) msg["content"] = blocks return msg @@ -3462,6 +3554,7 @@ def make_handler(svc: Service): use_mcp = bool(extra) tools = (tools or []) + extra or None svc.reasoning_budget(req) # a bad value is a 400 before anything is sent + stop_strings(req) # ... and so is a bad stop / stop_sequences ids, thinking, max_new = svc.prepare(messages, tools, kw, max_new) _debug_req("openai", req, messages, tools, max_new, thinking, len(ids)) cancel = threading.Event() @@ -3610,6 +3703,10 @@ def make_handler(svc: Service): svc.reasoning_budget(req) # a bad value is a 400 before anything is sent except ValueError as e: raise ResponsesError(str(e), "reasoning_budget_tokens") from None + try: + stop_strings(req) + except ValueError as e: + raise ResponsesError(str(e), "stop") from None svc.load() try: ids, thinking, max_new = svc.prepare(messages, tools, kw, req.get("max_output_tokens") or 0) @@ -3630,6 +3727,7 @@ def make_handler(svc: Service): read for the same request, rendered and tokenized - the model does not run.""" req = svc.with_shared(req, "anthropic") messages, tools, kw = anthropic_to_messages(req, svc.anthropic_think_unasked) + stop_strings(req) # the same 400 as the request itself would get self._json(200, {"input_tokens": len(svc.encode_prompt(messages, tools, kw))}) def _anthropic(self, req): @@ -3639,6 +3737,7 @@ def make_handler(svc: Service): self._no_local_images(messages) max_new = int(req.get("max_tokens") or 0) # 0/-1: the rest of the context svc.reasoning_budget(req) # a bad value is a 400 before anything is sent + stop_strings(req) # ... and so is a bad stop / stop_sequences ids, thinking, max_new = svc.prepare(messages, tools, kw, max_new) _debug_req("anthropic", req, messages, tools, max_new, thinking, len(ids)) cancel = threading.Event() diff --git a/serve/test_server.py b/serve/test_server.py index e5c9e2c003..266df8e92b 100644 --- a/serve/test_server.py +++ b/serve/test_server.py @@ -2874,5 +2874,132 @@ class ImageSources(unittest.TestCase): httpd.server_close() +class CountingEngine(MockEngine): + """Counts the tokens the engine was asked for, so a test can see it stopped early.""" + def generate(self, ids, max_new, sampling, cancel, embeddings=None): + self.yielded = 0 + for t in super().generate(ids, max_new, sampling, cancel, embeddings): + self.yielded += 1 + yield t + + +class StopStrings(unittest.TestCase): + """OpenAI `stop` and Anthropic `stop_sequences`: the answer ends before the first stop string, which is not sent, + and the engine stops there. The byte tokenizer gives one token per byte, so every stop string here is split + across tokens (and across streamed chunks).""" + ANSWER = "alpha END beta STOP gamma" + + @classmethod + def setUpClass(cls): + tok = ByteTokenizer() + cls.engine = CountingEngine(tok, "\n\n" + cls.ANSWER, max_context=CTX) + cls.svc = Service(cls.engine, tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) + cls.httpd = serve(cls.svc, port=0) + cls.base = f"http://127.0.0.1:{cls.httpd.server_address[1]}" + + @classmethod + def tearDownClass(cls): + cls.httpd.shutdown() + cls.httpd.server_close() + + def post(self, api, stream, **extra): + """-> (status, text, finish or stop_reason, stop_sequence, the streamed text pieces)""" + path = "/v1/chat/completions" if api == "openai" else "/v1/messages" + body = {"model": "x", "max_tokens": 200, "stream": stream, "messages": [{"role": "user", "content": "hi"}], + **extra} + req = urllib.request.Request(self.base + path, data=json.dumps(body).encode(), headers={ + "Content-Type": "application/json", "anthropic-version": "2023-06-01"}) + try: + with urllib.request.urlopen(req, timeout=30) as r: + raw = r.read().decode() + except urllib.error.HTTPError as e: + with e: + return e.code, json.loads(e.read()), None, None, None + if not stream: + b = json.loads(raw) + if api == "openai": + c = b["choices"][0] + return 200, c["message"]["content"] or "", c["finish_reason"], None, None + text = "".join(x.get("text", "") for x in b["content"] if x["type"] == "text") + return 200, text, b["stop_reason"], b["stop_sequence"], None + evs = [json.loads(line[6:]) for line in raw.splitlines() if line.startswith("data: {")] + if api == "openai": + pieces = [e["choices"][0]["delta"].get("content") or "" for e in evs] + return 200, "".join(pieces), evs[-1]["choices"][0]["finish_reason"], None, [p for p in pieces if p] + pieces = [e["delta"]["text"] for e in evs if e["type"] == "content_block_delta" + and e["delta"]["type"] == "text_delta"] + delta = [e for e in evs if e["type"] == "message_delta"][0]["delta"] + return 200, "".join(pieces), delta["stop_reason"], delta["stop_sequence"], pieces + + def stop_field(self, api, stops): + return {"stop": stops} if api == "openai" else {"stop_sequences": stops} + + def test_cut_at_the_stop_string(self): + for api in ("openai", "anthropic"): + for stream in (False, True): + with self.subTest(api=api, stream=stream): + code, text, finish, seq, pieces = self.post(api, stream, **self.stop_field(api, ["END"])) + self.assertEqual(code, 200, text) + self.assertEqual(text, "alpha ") + if api == "openai": + self.assertEqual(finish, "stop") + else: + self.assertEqual((finish, seq), ("stop_sequence", "END")) + if stream: + self.assertFalse(any("E" in p for p in pieces), pieces) # no part of it was sent + # the engine stopped at the stop string, it did not run to the end of the answer + self.assertLess(self.engine.yielded, len("\n\n" + self.ANSWER)) + + def test_the_first_of_several(self): + for api in ("openai", "anthropic"): + for stream in (False, True): + with self.subTest(api=api, stream=stream): + _, text, finish, seq, _ = self.post(api, stream, **self.stop_field(api, ["STOP", "beta", "zzz"])) + self.assertEqual(text, "alpha END ") + if api == "anthropic": + self.assertEqual((finish, seq), ("stop_sequence", "beta")) + + def test_openai_takes_a_string(self): + _, text, finish, _, _ = self.post("openai", False, stop="STOP") + self.assertEqual((text, finish), ("alpha END beta ", "stop")) + + def test_a_prefix_that_is_not_a_stop_is_sent(self): + """"ENDX" begins like the answer's "END" but is not in it: the held tail goes out and nothing is lost.""" + for api in ("openai", "anthropic"): + for stream in (False, True): + with self.subTest(api=api, stream=stream): + _, text, finish, seq, _ = self.post(api, stream, **self.stop_field(api, ["ENDX", "gammaZ"])) + self.assertEqual(text, self.ANSWER) + self.assertEqual(finish, "stop" if api == "openai" else "end_turn") + self.assertIsNone(seq) + + def test_no_stop_and_an_empty_list(self): + for api in ("openai", "anthropic"): + for stream in (False, True): + for extra in ({}, self.stop_field(api, []), self.stop_field(api, ["nowhere"])): + with self.subTest(api=api, stream=stream, extra=extra): + _, text, finish, seq, _ = self.post(api, stream, **extra) + self.assertEqual(text, self.ANSWER) + self.assertEqual(finish, "stop" if api == "openai" else "end_turn") + self.assertIsNone(seq) + + def test_bad_values_are_a_400(self): + for api, extra in (("openai", {"stop": ["a", "b", "c", "d", "e"]}), ("openai", {"stop": 5}), + ("anthropic", {"stop_sequences": "END"}), ("anthropic", {"stop_sequences": [1]})): + with self.subTest(api=api, extra=extra): + code, *_ = self.post(api, False, **extra) + self.assertEqual(code, 400) + + def test_matcher_holds_back_only_a_possible_prefix(self): + from serve.server import StopMatcher + m = StopMatcher([""]) + self.assertEqual(m.push("a <"), "a ") # "<" may start "" + self.assertEqual(m.push("b"), " d"), "") + self.assertEqual(m.hit, "") + self.assertEqual(m.push("more"), "") + + if __name__ == "__main__": unittest.main() From 0ad6e8ac54581dc6482b6a0343ea478f2a0cd918 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 5 Oct 2026 10:32:01 +0200 Subject: [PATCH 22/48] serve: validate stop in Responses and count_tokens; tests for stop in --batch and after a thinking budget (#454) --- serve/test_parallel.py | 12 ++++++++++++ serve/test_server.py | 7 +++++++ 2 files changed, 19 insertions(+) diff --git a/serve/test_parallel.py b/serve/test_parallel.py index a970fffae7..6e14001231 100644 --- a/serve/test_parallel.py +++ b/serve/test_parallel.py @@ -234,6 +234,18 @@ class ParallelService(unittest.TestCase): self.assertEqual(self.engine.batch, 2) self.assertEqual(self.get("/v1/status")["concurrency"]["serving"], 2) + def test_stop_strings_in_a_batch_slot(self): + """#454: a stop string cuts the answer in --batch mode too, and the slot is freed for the next request.""" + self.start(2) + body = {"messages": [{"role": "user", "content": "hi LONGREPLY"}], "max_tokens": 64, "reasoning_effort": "none", + "stop": ["la la"]} + req = urllib.request.Request(self.base + "/v1/chat/completions", data=json.dumps(body).encode(), + headers={"Content-Type": "application/json"}) + with urllib.request.urlopen(req, timeout=60) as r: + c = json.loads(r.read().decode())["choices"][0] + self.assertEqual((c["message"]["content"], c["finish_reason"]), ("ok, ", "stop")) + self.assertEqual(self.chat("again")["choices"][0]["message"]["content"], "ok, done.") + def test_engine_turns_batching_off(self): self.start(4, fit=0) self.assertEqual(self.engine.batch, 0) diff --git a/serve/test_server.py b/serve/test_server.py index 266df8e92b..77b1df9962 100644 --- a/serve/test_server.py +++ b/serve/test_server.py @@ -2134,6 +2134,13 @@ class ThinkingBudget(unittest.TestCase): self.assertEqual(b["usage"]["completion_tokens"], 20 + len(extra) + len(ThinkingEngine.ANSWER) + 1) self.assertEqual(b["usage"]["prompt_tokens"], len(first)) + def test_a_stop_string_is_found_in_the_answer_after_the_wrap_up(self): + """#454: the continuation after the thinking budget is cut at a stop string too.""" + code, b = self.openai(reasoning_budget_tokens=20, stop=["answer is"]) + self.assertEqual(code, 200, b) + msg = b["choices"][0]["message"] + self.assertEqual((msg["content"], b["choices"][0]["finish_reason"]), ("The ", "stop")) + def test_anthropic_stream(self): from serve.server import REASONING_WRAP_UP code, raw = self.post("/v1/messages", {"model": "m", "max_tokens": 400, "stream": True, From 612a4d450c9bafa9779134b9806453b166c71330 Mon Sep 17 00:00:00 2001 From: Guillaume PUTIER Date: Sat, 3 Oct 2026 08:17:35 +0200 Subject: [PATCH 23/48] serve: read the request body an answer left unread, so the close is not a reset The server answers before reading the body in some cases (401, 403, /load, /unload, a method with no handler) and then closes. Closing on unread bytes makes Windows send a reset, and a client that sends its body after the headers (http.client, urllib, requests) gets WinError 10054 instead of the answer. After an answer, the body no handler took is now read and dropped, up to 1 MiB and with a 5 s timeout. A larger or chunked body is left unread, as before. --- serve/server.py | 34 ++++++++++++++++++++++++-- serve/test_server.py | 58 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 90 insertions(+), 2 deletions(-) diff --git a/serve/server.py b/serve/server.py index 496f6f8053..2c11de079a 100644 --- a/serve/server.py +++ b/serve/server.py @@ -2989,10 +2989,40 @@ def make_handler(svc: Service): record = None # #332: this request's monitor record, if kept watch_done = None # #430 #431: stops this request's disconnect watcher + body_read = False # whether a handler took this request's body + DRAIN_LIMIT = 1 << 20 # the most an unread body is read and dropped def log_message(self, fmt, *args): pass + def handle_one_request(self): + super().handle_one_request() + self._drain_body() + + def _body(self) -> bytes: + self.body_read = True + return self.rfile.read(int(self.headers.get("Content-Length", 0))) + + def _drain_body(self): + """An answer sent before the body was read (a 401, a 403, /load, a method with no handler) must not close + the connection on unread bytes: the close then sends a reset, and a client that sends its body after the + headers (http.client, urllib, requests) gets a connection error instead of the answer. So the body is + read and dropped here, once, after an answer. A body over DRAIN_LIMIT is left unread.""" + headers = getattr(self, "headers", None) + if self.body_read or headers is None: + return + try: + left = int(headers.get("Content-Length", 0)) + except ValueError: + return + if not 0 < left <= self.DRAIN_LIMIT: + return + self.connection.settimeout(5) # a client that never sends what it announced + try: + self.rfile.read(left) + except OSError: + pass + def parse_request(self): """Without an API key, every request (any method) first passes the Host check: DNS rebinding protection (host_allowed). With a key a rebinding page cannot authenticate, so the check is skipped: tunnels and @@ -3269,7 +3299,7 @@ def make_handler(svc: Service): self._json(503, {"error": {"type": "server_error", "message": str(e)}}) return try: - req = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))) or b"{}") + req = json.loads(self._body() or b"{}") if not isinstance(req, dict): raise ValueError("send a JSON object") if path.startswith("/v1/responses/"): # retrieve/delete/cancel/compact: nothing is stored @@ -3474,7 +3504,7 @@ def make_handler(svc: Service): def _settings(self): # They change what every client gets, so only the app's own page may set them - body = self.rfile.read(int(self.headers.get("Content-Length", 0))) + body = self._body() if not self._own_page("settings can be changed"): return try: diff --git a/serve/test_server.py b/serve/test_server.py index 77b1df9962..6efa48d8aa 100644 --- a/serve/test_server.py +++ b/serve/test_server.py @@ -8,6 +8,7 @@ import contextlib import io import json import os +import socket import sys import tempfile import threading @@ -3008,5 +3009,62 @@ class StopStrings(unittest.TestCase): self.assertEqual(m.push("more"), "") +class AnswerBeforeTheBody(unittest.TestCase): + """An answer sent before the request body was read must still reach a client that sends the body after the headers + (http.client, urllib and requests do): closing the connection on unread bytes sends a reset that eats the answer.""" + + def setUp(self): + tok = ByteTokenizer() + self.engine = UnloadableEngine(tok, "\n\nok", max_context=CTX) + self.svc = Service(self.engine, tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) + self.httpd = serve(self.svc, port=0) + self.port = self.httpd.server_address[1] + + def tearDown(self): + self.httpd.shutdown() + self.httpd.server_close() + + def status(self, method, path, headers=None, body=b'{"x": 1}'): + """The status line of the answer to a request whose body follows the headers after a pause.""" + head = {"Host": f"127.0.0.1:{self.port}", "Content-Type": "application/json", "Content-Length": str(len(body)), + **(headers or {})} + with socket.create_connection(("127.0.0.1", self.port), timeout=10) as s: + s.sendall((f"{method} {path} HTTP/1.1\r\n" + "".join(f"{k}: {v}\r\n" for k, v in head.items()) + + "\r\n").encode()) + time.sleep(0.3) # the server answers (and, unfixed, closes) meanwhile + try: + s.sendall(body) + except OSError: + pass + answer = b"" + while chunk := s.recv(65536): # Windows raises a reset here, where Linux keeps the answer + answer += chunk + time.sleep(0.2) + # Linux shows the reset only as a pending socket error, after the answer and the end of the stream + self.assertEqual(s.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR), 0, "the connection was reset") + return answer.split(b"\r\n", 1)[0].decode() + + def test_a_wrong_key(self): + self.svc.api_key = "secret" + try: + self.assertEqual(self.status("POST", "/v1/chat/completions"), "HTTP/1.0 401 Unauthorized") + finally: + self.svc.api_key = "" + + def test_load_and_unload(self): + self.assertEqual(self.status("POST", "/unload"), "HTTP/1.0 200 OK") + self.assertEqual(self.status("POST", "/load"), "HTTP/1.0 200 OK") + + def test_not_the_apps_own_page(self): + self.assertEqual(self.status("POST", "/load", {"Origin": "https://example.com"}), "HTTP/1.0 403 Forbidden") + + def test_a_host_the_server_does_not_answer_to(self): + self.assertEqual(self.status("POST", "/v1/chat/completions", {"Host": "rebind.example.com"}), + "HTTP/1.0 403 Forbidden") + + def test_a_method_with_no_handler(self): + self.assertEqual(self.status("PUT", "/v1/chat/completions"), "HTTP/1.0 501 Unsupported method ('PUT')") + + if __name__ == "__main__": unittest.main() From a8497cf157ed09552386fd2f8371792e668b360d Mon Sep 17 00:00:00 2001 From: Guillaume PUTIER Date: Sat, 3 Oct 2026 19:22:55 +0200 Subject: [PATCH 24/48] serve: the unread body is dropped under a time limit only, so megabytes still get their answer A body over 1 MiB was left unread, and its answer was reset on Windows. The limit is now 5 s for the whole body, read one socket read at a time: a body of any size gets its answer, and a client that sends a byte at a time is let go after the 5 s (read() waited for the whole piece, with a new timeout for each byte). --- serve/server.py | 17 ++++++++++++----- serve/test_server.py | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 5 deletions(-) diff --git a/serve/server.py b/serve/server.py index 2c11de079a..62305b1e3e 100644 --- a/serve/server.py +++ b/serve/server.py @@ -2990,7 +2990,7 @@ def make_handler(svc: Service): record = None # #332: this request's monitor record, if kept watch_done = None # #430 #431: stops this request's disconnect watcher body_read = False # whether a handler took this request's body - DRAIN_LIMIT = 1 << 20 # the most an unread body is read and dropped + DRAIN_SECONDS = 5 # the longest an unread body is read and dropped def log_message(self, fmt, *args): pass @@ -3007,7 +3007,9 @@ def make_handler(svc: Service): """An answer sent before the body was read (a 401, a 403, /load, a method with no handler) must not close the connection on unread bytes: the close then sends a reset, and a client that sends its body after the headers (http.client, urllib, requests) gets a connection error instead of the answer. So the body is - read and dropped here, once, after an answer. A body over DRAIN_LIMIT is left unread.""" + read and dropped here, once, after an answer, in pieces so that its size is never held in memory. What + has not arrived DRAIN_SECONDS later is left unread: the limit is time, so that a conversation of many + megabytes, at any speed the client has, still gets its answer.""" headers = getattr(self, "headers", None) if self.body_read or headers is None: return @@ -3015,11 +3017,16 @@ def make_handler(svc: Service): left = int(headers.get("Content-Length", 0)) except ValueError: return - if not 0 < left <= self.DRAIN_LIMIT: + if left <= 0: return - self.connection.settimeout(5) # a client that never sends what it announced + deadline = time.monotonic() + self.DRAIN_SECONDS try: - self.rfile.read(left) + while left > 0 and (wait := deadline - time.monotonic()) > 0: + self.connection.settimeout(wait) # a client that never sends what it announced + piece = self.rfile.read1(min(left, 1 << 20)) # one socket read: read() would wait for it all + if not piece: + break + left -= len(piece) except OSError: pass diff --git a/serve/test_server.py b/serve/test_server.py index 6efa48d8aa..f5c1d445ed 100644 --- a/serve/test_server.py +++ b/serve/test_server.py @@ -3051,6 +3051,38 @@ class AnswerBeforeTheBody(unittest.TestCase): finally: self.svc.api_key = "" + def test_a_wrong_key_and_a_body_of_megabytes(self): + """An agent client's conversation, or one screenshot, is several MiB, and a rotated key is when the 401 matters.""" + self.svc.api_key = "secret" + try: + self.assertEqual(self.status("POST", "/v1/chat/completions", body=b'{"x": "' + b"a" * (80 << 20) + b'"}'), + "HTTP/1.0 401 Unauthorized") + finally: + self.svc.api_key = "" + + def test_a_body_that_comes_in_drops_does_not_hold_the_connection(self): + """A client that announces a body and sends it a byte at a time is let go after DRAIN_SECONDS, with its + answer: the time limit is on the whole body, not on each read.""" + self.svc.api_key = "secret" + try: + with mock.patch.object(self.httpd.RequestHandlerClass, "DRAIN_SECONDS", 0.5), \ + socket.create_connection(("127.0.0.1", self.port), timeout=10) as s: + s.sendall((f"POST /v1/chat/completions HTTP/1.1\r\nHost: 127.0.0.1:{self.port}\r\n" + f"Content-Length: {1 << 20}\r\n\r\n").encode()) + started, answer = time.monotonic(), b"" + s.settimeout(0.2) + while True: + try: + if not (chunk := s.recv(65536)): + break + answer += chunk + except TimeoutError: + s.sendall(b"a") # a byte every 0.2 s keeps each read of the server alive + self.assertEqual(answer.split(b"\r\n", 1)[0], b"HTTP/1.0 401 Unauthorized") + self.assertLess(time.monotonic() - started, 5) + finally: + self.svc.api_key = "" + def test_load_and_unload(self): self.assertEqual(self.status("POST", "/unload"), "HTTP/1.0 200 OK") self.assertEqual(self.status("POST", "/load"), "HTTP/1.0 200 OK") From da170f8ae7c326a101ae7b50f43f5e46d131b376 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 5 Oct 2026 10:33:03 +0200 Subject: [PATCH 25/48] serve: /config and /load bodies are marked read, so the close does not wait for the drain (#594) --- serve/server.py | 3 ++- serve/test_server.py | 8 ++++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/serve/server.py b/serve/server.py index 62305b1e3e..b8067f15c3 100644 --- a/serve/server.py +++ b/serve/server.py @@ -3435,6 +3435,7 @@ def make_handler(svc: Service): complete = False finally: self.connection.settimeout(timeout) + self.body_read = True # nothing left for the drain to wait for (#594) if not complete: self._json(400, {"error": {"message": "incomplete control request body"}}) return complete @@ -3465,7 +3466,7 @@ def make_handler(svc: Service): def _config_post(self): """#564: change a few documented keys of the run config - JSON from Strata's own page only, as /settings (the key is checked before); every other key of the file stays as it is.""" - body = self.rfile.read(int(self.headers.get("Content-Length", 0))) + body = self._body() if not self._own_page("the run config can be changed"): return if not svc.config_path: diff --git a/serve/test_server.py b/serve/test_server.py index f5c1d445ed..f1d70a285a 100644 --- a/serve/test_server.py +++ b/serve/test_server.py @@ -3090,6 +3090,14 @@ class AnswerBeforeTheBody(unittest.TestCase): def test_not_the_apps_own_page(self): self.assertEqual(self.status("POST", "/load", {"Origin": "https://example.com"}), "HTTP/1.0 403 Forbidden") + def test_a_body_a_handler_read_is_not_waited_for(self): + """#594: /config and /load read their body themselves: the close must not wait for the drain's 5 s.""" + for path in ("/config", "/load", "/unload"): + with self.subTest(path=path): + t0 = time.monotonic() + self.status("POST", path) + self.assertLess(time.monotonic() - t0, 1.5) # the status() helper itself pauses 0.5 s + def test_a_host_the_server_does_not_answer_to(self): self.assertEqual(self.status("POST", "/v1/chat/completions", {"Host": "rebind.example.com"}), "HTTP/1.0 403 Forbidden") From b3c63f7e0be3dc262a8be77877e422d6ddb92351 Mon Sep 17 00:00:00 2001 From: Amir Guindehi Date: Sat, 3 Oct 2026 21:10:13 +0200 Subject: [PATCH 26/48] serve: honour OpenAI tool_choice "required" and a named function Without a grammar decoder a forced tool_choice was ignored, so clients that need a call (an agent's first step, its "done" call) got text. The server now writes the call's opening itself - and int: return text.find(CALL_END, pos) +def tool_choice_of(tool_choice) -> tuple[str, str | None]: + """A client's `tool_choice` in either API's shape -> ("auto" | "none" | "required" | "named", name). OpenAI: + "auto" / "none" / "required", {"type": "function", "function": {"name": N}} or the flat {"type": "function", + "name": N}; Anthropic: {"type": "auto" | "any" | "none"} and {"type": "tool", "name": N}. A value it does not + know is ("unknown", None).""" + if tool_choice is None: + return "auto", None + if isinstance(tool_choice, str): + return (tool_choice, None) if tool_choice in ("auto", "none", "required") else ("unknown", None) + if isinstance(tool_choice, dict): + kind = tool_choice.get("type") + if kind in ("auto", "none"): + return kind, None + if kind in ("any", "required"): + return "required", None + if kind in ("function", "tool"): + fn = tool_choice.get("function") + name = (fn.get("name") if isinstance(fn, dict) else None) or tool_choice.get("name") + if isinstance(name, str) and name: + return "named", name + return "unknown", None + + +def forced_call(tool_choice, tools: list[dict] | None) -> str | None: + """`tool_choice` -> the text that opens the call the reply must make, or None (the model decides). + There is no grammar here: the server writes this opening itself, so the model can only go on with a call. + "required" / Anthropic "any": any of the tools; a named function: that one. A value it cannot honour (an + unknown shape, a name that is not one of the tools, "required" with no tools) is logged and acts as "auto", + not a 400: a client's odd choice must not stop its request. "none" is handled by the caller (no tools).""" + kind, name = tool_choice_of(tool_choice) + names = {t.get("name") for t in tools or [] if isinstance(t, dict)} + if kind in ("auto", "none"): + return None + if kind == "required" and names: + return CALL_START + "\n\n" + print(f"[strata] tool_choice {json.dumps(tool_choice)[:200]} is not supported here (or names no tool of the " + "request): the model decides, as with \"auto\"", flush=True) + return None + + def parse_tool_call(body: str, schema: dict | None = None) -> ToolCall: """`\\n\\nVALUE\\n...` -> ToolCall. Values are JSON-decoded when the tool's schema says the parameter is not a string (or, without a schema, when they parse as JSON diff --git a/serve/server.py b/serve/server.py index b8067f15c3..22ebeabd79 100644 --- a/serve/server.py +++ b/serve/server.py @@ -53,7 +53,8 @@ ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "tools")) sys.path.insert(0, str(ROOT)) # run as a script (run-.bat) as well as a module from serve.frontend import (ChatTemplate, Event, OutputParser, anthropic_to_messages, # noqa: E402 - images_of, mark_think_literals, openai_to_messages, unmark_think_literals) + forced_call, images_of, mark_think_literals, openai_to_messages, tool_choice_of, + unmark_think_literals) from serve.mcp import McpCancelled, hub_from_config # noqa: E402 from serve import runconfig # noqa: E402 from serve.winjob import contain # noqa: E402 @@ -2265,10 +2266,13 @@ class Service: prompt, plain = unmark_think_literals(prompt) return self.tok.encode(prompt, parse_special=True, plain=plain) - def prepare(self, messages, tools, kwargs, max_new=None): + def prepare(self, messages, tools, kwargs, max_new=None, force=None): """-> (ids, thinking, max_new). An unset or non-positive max_new (some clients send -1) means "unlimited": - the rest of the context.""" + the rest of the context. `force` (forced_call): without thinking the reply starts with it, so it ends the + prompt; with thinking, Service.run writes it once the thinking is over.""" ids = self.encode_prompt(messages, tools, kwargs) + if force and kwargs.get("enable_thinking", True) is False: + ids = ids + self.tok.encode(force, parse_special=True) self.embeddings.path = None images = images_of(messages) if images: @@ -2367,8 +2371,9 @@ class Service: f"{el:.0f} s", flush=True) return now - def run(self, ids, thinking, tools, max_new, sampling, cancel) -> Iterator[tuple[str, object]]: - """Yields ("event", Event) as text arrives, then ("done", {"finish": .., "completion_tokens": ..}).""" + def run(self, ids, thinking, tools, max_new, sampling, cancel, force=None) -> Iterator[tuple[str, object]]: + """Yields ("event", Event) as text arrives, then ("done", {"finish": .., "completion_tokens": ..}). + `force` (forced_call): the opening of the call the reply must make - see prepare().""" budget = self.reasoning_budget(sampling) if thinking else None # #123: opt-in, off by default defaults = {**self.sampling_defaults, **self.shared} # the config's, then the Chat settings shared with apps if defaults: # the request's own fields win (explicit 0 stays greedy) @@ -2399,6 +2404,10 @@ class Service: out.append(Event("content", held)) out.append(ev) return out + opening = [] # without thinking the prompt ends with the forced opening: + if force and not thinking: # the parser reads it as if the model had written it + opening, force = parser.feed(force), None + tail = "" # the last characters written (the newlines before a call) timings, before = None, None # this request's timings; the engine's `last` before it raw_ids = [] # every generated id (STRATA_DEBUG: dump raw model text) emb = getattr(self.embeddings, "path", None) @@ -2439,10 +2448,13 @@ class Service: before = getattr(self.engine, "last", None) last_print = time.time() prompt, thought = ids, 0 # thought: the reasoning tokens so far (the budget's count) + for ev in opening: + yield "event", ev while True: gen = self.engine.generate(prompt, max_new - n, sampling, cancel, embeddings=emb) if emb \ else self.engine.generate(prompt, max_new - n, sampling, cancel) seg, wrap, leaving = [], False, False # this pass's tokens; the budget is reached; closed + opens = False # the thinking is over: write the forced call's opening try: for t in gen: if t is None: # heartbeat while the engine is quiet @@ -2465,7 +2477,9 @@ class Service: if self.repeat_stop_tokens and run_len >= self.repeat_stop_tokens: repeated = True # #606: a degenerate output, not an answer: end it here break - evs = cut(parser.feed(detok.push(t))) + piece = detok.push(t) + tail = (tail + piece)[-2:] + evs = cut(parser.feed(piece)) self._note(n, evs, st, rate) last_print = self._progress(last_print, st=st) for ev in evs: @@ -2479,6 +2493,12 @@ class Service: if thought >= budget and not parser.buf and not detok.pending(): wrap = True break + if force: + if any(ev.kind in ("tool_start", "tool_call") for ev in evs): + force = None # the model is writing a call of its own + elif parser.state == "content" and not parser.buf and not detok.pending(): + opens = True + break except EngineDied as e: finish = "error" self._say_died(e) @@ -2500,17 +2520,25 @@ class Service: self._say_died(e) if not leaving and not cancel.is_set(): raise - if not wrap or cancel.is_set(): + if not (wrap or opens) or cancel.is_set(): break # #123: the thinking reached reasoning_budget_tokens. Close it the way the model would (a # short wrap-up and ) and let it answer: the next pass's prompt is this one plus what # was generated plus the wrap-up, so the engine continues from the prefix it already holds. - budget = None - extra = self.tok.encode(REASONING_WRAP_UP, parse_special=True) + # A forced call (tool_choice) is opened the same way: after the wrap-up, or where the + # thinking ended, after the blank line the template puts before a call. + if wrap: + budget = None + text = REASONING_WRAP_UP + (force or "") + else: + text = "\n" * (2 - (len(tail) - len(tail.rstrip("\n")))) + force + force = None + extra = self.tok.encode(text, parse_special=True) if max_new - n - len(extra) < 1: break # no room left to answer: "length", as without a budget - print(f"[strata] thinking budget reached ({thought} tokens): wrapping up the thinking", - flush=True) + if wrap: + print(f"[strata] thinking budget reached ({thought} tokens): wrapping up the thinking", + flush=True) for t in extra: n += 1 raw_ids.append(t) @@ -2757,9 +2785,9 @@ def run_with_mcp(svc: Service, hub, messages, tools, kw, ids, thinking, max_new, # ------------------------------------------------------------------------------------------------ OpenAI -def openai_chunks(svc: Service, req: dict, ids, thinking, tools, max_new, cancel, run=None): +def openai_chunks(svc: Service, req: dict, ids, thinking, tools, max_new, cancel, run=None, force=None): """`run`: the events to send instead of Service.run's (run_with_mcp); its ("mcp", {...}) items become chunks with - an empty delta and a `strata_mcp` field, which only the web app reads.""" + an empty delta and a `strata_mcp` field, which only the web app reads. `force`: see Service.run.""" cid, created = "chatcmpl-" + uuid.uuid4().hex[:24], int(time.time()) model = svc.model_for(req) @@ -2771,7 +2799,7 @@ def openai_chunks(svc: Service, req: dict, ids, thinking, tools, max_new, cancel calls = 0 streamed = {} # tool call id -> index, for calls sent piece by piece finished = set() # ... and the ones whose final tool_call came (#211) - for kind, x in run if run is not None else svc.run(ids, thinking, tools, max_new, req, cancel): + for kind, x in run if run is not None else svc.run(ids, thinking, tools, max_new, req, cancel, force=force): if kind == "ping": yield None elif kind == "mcp": @@ -2882,7 +2910,7 @@ def structured_chunks(chunks, validator): # ------------------------------------------------------------------------------------------------ Anthropic -def anthropic_events(svc: Service, req: dict, ids, thinking, tools, max_new, cancel): +def anthropic_events(svc: Service, req: dict, ids, thinking, tools, max_new, cancel, force=None): mid = "msg_" + uuid.uuid4().hex[:24] yield "message_start", {"type": "message_start", "message": { "id": mid, "type": "message", "role": "assistant", "model": svc.model_for(req), "content": [], @@ -2893,7 +2921,7 @@ def anthropic_events(svc: Service, req: dict, ids, thinking, tools, max_new, can return ("content_block_stop", {"type": "content_block_stop", "index": index}) streamed, finished = set(), set() # calls sent piece by piece; those whose final tool_call came (#211) - for kind, x in svc.run(ids, thinking, tools, max_new, req, cancel): + for kind, x in svc.run(ids, thinking, tools, max_new, req, cancel, force=force): if kind == "ping": yield None continue @@ -3577,6 +3605,9 @@ def make_handler(svc: Service): req = svc.with_shared(req, "openai") messages, tools, kw = openai_to_messages(req) self._no_local_images(messages) + if tool_choice_of(req.get("tool_choice"))[0] == "none": # as the Responses route: no tools are offered + tools = None + force = forced_call(req.get("tool_choice"), tools) # a bad value is a 400 before anything is sent messages, validator = prepare_format(req.get("response_format"), messages) if validator is not None and (tools or req.get("strata_mcp")): raise ValueError("structured response_format with tools/MCP is not supported") @@ -3591,15 +3622,17 @@ def make_handler(svc: Service): extra = svc.mcp.template_tools(exclude=own) # the request's own tools win a name clash use_mcp = bool(extra) tools = (tools or []) + extra or None + if force and use_mcp: + raise ValueError("a forced tool_choice with MCP tools is not supported") svc.reasoning_budget(req) # a bad value is a 400 before anything is sent stop_strings(req) # ... and so is a bad stop / stop_sequences - ids, thinking, max_new = svc.prepare(messages, tools, kw, max_new) + ids, thinking, max_new = svc.prepare(messages, tools, kw, max_new, force=force) _debug_req("openai", req, messages, tools, max_new, thinking, len(ids)) cancel = threading.Event() self._watch_client(cancel) # #430 #431 run = run_with_mcp(svc, svc.mcp, messages, tools, kw, ids, thinking, max_new, max_req, req, cancel, {t["name"] for t in extra}) if use_mcp else None - chunks = openai_chunks(svc, req, ids, thinking, tools, max_new, cancel, run=run) + chunks = openai_chunks(svc, req, ids, thinking, tools, max_new, cancel, run=run, force=force) if validator is not None: chunks = structured_chunks(chunks, validator) chunks = self._capture(chunks, "openai") @@ -3773,14 +3806,17 @@ def make_handler(svc: Service): req = svc.with_shared(req, "anthropic") messages, tools, kw = anthropic_to_messages(req, svc.anthropic_think_unasked) self._no_local_images(messages) + if tool_choice_of(req.get("tool_choice"))[0] == "none": # Anthropic's {"type": "none"}: no tools offered + tools = None + force = forced_call(req.get("tool_choice"), tools) # "any" / {"type": "tool", "name": N} max_new = int(req.get("max_tokens") or 0) # 0/-1: the rest of the context svc.reasoning_budget(req) # a bad value is a 400 before anything is sent stop_strings(req) # ... and so is a bad stop / stop_sequences - ids, thinking, max_new = svc.prepare(messages, tools, kw, max_new) + ids, thinking, max_new = svc.prepare(messages, tools, kw, max_new, force=force) _debug_req("anthropic", req, messages, tools, max_new, thinking, len(ids)) cancel = threading.Event() self._watch_client(cancel) # #430 #431 - events = anthropic_events(svc, req, ids, thinking, tools, max_new, cancel) + events = anthropic_events(svc, req, ids, thinking, tools, max_new, cancel, force=force) events = self._capture(events, "anthropic") if not req.get("stream"): return self._json(200, anthropic_collect(events)) diff --git a/serve/test_server.py b/serve/test_server.py index f1d70a285a..778e8f4f72 100644 --- a/serve/test_server.py +++ b/serve/test_server.py @@ -2204,6 +2204,183 @@ class ThinkingBudget(unittest.TestCase): self.assertEqual(self.engine.prompts, []) +class CallingEngine(MockEngine): + """Thinks, then answers in text - unless its prompt already opens a call (a forced tool_choice): then it finishes + that call. Records every prompt it is given.""" + THOUGHT = "I could look this up. " * 8 # 176 reasoning tokens (one per byte) + ANSWER = "The answer is 4." + ARGS = "\n2+2\n\n\n" + + def __init__(self, tok): + super().__init__(tok, "x", max_context=CTX) + self.prompts = [] + + def generate(self, ids, max_new, sampling, cancel, embeddings=None): + self.prompts.append(list(ids)) + prompt = self.tok.decode(ids) + if prompt.endswith("\n"): + text = self.ARGS + elif prompt.endswith("\n\n"): + text = self.ANSWER + else: + text = self.THOUGHT + "\n\n" + self.ANSWER + for t in (self.tok.encode(text) + self.tok.encode("<|im_end|>", parse_special=True))[:max_new]: + if cancel.is_set(): + return + yield t + + +class ForcedToolChoice(unittest.TestCase): + """tool_choice "required" or a named function: the server writes the call's opening - after the thinking, or at + the end of the prompt without thinking - so the model can only go on with a call.""" + TOOLS = [{"type": "function", "function": {"name": "search", "description": "search the web", + "parameters": {"type": "object", + "properties": {"q": {"type": "string"}}}}}, + {"type": "function", "function": {"name": "done", "parameters": {"type": "object", "properties": {}}}}] + NAMED = {"type": "function", "function": {"name": "search"}} + NO_THINKING = {"chat_template_kwargs": {"enable_thinking": False}} + + def setUp(self): + self.tok = ByteTokenizer() + self.engine = CallingEngine(self.tok) + self.svc = Service(self.engine, self.tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) + self.httpd = serve(self.svc, port=0) + self.base = f"http://127.0.0.1:{self.httpd.server_address[1]}" + + def tearDown(self): + self.httpd.shutdown() + self.httpd.server_close() + + def openai(self, **extra): + body = {"model": "m", "messages": [{"role": "user", "content": "2+2?"}], "max_tokens": 400, + "tools": self.TOOLS, **extra} + req = urllib.request.Request(self.base + "/v1/chat/completions", data=json.dumps(body).encode(), + headers={"Content-Type": "application/json"}) + try: + with urllib.request.urlopen(req, timeout=30) as r: + raw = r.read().decode() + return r.status, (json.loads(raw) if not body.get("stream") else raw) + except urllib.error.HTTPError as e: + with e: + return e.code, json.loads(e.read()) + + def call_of(self, code, b, stream): + """-> (finish_reason, [(name, arguments)], reasoning) of a whole or a streamed reply.""" + self.assertEqual(code, 200, b) + if not stream: + choice = b["choices"][0] + calls = [(c["function"]["name"], json.loads(c["function"]["arguments"])) + for c in choice["message"].get("tool_calls") or []] + return choice["finish_reason"], calls, choice["message"].get("reasoning_content") or "" + chunks = [json.loads(line[6:]) for line in b.splitlines() if line.startswith("data: {")] + names, args, reasoning, finish = {}, {}, "", None + for c in chunks: + d = c["choices"][0]["delta"] + reasoning += d.get("reasoning_content") or "" + for tc in d.get("tool_calls") or []: + names.setdefault(tc["index"], tc["function"].get("name")) + args[tc["index"]] = args.get(tc["index"], "") + tc["function"].get("arguments", "") + finish = c["choices"][0]["finish_reason"] or finish + return finish, [(names[i], json.loads(args[i])) for i in sorted(names)], reasoning + + def test_required_and_named_after_the_thinking(self): + for choice in ("required", self.NAMED): + for stream in (False, True): + with self.subTest(choice=choice, stream=stream): + self.engine.prompts = [] + code, b = self.openai(tool_choice=choice, stream=stream) + finish, calls, reasoning = self.call_of(code, b, stream) + self.assertEqual((finish, calls), ("tool_calls", [("search", {"q": "2+2"})])) + self.assertEqual(reasoning, CallingEngine.THOUGHT) + first, second = self.engine.prompts + opening = "\n\n" if choice == self.NAMED else "") + # where the thinking ended, after the blank line the template puts before a call + self.assertEqual(second, first + self.tok.encode(CallingEngine.THOUGHT + "\n\n" + opening)) + + def test_without_thinking_the_prompt_ends_with_the_opening(self): + for choice in ("required", self.NAMED): + for stream in (False, True): + with self.subTest(choice=choice, stream=stream): + self.engine.prompts = [] + code, b = self.openai(tool_choice=choice, stream=stream, **self.NO_THINKING) + finish, calls, reasoning = self.call_of(code, b, stream) + self.assertEqual((finish, calls, reasoning), ("tool_calls", [("search", {"q": "2+2"})], "")) + self.assertEqual(len(self.engine.prompts), 1) + opening = "\n\n" if choice == self.NAMED else "") + self.assertTrue(self.tok.decode(self.engine.prompts[0]).endswith("\n\n" + opening)) + + def test_the_budget_wrap_up_opens_the_call(self): + from serve.server import REASONING_WRAP_UP + code, b = self.openai(tool_choice="required", reasoning_budget_tokens=20) + finish, calls, reasoning = self.call_of(code, b, False) + self.assertEqual((finish, calls), ("tool_calls", [("search", {"q": "2+2"})])) + self.assertEqual(reasoning, CallingEngine.THOUGHT[:20] + REASONING_WRAP_UP.split("")[0]) + first, second = self.engine.prompts + extra = self.tok.encode(REASONING_WRAP_UP + "\n Date: Sat, 3 Oct 2026 17:15:55 -0600 Subject: [PATCH 27/48] serve: a named in prose before the real call is content, not a malformed call A reply such as "I will use the `` format now." followed by the call raised ValueError("malformed tool call") in OutputParser.feed and ended the request: everything after the first was taken as the call body. A call is the tag followed (after whitespace) by ` and then (after whitespace) ` block") - content, not a malformed call + # that ends the request. Until its follower has arrived it is held, like a partial tag. + after = self.buf[i + len(CALL_START):].lstrip() + if after and not after.startswith(FUNC_START) and not FUNC_START.startswith(after): + out.append(Event("content", self.buf[:i + len(CALL_START)])) + self.buf = self.buf[i + len(CALL_START):] + continue + if not after.startswith(FUNC_START): + j = i + while j > 0 and self.buf[j - 1] == "\n": + j -= 1 + if j > 0: + out.append(Event("content", self.buf[:j])) + self.buf = self.buf[j:] + return out if i and self.buf[:i].strip(): out.append(Event("content", self.buf[:i].rstrip("\n"))) self.buf = self.buf[i + len(CALL_START):] diff --git a/serve/test_server.py b/serve/test_server.py index 778e8f4f72..a5c5be9738 100644 --- a/serve/test_server.py +++ b/serve/test_server.py @@ -483,6 +483,41 @@ class ToolCallTerminators(unittest.TestCase): self.assertEqual(json.loads(streamed), {"path": "doc.md", "content": self.CONTENT}) +class ToolCallTagInProse(unittest.TestCase): + """A reply that names the `` tag in its prose before the real call keeps the tag as content and still + returns the call; it was a "malformed tool call" ValueError that ended the request. A call is the tag followed + (after whitespace) by `\n\n\na.md\n\n\nhi\n" + "\n\n") + + def parse(self, text, stream_tools, step): + from serve.frontend import OutputParser + p = OutputParser(thinking=True, tools=self.SCHEMA, stream_tools=stream_tools) + evs = [] + for i in range(0, len(text), step): + evs += p.feed(text[i:i + step]) + evs += p.finish() + return ([e.call.arguments for e in evs if e.kind == "tool_call"], + "".join(e.text for e in evs if e.kind == "content")) + + def test_named_tag_is_content(self): + call = {"path": "a.md", "content": "hi"} + for prose in ("I will use the `` format now.", "Next I emit a block.", + "Two tags and x, then the call."): + for stream_tools in (False, True): + for step in (1, 7, 10_000): + with self.subTest(prose=prose, stream_tools=stream_tools, step=step): + calls, content = self.parse(f"\n\n{prose}\n{self.CALL}", stream_tools, step) + self.assertEqual((calls, content), ([call], prose)) + + def test_tag_alone_at_the_end_is_content(self): + for step in (1, 7, 10_000): + with self.subTest(step=step): + self.assertEqual(self.parse("\n\nThe format starts with ", False, step), + ([], "The format starts with ")) + + class UnfinishedToolCall(unittest.TestCase): """#211: a call the output ends inside is not reported as a whole one - its streamed JSON is not closed and the finish reason is not "tool_calls" / "tool_use" - so a client can tell it from a call to run.""" From a42a0c0b00f1d52c2fda775ed09e3bcb7a15301b Mon Sep 17 00:00:00 2001 From: Evan Date: Sun, 4 Oct 2026 04:01:21 +0200 Subject: [PATCH 28/48] serve: say Connection: close on every response The server is HTTP/1.0 and closes the connection after each response, but never said so. A client that pools connections (.NET's SocketsHttpHandler) then sometimes put its next request on the closing socket and got 'response ended prematurely' without the server ever reading it: 25 of ~1000 requests in one night from an agent app, each 1-24 ms after the previous answer. --- serve/server.py | 8 ++++++++ serve/test_server.py | 24 ++++++++++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/serve/server.py b/serve/server.py index 22ebeabd79..a23f7952e8 100644 --- a/serve/server.py +++ b/serve/server.py @@ -3098,6 +3098,14 @@ def make_handler(svc: Service): return True return False + def end_headers(self): + # HTTP/1.0 without keep-alive: the server closes the connection after every response. Say so, or a + # client that pools connections (.NET's SocketsHttpHandler) can put its next request on this socket + # before the close reaches it, and that request fails with "response ended prematurely" without the + # server ever reading it (a .NET agent app, 2026-10-03: 25 of ~1000 requests, 1-24 ms after the previous answer). + self.send_header("Connection", "close") + super().end_headers() + def _watch_client(self, cancel: threading.Event) -> None: """#430 #431: cancel the request as soon as its client hangs up. A non-streamed request writes nothing until it ends, and a streamed one only a keep-alive per prompt chunk (and the first write after a hang-up diff --git a/serve/test_server.py b/serve/test_server.py index a5c5be9738..e1b04c1d26 100644 --- a/serve/test_server.py +++ b/serve/test_server.py @@ -3109,11 +3109,20 @@ class StopStrings(unittest.TestCase): across tokens (and across streamed chunks).""" ANSWER = "alpha END beta STOP gamma" + +class ConnectionClose(unittest.TestCase): + """The server is HTTP/1.0 and closes the connection after every response. Without saying so, .NET's pooled + HttpClient put its next request on the closing socket and got "response ended prematurely" (2026-10-03).""" + @classmethod def setUpClass(cls): tok = ByteTokenizer() cls.engine = CountingEngine(tok, "\n\n" + cls.ANSWER, max_context=CTX) cls.svc = Service(cls.engine, tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) + + + cls.svc = Service(MockEngine(tok, "\n\nok", max_context=CTX), tok, + ChatTemplate(ROOT / "serve/chat_template.jinja")) cls.httpd = serve(cls.svc, port=0) cls.base = f"http://127.0.0.1:{cls.httpd.server_address[1]}" @@ -3318,5 +3327,20 @@ class AnswerBeforeTheBody(unittest.TestCase): self.assertEqual(self.status("PUT", "/v1/chat/completions"), "HTTP/1.0 501 Unsupported method ('PUT')") + def headers(self, stream): + body = {"model": "x", "max_tokens": 20, "messages": [{"role": "user", "content": "hi"}], "stream": stream} + req = urllib.request.Request(self.base + "/v1/chat/completions", data=json.dumps(body).encode(), + headers={"Content-Type": "application/json"}) + with urllib.request.urlopen(req, timeout=30) as r: + r.read() + return r.headers + + def test_a_non_streamed_answer_says_the_connection_closes(self): + self.assertEqual(self.headers(stream=False).get("Connection"), "close") + + def test_a_streamed_answer_says_the_connection_closes(self): + self.assertEqual(self.headers(stream=True).get("Connection"), "close") + + if __name__ == "__main__": unittest.main() From 773657cd1f998d0413773db59a2a82d5361da2e4 Mon Sep 17 00:00:00 2001 From: siddolo Date: Sun, 4 Oct 2026 17:17:50 +0200 Subject: [PATCH 29/48] serve: tolerate broken stdin pipes during engine cleanup --- serve/server.py | 5 ++++- serve/test_lifecycle.py | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/serve/server.py b/serve/server.py index a23f7952e8..39685f88e9 100644 --- a/serve/server.py +++ b/serve/server.py @@ -1279,7 +1279,10 @@ class StrataEngine: if self.proc.poll() is not None: if self.pump is not None: self.pump.join(timeout=2) - self.proc.stdin.close() + try: + self.proc.stdin.close() # buffered data may flush again after the engine has exited + except OSError: + pass self.proc.stdout.close() if self.log not in (None, subprocess.DEVNULL): self.log.close() diff --git a/serve/test_lifecycle.py b/serve/test_lifecycle.py index 1d9f58c463..84847b59d0 100644 --- a/serve/test_lifecycle.py +++ b/serve/test_lifecycle.py @@ -1,6 +1,7 @@ """Model discovery, on-demand loading and safe unloading over the actual HTTP API.""" import json import io +import os import subprocess import time import unittest @@ -45,6 +46,41 @@ class ResidentEngine(StrataEngine): class Lifecycle(unittest.TestCase): + def test_close_cleans_up_after_a_broken_stdin_pipe(self): + for running in (False, True): + with self.subTest(running=running): + engine = StrataEngine("missing-executable", [], lazy=True) + read_fd, write_fd = os.pipe() + stdin = os.fdopen(write_fd, "w") + self.addCleanup(stdin.close) + os.close(read_fd) # the engine's end of the pipe is already gone + stdin.write("pending") # buffered: flush() and close() will hit the broken pipe + proc = mock.Mock(stdin=stdin, stdout=io.StringIO()) + self.addCleanup(proc.stdout.close) + proc.poll.side_effect = [None if running else 0, 0] + engine.proc, engine.pump, engine.log = proc, mock.Mock(), io.StringIO() + self.addCleanup(engine.log.close) + engine.ended, engine.progress, engine.last = False, (1, 2), {"generated": 1} + + engine.close() + + self.assertTrue(stdin.closed) + self.assertTrue(proc.stdout.closed) + self.assertTrue(engine.log.closed) + engine.pump.join.assert_called_once_with(timeout=2) + self.assertIsNone(engine.proc) + self.assertTrue(engine.ended) + self.assertIsNone(engine.progress) + self.assertEqual(engine.last, {}) + if running: + proc.terminate.assert_called_once() + proc.wait.assert_called_once_with(timeout=20) + else: + proc.terminate.assert_not_called() + proc.wait.assert_not_called() + proc.kill.assert_not_called() + engine.close() # repeated cleanup is harmless + def test_close_sends_eof_before_waiting_for_windows_reader(self): engine = StrataEngine("missing-executable", [], lazy=True) proc = mock.Mock() From bcc39a1e4290729e1f36af52f9c3abde05b79ce3 Mon Sep 17 00:00:00 2001 From: Juan Canfield Date: Sun, 4 Oct 2026 13:18:35 -0500 Subject: [PATCH 30/48] serve: accept json_schema roots that are unions of object schemas prepare_format refused every schema whose root was not literally "type":"object", so a root anyOf/oneOf of object shapes - what apps written for llama.cpp's json_schema send - got a 400, although every answer it allows is one JSON object. _only_objects() accepts a root that can only be an object: "type":"object", an anyOf/oneOf whose branches all qualify, an allOf with a qualifying member, or a local $ref to one (a $ref cycle never qualifies). The "return exactly one JSON object" directive and the object check without jsonschema stay true. A root that also allows an array, string, number, boolean or null (including "type":["object","null"] and a schema without a type) is still refused before the engine loads. Tests: serve/test_structured.py, unions accepted (a non-object answer is still refused) and non-object roots refused: 10 OK with and without jsonschema installed. test_server/security/lifecycle/detok/mcp/monitor/winjob: 214 OK. docs/DETAILS.md: the root rule. --- docs/DETAILS.md | 5 ++++- serve/structured.py | 34 +++++++++++++++++++++++++++++-- serve/test_structured.py | 44 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 80 insertions(+), 3 deletions(-) diff --git a/docs/DETAILS.md b/docs/DETAILS.md index a1aa466b56..65e486db98 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -1102,7 +1102,10 @@ times out, the server keeps ownership and reports an error rather than claiming `POST /v1/chat/completions` accepts `response_format: {"type":"json_object"}` or `{"type":"json_schema","json_schema":{"name":"answer","strict":true,"schema":{"type":"object","properties":{"answer":{"type":"integer"}},"required":["answer"],"additionalProperties":false}}}`. -The schema must describe an object at its root. Local `#` references work; remote references are refused. +The schema must accept only JSON objects at its root: `"type":"object"`, or an `anyOf`/`oneOf` whose branches are all +object schemas (an `allOf` with an object member, or a local `$ref` to one, also counts), as apps written for +llama.cpp's `json_schema` send. A root that also allows an array, string, number, boolean or null is refused. Local +`#` references work; remote references are refused. `json_schema` is checked with the Python package `jsonschema` when it is installed (`python -m pip install "jsonschema>=4.23,<5"`; setup does not add it); without it the answer is only checked to be one JSON object, and the server says so once. diff --git a/serve/structured.py b/serve/structured.py index b5f079ccea..3a726d6079 100644 --- a/serve/structured.py +++ b/serve/structured.py @@ -51,6 +51,35 @@ def jsonschema_modules(): return _jsonschema or None +def _only_objects(node, root, refs=()): + """True when every value `node` accepts is a JSON object, so "return one JSON object" stays true. + + `type: object`, an anyOf/oneOf whose branches all qualify (e.g. a root union of object shapes, which llama.cpp's + grammar path accepts and apps send), an allOf with a qualifying member, or a local `$ref` to one of these. + Anything that can also be an array, string, number, boolean or null (including `type: ["object", "null"]`) is + not, and a `$ref` cycle never qualifies. + """ + if not isinstance(node, dict): + return False + if node.get("type") == "object": + return True + ref = node.get("$ref") + if isinstance(ref, str) and ref.startswith("#") and ref not in refs: + target = root + for part in ref[1:].split("/")[1:]: + part = part.replace("~1", "/").replace("~0", "~") + if not isinstance(target, dict) or part not in target: + return False + target = target[part] + return _only_objects(target, root, refs + (ref,)) + for key in ("anyOf", "oneOf"): + branches = node.get(key) + if isinstance(branches, list) and branches and all(_only_objects(b, root, refs) for b in branches): + return True + branches = node.get("allOf") + return isinstance(branches, list) and any(_only_objects(b, root, refs) for b in branches) + + def prepare_format(response_format, messages): if response_format is None: return messages, None @@ -71,8 +100,9 @@ def prepare_format(response_format, messages): if "strict" in spec and not isinstance(spec["strict"], bool): raise ValueError("response_format.json_schema.strict must be boolean") schema = spec["schema"] - if schema.get("type") != "object": - raise ValueError("response_format schema must have type object at its root") + if not _only_objects(schema, schema): + raise ValueError("response_format schema must accept only JSON objects at its root " + "(type object, or anyOf/oneOf of object schemas)") modules = jsonschema_modules() else: raise ValueError("response_format.type must be text, json_object or json_schema") diff --git a/serve/test_structured.py b/serve/test_structured.py index cc157a76d8..be9fd0ee0d 100644 --- a/serve/test_structured.py +++ b/serve/test_structured.py @@ -154,6 +154,50 @@ class Structured(unittest.TestCase): self.assertEqual(reply["error"]["code"], "structured_output_failed") self.assertEqual(self.chat('{"answer":4}', response_format={"type": "json_object"})[0], 200) + def test_root_unions_of_object_shapes_are_accepted(self): + # A root anyOf of object shapes (sent by apps written against llama.cpp's grammar path) still means + # "one JSON object", so it is accepted; a non-object answer is still refused. + claim = {"type": "object", "additionalProperties": False, "required": ["claim_text"], + "properties": {"claim_text": {"type": "string", "minLength": 1}}} + empty = {"type": "object", "additionalProperties": False, "required": ["outcome"], + "properties": {"outcome": {"type": "string", "enum": ["no_substantive_content"]}}} + schemas = [ + {"anyOf": [claim, empty]}, + {"oneOf": [claim, empty]}, + {"allOf": [claim, {"required": ["claim_text"]}]}, + {"$ref": "#/$defs/claim", "$defs": {"claim": claim}}, + {"anyOf": [{"$ref": "#/$defs/claim"}, {"anyOf": [empty]}], "$defs": {"claim": claim}}, + ] + for schema in schemas: + fmt = {"type": "json_schema", "json_schema": {"name": "union", "strict": True, "schema": schema}} + with self.subTest(schema=schema): + self.assertEqual(self.chat('{"claim_text":"The term is 12 months."}', response_format=fmt)[0], 200) + self.assertEqual(self.chat("[1, 2]", response_format=fmt)[0], 502) + + def test_schemas_that_allow_non_objects_are_still_rejected(self): + obj = {"type": "object"} + schemas = [ + {"type": "array", "items": obj}, + {"type": "string"}, + {"type": ["object", "null"]}, + {"anyOf": [obj, {"type": "string"}]}, + {"anyOf": []}, + {"oneOf": [obj, {"type": "array"}]}, + {"allOf": [{"type": "string"}]}, + {"properties": {"x": {"type": "string"}}}, # no type: any JSON value validates + {"$ref": "#/$defs/a", "$defs": {"a": {"$ref": "#/$defs/a"}}}, # reference cycle + {"$ref": "#/$defs/missing", "$defs": {}}, + {"$ref": "#/$defs/s", "$defs": {"s": {"type": "string"}}}, + ] + with mock.patch.object(self.svc, "load") as load: + for schema in schemas: + fmt = {"type": "json_schema", "json_schema": {"name": "bad", "schema": schema}} + with self.subTest(schema=schema): + code, reply = self.chat(response_format=fmt) + self.assertEqual(code, 400) + self.assertIn("only JSON objects", reply["error"]["message"]) + load.assert_not_called() + def test_the_server_does_not_import_jsonschema_at_start(self): import subprocess import sys From 3794826b078e8b09edb066e8c1e28092640a9fef Mon Sep 17 00:00:00 2001 From: robwijnhoven <100681185+robwijnhoven@users.noreply.github.com> Date: Sun, 4 Oct 2026 20:33:53 +0200 Subject: [PATCH 31/48] serve: map namespace calls written as namespace__name back to their namespace Codex sends its MCP tools as namespace tools (mcp__websearch with web_search inside). The Responses adapter shows the model mcp__websearch.web_search, but Qwen3.8-Flash-Next writes the call as mcp__websearch__web_search, the flat form Codex used for MCP tools. That name had no entry in the reverse map, so the call came back without a namespace and Codex rejected it as an unsupported call. Register the double-underscore spelling too (setdefault, so a real tool of that name still wins). --- serve/responses.py | 4 ++++ serve/test_responses.py | 16 ++++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/serve/responses.py b/serve/responses.py index 4a017c38d8..01f2b17d32 100644 --- a/serve/responses.py +++ b/serve/responses.py @@ -257,6 +257,10 @@ def request_tools(req: dict): "required": ["input"]} tools.append({"name": flat, "description": description, "parameters": params}) names[flat] = (namespace, name, kind) + if namespace: + # Qwen writes Codex's MCP tools as `mcp__server__tool` (the flat name it + # learned), not `mcp__server.tool`: map that spelling back as well. + names.setdefault(f"{namespace}__{name}", (namespace, name, kind)) for i, tool in enumerate(given): param = f"tools[{i}]" diff --git a/serve/test_responses.py b/serve/test_responses.py index 2878cb6c9d..caac3d6886 100644 --- a/serve/test_responses.py +++ b/serve/test_responses.py @@ -348,6 +348,22 @@ class ToolRoundTrip(Server): self.assertIn("\nbefore\n", second_prompt) self.assertEqual(r["output"][-1]["content"][0]["text"], "The file says before.") + def test_namespace_call_written_with_double_underscore(self): + # Qwen writes Codex's MCP tools in their flat `mcp__server__tool` form; Codex only + # runs the call when it comes back with its namespace. + self.engine.scripts = [self.tok.encode( + "\n\n\n\n\nstrata\n" + "\n\n<|im_end|>", parse_special=True)] + self.engine.script = self.engine.scripts[0] + tools = [{"type": "namespace", "name": "mcp__websearch", "description": "Search.", "tools": [ + {"type": "function", "name": "web_search", + "parameters": {"type": "object", "properties": {"query": {"type": "string"}}}}]}] + code, r = self.post({"model": "m", "input": "go", "tools": tools}) + self.assertEqual(code, 200, r) + call, = r["output"] + self.assertEqual((call["namespace"], call["name"], json.loads(call["arguments"])), + ("mcp__websearch", "web_search", {"query": "strata"})) + def test_namespace_and_custom_calls_come_back_under_their_own_names(self): self.engine.scripts = [self.tok.encode( "\n\n\n\n\nhi\n\n" From 0d95958f5179c1ca9caf248a1f4093d750ab4983 Mon Sep 17 00:00:00 2001 From: cipgysmo Date: Sun, 4 Oct 2026 14:06:22 +0200 Subject: [PATCH 32/48] serve: extract JSON from prose and code fences --- serve/structured.py | 39 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 38 insertions(+), 1 deletion(-) diff --git a/serve/structured.py b/serve/structured.py index 3a726d6079..101c78f6d3 100644 --- a/serve/structured.py +++ b/serve/structured.py @@ -148,6 +148,43 @@ def prepare_format(response_format, messages): return messages, validator +def _extract_json(text: str) -> str: + s = (text or "").strip() + if not s: + return "" + if s.startswith("```"): + first = s.find("\n") + if first != -1: + end = s.find("```", first + 1) + if end != -1: + s = s[first + 1:end].strip() + start = s.find("{") + if start == -1: + return s + depth = 0 + in_str = False + esc = False + for i in range(start, len(s)): + ch = s[i] + if in_str: + if esc: + esc = False + elif ch == "\\": + esc = True + elif ch == "\"": + in_str = False + else: + if ch == "\"": + in_str = True + elif ch == "{": + depth += 1 + elif ch == "}": + depth -= 1 + if depth == 0: + return s[start:i + 1] + return s[start:] + + def validated_json(text, validator, finish): def pairs(items): obj = {} @@ -163,7 +200,7 @@ def validated_json(text, validator, finish): if finish != "stop": raise StructuredOutputError(f"structured output was incomplete (finish_reason={finish}); increase the output budget") try: - value = json.loads(text or "", object_pairs_hook=pairs, parse_constant=constant) + value = json.loads(_extract_json(text), object_pairs_hook=pairs, parse_constant=constant) canonical = json.dumps(value, ensure_ascii=False, allow_nan=False, separators=(",", ":")) except (ValueError, TypeError) as exc: raise StructuredOutputError(f"model did not return valid JSON: {exc}") from exc From 2190b48a8222df8466e871157ca8bb5132530d24 Mon Sep 17 00:00:00 2001 From: sergiywith Date: Sun, 4 Oct 2026 17:48:46 +0300 Subject: [PATCH 33/48] serve tests: test_json_schema_text_format's schema failure only where jsonschema is installed jsonschema is optional (serve/structured.py): without it a json_schema answer is checked to be one JSON object, so the answer the test expects to fail passes, and the test failed on every install without it (0.1.39's own as well). --- serve/test_responses.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/serve/test_responses.py b/serve/test_responses.py index caac3d6886..b146852d6b 100644 --- a/serve/test_responses.py +++ b/serve/test_responses.py @@ -291,7 +291,12 @@ class OverHttp(Server): code, events = self.post({"model": "m", "input": "a number", "text": {"format": fmt}, "stream": True}) self.assertEqual([e["delta"] for e in events if e["type"] == "response.output_text.delta"], ["{\"n\":3}"]) self.assertEqual(events[-1]["type"], "response.completed") - # an answer that fails the schema + # an answer that fails the schema - only jsonschema can tell: it is optional (serve/structured.py), and + # without it a json_schema answer is checked to be one JSON object, which {"n": 3} is + try: + import jsonschema # noqa: F401 + except ImportError: + return bad = {**fmt, "schema": {**fmt["schema"], "properties": {"n": {"type": "string"}}}} code, r = self.post({"model": "m", "input": "a number", "text": {"format": bad}}) self.assertEqual((code, r["error"]["code"]), (502, "structured_output_failed")) From 64be7561c521dbd8c8df45b0a6f2a3e0298b142b Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 5 Oct 2026 10:36:40 +0200 Subject: [PATCH 34/48] serve tests: a fenced or prose-wrapped JSON object is now accepted in json_object mode (#762) --- serve/test_structured.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/serve/test_structured.py b/serve/test_structured.py index be9fd0ee0d..6b66cf8b11 100644 --- a/serve/test_structured.py +++ b/serve/test_structured.py @@ -103,8 +103,11 @@ class Structured(unittest.TestCase): def test_object_mode_strict_json_and_truncation(self): fmt = {"type": "json_object"} self.assertEqual(self.chat('{"answer":4}', response_format=fmt)[0], 200) - for script in ('[]', '{"x":NaN}', '{"x":1,"x":2}', '{"x":1e999}', '```json\n{}\n```'): + for script in ('[]', '{"x":NaN}', '{"x":1,"x":2}', '{"x":1e999}', 'no json at all', '{"x":'): self.assertEqual(self.chat(script, response_format=fmt)[0], 502) + # #762: the JSON object is taken out of a code fence or the prose around it (the object itself stays strict) + for script in ('```json\n{}\n```', 'Here it is: {"answer":4} - done'): + self.assertEqual(self.chat(script, response_format=fmt)[0], 200, script) self.assertEqual(self.chat('{"answer":4}', response_format=fmt, max_tokens=5)[0], 502) # Plain text callers retain normal streaming, without a JSON validation gate. self.assertEqual(self.chat("Prose.", response_format={"type": "text"})[0], 200) From d6b3f578114f76383c96b331c8a00243193058da Mon Sep 17 00:00:00 2001 From: sergiywith Date: Fri, 2 Oct 2026 22:16:47 +0300 Subject: [PATCH 35/48] serve: an image in an Anthropic tool_result reaches the encoder (Claude Code's Read of a picture) Claude Code returns a picture it opens with Read as an image block inside a tool_result. The Anthropic path turned every tool_result into its text, so the image never reached the encoder and the model described a picture it had not seen. The tool message now carries the image item, as the OpenAI path's tool messages already did; the chat template renders it inside . An image sent beside tool results in the same user turn is kept too. A text-only tool result is still one string, so text prompts are unchanged. --- serve/frontend.py | 14 ++++++++++---- serve/test_server.py | 30 ++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 4 deletions(-) diff --git a/serve/frontend.py b/serve/frontend.py index 31b1fa56cc..f9f7c2dbba 100644 --- a/serve/frontend.py +++ b/serve/frontend.py @@ -332,19 +332,25 @@ def anthropic_to_messages(req: dict, think_unasked: bool = True) -> tuple[list[d isinstance(b, dict) and b.get("type") == "tool_result" for b in content): messages.append({"role": "user", "content": _parts_of(content)}) continue - text, reasoning, calls = [], [], [] + text, reasoning, calls, parts = [], [], [], [] for block in content or []: kind = block.get("type") if kind == "text": text.append(block.get("text", "")) + parts.append(block) + elif kind in IMAGE_PARTS: + parts.append(block) elif kind == "thinking": reasoning.append(block.get("thinking", "")) elif kind == "tool_use": calls.append({"function": {"name": block.get("name"), "arguments": tool_arguments(block.get("input"))}}) elif kind == "tool_result": - messages.append({"role": "tool", "content": _text_of(block.get("content"))}) - if text or calls or reasoning: - out = {"role": m["role"], "content": "".join(text)} + # A tool's image (Claude Code's Read of a picture) reaches the encoder like a user's, as the OpenAI + # path's tool messages already do; a text-only result is one string, as before. + messages.append({"role": "tool", "content": _parts_of(block.get("content"))}) + if text or calls or reasoning or parts: + # an image sent beside tool results stays in this turn instead of being dropped + out = {"role": m["role"], "content": _parts_of(parts) if _has_image(parts) else "".join(text)} if reasoning: out["reasoning_content"] = "".join(reasoning) if calls: diff --git a/serve/test_server.py b/serve/test_server.py index e1b04c1d26..2b6bc6749a 100644 --- a/serve/test_server.py +++ b/serve/test_server.py @@ -243,6 +243,36 @@ class ImageMarkers(unittest.TestCase): self.assertIn("<|image_pad|> marks" if "docs" in text else "plain", tok.decode(ids)) svc.embeddings.path.unlink(missing_ok=True) + def test_anthropic_tool_result_image(self): + """Claude Code's Read of a picture returns it inside a tool_result: it reaches the encoder, in place.""" + import tempfile + from serve.frontend import anthropic_to_messages + tok = ByteTokenizer() + img = {"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": "AAAA"}} + call = {"role": "assistant", "content": [{"type": "tool_use", "id": "t1", "name": "Read", "input": {"file_path": "a.png"}}]} + with tempfile.TemporaryDirectory() as d: + svc = Service(MockEngine(tok, "ok", max_context=CTX), tok, ChatTemplate(ROOT / "serve/chat_template.jinja"), + vision=self.FakeVision(d)) + pad = tok.encode("<|image_pad|>", parse_special=True)[0] + for result, extra, n in (([img], [], 3), ([{"type": "text", "text": "a.png"}, img], [], 3), + ("plain text", [img, {"type": "text", "text": "and this one"}], 3), + ([img], [img], 6)): + with self.subTest(result=str(result)[:30], extra=len(extra)): + msgs = [{"role": "user", "content": "look at a.png"}, call, + {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "t1", "content": result}] + extra}] + m, _, _ = anthropic_to_messages({"messages": msgs}) + ids, _, _ = svc.prepare(m, None, {}) + self.assertEqual(ids.count(pad), n) + prompt = tok.decode(ids) + inside = prompt.split("", 1)[1].split("", 1)[0] + self.assertEqual("<|vision_start|>" in inside, not isinstance(result, str)) + self.assertEqual("<|vision_start|>" in prompt.split("", 1)[1], bool(extra)) + svc.embeddings.path.unlink(missing_ok=True) + # a text-only tool result renders exactly as before: one string + msgs = [{"role": "user", "content": "q"}, call, + {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "t1", "content": [{"type": "text", "text": "r"}]}]}] + self.assertEqual(anthropic_to_messages({"messages": msgs})[0][-1], {"role": "tool", "content": "r"}) + class ThinkTokenizer(ByteTokenizer): """The byte tokenizer with the model's reasoning markers as specials that are matched even without parse_special, From 3709c15f1d6869c4428316174eed97227761785b Mon Sep 17 00:00:00 2001 From: sergiywith Date: Sat, 3 Oct 2026 00:25:33 +0300 Subject: [PATCH 36/48] serve: a tool's picture the server cannot read becomes a note, not a 400 With tool_result pictures reaching the encoder, a server without one (every lazy-start config is text-only) or an encoder that refuses a picture (WebP without Pillow, an error from strata-vision) answered 400. Clients resend the whole history every turn, so one such picture failed every later request of the conversation; before, the picture was dropped silently. Now a tool's picture that cannot be read becomes "[image omitted: ]" in its place; a picture the user sends keeps the 400. Maintainer: log a left-out tool picture, a tool picture's URL is downloaded once (bytes reused by prepare), tests (#529; #582 and #819 are duplicates) --- serve/server.py | 33 +++++++++++++++++++++++++++++++- serve/test_server.py | 45 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 77 insertions(+), 1 deletion(-) diff --git a/serve/server.py b/serve/server.py index 39685f88e9..fb5d12d0c7 100644 --- a/serve/server.py +++ b/serve/server.py @@ -2269,10 +2269,40 @@ class Service: prompt, plain = unmark_think_literals(prompt) return self.tok.encode(prompt, parse_special=True, plain=plain) + def _note_unreadable_tool_images(self, messages): + """A picture a tool returned (Claude Code's Read of an image file) that this server cannot read - it has no + image encoder, or the encoder refuses that picture - becomes a short note in its place instead of a 400. + Clients resend the whole history every turn, so one unreadable tool picture would fail every later request of + the conversation; a picture the user sends keeps the 400. A picture that encodes stays in the cache, so the + prompt's own encode below finds it.""" + fetched = {} # a URL's bytes, so prepare() does not download the same picture again + for m in messages: + content = m.get("content") + if m.get("role") != "tool" or not isinstance(content, list): + continue + for n, item in enumerate(content): + if not isinstance(item, dict) or item.get("type") != "image": + continue + why = "this server has no image encoder" if self.vision is None else None + if why is None: + src = item["source"] + try: + if src.startswith(("http://", "https://")): + src = fetched[item["source"]] = Vision.download(src) # outside the FIFO, as in prepare() + with self.fifo: # the encoder takes its turn with the requests (see below) + self.vision.encode(src) + except (ValueError, OSError) as e: + why = str(e) + if why is not None: + print(f"[strata] a picture a tool returned was left out of the prompt: {why}", flush=True) + content[n] = {"type": "text", "text": f"[image omitted: {why}]"} + return fetched + def prepare(self, messages, tools, kwargs, max_new=None, force=None): """-> (ids, thinking, max_new). An unset or non-positive max_new (some clients send -1) means "unlimited": the rest of the context. `force` (forced_call): without thinking the reply starts with it, so it ends the prompt; with thinking, Service.run writes it once the thinking is over.""" + fetched = self._note_unreadable_tool_images(messages) ids = self.encode_prompt(messages, tools, kwargs) if force and kwargs.get("enable_thinking", True) is False: ids = ids + self.tok.encode(force, parse_special=True) @@ -2286,7 +2316,8 @@ class Service: start = self.tok.encode(VISION_START, parse_special=True)[0] # An image URL is downloaded first, outside the FIFO: under it, a slow server held every other request # for as long as urlopen waited. - images = [Vision.download(src) if src.startswith(("http://", "https://")) else src for src in images] + images = [fetched[src] if src in fetched else Vision.download(src) if src.startswith(("http://", "https://")) + else src for src in images] # Encode only while the engine is idle: the engine and the image encoder (a separate process) must not # run on the GPU at the same time - an encode during a running request left that request stuck at # "reading the prompt" with CPU and GPU busy, for good (reproduced). So encoding takes its turn in the diff --git a/serve/test_server.py b/serve/test_server.py index 2b6bc6749a..e55323e038 100644 --- a/serve/test_server.py +++ b/serve/test_server.py @@ -268,6 +268,51 @@ class ImageMarkers(unittest.TestCase): self.assertEqual("<|vision_start|>" in inside, not isinstance(result, str)) self.assertEqual("<|vision_start|>" in prompt.split("", 1)[1], bool(extra)) svc.embeddings.path.unlink(missing_ok=True) + # a tool's picture the server cannot read is a note, not a 400 (the client resends it every turn); the user's + # own picture still fails + class Refusing(self.FakeVision): + def encode(self, source): + if "bad" in str(source): + raise ValueError("this image format needs Pillow") + return super().encode(source) + good = {"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": "AAAA"}} + bad = {"type": "image", "source": {"type": "base64", "media_type": "image/webp", "data": "badd"}} + tool_msgs = [{"role": "user", "content": "look"}, call, + {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "t1", "content": [bad, good]}]}] + with tempfile.TemporaryDirectory() as d: + for vision, n, note in ((None, 0, "[image omitted: this server has no image encoder]"), + (Refusing(d), 3, "[image omitted: this image format needs Pillow]")): + with self.subTest(vision=vision is not None): + svc = Service(MockEngine(tok, "ok", max_context=CTX), tok, + ChatTemplate(ROOT / "serve/chat_template.jinja"), vision=vision) + m, _, _ = anthropic_to_messages({"messages": tool_msgs}) + ids, _, _ = svc.prepare(m, None, {}) + self.assertEqual(ids.count(pad), n) + self.assertIn(note, tok.decode(ids)) + if svc.embeddings.path: + svc.embeddings.path.unlink(missing_ok=True) + # a tool's picture at a URL is downloaded once (the check and the prompt share the bytes), and one that + # cannot be fetched is a note too + import serve.server as server + url = {"type": "image", "source": {"type": "url", "url": "http://x/ok.png"}} + url_msgs = [{"role": "user", "content": "look"}, call, + {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "t1", "content": [url]}]}] + svc = Service(MockEngine(tok, "ok", max_context=CTX), tok, ChatTemplate(ROOT / "serve/chat_template.jinja"), + vision=self.FakeVision(d)) + m, _, _ = anthropic_to_messages({"messages": url_msgs}) + with mock.patch.object(server.Vision, "download", return_value=b"the picture") as dl: + ids, _, _ = svc.prepare(m, None, {}) + self.assertEqual((dl.call_count, ids.count(pad)), (1, 3)) + svc.embeddings.path.unlink(missing_ok=True) + m, _, _ = anthropic_to_messages({"messages": url_msgs}) + with mock.patch.object(server.Vision, "download", side_effect=ValueError("the image URL could not be read")): + ids, _, _ = svc.prepare(m, None, {}) + self.assertEqual(ids.count(pad), 0) + self.assertIn("[image omitted: the image URL could not be read]", tok.decode(ids)) + svc = Service(MockEngine(tok, "ok", max_context=CTX), tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) + m, _, _ = anthropic_to_messages({"messages": [{"role": "user", "content": [good]}]}) + with self.assertRaises(ValueError): + svc.prepare(m, None, {}) # a text-only tool result renders exactly as before: one string msgs = [{"role": "user", "content": "q"}, call, {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "t1", "content": [{"type": "text", "text": "r"}]}]}] From d6527e395a8b6e73b48fc14f640275303bd93bfc Mon Sep 17 00:00:00 2001 From: sergiywith Date: Sat, 3 Oct 2026 01:09:39 +0300 Subject: [PATCH 37/48] serve: the vision markers inside a message's text stay text and no longer take a picture's place (#150 follow-up) The markers are special tokens only where the template writes them for an image item. The same strings in a message's text (an agent reading chat_template.jinja, a tool result quoting it) became the same special ids, so text with <|vision_start|><|image_pad|> before a picture took that picture's embeddings, every later picture moved up one and the last real marker became text - every count still matched. On 0.1.39 this takes #537's path: the vision markers join / as literal tags (frontend.VISION_TAGS), swapped for private-use marks before the template and encoded as text through the tokenizer's plain spans. A pair of markers cut apart across text parts is refused ("the prompt and its images do not match") instead of shifting. --- serve/frontend.py | 15 ++++++++---- serve/server.py | 5 +++- serve/test_server.py | 56 ++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 71 insertions(+), 5 deletions(-) diff --git a/serve/frontend.py b/serve/frontend.py index f9f7c2dbba..500ceeb0bf 100644 --- a/serve/frontend.py +++ b/serve/frontend.py @@ -148,11 +148,17 @@ def images_of(messages: list[dict]) -> list[str]: # a user quoting "" used to hand the model a real end-of-reasoning token. Before the template is rendered # they are swapped for these private-use characters, and the server encodes the spans they mark as ordinary text. THINK_TAGS = {"": "\U000F0E01", "": "\U000F0E02"} -THINK_MARKS = {v: k for k, v in THINK_TAGS.items()} +# #554: the vision markers the same way. They are special tokens only where the template writes them for an image +# item; the same strings in a message's text (an agent reading chat_template.jinja, a tool result quoting it) became +# the same special ids, so text with <|vision_start|><|image_pad|> before a picture took that picture's embeddings +VISION_TAGS = {"<|vision_start|>": "\U000F0E03", "<|image_pad|>": "\U000F0E04", "<|vision_end|>": "\U000F0E05", + "<|video_pad|>": "\U000F0E06"} +LITERAL_TAGS = {**THINK_TAGS, **VISION_TAGS} +THINK_MARKS = {v: k for k, v in LITERAL_TAGS.items()} def _mark(text: str) -> str: - for tag, mark in THINK_TAGS.items(): + for tag, mark in LITERAL_TAGS.items(): text = text.replace(tag, mark) return text @@ -169,7 +175,7 @@ def _mark_deep(v): def _has_tag(v) -> bool: if isinstance(v, str): - return "" in v or "" in v + return any(tag in v for tag in LITERAL_TAGS) if isinstance(v, dict): return any(_has_tag(x) for x in v.values()) if isinstance(v, list): @@ -178,7 +184,8 @@ def _has_tag(v) -> bool: def mark_think_literals(messages: list[dict], tools: list[dict] | None): - """#537: (messages, tools) with every literal / in their text swapped for THINK_TAGS' marks, and + """#537: (messages, tools) with every literal / (#554: and vision marker) in their text swapped for + LITERAL_TAGS' marks, and whether there was one (None: no change, the same objects back - a prompt without them renders as it always did). An assistant message whose content opens with a whole ... block (clients that send the reasoning inline) keeps that one block as the model's markers, as before.""" diff --git a/serve/server.py b/serve/server.py index fb5d12d0c7..d798cdf362 100644 --- a/serve/server.py +++ b/serve/server.py @@ -2330,7 +2330,10 @@ class Service: literal = self.tok.encode(IMAGE_PAD, parse_special=False) out, k = [], 0 for j, t in enumerate(ids): - if t == pad and j > 0 and ids[j - 1] == start and k < len(encoded): + if t == pad and j > 0 and ids[j - 1] == start: + # more pairs than images: text parts that cut both markers apart (the literal marks keep whole ones text) + if k == len(encoded): + raise ValueError("the prompt and its images do not match") out += [pad] * encoded[k][1] k += 1 elif t == pad: diff --git a/serve/test_server.py b/serve/test_server.py index e55323e038..2df280c1ef 100644 --- a/serve/test_server.py +++ b/serve/test_server.py @@ -319,6 +319,62 @@ class ImageMarkers(unittest.TestCase): self.assertEqual(anthropic_to_messages({"messages": msgs})[0][-1], {"role": "tool", "content": "r"}) + def test_the_whole_marker_in_text_before_images(self): + # Text quoting the template's marker (an agent reading chat_template.jinja) took the first picture's rows, the + # later pictures moved up one and the last real marker became text - every count still matched. + tok = ByteTokenizer() + start, pad, end = (tok.encode(s, parse_special=True)[0] + for s in ("<|vision_start|>", "<|image_pad|>", "<|vision_end|>")) + quoted = "the template writes <|vision_start|><|image_pad|><|vision_end|> per picture" + + class TwoPictures(self.FakeVision): + def encode(self, source): + return self.rows, {"a.png": 2, "b.png": 5}[source] + + def holds(ids, part): + return any(ids[i:i + len(part)] == part for i in range(len(ids) - len(part) + 1)) + + with tempfile.TemporaryDirectory() as d: + svc = Service(MockEngine(tok, "ok", max_context=CTX), tok, ChatTemplate(ROOT / "serve/chat_template.jinja"), + vision=TwoPictures(d)) + pictures = [{"type": "image", "source": "a.png"}, {"type": "text", "text": "and"}, + {"type": "image", "source": "b.png"}] + tools = [{"name": "read", "description": quoted, "parameters": {}}] + cases = {"text part": ([{"role": "user", "content": [{"type": "text", "text": quoted}, *pictures]}], None), + "earlier turns and tools": ([{"role": "user", "content": "read it"}, + {"role": "assistant", "content": quoted, "reasoning_content": quoted, + "tool_calls": [{"function": {"name": "read", + "arguments": {"text": quoted}}}]}, + {"role": "tool", "content": quoted}, + {"role": "user", "content": pictures}], tools)} + for name, (msgs, tools) in cases.items(): + with self.subTest(case=name): + ids, _, _ = svc.prepare(msgs, tools, {}) + starts = [j for j, t in enumerate(ids) if t == start] + self.assertEqual(len(starts), 2) # the pictures' markers, nothing else + for j, rows in zip(starts, (2, 5)): # each followed by its own picture's rows + self.assertEqual(ids[j + 1:j + 2 + rows], [pad] * rows + [end]) + self.assertEqual((ids.count(pad), ids.count(end)), (7, 2)) + self.assertTrue(holds(ids, tok.encode(quoted))) # the text kept its own tokens + # no picture: the quoted markers are text too + ids, _, _ = svc.prepare([{"role": "user", "content": quoted}], None, {}) + self.assertEqual([t for t in ids if t in (start, pad, end)], []) + # markers cut apart across three text parts are no picture's: refused, not a silent shift + cut = [{"type": "text", "text": "<|vision_sta"}, {"type": "text", "text": "rt|><|image_pa"}, + {"type": "text", "text": "d|>"}, *pictures] + with self.assertRaisesRegex(ValueError, "do not match"): + svc.prepare([{"role": "user", "content": cut}], None, {}) + # a prompt without the marker strings has exactly the ids it had (other special tokens as well) + old = lambda m, t=None: tok.encode(svc.template.render(m, tools=t), parse_special=True) # noqa: E731 + for msgs, tools in (([{"role": "user", "content": "plain <|im_end|> <|endoftext|>"}], None), + ([{"role": "system", "content": "s"}, {"role": "user", "content": pictures}], None), + ([{"role": "user", "content": "x"}, {"role": "assistant", "content": "", + "tool_calls": [{"function": {"name": "f", "arguments": {"a": "<|image"}}}]}], + [{"name": "f", "description": "<|vision_", "parameters": {}}])): + with self.subTest(msgs=msgs): + self.assertEqual(svc.encode_prompt(msgs, tools, {}), old(msgs, tools)) + + class ThinkTokenizer(ByteTokenizer): """The byte tokenizer with the model's reasoning markers as specials that are matched even without parse_special, as the real tokenizer does (GGUF token type 4).""" From d50dc91177e9a1012b156fe4c3ecf3d0f6d66501 Mon Sep 17 00:00:00 2001 From: sergiywith Date: Sat, 3 Oct 2026 01:14:43 +0300 Subject: [PATCH 38/48] serve: a request's combined image file is deleted when the request is refused or its answer never starts prepare() wrote the request's combined embeddings file (req-.sve in the vision directory, ~10 MB a picture) right after encoding, and only run()'s finally deleted it. But prepare() could still raise after writing it - EngineStarting (the 503 while the engine starts, #344), the "no room to answer" and "exceeds the context" 400s - and a request can end between prepare() and run(): its client gone before the first chunk was written, anything raised in between. run() is a generator, so one that never started has no finally to run. Each of these left its file behind for good, and clients that retry 503s added one per retry. prepare() now writes the file only after those checks, and records its path before writing it. run() takes the path over as it starts and deletes the file as before; do_POST's finally calls the new Service.drop_embeddings(), which deletes a file that no run() took over. Tests: EngineStarting, no room and exceeds-the-context leave no req-*.sve; over HTTP, on both APIs, a 503, a 400, a client gone after prepare() and answered requests leave none. --- serve/server.py | 25 ++++++++++---- serve/test_server.py | 78 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 97 insertions(+), 6 deletions(-) diff --git a/serve/server.py b/serve/server.py index d798cdf362..1cdafd8285 100644 --- a/serve/server.py +++ b/serve/server.py @@ -2343,11 +2343,6 @@ class Service: if k != len(encoded): raise ValueError("the prompt and its images do not match") ids = out - combined = self.vision.dir / f"req-{uuid.uuid4().hex[:12]}.sve" - with open(combined, "wb") as f: - for path, _ in encoded: - f.write(path.read_bytes()) - self.embeddings.path = combined ctx = self.engine.max_context if ctx <= 0: if getattr(self.engine, "starting", False): # #344: (re)starting, not a prompt that is too long @@ -2370,8 +2365,25 @@ class Service: f"max_tokens (at most {max(0, room)} here), or add \"fit_max_tokens\": true to the " "model's strata-.json to shorten it to the room left (#545)") max_new = max(1, room) # --fit-max-tokens: a shorter completion beats a 400 + if images: + # The request's images in one file for GENI (~10 MB a picture), written once nothing above refuses the + # request: one refused after it (the engine starting, no room) left it in the vision directory for good, + # one more for every retry of a 503. run() deletes it; drop_embeddings() if run() never starts. + combined = self.vision.dir / f"req-{uuid.uuid4().hex[:12]}.sve" + self.embeddings.path = combined # first, so a half-written one is found as well + with open(combined, "wb") as f: + for path, _ in encoded: + f.write(path.read_bytes()) return ids, kwargs.get("enable_thinking", True) is not False, max_new + def drop_embeddings(self) -> None: + """Delete the combined image file prepare() wrote when no run() took it over (a run deletes its own as it + ends): a request can end before its answer starts - its client gone, anything raised after prepare() - and + then nothing else would. The handler calls this when a request is done.""" + path, self.embeddings.path = getattr(self.embeddings, "path", None), None + if path is not None: + Path(path).unlink(missing_ok=True) + def _note(self, n, evs, st=None, rate=None): with self.status_lock: s = self.status if st is None else st @@ -2447,7 +2459,7 @@ class Service: tail = "" # the last characters written (the newlines before a call) timings, before = None, None # this request's timings; the engine's `last` before it raw_ids = [] # every generated id (STRATA_DEBUG: dump raw model text) - emb = getattr(self.embeddings, "path", None) + emb, self.embeddings.path = getattr(self.embeddings, "path", None), None # this run's to delete now # Identity token: only a DONE line replaces engine.last, so a request that died, errored or was # disconnected must not have the PREVIOUS request's decode figures recorded as its own. engine_last0 = getattr(self.engine, "last", None) @@ -3455,6 +3467,7 @@ def make_handler(svc: Service): self._note(outcome="disconnected") raise # as before #332: the server's own handling finally: + svc.drop_embeddings() # the images' file of a request that never got to run() if self.watch_done is not None: self.watch_done.set() record = self.record diff --git a/serve/test_server.py b/serve/test_server.py index 2df280c1ef..c868d2bd33 100644 --- a/serve/test_server.py +++ b/serve/test_server.py @@ -215,6 +215,84 @@ class FitMaxTokens(unittest.TestCase): self.assertIn("no room to answer", b["error"]["message"]) +class VisionTempFiles(unittest.TestCase): + """A request's combined image file (req-*.sve, ~10 MB a picture) goes with the request: one refused after prepare() + wrote it (the engine starting, no room) or whose answer never started left it in the vision directory for good.""" + + MSGS = [{"role": "user", "content": [{"type": "text", "text": "what is it?"}, + {"type": "image", "source": "x.png"}]}] + + @staticmethod + def leftovers(d): + return sorted(p.name for p in Path(d).glob("req-*.sve")) + + def test_a_refused_request_writes_none(self): + from serve.server import EngineStarting + tok = ByteTokenizer() + with tempfile.TemporaryDirectory() as d: + engine = MockEngine(tok, "ok", max_context=0) + svc = Service(engine, tok, ChatTemplate(ROOT / "serve/chat_template.jinja"), + vision=ImageMarkers.FakeVision(d)) + with self.assertRaises(EngineStarting): + svc.prepare(self.MSGS, None, {}, 16) + engine.max_context = 64 # the prompt alone fills it + with self.assertRaisesRegex(ValueError, "no room to answer"): + svc.prepare(self.MSGS, None, {}) + engine.max_context = CTX + with self.assertRaisesRegex(ValueError, "exceeds the context"): + svc.prepare(self.MSGS, None, {}, CTX) + self.assertEqual(self.leftovers(d), []) + svc.prepare(self.MSGS, None, {}, 16) # one that fits has it + self.assertEqual(len(self.leftovers(d)), 1) + svc.drop_embeddings() # ... until the request is done + self.assertEqual(self.leftovers(d), []) + + def test_over_http(self): + import serve.server as server + tok = ByteTokenizer() + with tempfile.TemporaryDirectory() as d: + engine = MockEngine(tok, "\n\nok", max_context=0) + svc = Service(engine, tok, ChatTemplate(ROOT / "serve/chat_template.jinja"), + vision=ImageMarkers.FakeVision(d)) + httpd = serve(svc, port=0) + base = f"http://127.0.0.1:{httpd.server_address[1]}" + + def post(path): + image = {"type": "image_url", "image_url": {"url": "data:image/png;base64,AAAA"}} \ + if path.endswith("completions") else \ + {"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": "AAAA"}} + body = {"model": "m", "max_tokens": 8, "messages": [{"role": "user", "content": [ + {"type": "text", "text": "what is it?"}, image]}]} + req = urllib.request.Request(base + path, data=json.dumps(body).encode(), + headers={"Content-Type": "application/json"}) + try: + with urllib.request.urlopen(req, timeout=30) as r: + return r.status + except urllib.error.HTTPError as e: + with e: + return e.code + + try: + paths = ("/v1/chat/completions", "/v1/messages") + for path in paths: + self.assertEqual(post(path), 503) # the engine is starting (#344); clients retry + engine.max_context = 64 + for path in paths: + self.assertEqual(post(path), 400) # no room to answer + engine.max_context = CTX + # the client gone after prepare(), before the answer started + with mock.patch.object(server, "_debug_req", side_effect=ConnectionResetError("the client is gone")): + for path in paths: + with self.assertRaises(OSError): + post(path) + for path in paths: + self.assertEqual(post(path), 200) + self.assertEqual(self.leftovers(d), []) + finally: + httpd.shutdown() + httpd.server_close() + + class ImageMarkers(unittest.TestCase): """#150: the text "<|image_pad|>" inside a message is text, not an image's place.""" From f6af1ddef91b9e01fc595b6d00bd64e94527a476 Mon Sep 17 00:00:00 2001 From: Breno Perucchi Date: Sun, 4 Oct 2026 20:15:46 -0300 Subject: [PATCH 39/48] serve: "strata_checkpoint": false lets a one-shot request skip its conversation checkpoint (#830) A request with "strata_checkpoint": false sends ckpt=0 to the engine. That request reads its prompt in one part and saves no checkpoint at its last turn boundary, nor the periodic ones of a long prompt. It still resumes from a checkpoint it matches and still saves the system-prompt root. Absent or true: today's behavior; an engine without the key skips it. --- docs/DETAILS.md | 4 ++++ serve/server.py | 4 ++++ serve/test_server.py | 5 +++++ src/program/generate.cpp | 11 +++++++++-- 4 files changed, 22 insertions(+), 2 deletions(-) diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 65e486db98..22b30ef347 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -635,6 +635,10 @@ reading after it instead of from token 0. A prompt read from the start is also c prompt when that is 2,048 tokens or more (engine 0.1.20; PR #62 + #65), so that root exists for agent clients with long system prompts and tool lists. Engine options: `--prompt-cache N` (0 = off), `--prompt-cache-every N`, `--prompt-cache-root N` (0 = no system-prompt checkpoint), `--turn-token ID`. +A one-shot request that no later request continues (a classification call, a probe) can send +`"strata_checkpoint": false` in its body: it then saves no checkpoint at its last turn and reads its prompt in one +part, which skips work nothing would reuse. It still starts from a checkpoint it matches, and the system-prompt root +is still taken. Without the field (or with `true`) nothing changes. **Multiple conversations (opt-in).** Add `--conversation-cache-mib 8192 --conversation-cache-slots 4` to the engine arguments to park up to four conversations diff --git a/serve/server.py b/serve/server.py index 1cdafd8285..00841fcffa 100644 --- a/serve/server.py +++ b/serve/server.py @@ -716,6 +716,10 @@ class StrataEngine: v = tune.get(k) if isinstance(v, (int, float)) and not isinstance(v, bool) and 0.0 <= float(v) <= 1.0: keys += f" {k}={float(v)!r}" + # "strata_checkpoint": false - a one-shot call (a classification, a probe) whose turn no later request + # extends: no conversation checkpoint at its end (#830). It still reuses a cached prefix. Absent = today's. + if sampling.get("strata_checkpoint") is False: + keys += " ckpt=0" return keys + StrataEngine.projection_key(sampling) @staticmethod diff --git a/serve/test_server.py b/serve/test_server.py index c868d2bd33..133db7d3e1 100644 --- a/serve/test_server.py +++ b/serve/test_server.py @@ -1070,6 +1070,11 @@ class SamplingKeys(unittest.TestCase): bad = self.keys(strata_tune={"pcie_frac": 3, "spec_min_p": True, "pool_workers": 2}) self.assertFalse([x for x in bad if x.split("=")[0] in ("pcie_frac", "spec_min_p", "pool_workers")]) + def test_checkpoint_key(self): + self.assertIn("ckpt=0", self.keys(temperature=0, strata_checkpoint=False)) + for absent in ({}, {"strata_checkpoint": True}, {"strata_checkpoint": 0}, {"cache_prompt": False}): + self.assertNotIn("ckpt=0", self.keys(**absent), absent) + def test_penalty_window(self): self.assertIn("penalty_last_n=64", self.keys(presence_penalty=1.5)) self.assertIn("penalty_last_n=4096", self.keys(repetition_penalty=1.1, penalty_last_n=4096)) diff --git a/src/program/generate.cpp b/src/program/generate.cpp index c30713cf5f..e013cefad9 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -6316,6 +6316,10 @@ int main(int argc, char** argv) { float req_min_p = 0.0f, req_penalty_repeat = 1.0f, req_penalty_freq = 0.0f, req_penalty_present = 0.0f; int req_penalty_last_n = 0; int req_cvec = 1; // cvec=0|1: a loaded control vector for this request (on when absent) + // ckpt=0: a one-shot call whose turn no later request extends. It reads its prompt in one part and saves + // no checkpoint at the last turn boundary (nor the periodic ones of a long prompt); it still resumes from + // a checkpoint it matches, and still saves the root of a long enough system prompt. Absent = today's. + int req_ckpt = 1; // tuning keys (setup's calibration measures settings without restarting the engine): the PCIe share of // the missed experts and the draft-probability floor, for this request only double req_pcie_frac = o.pcie_frac, req_spec_min_p = o.spec_min_p; @@ -6332,6 +6336,7 @@ int main(int argc, char** argv) { const std::string key = tok.substr(0, eq); const float fv = std::strtof(tok.c_str() + eq + 1, nullptr); if (key == "cvec") req_cvec = std::atoi(tok.c_str() + eq + 1); + else if (key == "ckpt") req_ckpt = std::atoi(tok.c_str() + eq + 1) != 0; else if (key == "temperature") req_temperature = fv; else if (key == "top_p") req_top_p = fv; else if (key == "top_k") req_top_k = std::atoi(tok.c_str() + eq + 1); @@ -6720,7 +6725,7 @@ int main(int argc, char** argv) { pp_from = read_from; pp_reached = read_from; pp_t0 = r0; - pp_next_check = reread_to > 0 ? INT64_MAX : resume + o.prompt_cache_every; + pp_next_check = reread_to > 0 || !req_ckpt ? INT64_MAX : resume + o.prompt_cache_every; // ckpt=0: none { std::lock_guard lk(part_mu); part_at.clear(); @@ -7047,9 +7052,11 @@ int main(int argc, char** argv) { // which the retention policy pins (conv_cache.hpp), so the next new chat reads only what comes after it. // (PR #65, code-martin.) Only for a system prompt of --prompt-cache-root tokens or more: a small one // is cheaper to read again than the extra part costs (~0.3 s). + const int64_t last_turn = turn_at; // ckpt=0 drops the split there, the root is still looked for before it + if (!req_ckpt) turn_at = -1; int64_t root_at = -1; if (o.prompt_cache > 0 && o.turn_token >= 0 && o.prompt_cache_root > 0 && (read_from == 0 || resumed_from0)) - for (int64_t i = 1; i < turn_at; ++i) + for (int64_t i = 1; i < last_turn; ++i) if (ids[(size_t) i] == o.turn_token) { if (i >= o.prompt_cache_root) root_at = i; break; From 5f317a3afc0bb0225f9705f4bb66f716fb60b1d2 Mon Sep 17 00:00:00 2001 From: Breno Perucchi Date: Sun, 4 Oct 2026 20:28:36 -0300 Subject: [PATCH 40/48] ckpt=0: its session is neither continued nor parked; docs say what is skipped and when the root is taken --- docs/DETAILS.md | 7 ++++--- serve/server.py | 2 +- src/program/generate.cpp | 9 +++++---- 3 files changed, 10 insertions(+), 8 deletions(-) diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 22b30ef347..737b08563d 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -636,9 +636,10 @@ prompt when that is 2,048 tokens or more (engine 0.1.20; PR #62 + #65), so that system prompts and tool lists. Engine options: `--prompt-cache N` (0 = off), `--prompt-cache-every N`, `--prompt-cache-root N` (0 = no system-prompt checkpoint), `--turn-token ID`. A one-shot request that no later request continues (a classification call, a probe) can send -`"strata_checkpoint": false` in its body: it then saves no checkpoint at its last turn and reads its prompt in one -part, which skips work nothing would reuse. It still starts from a checkpoint it matches, and the system-prompt root -is still taken. Without the field (or with `true`) nothing changes. +`"strata_checkpoint": false` in its body: it saves no checkpoint at its last turn nor every 16K tokens, so what +follows the reused prefix (or the root) is read in one run, and its session is not kept or parked for a next request. +It still starts from a checkpoint it matches, and still saves the system-prompt root when that reaches +`--prompt-cache-root`. Without the field (or with `true`) nothing changes. **Multiple conversations (opt-in).** Add `--conversation-cache-mib 8192 --conversation-cache-slots 4` to the engine arguments to park up to four conversations diff --git a/serve/server.py b/serve/server.py index 00841fcffa..6f4bdf9d6b 100644 --- a/serve/server.py +++ b/serve/server.py @@ -717,7 +717,7 @@ class StrataEngine: if isinstance(v, (int, float)) and not isinstance(v, bool) and 0.0 <= float(v) <= 1.0: keys += f" {k}={float(v)!r}" # "strata_checkpoint": false - a one-shot call (a classification, a probe) whose turn no later request - # extends: no conversation checkpoint at its end (#830). It still reuses a cached prefix. Absent = today's. + # extends: no conversation checkpoint for it (#830). It still reuses a cached prefix. Absent = as before. if sampling.get("strata_checkpoint") is False: keys += " ckpt=0" return keys + StrataEngine.projection_key(sampling) diff --git a/src/program/generate.cpp b/src/program/generate.cpp index e013cefad9..5e4521673f 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -6316,9 +6316,10 @@ int main(int argc, char** argv) { float req_min_p = 0.0f, req_penalty_repeat = 1.0f, req_penalty_freq = 0.0f, req_penalty_present = 0.0f; int req_penalty_last_n = 0; int req_cvec = 1; // cvec=0|1: a loaded control vector for this request (on when absent) - // ckpt=0: a one-shot call whose turn no later request extends. It reads its prompt in one part and saves - // no checkpoint at the last turn boundary (nor the periodic ones of a long prompt); it still resumes from - // a checkpoint it matches, and still saves the root of a long enough system prompt. Absent = today's. + // ckpt=0: a one-shot call whose turn no later request extends. No checkpoint at its last turn boundary + // (so no split there) nor every --prompt-cache-every tokens, and its session is neither continued nor + // parked after it. It still resumes from a checkpoint it matches, and still saves the system-prompt root + // when that reaches --prompt-cache-root. Absent = checkpointed as before. int req_ckpt = 1; // tuning keys (setup's calibration measures settings without restarting the engine): the PCIe share of // the missed experts and the draft-probability floor, for this request only @@ -7291,7 +7292,7 @@ int main(int argc, char** argv) { // (the checkpoints taken while reading it are still good) live.swap(consumed); live_imgs = imgs_below(req_imgs, (int64_t) live.size()); - live_ok = o.prompt_cache > 0; + live_ok = o.prompt_cache > 0 && req_ckpt; // ckpt=0: nothing to continue or park (#830) } static const bool state_hash = std::getenv("STRATA_STATE_HASH") != nullptr; if (state_hash && live_ok) { From 600c4288215dd79ef6b9e0fe23132e07df953834 Mon Sep 17 00:00:00 2001 From: Breno Perucchi Date: Sun, 4 Oct 2026 20:59:29 -0300 Subject: [PATCH 41/48] ckpt=0: still print STRATA_STATE_HASH for the request, so the parity gates see every request --- src/program/generate.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 5e4521673f..907a23c6b0 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -7295,7 +7295,7 @@ int main(int argc, char** argv) { live_ok = o.prompt_cache > 0 && req_ckpt; // ckpt=0: nothing to continue or park (#830) } static const bool state_hash = std::getenv("STRATA_STATE_HASH") != nullptr; - if (state_hash && live_ok) { + if (state_hash && !cancelled && o.prompt_cache > 0) { // every finished request, ckpt=0 too (parity gates) // DEBUG: a fingerprint of every part of the session over the positions it holds ([0, L)), and // separately of what lies past them in the last KV page (stale cells, fine unless something reads them) if (cudaDeviceSynchronize() != cudaSuccess) { From add41aef65a71c55e2995fab1d859df2482e5669 Mon Sep 17 00:00:00 2001 From: Elias Klughammer Date: Sun, 4 Oct 2026 22:35:17 +0200 Subject: [PATCH 42/48] server: "return_progress": true puts the prompt's PP line on the stream as llama.cpp's prompt_progress Maintainer: prompt_progress() returns nothing under --batch (one global progress line), test (#837) --- docs/DETAILS.md | 9 +++++ serve/server.py | 55 ++++++++++++++++++++++---- serve/test_server.py | 91 ++++++++++++++++++++++++++++++++++++++++++-- 3 files changed, 144 insertions(+), 11 deletions(-) diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 737b08563d..c566b06e88 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -534,6 +534,15 @@ print(r.choices[0].message.content) long prompt the stream sends keep-alives, so agents do not time out; the server window prints progress every 15 s, and `GET /status` says what it is doing (`reading the prompt`, `answering`, tokens so far). Closing the connection or pressing stop in your app really stops the model, so the next request starts at once. +- **Prefill progress in the stream (opt-in).** `"return_progress": true` puts that progress on the stream instead of + sending only the keep-alive, as one extra field on a chunk with an empty delta: `prompt_progress` with `total`, + `cache`, `processed` and `time_ms`. Those are llama.cpp's four fields and mean the same there (`time_ms` is the time + since the prompt started reading, and the work still to do is `(total-cache) - (processed-cache)`), so a client that + draws a prefill bar for llama.cpp draws one here too. It is off unless the request asks, as it is in llama.cpp. + The engine says one line per `--prefill` chunk, so that chunk is the step: measured on two RTX 3090s with + `--prefill auto` (8192 tokens), a 42,131 token prompt read in 15 s sent six of them. A prompt shorter than one chunk + sends nothing, and that is on purpose: its only line arrives once the prompt is read, because the last tokens go + through the verify windows rather than the batched path, so it stops up to `--short-read` tokens short of the end. - **Chat apps.** Any app with an "OpenAI-compatible" provider works: base URL `http://127.0.0.1:8080/v1`, any API key. - **OpenCode** (#543). A starting point for `opencode.jsonc` (in your project, or `~/.config/opencode/`); the field names are OpenCode's, so check its config docs if your version differs: diff --git a/serve/server.py b/serve/server.py index 6f4bdf9d6b..5681e71cfb 100644 --- a/serve/server.py +++ b/serve/server.py @@ -440,6 +440,8 @@ class StrataEngine: self.info = {} # INFO key=value facts (engine 0.1.8+): kv, expert slots, ... (Monitor tab) self.prefill_tok_s_mean = None self.progress = None # (read, total) prompt tokens while a prompt is read, from PP lines + self.progress_ms = 0 # PP's own milliseconds since the prompt started (its third field) + self.reused = 0 # RESUME: prompt tokens not read again (a client takes them out of the work) self.silent_note = None try: # a ready-made engine's BUILD.json says its version self.info["version"] = json.loads((Path(exe).parent / "BUILD.json").read_text()).get("version") @@ -766,6 +768,7 @@ class StrataEngine: f = line.split() if len(f) >= 3 and f[1].isdigit() and f[2].isdigit(): self.progress = (int(f[1]), int(f[2])) + self.progress_ms = float(f[3]) if len(f) >= 4 else 0.0 self.prefill_tok_s_mean = float(f[4]) if len(f) >= 5 else None if not stopped and cancel.is_set(): # #879: a Stop during the prompt read went out only after the first token (or after 10 s of @@ -901,7 +904,7 @@ class StrataEngine: admission to its BADM, a slot is BSTOPped and freed at its BDONE.""" if not self.alive(): raise EngineDied("the engine is unavailable; this request was not sent") - self.progress = None + self.progress, self.progress_ms, self.reused = None, 0, 0 keys = self.sampling_keys(sampling or {}) out: list[int] = [] pending: list[int] = [] @@ -1146,7 +1149,7 @@ class StrataEngine: if getattr(self, "batch", 0): yield from self.generate_batched(ids, max_new, sampling, cancel, embeddings) return - self.progress = None + self.progress, self.progress_ms, self.reused = None, 0, 0 self.prefill_tok_s_mean = None # an image request takes the same sampling keys as text (#75: it used to decode greedily whatever was asked) head = f"GENI {int(max_new)}{self.sampling_keys(sampling or {})} {embeddings}" if embeddings else \ @@ -1192,6 +1195,7 @@ class StrataEngine: f = line.split() if len(f) >= 3 and f[1].isdigit() and f[2].isdigit(): self.progress = (int(f[1]), int(f[2])) # prompt progress, one per chunk: also a heartbeat (the + self.progress_ms = float(f[3]) if len(f) >= 4 else 0.0 self.prefill_tok_s_mean = float(f[4]) if len(f) >= 5 else None rate, chunk = self.prefill_tok_s_mean or 0.0, int(f[1]) - read_to read_to = int(f[1]) @@ -1202,7 +1206,7 @@ class StrataEngine: yield None elif line.startswith("RESUME "): # the reused tokens: the first chunk starts after them try: - read_to = int(line.split()[1]) + read_to = self.reused = int(line.split()[1]) except (IndexError, ValueError): pass elif line.startswith("DONE"): @@ -1293,6 +1297,7 @@ class StrataEngine: self.proc = None self.ended = True self.progress, self.last = None, {} + self.progress_ms, self.reused = 0, 0 IMAGE_URL_MAX = 32 << 20 # an image URL is read up to this (the web app attaches pictures of up to 20 MB) @@ -2838,11 +2843,41 @@ def run_with_mcp(svc: Service, hub, messages, tools, kw, ids, thinking, max_new, # ------------------------------------------------------------------------------------------------ OpenAI +# The engine's last PP line stops short of the prompt: up to `--short-read` tokens (generate.cpp's `short_read`, 64 by +# default) are read through the verify windows instead of the batched path, so the batched path never reports the whole +# prompt. A PP that close to the end says the prompt is read. It matters because a prompt shorter than one `--prefill` +# chunk sends exactly one PP, that one: a client would see a bar that appears already full. Such a line is dropped, and +# the answer's first token ends the progress for the client anyway. +PP_DONE_TAIL = 64 + + +def prompt_progress(svc: Service): + """The last PP line as llama.cpp's `prompt_progress`, so a client written for llama.cpp reads both servers: the + same four fields, `time_ms` elapsed since prompt reading started, and `processed` counting from token 0 so that a + client takes the reused prefix out with `cache` (llama.cpp's rule: the timed progress is + `(processed-cache)/(total-cache)`). None when there is nothing to say: no PP yet, or the line that says the prompt + is read. An engine too old to print RESUME gives `cache` 0, which only makes a reused prefix count as work.""" + engine = svc.engine + if getattr(engine, "batch", 0): # --batch: the engine's progress is one global line, not this request's + return None + progress = getattr(engine, "progress", None) + if not progress: + return None + read, total = progress + if total <= 0 or total - read <= PP_DONE_TAIL: + return None + return {"total": int(total), "cache": int(getattr(engine, "reused", 0) or 0), "processed": int(read), + "time_ms": int(getattr(engine, "progress_ms", 0) or 0)} + + def openai_chunks(svc: Service, req: dict, ids, thinking, tools, max_new, cancel, run=None, force=None): """`run`: the events to send instead of Service.run's (run_with_mcp); its ("mcp", {...}) items become chunks with an empty delta and a `strata_mcp` field, which only the web app reads. `force`: see Service.run.""" cid, created = "chatcmpl-" + uuid.uuid4().hex[:24], int(time.time()) model = svc.model_for(req) + # llama.cpp's flag, and its default: a client that wants prompt progress asks for it, and nothing changes for one + # that does not. Strata already sends a keep-alive comment on every PP line, so this only fills that line in. + want_progress = bool(req.get("return_progress")) def chunk(delta, finish=None): return {"id": cid, "object": "chat.completion.chunk", "created": created, "model": model, @@ -2854,7 +2889,10 @@ def openai_chunks(svc: Service, req: dict, ids, thinking, tools, max_new, cancel finished = set() # ... and the ones whose final tool_call came (#211) for kind, x in run if run is not None else svc.run(ids, thinking, tools, max_new, req, cancel, force=force): if kind == "ping": - yield None + # a PP line: the prompt is being read and there is nothing to say yet. It used to be only the SSE comment; + # now it carries the progress when the client asked, and stays the comment when there is nothing to report. + pp = prompt_progress(svc) if want_progress else None + yield None if pp is None else {**chunk({}), "prompt_progress": pp} elif kind == "mcp": c = chunk({}) c["strata_mcp"] = x @@ -2944,11 +2982,12 @@ def structured_chunks(chunks, validator): heartbeat = time.monotonic() try: for chunk in chunks: - if chunk is not None: - buffered.append(chunk) - if chunk is None or time.monotonic() - heartbeat >= 1: + progress = chunk is not None and "prompt_progress" in chunk + if chunk is not None and not progress: + buffered.append(chunk) # a progress chunk carries no content: there is nothing in it to validate + if chunk is None or progress or time.monotonic() - heartbeat >= 1: heartbeat = time.monotonic() - yield None + yield chunk if progress else None result = openai_collect(buffered) choice = result["choices"][0] content = validated_json(choice["message"]["content"], validator, choice["finish_reason"]) diff --git a/serve/test_server.py b/serve/test_server.py index 133db7d3e1..498ace481e 100644 --- a/serve/test_server.py +++ b/serve/test_server.py @@ -21,9 +21,9 @@ from unittest import mock sys.path.insert(0, str(Path(__file__).resolve().parents[1])) from serve.frontend import ChatTemplate # noqa: E402 -from serve.server import (CTX_SLACK, ByteTokenizer, EngineDied, GpuBusy, MockEngine, Service, StrataEngine, # noqa: E402 - engine_args, layer_split_value, prompt_tokens_seen, request_timings, serve, - start_failure_hint) +from serve.server import (CTX_SLACK, ByteTokenizer, EngineDied, GpuBusy, MockEngine, PP_DONE_TAIL, Service, # noqa: E402 + StrataEngine, engine_args, layer_split_value, prompt_progress, prompt_tokens_seen, + request_timings, serve, start_failure_hint) from types import SimpleNamespace # noqa: E402 ROOT = Path(__file__).resolve().parents[1] @@ -1747,6 +1747,79 @@ class LiveRate(unittest.TestCase): httpd.server_close() +class PromptProgress(unittest.TestCase): + """`return_progress: true` puts the engine's PP line on the stream as llama.cpp's `prompt_progress`, so a client + written for llama.cpp shows prefill progress from either server. Off by default, as it is in llama.cpp.""" + + TOKENS, TOTAL = 40, 25000 + + class Reading(MockEngine): + """A prompt read in three chunks and then answered: the engine's PP lines reach the HTTP layer as pings.""" + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.progress, self.progress_ms, self.reused, self.total = None, 0.0, 0, 0 + + def generate(self, ids, max_new, sampling, cancel, embeddings=None): + for read, ms in ((8192, 2200.0), (16384, 4400.0), (24576, 6600.0)): + self.progress, self.progress_ms = (read, self.total), ms + yield None + yield from super().generate(ids, max_new, sampling, cancel, embeddings) + + def setUp(self): + tok = ByteTokenizer() + self.engine = self.Reading(tok, "y" * self.TOKENS, max_context=CTX) + self.engine.total = self.TOTAL + self.engine.reused = 4096 # RESUME: the conversation checkpoint's reused prefix + self.svc = Service(self.engine, tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) + self.httpd = serve(self.svc, port=0) + self.base = f"http://127.0.0.1:{self.httpd.server_address[1]}" + + def tearDown(self): + self.httpd.shutdown() + self.httpd.server_close() + + def stream(self, **req): + body = json.dumps({"model": "m", "max_tokens": self.TOKENS, "stream": True, + "messages": [{"role": "user", "content": "hi"}], **req}).encode() + with urllib.request.urlopen(urllib.request.Request(self.base + "/v1/chat/completions", data=body, + headers={"Content-Type": "application/json"}), + timeout=30) as r: + return r.read().decode() + + def test_a_client_that_asks_gets_one_progress_per_chunk(self): + steps = [json.loads(line[6:]) for line in self.stream(return_progress=True).splitlines() + if line.startswith("data: ") and "prompt_progress" in line] + self.assertEqual([s["prompt_progress"] for s in steps], + [{"total": self.TOTAL, "cache": 4096, "processed": 8192, "time_ms": 2200}, + {"total": self.TOTAL, "cache": 4096, "processed": 16384, "time_ms": 4400}, + {"total": self.TOTAL, "cache": 4096, "processed": 24576, "time_ms": 6600}], + "llama.cpp's four fields, time_ms elapsed since the read started") + self.assertTrue(all(s["choices"][0]["delta"] == {} for s in steps), "a progress chunk carries no content") + + def test_a_client_that_does_not_ask_gets_nothing(self): + text = self.stream() + self.assertNotIn("prompt_progress", text) + self.assertIn(": keep-alive", text, "the PP line still keeps the connection alive as it used to") + + def test_the_line_that_says_the_prompt_is_read_is_dropped(self): + # the batched path leaves up to --short-read tokens to the verify windows, so its last PP stops short of the + # prompt. A prompt under one --prefill chunk sends only that line, and it would show a bar already full. + for short in (PP_DONE_TAIL, PP_DONE_TAIL - 1, 1): + self.engine.progress, self.engine.progress_ms = (self.TOTAL - short, self.TOTAL), 6600.0 + self.assertIsNone(prompt_progress(self.svc), f"a PP {short} token(s) short of the end says it is read") + self.engine.progress = (self.TOTAL - PP_DONE_TAIL - 1, self.TOTAL) + self.assertEqual(prompt_progress(self.svc)["processed"], self.TOTAL - PP_DONE_TAIL - 1) + + def test_nothing_before_the_first_chunk(self): + self.engine.progress = None + self.assertIsNone(prompt_progress(self.svc), "no PP line yet: there is no rate to show") + self.engine.progress = (8192, self.TOTAL) + self.engine.reused = 0 # an engine too old to print RESUME never sets it + self.assertEqual(prompt_progress(self.svc)["cache"], 0, + "an engine too old to print RESUME counts the reused prefix as work") + + class SharedSettings(unittest.TestCase): """The web app's "Use for other apps too": POST /settings makes its Chat settings every client's defaults.""" @@ -3558,3 +3631,15 @@ class AnswerBeforeTheBody(unittest.TestCase): if __name__ == "__main__": unittest.main() + + +class PromptProgressBatch(unittest.TestCase): + """#837: under --batch the engine's progress is one global line: prompt_progress() says nothing.""" + + def test_nothing_under_batch(self): + from serve.server import prompt_progress + engine = SimpleNamespace(progress=(512, 4096), progress_ms=900, reused=0, batch=0) + svc = SimpleNamespace(engine=engine) + self.assertEqual(prompt_progress(svc), {"total": 4096, "cache": 0, "processed": 512, "time_ms": 900}) + engine.batch = 2 + self.assertIsNone(prompt_progress(svc)) From c34732624253ab1b5aec26f1c453b07301b6f490 Mon Sep 17 00:00:00 2001 From: wangmeng Date: Mon, 5 Oct 2026 08:54:50 +0800 Subject: [PATCH 43/48] serve: opt-in recovery from repeated reasoning passages Maintainer: separate stop and recover modes (reasoning_loop_recovery: false|stop|recover), token-level splice of the effort sentence (EFFORT_TEXT), a client's top_p/top_k never touched, checks at the first clean boundary after each 512 tokens, bounded history, tests incl. a literal think tag (#728, #869) --- docs/DETAILS.md | 14 ++ serve/server.py | 110 ++++++++++++++- serve/test_reasoning_loop_recovery.py | 195 ++++++++++++++++++++++++++ 3 files changed, 316 insertions(+), 3 deletions(-) create mode 100644 serve/test_reasoning_loop_recovery.py diff --git a/docs/DETAILS.md b/docs/DETAILS.md index c566b06e88..df47bd2eae 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -517,6 +517,20 @@ print(r.choices[0].message.content) server ends it there with `finish_reason` `"length"` and says so in its window: a model in a loop, or a broken state that answers one token forever (#606 saw 36,689 tokens of `!`). `"repeat_stop_tokens": N` in `strata-.json` sets the run length; `0` turns it off (for a request that really wants one token many times). +- **Repeated reasoning (opt-in, #728).** The single-token guard above does not see a model that repeats whole + passages. `"reasoning_loop_recovery"` in `strata-.json` is `false` (the default), `"stop"` or `"recover"` + (`true` means `"recover"`). Every 512 output tokens, at a complete character and parser boundary, the reasoning is + measured over its last 2,000 words and punctuation marks (counting passages over the last 30,000 words). If at + least 25% belong to 12-word passages seen three times, `"stop"` ends the reply there as `"length"` and says so in + the server window. `"recover"` stops and drains that generation, then goes on once from all its generated token + ids with the template's low-effort sentence in place of the xhigh one in the first system message (a splice of + token ids: the rest of the prompt is not decoded or re-encoded). The task stays the same; no answer or `` + is inserted, and both passes share the original output limit. On recovery only, temperature is raised to at least + 1.0 and presence penalty to at least 1.5; a client's top-p, top-k and seed are never changed. `/metrics` records + `reasoning_recoveries` and the coverage. This is a policy, not a numerical engine fix or a guarantee of an answer. + `"recover"` needs the exact xhigh sentence in the first system message and skips requests with images; re-reading + the changed prefix costs prompt time. Either mode can mistake repeated useful code or checks for a loop, so keep + the recorded answer quality alongside the completion rate when testing it. - **Changing the effort without re-reading the prompt (opt-in, 0.1.39, #458).** The effort's instruction is the first thing in the prompt, so a request that only changes the effort (an agent's "think harder" switch, `none` for a quick tool step) reads the whole conversation again. `"effort_position": "end"` in `strata-.json` renders diff --git a/serve/server.py b/serve/server.py index 5681e71cfb..1a1dd5ba9e 100644 --- a/serve/server.py +++ b/serve/server.py @@ -70,7 +70,11 @@ EFFORT_TURN = "<|im_start|>system\n{}<|im_end|>\n" EFFORT_TEXT = {"low": "Reasoning effort is set to low. Keep your thinking brief and focused, moving directly to the " "conclusion without unnecessary elaboration.", "medium": "Reasoning effort is set to medium. Think as much as the task needs, without unnecessary " - "elaboration."} + "elaboration.", + # the template's own xhigh sentence (chat_template.jinja), which #728's recovery swaps for the low one + "xhigh": "Reasoning effort is set to xhigh. Please think carefully through the task, validate key " + "assumptions, consider plausible alternatives, and prioritize correctness, consistency, and " + "clarity in the final answer."} VISION_START = "<|vision_start|>" # #606: a reply that repeats one token this many times in a row is ended there ("length"): a model in a loop, or a # broken state that answers one token forever (an issue saw 36,689 tokens of "!"). The config's "repeat_stop_tokens" @@ -78,6 +82,54 @@ VISION_START = "<|vision_start|>" REPEAT_STOP_TOKENS = 256 # #123: what closes the thinking when it reaches reasoning_budget_tokens (the model's own end-of-thinking tag after it) REASONING_WRAP_UP = "\n\nI have thought about this long enough; time to give my answer.\n\n\n" +# #728: opt-in handling of reasoning that repeats whole passages (which the single-token guard above cannot see). +# "reasoning_loop_recovery": "stop" ends the reply there; "recover" (or true) goes on from the same output with the +# low-effort instruction in place of the xhigh one. Both off by default. +HIGH_EFFORT = EFFORT_TEXT["xhigh"] +LOW_EFFORT = EFFORT_TEXT["low"] +LOOP_CHECK_EVERY = 512 # output tokens between two looks at the reasoning (at a clean parser boundary) +LOOP_COVERAGE = 0.25 # the share of the last 2,000 words inside 12-word passages seen three times +LOOP_HISTORY_WORDS = 30000 # how far back the passages are counted (bounds the cost of a look) + + +def reasoning_repeat_coverage(text): + """Coverage of recent words by 12-word passages seen at least three times. + + Only reasoning is supplied. The history (the last LOOP_HISTORY_WORDS words) detects repeated verification passes + separated by long code drafts; the recent window excludes old repetitions. + """ + words = re.findall(r"\w+|[^\w\s]", text.lower())[-LOOP_HISTORY_WORDS:] + width, window = 12, 2000 + if len(words) < window: + return 0.0 + grams = [tuple(words[i:i + width]) for i in range(len(words) - width + 1)] + counts = collections.Counter(grams) + start = max(0, len(words) - window) + covered = set() + for i in range(start, len(grams)): + if counts[grams[i]] >= 3: + covered.update(range(i, i + width)) + return len(covered) / (len(words) - start) + + +def focused_recovery_prompt(tok, ids, generated): + """The prompt's ids with the xhigh effort sentence of the first system message replaced by the low one, then + every token generated so far. A splice of token ids: the prompt is never decoded and encoded again, so a literal + `` or vision marker in it (#537, #554) stays what it was. None when the sentence is not there as whole + tokens in the first system message (a user's text never counts). No answer or end-of-thinking is inserted.""" + end = tok.encode(IM_END, parse_special=True) + if len(end) != 1 or end[0] not in ids: + return None + head = ids[:ids.index(end[0])] + if not tok.decode(head).startswith("<|im_start|>system\n"): + return None + old, new = tok.encode(HIGH_EFFORT, parse_special=False), tok.encode(LOW_EFFORT, parse_special=False) + for i in range(len(head) - len(old) + 1): + if head[i:i + len(old)] == old: + return ids[:i] + new + ids[i + len(old):] + list(generated) + return None + + LOOPBACK_NAMES = ("localhost", "127.0.0.1", "::1") CTX_SLACK = 8 # `strata --serve` rejects prompt + max_new + 8 > context: keep the same margin here # The live tok/s is a rate over a window, not a mean since the first token: a mean reads ~1/elapsed at the first @@ -1839,6 +1891,7 @@ class Service: self.min_free_vram_mib = 0 self.before_load = None self.vram_reserve = None # #533: the last POST /v1/vram reserve (None: the start's) + self.reasoning_loop_recovery = False self.reasoning_budget_tokens = 0 # #123: the config's default thinking budget (0: none) self.repeat_stop_tokens = REPEAT_STOP_TOKENS # #606: one token this many times in a row ends a reply (0: off) self.anthropic_think_unasked = True # #278: "anthropic_thinking": "on_request" -> False @@ -2467,6 +2520,8 @@ class Service: opening, force = parser.feed(force), None tail = "" # the last characters written (the newlines before a call) timings, before = None, None # this request's timings; the engine's `last` before it + recovery_count, reasoning_text, repeat_coverage = 0, "", 0.0 + looped, next_loop_check = False, LOOP_CHECK_EVERY # #728: reasoning that repeats whole passages raw_ids = [] # every generated id (STRATA_DEBUG: dump raw model text) emb, self.embeddings.path = getattr(self.embeddings, "path", None), None # this run's to delete now # Identity token: only a DONE line replaces engine.last, so a request that died, errored or was @@ -2497,7 +2552,7 @@ class Service: with self.status_lock: st.update(busy=True, phase="reading the prompt", prompt_tokens=len(ids), generated=0, started=time.time(), first_token=None, tool=None, tail="", - max_tokens=max_new) + max_tokens=max_new, reasoning_recoveries=0) if par: self.live_reqs[id(st)] = (st, rate) self.status.update(st) @@ -2511,6 +2566,7 @@ class Service: while True: gen = self.engine.generate(prompt, max_new - n, sampling, cancel, embeddings=emb) if emb \ else self.engine.generate(prompt, max_new - n, sampling, cancel) + recover_prompt = None seg, wrap, leaving = [], False, False # this pass's tokens; the budget is reached; closed opens = False # the thinking is over: write the forced call's opening try: @@ -2541,10 +2597,24 @@ class Service: self._note(n, evs, st, rate) last_print = self._progress(last_print, st=st) for ev in evs: + if self.reasoning_loop_recovery and ev.kind == "reasoning": + reasoning_text += ev.text or "" yield "event", ev if stops is not None and stops.hit is not None: finish = "stop" # gen.close() below STOPs the engine, as for a stop token break + if (self.reasoning_loop_recovery and not recovery_count and parser.state == "reasoning" + and n >= next_loop_check and not parser.buf and not detok.pending()): + next_loop_check = n + LOOP_CHECK_EVERY + repeat_coverage = reasoning_repeat_coverage(reasoning_text) + if repeat_coverage >= LOOP_COVERAGE: + if self.reasoning_loop_recovery == "stop": + looped = True # #728: end the reply here, as for a repeated token + break + if not emb: # "recover": not for a request with pictures + recover_prompt = focused_recovery_prompt(self.tok, ids, raw_ids) + if recover_prompt is not None: + break if budget and parser.state == "reasoning": thought += 1 # at a clean point: no tag held back, no character split across tokens @@ -2578,6 +2648,26 @@ class Service: self._say_died(e) if not leaving and not cancel.is_set(): raise + if recover_prompt is not None and not cancel.is_set() and n < max_new: + recovery_count += 1 + # Only the two settings that keep the same words coming are raised (temperature to at + # least 1.0, presence penalty to at least 1.5): a client's top_p and top_k are never + # touched, and its own request dict is copied, not changed. + want = (max(1.0, float((sampling or {}).get("temperature") or 0)), + max(1.5, float((sampling or {}).get("presence_penalty") or 0))) + if want != tuple(float((sampling or {}).get(k) or 0) + for k in ("temperature", "presence_penalty")): + sampling = {**(sampling or {}), "temperature": want[0], "presence_penalty": want[1]} + prompt = recover_prompt + with self.status_lock: + st["reasoning_recoveries"] = recovery_count + if trace is not None: + trace["reasoning_recoveries"] = recovery_count + trace["reasoning_repeat_coverage"] = round(repeat_coverage, 3) + print(f"[strata] repeated reasoning detected at {n} tokens " + f"(coverage={repeat_coverage:.3f}); resuming the same output with the low-effort " + "instruction (reasoning_loop_recovery)", flush=True) + continue if not (wrap or opens) or cancel.is_set(): break # #123: the thinking reached reasoning_budget_tokens. Close it the way the model would (a @@ -2611,6 +2701,10 @@ class Service: prompt = prompt + seg + extra if cancel.is_set(): finish = "cancel" + elif looped: + print(f"[strata] the thinking repeated the same passages (coverage={repeat_coverage:.3f}) at " + f"{n} tokens: ended as \"length\" (reasoning_loop_recovery: \"stop\" in " + "strata-.json; remove it to turn this off)", flush=True) elif repeated: print(f"[strata] the reply repeated one token ({self.tok.decode([run_tok])!r}) " f"{run_len} times in a row: ended as \"length\" (repeat_stop_tokens in " @@ -2645,6 +2739,8 @@ class Service: "prompt_tokens": seen, "reused": last.get("reused"), "output_tokens": n, # the request's whole prompt, and the tokens read of it (None: an older engine) "prompt_total": len(ids), "prompt_read": last.get("prompt_read"), + "reasoning_recoveries": recovery_count, + "reasoning_repeat_coverage": round(repeat_coverage, 3), "engine_generated": last.get("generated"), "prompt_ms": last.get("prompt_ms"), "decode_ms": last.get("decode_ms"), "decode_tok_s": round(last["generated"] / (last["decode_ms"] / 1000), 1) @@ -2702,7 +2798,8 @@ class Service: if stops is not None and stops.hit is None and stops.held: yield "event", Event("content", stops.flush()) # the held tail was not a stop string after all done = {"finish": finish, "completion_tokens": n, "reused": (timings or {}).get("cache_n", 0), - "timings": timings, "reasoning_tokens": thinking_n} + "timings": timings, "reasoning_tokens": thinking_n, + "reasoning_recoveries": recovery_count} if stops is not None and stops.hit is not None: done["stop_sequence"] = stops.hit yield "done", done @@ -4434,6 +4531,13 @@ def main() -> int: if budget: print(f"[strata] thinking budget: {budget} tokens (reasoning_budget_tokens; a request can set its own)", flush=True) + recovery = cfg.get("reasoning_loop_recovery", False) # #728: false (default) | "stop" | "recover" (true) + if recovery is True: + recovery = "recover" + if recovery is not False and recovery not in ("stop", "recover"): + raise SystemExit("[strata] config \"reasoning_loop_recovery\" must be false, \"stop\" or \"recover\", " + f"not {recovery!r}") + svc.reasoning_loop_recovery = recovery svc.gpu_index = (gpu_list(cfg) or [0])[0] # the Monitor reads the card the engine runs on (issue #51) svc.gpu_indices = gpu_list(cfg) # ... or every card of a layer split (issue #112) svc.backend = cfg.get("backend") # "hip": the AMD cards' readings come from sysfs (#301) diff --git a/serve/test_reasoning_loop_recovery.py b/serve/test_reasoning_loop_recovery.py new file mode 100644 index 0000000000..879fd0ba71 --- /dev/null +++ b/serve/test_reasoning_loop_recovery.py @@ -0,0 +1,195 @@ +"""CPU-only regression for opt-in reasoning recovery: python -m unittest serve.test_reasoning_loop_recovery.""" +import threading +import unittest +from serve.server import (Service, ByteTokenizer, MockEngine, HIGH_EFFORT, + reasoning_repeat_coverage, focused_recovery_prompt) + + +class Tokenizer(ByteTokenizer): + def token_bytes(self, token): + return self.SPECIALS[token - 256].encode() if token >= 256 else bytes([token]) + + +class RecordingEngine(MockEngine): + def __init__(self, tokenizer, scripts): + super().__init__(tokenizer, scripts, max_context=100000) + self.calls = [] + self.sampling_calls = [] + self.sampling_objects = [] + + def generate(self, ids, max_new, sampling, cancel, **kwargs): + self.calls.append((list(ids), max_new)) + self.sampling_calls.append(dict(sampling or {})) + self.sampling_objects.append(sampling) + yield from super().generate(ids, max_new, sampling, cancel, **kwargs) + + +class ReasoningLoopRecovery(unittest.TestCase): + def setUp(self): + self.tok = Tokenizer() + self.ids = self.tok.encode('<|im_start|>system\n' + HIGH_EFFORT + + '<|im_end|>\n<|im_start|>user\nSolve this unchanged task<|im_end|>\n' + '<|im_start|>assistant\n\n', parse_special=True) + self.loop = 'Need maybe Agent support agent seven b. ' * 700 + + def test_repetition_and_novel_work(self): + self.assertEqual(reasoning_repeat_coverage(' '.join(str(i) for i in range(4000))), 0) + self.assertGreater(reasoning_repeat_coverage(self.loop), .9) + + def test_user_instruction_is_never_rewritten(self): + ids = self.tok.encode('<|im_start|>user\n' + HIGH_EFFORT, parse_special=True) + self.assertIsNone(focused_recovery_prompt(self.tok, ids, [])) + + def test_preserves_task_and_exact_generated_tokens(self): + generated = self.tok.encode('中文 partially checked code', parse_special=False) + prompt = focused_recovery_prompt(self.tok, self.ids, generated) + self.assertEqual(prompt[-len(generated):], generated) + self.assertIn('Solve this unchanged task', self.tok.decode(prompt)) + self.assertNotIn('', self.tok.decode(prompt)) + + def run_case(self, enabled): + engine = RecordingEngine(self.tok, [self.loop, + 'I have verified the solution.\n\nComplete solution.']) + service = Service(engine, self.tok, None) + service.reasoning_loop_recovery = enabled + events = list(service.run(self.ids, True, [], 40000, {}, threading.Event())) + return engine, events + + def test_old_explicit_sampler_recovers_without_mutating_request(self): + engine = RecordingEngine(self.tok, [self.loop, + 'Verified.\n\nComplete solution.']) + service = Service(engine, self.tok, None) + service.reasoning_loop_recovery = True + request = {'temperature': .2, 'presence_penalty': 0, 'top_p': .95, 'top_k': 64, 'seed': 2} + list(service.run(self.ids, True, [], 40000, request, threading.Event())) + self.assertEqual(engine.sampling_calls[0], request) + self.assertEqual(engine.sampling_calls[1]['temperature'], 1.0) + self.assertEqual(engine.sampling_calls[1]['presence_penalty'], 1.5) + self.assertEqual(engine.sampling_calls[1]['top_k'], 64) # a client's top_k and top_p are never touched + self.assertEqual(engine.sampling_calls[1]['top_p'], .95) + self.assertEqual(engine.sampling_calls[1]['seed'], request['seed']) + self.assertEqual(request['temperature'], .2) + self.assertEqual(request['presence_penalty'], 0) + + def test_frozen_cohort_sampler_is_unchanged_during_recovery(self): + engine = RecordingEngine(self.tok, [self.loop, 'Done.\n\nComplete solution.']) + service = Service(engine, self.tok, None) + service.reasoning_loop_recovery = True + sampler = {'temperature': 1.0, 'top_p': .95, 'top_k': 20, 'presence_penalty': 1.5, 'seed': 2} + list(service.run(self.ids, True, [], 40000, sampler, threading.Event())) + self.assertEqual(len(engine.sampling_objects), 2) + self.assertIs(engine.sampling_objects[0], engine.sampling_objects[1]) + self.assertIs(engine.sampling_objects[1], sampler) + + def test_a_lower_top_p_and_top_k_are_never_raised_or_lowered(self): + engine = RecordingEngine(self.tok, [self.loop, 'Verified.\n\nComplete solution.']) + service = Service(engine, self.tok, None) + service.reasoning_loop_recovery = "recover" + list(service.run(self.ids, True, [], 40000, {'temperature': 0, 'top_p': .5, 'top_k': 5}, threading.Event())) + self.assertEqual((engine.sampling_calls[1]['top_p'], engine.sampling_calls[1]['top_k']), (.5, 5)) + self.assertEqual((engine.sampling_calls[1]['temperature'], engine.sampling_calls[1]['presence_penalty']), (1.0, 1.5)) + + def test_the_splice_keeps_a_literal_think_tag_as_text(self): + """#537: the prompt is spliced as token ids, never decoded and encoded again.""" + from serve.frontend import THINK_TAGS + head = '<|im_start|>system\n' + HIGH_EFFORT + marked = self.tok.encode(head + '<|im_end|>\n<|im_start|>user\nquote ' + THINK_TAGS[''] + + ' please<|im_end|>\n<|im_start|>assistant\n\n', parse_special=True) + spliced = focused_recovery_prompt(self.tok, marked, []) + tail = marked[len(self.tok.encode(head, parse_special=True)):] + self.assertEqual(spliced[-len(tail):], tail) # everything after the sentence is the same ids + self.assertNotEqual(spliced, marked) + + def test_stop_mode_ends_the_reply_at_the_loop(self): + engine = RecordingEngine(self.tok, [self.loop]) + service = Service(engine, self.tok, None) + service.reasoning_loop_recovery = "stop" + events = list(service.run(self.ids, True, [], 40000, {}, threading.Event())) + self.assertEqual(len(engine.calls), 1) # no second pass + self.assertEqual(events[-1][1]['finish'], 'length') + self.assertLess(events[-1][1]['completion_tokens'], 20000) + self.assertEqual(events[-1][1]['reasoning_recoveries'], 0) + + def test_disabled_is_one_pass(self): + engine, events = self.run_case(False) + self.assertEqual(len(engine.calls), 1) + self.assertEqual(events[-1][1]['reasoning_recoveries'], 0) + + def test_default_single_token_guard_does_not_detect_passage_loop(self): + engine = RecordingEngine(self.tok, [self.loop]) + service = Service(engine, self.tok, None) + events = list(service.run(self.ids, True, [], 16384, {}, threading.Event())) + self.assertEqual(service.repeat_stop_tokens, 256) + self.assertEqual(events[-1][1]['finish'], 'length') + self.assertEqual(events[-1][1]['completion_tokens'], 16384) + self.assertFalse(any(e.kind == 'content' for kind, e in events if kind == 'event')) + + def test_recovery_is_once_and_never_extends_output_limit(self): + engine = RecordingEngine(self.tok, [self.loop, self.loop]) + service = Service(engine, self.tok, None) + service.reasoning_loop_recovery = True + events = list(service.run(self.ids, True, [], 16384, {}, threading.Event())) + self.assertEqual(len(engine.calls), 2) + self.assertEqual(events[-1][1]['finish'], 'length') + self.assertEqual(events[-1][1]['completion_tokens'], 16384) + self.assertEqual(events[-1][1]['reasoning_recoveries'], 1) + + def test_repeated_final_text_does_not_change_sampler_or_prompt(self): + engine = RecordingEngine(self.tok, [self.loop]) + service = Service(engine, self.tok, None) + service.reasoning_loop_recovery = True + events = list(service.run(self.ids, False, [], 40000, {}, threading.Event())) + self.assertEqual(len(engine.calls), 1) + self.assertEqual(events[-1][1]['reasoning_recoveries'], 0) + + def test_missing_native_high_hint_skips_recovery(self): + engine = RecordingEngine(self.tok, [self.loop]) + service = Service(engine, self.tok, None) + service.reasoning_loop_recovery = True + ids = self.tok.encode('<|im_start|>user\nTask<|im_end|>\n', parse_special=True) + events = list(service.run(ids, True, [], 40000, {}, threading.Event())) + self.assertEqual(len(engine.calls), 1) + self.assertEqual(events[-1][1]['reasoning_recoveries'], 0) + + def test_cancel_during_reasoning_does_not_start_recovery(self): + engine = RecordingEngine(self.tok, [self.loop, 'Unused']) + service = Service(engine, self.tok, None) + service.reasoning_loop_recovery = True + cancel = threading.Event() + events = [] + for event in service.run(self.ids, True, [], 40000, {}, cancel): + events.append(event) + if event[0] == 'event': + cancel.set() + self.assertEqual(len(engine.calls), 1) + self.assertEqual(events[-1][1]['finish'], 'cancel') + self.assertEqual(events[-1][1]['reasoning_recoveries'], 0) + + def test_batch_status_and_history_record_recovery(self): + engine = RecordingEngine(self.tok, [self.loop, 'Done.\n\nAnswer.']) + engine.batch = 2 + service = Service(engine, self.tok, None) + service.reasoning_loop_recovery = True + events = list(service.run(self.ids, True, [], 40000, {}, threading.Event())) + self.assertEqual(events[-1][1]['reasoning_recoveries'], 1) + self.assertEqual(service.history[-1]['reasoning_recoveries'], 1) + self.assertGreaterEqual(service.history[-1]['reasoning_repeat_coverage'], .25) + self.assertFalse(service.status['busy']) + self.assertEqual(service.live_reqs, {}) + + def test_natural_answer_with_shared_budget_and_preserved_prefix(self): + engine, events = self.run_case(True) + self.assertEqual(len(engine.calls), 2) + self.assertEqual(events[-1][1]['reasoning_recoveries'], 1) + self.assertEqual(events[-1][1]['finish'], 'stop') + content = ''.join(e.text or '' for kind, e in events if kind == 'event' and e.kind == 'content') + self.assertEqual(content, 'Complete solution.') + head_size = len(focused_recovery_prompt(self.tok, self.ids, [])) + retained = engine.calls[1][0][head_size:] + self.assertEqual(retained, self.tok.encode(self.loop)[:len(retained)]) + self.assertEqual(engine.calls[1][1], 40000 - len(retained)) + self.assertNotIn('', self.tok.decode(engine.calls[1][0])) + + +if __name__ == '__main__': + unittest.main() From 0eacbaba81fbd69286cbae19580911fd26beb570 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 5 Oct 2026 10:42:37 +0200 Subject: [PATCH 44/48] vision: --min-tokens N passes mtmd's image_min_tokens (vision.min_tokens, hand-edited); CPU encode time in the docs (#767) --- docs/DETAILS.md | 11 +++++++++-- docs/INSTALL.md | 6 +++--- docs/TROUBLESHOOTING.md | 2 +- serve/server.py | 2 ++ serve/test_server.py | 29 +++++++++++++++++++++++++++++ tools/vision/strata_vision.cpp | 8 +++++--- 6 files changed, 49 insertions(+), 9 deletions(-) diff --git a/docs/DETAILS.md b/docs/DETAILS.md index df47bd2eae..fea7515ad2 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -901,7 +901,7 @@ helper (`strata-vision`, from llama.cpp's `mtmd` library) and adds it to your st | Encoder on | Time per picture | Cost | | --- | --- | --- | | **GPU** (recommended) | **0.1-0.5 s** (up to 1,024 image tokens) | ~1.4 GB of VRAM is kept free for it, so the expert cache is smaller: text output is a few % slower (table below) | -| CPU | 10-30 s (pictures are scaled down to ~300 image tokens) | nothing on the GPU | +| CPU | about 3 s at 300 image tokens on 8 cores (6-13 s on 4 threads); more tokens take longer, in proportion (#767, #625) | nothing on the GPU | A picture becomes up to 1,024 tokens of the context (a 640x480 photo: 300). The same picture sent again, as chat apps do on every turn, is encoded only once. @@ -911,6 +911,13 @@ do on every turn, is encoded only once. `strata-.json`, which you can also edit by hand. More tokens keep more detail (small text, charts, screenshots) and take longer to encode, on the CPU most of all; a setup run again keeps the value. +**A minimum number of image tokens (0.1.40, #767):** `"min_tokens": N` in the `"vision"` section of +`strata-.json` (edit it by hand; a setup run again keeps it) is passed to the encoder as `--min-tokens N` +(mtmd's `image_min_tokens`): a small picture is scaled up to at least N tokens. llama.cpp's mtmd prints that Qwen-VL +models want at least 1,024 for grounding tasks (pointing, counting small items); the CPU default stays at 300 at most +and no minimum, because a larger minimum changes the image answers and costs encode time (about 3 s at 300 tokens on +8 cores, in proportion to the tokens). + **A Q8_0 encoder (#625):** `"mmproj"` in the `"vision"` section can point to another mmproj file of this model, for example a Q8_0 one (llama.cpp's `convert_hf_to_gguf.py --mmproj --outtype q8_0` makes one): the encoder's library reads quantized weights, the file is half the size, and on the CPU it can encode faster than BF16. Setup downloads @@ -1038,7 +1045,7 @@ the document, +0.4% on the chat. Details: `bench/results/2026-09-27-esp/`. | Slower than the tables | The monitor plugged into the GPU and other GPU programs take VRAM from the expert cache; RAM running below its rated speed (enable EXPO/XMP in the BIOS) slows the CPU half. | | `this server was started without the vision encoder` | The model was set up for text only: run setup again with `--vision gpu`. | | A picture is refused or `cannot read the image` | The file is not a picture Pillow can open (JPEG, PNG, WebP, GIF, BMP, TIFF, AVIF work). | -| Pictures are slow (10-30 s) | The encoder runs on the CPU: run setup again with `--vision gpu` (needs ~1.4 GB of VRAM). | +| Pictures are slow (3-30 s) | The encoder runs on the CPU: run setup again with `--vision gpu` (needs ~1.4 GB of VRAM). | | A request never finishes: "reading the prompt", GPU "100%" at low power | The GPU ran out of VRAM (engines before 0.1.9 could end with ~30 MiB free at large contexts). Run `START-HERE.bat` once to get engine 0.1.9 or newer; the log then says `... MiB of VRAM free with everything loaded` (a few hundred) and names the `--vram-reserve-mib` to add if it is low. | | Generation stops mid-answer, GPU "100%", one CPU core busy | Fixed in engine 0.1.12 (issue #29, a race in the CPU expert pool on big-VRAM cards). Since then a request that stops moving ends with an error instead of hanging (after 2 minutes; 1 minute from 0.1.13): the log says `no progress for ... s ... (issue #29)` with where it stopped, and the next request starts the engine again. If you see that line, please open an issue with it. Engine 0.1.13 adds a stall report under it (what every expert-pool thread and the GPU handshake were doing, memory and page faults) and, on Windows, a `strata-stall-.dmp` file with every thread's stack: attach both. (`STRATA_WATCHDOG_S` sets the time in seconds; 0 turns it off.) Engine 0.1.14 fixes the stall those reports found (issue #31: with the IQ packs the host could wait forever inside the NVIDIA driver while copying experts in a verify window; the experts are now copied by a GPU kernel, `--pcie-mode dma` restores the old way). | | `no progress for 60 s ... reading the prompt` on Linux, and the stall report says `threads waiting on the disk (state D): 16 ...` | The engine waits for the drive, not a deadlock: the n-gram table is read at random (`--ple-io direct`), which a rotational disk cannot keep up with (#605). The engine warns at start when the table is on one; `--ple-io ram` (Linux, needs RAM for the table) or the model on an SSD fixes it. Setup adds `--ple-io ram` itself on a rotational disk when the RAM holds the table (0.1.39). | diff --git a/docs/INSTALL.md b/docs/INSTALL.md index 4ab28fb12c..05b1035d29 100644 --- a/docs/INSTALL.md +++ b/docs/INSTALL.md @@ -69,8 +69,8 @@ On Linux setup uses a system ROCm 7 when there is one, or installs ROCm into `.v sudo), and compiles the engine on your PC for the card (10-20 minutes, once; it needs a C++ compiler and git: `sudo apt install build-essential git`). Several AMD cards share the model with `--gpus`, as on NVIDIA. -What differs from NVIDIA for now: pictures are read by the image encoder on the CPU (`--vision cpu`, 10-30 s per -picture), `--calibrate` is NVIDIA-only, and Unsloth's 4-bit model needs an NVIDIA card. Measurements per card, the +What differs from NVIDIA for now: pictures are read by the image encoder on the CPU (`--vision cpu`, about 3 s per +picture at the default 300 image tokens on 8 cores), `--calibrate` is NVIDIA-only, and Unsloth's 4-bit model needs an NVIDIA card. Measurements per card, the build by hand and the tuning tables: [AMD_HIP.md](AMD_HIP.md). ## Two or three cards @@ -197,7 +197,7 @@ says so and starts the engine you had. covering factor; `--rope-scaling`/`--rope-scale` override) ([details](DETAILS.md): "Context extension past 262K"). - **Images?** Whether it should also read pictures. The image encoder (0.9 GB) runs on the GPU (0.1-0.5 s per - picture, ~1.4 GB of VRAM kept free for it) or on the CPU (10-30 s per picture, nothing on the GPU); with AMD cards + picture, ~1.4 GB of VRAM kept free for it) or on the CPU (about 3-13 s per picture, nothing on the GPU); with AMD cards on the CPU for now. [Details](DETAILS.md#images-vision). - **Experimental speed projection?** Off unless you say yes - [read what it does](DETAILS.md#experimental-speed-projection-experimental-off-by-default) first. It changes how the model answers, and only the original model offers it. diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md index 7287409e45..bd9226c628 100644 --- a/docs/TROUBLESHOOTING.md +++ b/docs/TROUBLESHOOTING.md @@ -56,7 +56,7 @@ its rated speed (enable EXPO/XMP in the BIOS) slows the CPU half. **Pictures are refused, or slow.** "this server was started without the vision encoder": the model was set up for text only - run setup again with -`--vision gpu` (or `--vision cpu`). Pictures that take 10-30 s are read by the encoder on the CPU; `--vision gpu` +`--vision gpu` (or `--vision cpu`). Pictures that take several seconds (about 3 s at 300 image tokens on 8 cores, more with more tokens) are read by the encoder on the CPU; `--vision gpu` (NVIDIA, ~1.4 GB of VRAM) makes it 0.1-0.5 s. ## AMD cards diff --git a/serve/server.py b/serve/server.py index 1a1dd5ba9e..e755e00bbb 100644 --- a/serve/server.py +++ b/serve/server.py @@ -1376,6 +1376,8 @@ class Vision: args += ["--threads", str(cfg["threads"])] if cfg.get("max_tokens"): args += ["--max-tokens", str(cfg["max_tokens"])] + if cfg.get("min_tokens"): # #767: mtmd's image_min_tokens (a hand-edited key) + args += ["--min-tokens", str(cfg["min_tokens"])] self.dir = Path(tempfile.mkdtemp(prefix="strata-vision-")) self.spawn = (args, log, env) # to start it again after an unload self.stopped = False diff --git a/serve/test_server.py b/serve/test_server.py index 498ace481e..de6fc3c329 100644 --- a/serve/test_server.py +++ b/serve/test_server.py @@ -3643,3 +3643,32 @@ class PromptProgressBatch(unittest.TestCase): self.assertEqual(prompt_progress(svc), {"total": 4096, "cache": 0, "processed": 512, "time_ms": 900}) engine.batch = 2 self.assertIsNone(prompt_progress(svc)) + + +class VisionArgs(unittest.TestCase): + """#767: vision.min_tokens reaches the encoder as --min-tokens (mtmd's image_min_tokens).""" + + def args_for(self, cfg): + import serve.server as server + seen = [] + + class Proc: + stdout = io.StringIO("READY 4096\n") + stdin = io.StringIO() + + def poll(self): + return None + + def popen(args, **kw): + seen.append(args) + return Proc() + + with mock.patch.object(server.subprocess, "Popen", popen), mock.patch.object(server, "contain"): + server.Vision({"exe": "strata-vision", "mmproj": "m.gguf", "model": "t.gguf", **cfg}) + return seen[0] + + def test_min_tokens_is_passed_only_when_set(self): + base = self.args_for({"max_tokens": 300}) + self.assertNotIn("--min-tokens", base) + self.assertEqual(self.args_for({"max_tokens": 1024, "min_tokens": 768})[-4:], + ["--max-tokens", "1024", "--min-tokens", "768"]) diff --git a/tools/vision/strata_vision.cpp b/tools/vision/strata_vision.cpp index 6be3f44beb..99e51f3554 100644 --- a/tools/vision/strata_vision.cpp +++ b/tools/vision/strata_vision.cpp @@ -5,7 +5,7 @@ // rows at the image's pad tokens and gives them their 2-D M-RoPE positions (see --serve GENI in generate.cpp). // // strata-vision --mmproj --model [--gpu] [--threads N] -// [--max-tokens N] [--flash-attn on|off|auto] +// [--max-tokens N] [--min-tokens N] [--flash-attn on|off|auto] // // Resident: prints "READY ", then per stdin line // ENC -> "OK " or "ERR " @@ -51,7 +51,7 @@ bool parse_enc(const std::string& line, std::string& img, std::string& out) { int main(int argc, char** argv) { std::string mmproj, model; bool gpu = false; - int threads = 0, max_tokens = 0; + int threads = 0, max_tokens = 0, min_tokens = 0; llama_flash_attn_type fa = LLAMA_FLASH_ATTN_TYPE_AUTO; for (int i = 1; i < argc; ++i) { const std::string a = argv[i]; @@ -64,6 +64,7 @@ int main(int argc, char** argv) { else if (a == "--gpu") gpu = true; else if (a == "--threads") threads = std::atoi(next().c_str()); else if (a == "--max-tokens") max_tokens = std::atoi(next().c_str()); + else if (a == "--min-tokens") min_tokens = std::atoi(next().c_str()); // mtmd image_min_tokens (#767) else if (a == "--flash-attn") { // FA keeps K and V in FP16; off = the attention in FP32 const std::string v = next(); fa = v == "on" ? LLAMA_FLASH_ATTN_TYPE_ENABLED : v == "off" ? LLAMA_FLASH_ATTN_TYPE_DISABLED @@ -73,7 +74,7 @@ int main(int argc, char** argv) { } if (mmproj.empty() || model.empty()) { std::fprintf(stderr, "usage: strata-vision --mmproj --model [--gpu] [--threads N] " - "[--max-tokens N] [--flash-attn on|off|auto]\n"); + "[--max-tokens N] [--min-tokens N] [--flash-attn on|off|auto]\n"); return 2; } // On the CPU the GPU stays unseen: a CUDA build otherwise opens a context there (measured: 0.4-0.7 GB of VRAM, @@ -103,6 +104,7 @@ int main(int argc, char** argv) { if (threads <= 0 && !gpu) threads = std::max(1u, std::thread::hardware_concurrency() / 2); if (threads > 0) cp.n_threads = threads; if (max_tokens > 0) cp.image_max_tokens = max_tokens; + if (min_tokens > 0) cp.image_min_tokens = min_tokens; mtmd_context* ctx = mtmd_init_from_file(mmproj.c_str(), text, cp); if (!ctx || !mtmd_support_vision(ctx)) { std::printf("ERR cannot load the vision encoder %s\n", mmproj.c_str()); From 378dc39348583ad8b0a0d3fe0fc4f32920cd2fb0 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 5 Oct 2026 10:44:00 +0200 Subject: [PATCH 45/48] setup: a tip for a Q8_0 vision encoder on the CPU; docs: the llama-quantize command and measured fidelity (#625) --- docs/DETAILS.md | 11 ++++++++--- setup.py | 3 +++ 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/docs/DETAILS.md b/docs/DETAILS.md index fea7515ad2..20e9334356 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -920,9 +920,14 @@ and no minimum, because a larger minimum changes the image answers and costs enc **A Q8_0 encoder (#625):** `"mmproj"` in the `"vision"` section can point to another mmproj file of this model, for example a Q8_0 one (llama.cpp's `convert_hf_to_gguf.py --mmproj --outtype q8_0` makes one): the encoder's library -reads quantized weights, the file is half the size, and on the CPU it can encode faster than BF16. Setup downloads -the BF16 file, and a setup run again keeps a file of your own that still exists. We have not measured its accuracy -against BF16 yet; numbers are welcome in #625. +reads quantized weights, the file is smaller (590 MiB against 865 MiB for the BF16 one, from `llama-quantize +mmproj-Qwen3.8-Flash-Next-BF16.gguf mmproj-Qwen3.8-Flash-Next-Q8_0.gguf Q8_0`), and on the CPU it uses less RAM +(about 280 MiB less in the encoder) and can encode faster than BF16 at the default 300 tokens. Setup downloads the +BF16 file, and a setup run again keeps a file of your own that still exists. **Recommended for `--vision cpu`.** +Accuracy against BF16, per image token: the cosine of the embeddings is 0.997-0.999 on average (#625's report, with +a community Q8_0 file, at 300, 768 and 1,024 tokens), and 0.9988 and 0.9987 on two pictures with the file made by +the command above (300 tokens; the worst single token 0.94-0.96). Encode time above 768 tokens is the same as BF16's +within about 3%. Numbers on more pictures (charts, small text) are welcome in #625. **A spare GPU for the encoder (0.1.33, #408):** with a card the engine doesn't use, add `"cuda_device": 2` (numbered like `nvidia-smi`) to the `"vision"` section of `strata-.json`: the encoder then runs on that card alone. Lower diff --git a/setup.py b/setup.py index 1368f94017..968640950f 100644 --- a/setup.py +++ b/setup.py @@ -4187,6 +4187,9 @@ def main() -> int: else: download(fam["mmproj_hf"] + fam["mmproj"], mmproj, "vision encoder") ok(f"vision encoder: {mmproj}") + if vision == "cpu" and "BF16" in mmproj.name: # a tip only (recommend, never force; #625) + say(" tip: on the CPU a Q8_0 copy of this encoder is a third smaller and about as exact (embedding " + "cosine 0.999 vs BF16); see 'A Q8_0 encoder' in docs/DETAILS.md") # ---- 6. the pack and the MTP draft layer step(6, "preparing the model for Strata") From ee412cd776c3980f354fa317efa8731c30e7b381 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 5 Oct 2026 10:47:10 +0200 Subject: [PATCH 46/48] serve: a in the reasoning that never closes stops holding the thinking back after 32 KiB (#804) --- serve/frontend.py | 7 +++++++ serve/test_reasoning_tools.py | 11 +++++++++++ 2 files changed, 18 insertions(+) diff --git a/serve/frontend.py b/serve/frontend.py index 500ceeb0bf..716e64f80c 100644 --- a/serve/frontend.py +++ b/serve/frontend.py @@ -538,6 +538,9 @@ def parse_tool_call(body: str, schema: dict | None = None) -> ToolCall: return ToolCall(name=name, arguments=args) +RCALL_MAX = 32768 # the most of a `` inside the reasoning that is held while waiting for its end (#804) + + class OutputParser: """Incremental parser of the model's text. Feed deltas; get events. A tag split across deltas is held back until it is complete, so clients never see ` RCALL_MAX: # a tag in the prose that never closes: stop holding the thinking back + out.append(Event("reasoning", self.buf)) + self.buf = "" + self.state = "reasoning" else: return out elif self.state == "reasoning": diff --git a/serve/test_reasoning_tools.py b/serve/test_reasoning_tools.py index a75adcd1d7..4468fbd35a 100644 --- a/serve/test_reasoning_tools.py +++ b/serve/test_reasoning_tools.py @@ -10,6 +10,7 @@ from __future__ import annotations import json import sys import unittest +import unittest.mock import urllib.request from pathlib import Path @@ -93,6 +94,16 @@ class Parser(unittest.TestCase): self.assertEqual(len([e for e in evs if e.kind == "tool_call"]), 1) self.assertEqual(joined(evs, "reasoning"), "think") + def test_a_tag_that_never_closes_does_not_hold_the_thinking_back(self): + from serve import frontend + text = "a " + "thinking on and on " * 3000 + "\n\nanswer" + with unittest.mock.patch.object(frontend, "RCALL_MAX", 1000): + evs = run(text, 50) + first_reasoning_at = next(i for i, e in enumerate(evs) if e.kind == "reasoning" and len(e.text) > 100) + self.assertLess(first_reasoning_at, 100) # streamed, not kept until + self.assertEqual(joined(evs, "reasoning"), text.split("")[0]) + self.assertEqual(joined(evs, "content"), "answer") + def test_a_partial_tag_is_held(self): p = OutputParser(thinking=True, tools=TOOLS) evs = p.feed("hello Date: Mon, 5 Oct 2026 12:09:08 +0200 Subject: [PATCH 47/48] serve tests: put the StopStrings and ConnectionClose classes back together after a merge (#715) --- serve/test_server.py | 64 +++++++++++++++++++++++++------------------- 1 file changed, 36 insertions(+), 28 deletions(-) diff --git a/serve/test_server.py b/serve/test_server.py index de6fc3c329..4130ede1d4 100644 --- a/serve/test_server.py +++ b/serve/test_server.py @@ -3396,20 +3396,11 @@ class StopStrings(unittest.TestCase): across tokens (and across streamed chunks).""" ANSWER = "alpha END beta STOP gamma" - -class ConnectionClose(unittest.TestCase): - """The server is HTTP/1.0 and closes the connection after every response. Without saying so, .NET's pooled - HttpClient put its next request on the closing socket and got "response ended prematurely" (2026-10-03).""" - @classmethod def setUpClass(cls): tok = ByteTokenizer() cls.engine = CountingEngine(tok, "\n\n" + cls.ANSWER, max_context=CTX) cls.svc = Service(cls.engine, tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) - - - cls.svc = Service(MockEngine(tok, "\n\nok", max_context=CTX), tok, - ChatTemplate(ROOT / "serve/chat_template.jinja")) cls.httpd = serve(cls.svc, port=0) cls.base = f"http://127.0.0.1:{cls.httpd.server_address[1]}" @@ -3517,6 +3508,38 @@ class ConnectionClose(unittest.TestCase): self.assertEqual(m.push("more"), "") +class ConnectionClose(unittest.TestCase): + """The server is HTTP/1.0 and closes the connection after every response. Without saying so, .NET's pooled + HttpClient put its next request on the closing socket and got "response ended prematurely" (2026-10-03).""" + + @classmethod + def setUpClass(cls): + tok = ByteTokenizer() + cls.svc = Service(MockEngine(tok, "\n\nok", max_context=CTX), tok, + ChatTemplate(ROOT / "serve/chat_template.jinja")) + cls.httpd = serve(cls.svc, port=0) + cls.base = f"http://127.0.0.1:{cls.httpd.server_address[1]}" + + @classmethod + def tearDownClass(cls): + cls.httpd.shutdown() + cls.httpd.server_close() + + def headers(self, stream): + body = {"model": "x", "max_tokens": 20, "messages": [{"role": "user", "content": "hi"}], "stream": stream} + req = urllib.request.Request(self.base + "/v1/chat/completions", data=json.dumps(body).encode(), + headers={"Content-Type": "application/json"}) + with urllib.request.urlopen(req, timeout=30) as r: + r.read() + return r.headers + + def test_a_non_streamed_answer_says_the_connection_closes(self): + self.assertEqual(self.headers(stream=False).get("Connection"), "close") + + def test_a_streamed_answer_says_the_connection_closes(self): + self.assertEqual(self.headers(stream=True).get("Connection"), "close") + + class AnswerBeforeTheBody(unittest.TestCase): """An answer sent before the request body was read must still reach a client that sends the body after the headers (http.client, urllib and requests do): closing the connection on unread bytes sends a reset that eats the answer.""" @@ -3614,25 +3637,6 @@ class AnswerBeforeTheBody(unittest.TestCase): self.assertEqual(self.status("PUT", "/v1/chat/completions"), "HTTP/1.0 501 Unsupported method ('PUT')") - def headers(self, stream): - body = {"model": "x", "max_tokens": 20, "messages": [{"role": "user", "content": "hi"}], "stream": stream} - req = urllib.request.Request(self.base + "/v1/chat/completions", data=json.dumps(body).encode(), - headers={"Content-Type": "application/json"}) - with urllib.request.urlopen(req, timeout=30) as r: - r.read() - return r.headers - - def test_a_non_streamed_answer_says_the_connection_closes(self): - self.assertEqual(self.headers(stream=False).get("Connection"), "close") - - def test_a_streamed_answer_says_the_connection_closes(self): - self.assertEqual(self.headers(stream=True).get("Connection"), "close") - - -if __name__ == "__main__": - unittest.main() - - class PromptProgressBatch(unittest.TestCase): """#837: under --batch the engine's progress is one global line: prompt_progress() says nothing.""" @@ -3672,3 +3676,7 @@ class VisionArgs(unittest.TestCase): self.assertNotIn("--min-tokens", base) self.assertEqual(self.args_for({"max_tokens": 1024, "min_tokens": 768})[-4:], ["--max-tokens", "1024", "--min-tokens", "768"]) + + +if __name__ == "__main__": + unittest.main() From 8e368af984d4aab0ea2b0af2ab23a2fa65214535 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 5 Oct 2026 12:09:52 +0200 Subject: [PATCH 48/48] serve: tool_choice required with a single tool names it (#790) --- serve/frontend.py | 2 ++ serve/test_frontend.py | 9 +++++++++ 2 files changed, 11 insertions(+) diff --git a/serve/frontend.py b/serve/frontend.py index 716e64f80c..a6e181d255 100644 --- a/serve/frontend.py +++ b/serve/frontend.py @@ -496,6 +496,8 @@ def forced_call(tool_choice, tools: list[dict] | None) -> str | None: names = {t.get("name") for t in tools or [] if isinstance(t, dict)} if kind in ("auto", "none"): return None + if kind == "required" and len(names) == 1: # one tool to call: name it, the model cannot invent another + kind, name = "named", next(iter(names)) if kind == "required" and names: return CALL_START + "\n\n")) + self.assertTrue(forced_call("required", two).endswith("