From 46c46ecfc11d2315512f21f7549b0a7792ccd2ae Mon Sep 17 00:00:00 2001 From: Robert Karl Date: Thu, 8 Oct 2026 15:54:03 -0700 Subject: [PATCH] Front end: image input through the model's vision encoder; engine child supervision; tests Images: --mmproj PATH loads the Qwen3.8 Flash-Next projector through llama.cpp's mtmd library and encodes image_url parts on the CPU (frontend/vision.hpp). The embeddings go to the engine as a GENI request, its existing vision path, with the prompt's <|image_pad|> runs standing in for each image. --vision-tokens caps the tokens per image. GET /v1/models lists "image" under input_modalities when the encoder is loaded. Checked on an RTX 4090: screenshots, photos, several images in one message, and pi's file attachments and clipboard paste. Engine process: the engine is started and watched from frontend/engine.hpp; when it exits or its stall watchdog fires, the front end exits too, for a supervisor to restart. Stall reports add the current stage and thread wait channels. Reasoning streams; content and tool calls are sent once the whole message is parsed, so partial JSON never changes arguments already sent. Tests: make test-frontend (child exit, protocol, backpressure; no model needed) and make test-chat-parser MODEL= (template and tool-call parsing against the real GGUF). The image path and the supervision were written by a Codex session; this commit finishes, documents and checks them. Co-Authored-By: Claude Fable 5.1 --- CMakeLists.txt | 3 +- Makefile | 26 +++ README.md | 25 ++- frontend/chat_parser_test.cpp | 72 +++++++ frontend/child_watch.hpp | 22 ++ frontend/child_watch_test.cpp | 31 +++ frontend/engine.hpp | 166 +++++++++++++++ frontend/engine_backpressure_test.cpp | 71 +++++++ frontend/engine_test.cpp | 49 +++++ frontend/main.cpp | 287 ++++++++++++++------------ frontend/vision.hpp | 143 +++++++++++++ src/program/generate.cpp | 17 ++ 12 files changed, 773 insertions(+), 139 deletions(-) create mode 100644 frontend/chat_parser_test.cpp create mode 100644 frontend/child_watch.hpp create mode 100644 frontend/child_watch_test.cpp create mode 100644 frontend/engine.hpp create mode 100644 frontend/engine_backpressure_test.cpp create mode 100644 frontend/engine_test.cpp create mode 100644 frontend/vision.hpp diff --git a/CMakeLists.txt b/CMakeLists.txt index b8de868..30d85cb 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1251,6 +1251,7 @@ endif() # The front end takes its tokenizer, its Jinja chat-template engine and its HTTP library from the same pinned # llama.cpp checkout that ggml comes from. ggml is already configured above, so llama.cpp's own build reuses it. if(STRATA_ENABLE_CUDA AND STRATA_NATIVE_EXPERTS) + set(LLAMA_BUILD_MTMD ON CACHE BOOL "" FORCE) set(LLAMA_BUILD_COMMON ON CACHE BOOL "" FORCE) foreach(_o LLAMA_BUILD_TESTS LLAMA_BUILD_TOOLS LLAMA_BUILD_EXAMPLES LLAMA_BUILD_SERVER LLAMA_BUILD_APP LLAMA_BUILD_UI LLAMA_USE_PREBUILT_UI LLAMA_OPENSSL LLAMA_LLGUIDANCE LLAMA_ALL_WARNINGS) @@ -1261,5 +1262,5 @@ if(STRATA_ENABLE_CUDA AND STRATA_NATIVE_EXPERTS) add_executable(unbiased-strata frontend/main.cpp frontend/engine_entry.cpp) target_include_directories(unbiased-strata PRIVATE ${_strata_gpu_include_directories} ${STRATA_GGML_DIR}/vendor) target_link_libraries(unbiased-strata PRIVATE strata_engine strata_prefill strata_spec ${_strata_gpu_runtime_target} - llama-common llama cpp-httplib Threads::Threads) + llama-common llama mtmd cpp-httplib Threads::Threads) endif() diff --git a/Makefile b/Makefile index 9e6e01a..8006d68 100644 --- a/Makefile +++ b/Makefile @@ -19,3 +19,29 @@ build: clean: rm -rf $(BUILD_DIR) + +# Protocol and child supervision regressions; no CUDA/model required. +.PHONY: test-frontend +test-frontend: + mkdir -p $(BUILD_DIR)/frontend-tests + $(CXX) -std=c++20 -Wall -Wextra -Werror frontend/child_watch_test.cpp -o $(BUILD_DIR)/frontend-tests/child-watch-test + $(BUILD_DIR)/frontend-tests/child-watch-test + $(CXX) -std=c++20 -Wall -Wextra -Werror frontend/engine_test.cpp -o $(BUILD_DIR)/frontend-tests/engine-test + $(BUILD_DIR)/frontend-tests/engine-test + $(CXX) -std=c++20 -Wall -Wextra -Werror -pthread frontend/engine_backpressure_test.cpp -o $(BUILD_DIR)/frontend-tests/engine-backpressure-test + $(BUILD_DIR)/frontend-tests/engine-backpressure-test + +# Model-template compatibility; CPU only, after the regular build produced llama libraries. +.PHONY: test-chat-parser +test-chat-parser: + @test -n "$(MODEL)" || { echo 'set MODEL to the first GGUF shard'; exit 2; } + mkdir -p $(BUILD_DIR)/frontend-tests + $(CXX) -std=c++20 -O0 -Ifrontend -Ithird_party/llama.cpp/include -Ithird_party/llama.cpp/common \ + -Ithird_party/llama.cpp/ggml/include -Ithird_party/llama.cpp/vendor -Ithird_party/llama.cpp/tools/mtmd \ + frontend/chat_parser_test.cpp \ + -o $(BUILD_DIR)/frontend-tests/chat-parser-test $(BUILD_DIR)/llama.cpp/tools/mtmd/libmtmd.a \ + $(BUILD_DIR)/llama.cpp/vendor/hash/libvendor-hash.a $(BUILD_DIR)/llama.cpp/common/libllama-common.a \ + $(BUILD_DIR)/llama.cpp/src/libllama.a $(BUILD_DIR)/llama.cpp/vendor/cpp-httplib/libcpp-httplib.a \ + $(BUILD_DIR)/ggml/src/libggml.a $(BUILD_DIR)/ggml/src/libggml-cpu.a $(BUILD_DIR)/ggml/src/libggml-base.a \ + $(BUILD_DIR)/llama.cpp/common/libllama-common-base.a -lpthread -ldl -lm + $(BUILD_DIR)/frontend-tests/chat-parser-test "$(MODEL)" diff --git a/README.md b/README.md index b402c16..20adb4c 100644 --- a/README.md +++ b/README.md @@ -36,11 +36,25 @@ build fetches nothing. `make build JOBS=N` sets the job count; `CUDA_ARCHS` defa | | | | --- | --- | | Endpoints | `POST /v1/chat/completions` (streaming or not), `GET /v1/models`, `GET /health`, on `127.0.0.1:8080` | -| Options | `--ctx N` (32768), `--threads N` (default: physical cores, or half the CPU quota in a container), `--host`, `--port`; engine flags after `--` | +| Options | `--ctx N` (32768), `--threads N` (default: physical cores, or half the CPU quota in a container), `--host`, `--port`, `--mmproj PATH`, `--vision-tokens N` (1024); engine flags after `--` | | Sampling | greedy unless `temperature` > 0 | | Reasoning | returned as `reasoning_content`; `"reasoning_effort": "none"` turns it off | | Tools | OpenAI format (`tools`, `tool_calls`) | -| Not supported | image input, more than one GPU, batch requests | +| Images | with `--mmproj`, OpenAI `image_url` parts holding a base64 `data:image/...` URL (PNG, JPEG, BMP or GIF), several per message | +| Not supported | more than one GPU, batch requests | + +Images: `--mmproj /models/mmproj-Qwen3.8-Flash-Next-BF16.gguf` loads the model's own vision encoder (from the same +Hugging Face repository as the GGUF; 0.9 GB). The encoder runs on the CPU, so the card keeps its expert cache: +about 25 s and 1,000 prompt tokens for a 1-megapixel screenshot on 8 threads, 0.2 s for a small image; a repeated +image is served from a cache. `GET /v1/models` then lists `image` under `input_modalities`. Without `--mmproj` an +image request is refused with a 400. + +The engine runs as a child process. When it exits or its stall watchdog fires, the front end exits with a failure +status, for a supervisor such as systemd (`Restart=on-failure`) to restart; `/health` and `/v1/models` answer 503 +while the engine is down. Reasoning streams as it is generated; content and tool calls are sent once the whole +message is parsed, so a partial tool-call JSON never changes arguments already sent. `make test-frontend` checks +the child handling and the protocol without a model; `make test-chat-parser MODEL=` checks the chat +template and tool-call parsing against the real GGUF. ## The one supported model @@ -69,9 +83,10 @@ Checked on one machine: RTX 3090, 32 vCPUs of an EPYC 7763, 125 GB RAM, CUDA 12. | --- | --- | | Build | from an rsynced tree with no git metadata; the binary holds no download code | | Serving | chat, streaming, reasoning, tool calls; a coding agent (pi) wrote and ran a program through it | +| RTX 4090 (24 GB), 82 GB RAM, Debian, bare metal | serving with tool calls and images, through pi (file attachments and clipboard paste) and curl, over several days of use | | Start from local disk | 19 s with the files in the OS file cache | | Start from a network volume | 12 min for 76 GB (S3-backed RunPod volume, 120 to 330 MB/s). The volume refused reads twice with "cannot allocate memory"; the loader retried and went on | -| Not tested | RTX 40 and RTX 50 cards; a cold start from local disk | +| Not tested | RTX 50 cards; a cold start from local disk | Speed, one run of each, same machine and model files, greedy sampling, reasoning off. Generation is the mean of 8 different prompts of 400 tokens; prompt speed is the mean of 2 different prompts of about 20,000 tokens. @@ -98,9 +113,9 @@ builds differ in compile flags and in how the n-gram table is held in RAM, and e | | Upstream | This fork | | --- | --- | --- | | Engine source (`src/`, `include/`) | 272 files | two files changed, one added (retrying reads from slow stores); cutting it down is the next work | -| Build | clones llama.cpp during CMake | pinned submodule, fetches nothing | +| Build | clones llama.cpp during CMake | pinned submodule, fetches nothing; one patch, applied by `make build`: tool-call arguments in any order (see UPSTREAM.md) | | Setup | Python installer downloads the model and builds the pack and draft head | none; files must already exist | -| Server | Python | C++, in the same binary (`frontend/`) | +| Server | Python | C++, in the same binary (`frontend/`), with the image encoder from llama.cpp's `mtmd` | | Python | 33,745 lines | 0 | | C, C++ and CUDA | 208,254 lines (with tests and the Intel port) | 84,086 lines | | Tracked files | 851, 27 MB | 292, 6 MB | diff --git a/frontend/chat_parser_test.cpp b/frontend/chat_parser_test.cpp new file mode 100644 index 0000000..ef700fc --- /dev/null +++ b/frontend/chat_parser_test.cpp @@ -0,0 +1,72 @@ +// Exercise request preparation and final tool parsing with the actual GGUF. +// No inference engine or CUDA context is created. +#define main unused_serving_main +#include "main.cpp" +#undef main +#include +#include + +int strata_engine_main(int, char**) { return 99; } + +int main(int argc, char** argv) { + if (argc != 2) return 2; + llama_log_set(quiet_log, nullptr); + llama_backend_init(); + Server server; + server.opt.ctx = 196608; + auto params = llama_model_default_params(); params.vocab_only = true; + server.model = llama_model_load_from_file(argv[1], params); + assert(server.model); + server.vocab = llama_model_get_vocab(server.model); + server.tmpls = common_chat_templates_init(server.model, ""); + assert(common_chat_templates_get_caps(server.tmpls.get()).at("supports_parallel_tool_calls")); + auto request = common_json::parse_no_throw(R"({ + "messages":[{"role":"user","content":"Check the files and the date."}], + "tools":[{"type":"function","function":{"name":"bash","parameters":{ + "type":"object","properties":{"command":{"type":"string"}},"required":["command"] + }}}] + })"); + const std::string output = "Reasoning.\n\n\n" + "\n\n\nls\n\n\n\n" + "\n\n\ndate\n\n\n"; + Prepared default_request, explicit_request; + std::string error; + assert(server.prepare(request, default_request, error)); + auto message = common_chat_parse(output, false, default_request.parser); + assert(message.tool_calls.size() == 2); + assert(message.tool_calls[0].arguments == "{\"command\":\"ls\"}"); + assert(message.tool_calls[1].arguments == "{\"command\":\"date\"}"); + request["parallel_tool_calls"] = true; + assert(server.prepare(request, explicit_request, error)); + assert(explicit_request.ids == default_request.ids); + assert(common_chat_parse(output, false, explicit_request.parser).tool_calls.size() == 2); + request["parallel_tool_calls"] = false; + assert(server.prepare(request, explicit_request, error)); + assert(explicit_request.ids == default_request.ids); + assert(common_chat_parse(output, false, explicit_request.parser).tool_calls.size() == 1); + // Arguments in any order: the model writes optional parameters before required ones, and upstream's + // required-first rule dropped such calls without an error (patches/llama.cpp-qwen3-coder-any-argument-order.patch). + auto read_request = common_json::parse_no_throw(R"({ + "messages":[{"role":"user","content":"Read the file."}], + "tools":[{"type":"function","function":{"name":"read","parameters":{ + "type":"object","required":["path"],"properties":{"path":{"type":"string"}, + "offset":{"type":"number"},"limit":{"type":"number"}} + }}}] + })"); + Prepared read_prepared; + assert(server.prepare(read_request, read_prepared, error)); + for (const char* order : {"limit offset path", "offset path limit", "path limit offset", "path"}) { + std::string text = "Reasoning.\n\n\n\n\n"; + std::istringstream names(order); + for (std::string name; names >> name;) + text += "\n" + (name == "path" ? "/tmp/a.txt" : "40") + "\n\n"; + text += "\n"; + auto parsed = common_chat_parse(text, false, read_prepared.parser); + assert(parsed.tool_calls.size() == 1); + assert(parsed.tool_calls[0].name == "read"); + assert(parsed.tool_calls[0].arguments.find("\"path\":\"/tmp/a.txt\"") != std::string::npos); + } + llama_model_free(server.model); + std::puts("PASS: omitted parallel_tool_calls uses the model capability; explicit false remains honored; " + "tool arguments parse in any order"); +} diff --git a/frontend/child_watch.hpp b/frontend/child_watch.hpp new file mode 100644 index 0000000..207f2b4 --- /dev/null +++ b/frontend/child_watch.hpp @@ -0,0 +1,22 @@ +#pragma once + +#include +#include +#include +#include + +namespace strata_frontend { +// Called only by the supervisor, which is joined before Engine::quit(). +// Reap dead children: kill(pid, 0) would report a zombie as still alive. +inline bool child_running(pid_t& pid, std::string& why) { + int status = 0; + const pid_t result = ::waitpid(pid, &status, WNOHANG); + if (result == 0 || (result < 0 && errno == EINTR)) return true; + if (result < 0) why = std::string("waitpid: ") + std::strerror(errno); + else if (WIFSIGNALED(status)) why = "engine killed by signal " + std::to_string(WTERMSIG(status)); + else if (WIFEXITED(status)) why = "engine exited with code " + std::to_string(WEXITSTATUS(status)); + else why = "engine exited unexpectedly"; + pid = -1; + return false; +} +} diff --git a/frontend/child_watch_test.cpp b/frontend/child_watch_test.cpp new file mode 100644 index 0000000..abcb3a1 --- /dev/null +++ b/frontend/child_watch_test.cpp @@ -0,0 +1,31 @@ +#include "child_watch.hpp" +#include +#include +#include +#include +#include + +int main() { + for (bool crash : {false, true}) { + pid_t pid = ::fork(); + assert(pid >= 0); + if (pid == 0) { + const struct rlimit no_core{0, 0}; + ::setrlimit(RLIMIT_CORE, &no_core); + ::usleep(30000); + if (crash) ::raise(SIGABRT); + ::_exit(17); + } + std::string why; + assert(strata_frontend::child_running(pid, why)); + bool exited = false; + for (int i = 0; i < 100; ++i) { + if (!strata_frontend::child_running(pid, why)) { exited = true; break; } + ::usleep(10000); + } + assert(exited && pid == -1); + assert(why == (crash ? "engine killed by signal " + std::to_string(SIGABRT) : "engine exited with code 17")); + std::puts(why.c_str()); + } + std::puts("PASS: normal exit and watchdog-style abort reaped and diagnosed"); +} diff --git a/frontend/engine.hpp b/frontend/engine.hpp new file mode 100644 index 0000000..403dcf1 --- /dev/null +++ b/frontend/engine.hpp @@ -0,0 +1,166 @@ +#pragma once +#include "child_watch.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace strata_frontend { +struct GenResult { + bool ok = false; + std::string error; + std::string finish = "length"; + long long produced = 0, prompt_n = 0, draft_accepted = 0, draft_offered = 0; + double prompt_ms = 0, decode_ms = 0; +}; + +class Engine { +public: + bool start(const std::vector& args, std::string& err, const char* executable = "/proc/self/exe") { + int to_child[2], from_child[2]; + if (::pipe(to_child) != 0 || ::pipe(from_child) != 0) { err = "pipe failed"; return false; } + pid_ = ::fork(); + if (pid_ < 0) { err = "fork failed"; return false; } + if (pid_ == 0) { + ::dup2(to_child[0], STDIN_FILENO); + ::dup2(from_child[1], STDOUT_FILENO); + ::close(to_child[0]); ::close(to_child[1]); ::close(from_child[0]); ::close(from_child[1]); + std::vector argv; + for (const std::string& a : args) argv.push_back(const_cast(a.c_str())); + argv.push_back(nullptr); + ::execv(executable, argv.data()); + std::fprintf(stderr, "unbiased-strata: could not start the engine: %s\n", std::strerror(errno)); + ::_exit(127); + } + ::close(to_child[0]); + ::close(from_child[1]); + in_fd_ = to_child[1]; + out_ = ::fdopen(from_child[0], "r"); + return out_ != nullptr; + } + + /// Reads the engine's start-up lines until it says READY. Loading the model takes minutes. + bool wait_ready(std::string& err) { + std::string line; + while (read_line(line)) { + if (line.rfind("READY", 0) == 0) return true; + if (line.rfind("ERR", 0) == 0) { err = line; return false; } + } + err = "the engine exited before it was ready (its messages are above)"; + return false; + } + + /// One request. `on_token` returns false when the client has gone: the engine is told to stop and the rest of + /// its output for this request is read and dropped, so the next request starts clean. + GenResult generate(const std::string& header, const std::vector& ids, + const std::function& on_token) { + GenResult r; + if (!alive_) { r.error = "the engine is not running"; return r; } + std::string req = header; + req.reserve(header.size() + ids.size() * 7 + 2); + for (size_t i = 0; i < ids.size(); ++i) { + if (i) req += ','; + req += std::to_string(ids[i]); + } + req += '\n'; + if (!send(req)) { r.error = "the engine is not running"; return r; } + bool stopped = false; + std::string callback_error; + std::string line; + while (read_line(line)) { + if (line.size() > 2 && line[0] == 'T' && line[1] == ' ') { + if (!stopped) { + bool keep_going = false; + try { + keep_going = on_token((int32_t) std::atoi(line.c_str() + 2)); + } catch (const std::exception& ex) { + callback_error = ex.what(); + std::fprintf(stderr, "unbiased-strata: response formatter failed; stopping and draining request: %s\n", ex.what()); + } + if (!keep_going) { + stopped = true; + send("STOP\n"); + } + } + } else if (line.rfind("DONE ", 0) == 0) { + char finish[32] = {0}; + std::sscanf(line.c_str(), "DONE %lld %lld %lf %lf %31s %lld %lld", &r.produced, &r.prompt_n, &r.prompt_ms, + &r.decode_ms, finish, &r.draft_accepted, &r.draft_offered); + r.finish = finish; + if (r.prompt_n != (long long) ids.size()) { + r.error = "engine response prompt size mismatch: submitted " + std::to_string(ids.size()) + + ", returned " + std::to_string(r.prompt_n); + std::fprintf(stderr, "unbiased-strata: %s; refusing this response\n", r.error.c_str()); + alive_ = false; + return r; + } + r.ok = callback_error.empty(); + if (!r.ok) r.error = "response formatter failed: " + callback_error; + return r; + } else if (line.rfind("ERR", 0) == 0) { + r.error = line.size() > 4 ? line.substr(4) : "the engine reported an error"; + return r; + } + // PP (prompt progress), RESUME, REUSED and INFO lines need no action here + } + alive_ = false; + r.error = "the engine exited during the request"; + return r; + } + + void quit() { + if (pid_ > 0) { + send("QUIT\n"); + int status = 0; + for (int i = 0; i < 100 && ::waitpid(pid_, &status, WNOHANG) == 0; ++i) ::usleep(100 * 1000); + ::kill(pid_, SIGKILL); + ::waitpid(pid_, &status, 0); + pid_ = -1; + } + } + + bool reap_exit(std::string& why) { + if (strata_frontend::child_running(pid_, why)) return false; + alive_ = false; + return true; + } + + bool alive() const { return alive_; } + std::mutex mu; // one request at a time: the engine holds one conversation + +private: + bool send(const std::string& s) { + size_t off = 0; + while (off < s.size()) { + const ssize_t n = ::write(in_fd_, s.data() + off, s.size() - off); + if (n <= 0) { alive_ = false; return false; } + off += (size_t) n; + } + return true; + } + + bool read_line(std::string& line) { + char* buf = nullptr; + size_t cap = 0; + const ssize_t n = ::getline(&buf, &cap, out_); + if (n < 0) { std::free(buf); alive_ = false; return false; } + line.assign(buf, (size_t) n); + std::free(buf); + while (!line.empty() && (line.back() == '\n' || line.back() == '\r')) line.pop_back(); + return true; + } + + pid_t pid_ = -1; + int in_fd_ = -1; + FILE* out_ = nullptr; + std::atomic alive_{true}; +}; + +} diff --git a/frontend/engine_backpressure_test.cpp b/frontend/engine_backpressure_test.cpp new file mode 100644 index 0000000..287dce9 --- /dev/null +++ b/frontend/engine_backpressure_test.cpp @@ -0,0 +1,71 @@ +#include "engine.hpp" +#include +#include +#include +#include +#include + +// Enough output to fill a Linux pipe, with the same independent stdin reader +// and per-token STOP check as the backend. This requires no model or CUDA. +int fake_backend() { + std::setvbuf(stdout, nullptr, _IONBF, 0); + std::mutex mutex; + std::condition_variable ready; + std::deque commands; + std::atomic stop{false}; + auto reader = std::thread([&] { + std::string input; + char byte; + while (::read(0, &byte, 1) == 1) { + if (byte != '\n') { input += byte; continue; } + if (input == "STOP") { stop.store(true); input.clear(); continue; } + const bool quit = input == "QUIT"; + { std::lock_guard lock(mutex); commands.push_back(input); } + input.clear(); ready.notify_one(); + if (quit) return; + } + }); + std::puts("READY"); + for (;;) { + std::unique_lock lock(mutex); + ready.wait(lock, [&] { return !commands.empty(); }); + auto command = commands.front(); commands.pop_front(); lock.unlock(); + if (command == "QUIT") break; + stop.store(false); + const int token = command.find("99") != std::string::npos ? 99 : 11; + int count = 0; + while (count < 100000) { + std::printf("T %d\n", token); ++count; + if (stop.load()) break; + } + std::printf("DONE %d 1 1 1 stop 0 0\n", count); + } + reader.join(); + return 0; +} + +int main(int argc, char** argv) { + if (argc > 1) return fake_backend(); + strata_frontend::Engine engine; + std::string error; + assert(engine.start({argv[0], "--fake-backend"}, error, argv[0])); + assert(engine.wait_ready(error)); + auto failed = engine.generate("GEN 100000 ", {11}, [](int32_t) -> bool { + throw std::runtime_error("partial tool JSON formatter failure"); + }); + assert(!failed.ok); + int count = 0; + auto next = engine.generate("GEN 100000 ", {99}, [&](int32_t token) { + assert(token == 99); ++count; return true; + }); + assert(next.ok && count == 100000); + auto cancel = engine.generate("GEN 100000 ", {11}, [](int32_t) { return false; }); + assert(cancel.ok); + count = 0; + next = engine.generate("GEN 100000 ", {99}, [&](int32_t token) { + assert(token == 99); ++count; return true; + }); + assert(next.ok && count == 100000); + engine.quit(); + std::puts("PASS: large responses cannot fill an abandoned pipe or leak into the next request"); +} diff --git a/frontend/engine_test.cpp b/frontend/engine_test.cpp new file mode 100644 index 0000000..ab531b5 --- /dev/null +++ b/frontend/engine_test.cpp @@ -0,0 +1,49 @@ +#include "engine.hpp" +#include +#include + +int main(int argc, char** argv) { + if (argc > 1 && std::string(argv[1]) == "--fake-engine") { + std::puts("READY"); std::fflush(stdout); + char* line = nullptr; size_t capacity = 0; + while (::getline(&line, &capacity, stdin) > 0) { + const std::string request(line); + if (request == "QUIT\n") break; + if (request == "STOP\n") continue; + if (request.rfind("GEN ", 0) != 0) continue; + if (request.find("88") != std::string::npos) { + std::printf("T 88\nDONE 1 2 1 1 stop 0 0\n"); + std::fflush(stdout); + continue; + } + const int base = request.find("99") != std::string::npos ? 99 : 11; + std::printf("T %d\nT %d\nDONE 2 1 1 1 stop 0 0\n", base, base+1); + std::fflush(stdout); + } + std::free(line); + return 0; + } + strata_frontend::Engine engine; + std::string error; + assert(engine.start({argv[0], "--fake-engine"}, error, argv[0])); + assert(engine.wait_ready(error)); + auto failed = engine.generate("GEN 2 ", {11}, [](int32_t) -> bool { + throw std::runtime_error("synthetic partial tool JSON diff error"); + }); + assert(!failed.ok && failed.error.find("synthetic") != std::string::npos); + std::vector tokens; + auto next = engine.generate("GEN 2 ", {99}, [&](int32_t token) { tokens.push_back(token); return true; }); + assert(next.ok && (tokens == std::vector{99,100})); + auto cancelled = engine.generate("GEN 2 ", {11}, [](int32_t) { return false; }); + assert(cancelled.ok); + tokens.clear(); + next = engine.generate("GEN 2 ", {99}, [&](int32_t token) { tokens.push_back(token); return true; }); + assert(next.ok && (tokens == std::vector{99,100})); + auto mismatched = engine.generate("GEN 2 ", {88}, [](int32_t) { return true; }); + assert(!mismatched.ok && !engine.alive()); + assert(mismatched.error.find("prompt size mismatch") != std::string::npos); + auto rejected = engine.generate("GEN 2 ", {99}, [](int32_t) { return true; }); + assert(!rejected.ok && rejected.produced == 0); + engine.quit(); + std::puts("PASS: formatter exceptions and client cancellation drain the old request before the next request"); +} diff --git a/frontend/main.cpp b/frontend/main.cpp index 3687f6a..ef39a68 100644 --- a/frontend/main.cpp +++ b/frontend/main.cpp @@ -8,6 +8,8 @@ // // The tokenizer and the chat template come from llama.cpp (the pinned submodule): the GGUF's own vocabulary and // its own Jinja template. Nothing here opens an outgoing connection. +#include "engine.hpp" +#include "vision.hpp" #include "chat.h" #include "common.h" #include "llama.h" @@ -25,6 +27,7 @@ #include #include #include +#include #include #include @@ -42,6 +45,8 @@ struct Options { std::string model; // shard 1 of the GGUF std::string pack; // the prepared pack directory std::string mtp; // the prepared draft-head directory + std::string mmproj; + int vision_tokens = 1024; std::string host = "127.0.0.1"; int port = 8080; long long ctx = 32768; @@ -55,6 +60,8 @@ void usage() { " --model PATH the model's first GGUF shard (...-00001-of-00002.gguf); the second must be beside it\n" " --pack DIR the prepared pack for that model\n" " --mtp DIR the prepared draft head\n" + " --mmproj PATH enable image input using this vision encoder (CPU)\n" + " --vision-tokens N maximum tokens per image (default 1024)\n" " --ctx N context length in tokens (default 32768)\n" " --threads N CPU threads for the experts the GPU does not hold (default: every physical core,\n" " or half the CPU quota inside a container that has one)\n" @@ -70,130 +77,8 @@ bool file_exists(const std::string& p) { // ---------------------------------------------------------------------------------------------------- the engine -struct GenResult { - bool ok = false; - std::string error; - std::string finish = "length"; - long long produced = 0, prompt_n = 0, draft_accepted = 0, draft_offered = 0; - double prompt_ms = 0, decode_ms = 0; -}; - -class Engine { -public: - bool start(const std::vector& args, std::string& err) { - int to_child[2], from_child[2]; - if (::pipe(to_child) != 0 || ::pipe(from_child) != 0) { err = "pipe failed"; return false; } - pid_ = ::fork(); - if (pid_ < 0) { err = "fork failed"; return false; } - if (pid_ == 0) { - ::dup2(to_child[0], STDIN_FILENO); - ::dup2(from_child[1], STDOUT_FILENO); - ::close(to_child[0]); ::close(to_child[1]); ::close(from_child[0]); ::close(from_child[1]); - std::vector argv; - for (const std::string& a : args) argv.push_back(const_cast(a.c_str())); - argv.push_back(nullptr); - ::execv("/proc/self/exe", argv.data()); - std::fprintf(stderr, "unbiased-strata: could not start the engine: %s\n", std::strerror(errno)); - ::_exit(127); - } - ::close(to_child[0]); - ::close(from_child[1]); - in_fd_ = to_child[1]; - out_ = ::fdopen(from_child[0], "r"); - return out_ != nullptr; - } - - /// Reads the engine's start-up lines until it says READY. Loading the model takes minutes. - bool wait_ready(std::string& err) { - std::string line; - while (read_line(line)) { - if (line.rfind("READY", 0) == 0) return true; - if (line.rfind("ERR", 0) == 0) { err = line; return false; } - } - err = "the engine exited before it was ready (its messages are above)"; - return false; - } - - /// One request. `on_token` returns false when the client has gone: the engine is told to stop and the rest of - /// its output for this request is read and dropped, so the next request starts clean. - GenResult generate(const std::string& header, const std::vector& ids, - const std::function& on_token) { - GenResult r; - std::string req = header; - req.reserve(header.size() + ids.size() * 7 + 2); - for (size_t i = 0; i < ids.size(); ++i) { - if (i) req += ','; - req += std::to_string(ids[i]); - } - req += '\n'; - if (!send(req)) { r.error = "the engine is not running"; return r; } - bool stopped = false; - std::string line; - while (read_line(line)) { - if (line.size() > 2 && line[0] == 'T' && line[1] == ' ') { - if (!stopped && !on_token((llama_token) std::atoi(line.c_str() + 2))) { - stopped = true; - send("STOP\n"); - } - } else if (line.rfind("DONE ", 0) == 0) { - char finish[32] = {0}; - std::sscanf(line.c_str(), "DONE %lld %lld %lf %lf %31s %lld %lld", &r.produced, &r.prompt_n, &r.prompt_ms, - &r.decode_ms, finish, &r.draft_accepted, &r.draft_offered); - r.finish = finish; - r.ok = true; - return r; - } else if (line.rfind("ERR", 0) == 0) { - r.error = line.size() > 4 ? line.substr(4) : "the engine reported an error"; - return r; - } - // PP (prompt progress), RESUME, REUSED and INFO lines need no action here - } - alive_ = false; - r.error = "the engine exited during the request"; - return r; - } - - void quit() { - if (pid_ > 0) { - send("QUIT\n"); - int status = 0; - for (int i = 0; i < 100 && ::waitpid(pid_, &status, WNOHANG) == 0; ++i) ::usleep(100 * 1000); - ::kill(pid_, SIGKILL); - ::waitpid(pid_, &status, 0); - pid_ = -1; - } - } - - bool alive() const { return alive_; } - std::mutex mu; // one request at a time: the engine holds one conversation - -private: - bool send(const std::string& s) { - size_t off = 0; - while (off < s.size()) { - const ssize_t n = ::write(in_fd_, s.data() + off, s.size() - off); - if (n <= 0) { alive_ = false; return false; } - off += (size_t) n; - } - return true; - } - - bool read_line(std::string& line) { - char* buf = nullptr; - size_t cap = 0; - const ssize_t n = ::getline(&buf, &cap, out_); - if (n < 0) { std::free(buf); alive_ = false; return false; } - line.assign(buf, (size_t) n); - std::free(buf); - while (!line.empty() && (line.back() == '\n' || line.back() == '\r')) line.pop_back(); - return true; - } - - pid_t pid_ = -1; - int in_fd_ = -1; - FILE* out_ = nullptr; - std::atomic alive_{true}; -}; +using strata_frontend::Engine; +using strata_frontend::GenResult; // ------------------------------------------------------------------------------------------------ text handling @@ -237,8 +122,10 @@ void json_error(httplib::Response& res, int status, const std::string& message, // ------------------------------------------------------------------------------------------------- the request struct Prepared { + std::shared_ptr images; std::vector ids; std::string header; // "GEN key=value ... " - the ids follow + std::string request_id; common_chat_parser_params parser; // how to split the output into reasoning, answer and tool calls bool stream = false; long long max_new = 0; @@ -247,6 +134,7 @@ struct Prepared { struct Server { Options opt; Engine engine; + strata_frontend::Vision vision; llama_model* model = nullptr; const llama_vocab* vocab = nullptr; common_chat_templates_ptr tmpls; @@ -255,12 +143,31 @@ struct Server { bool prepare(const common_json& body, Prepared& p, std::string& err) { if (!body.is_object() || !body.contains("messages")) { err = "the request needs a \"messages\" array"; return false; } common_chat_templates_inputs in; - in.messages = common_chat_msgs_parse_oaicompat(body.at("messages")); + common_json messages = body.at("messages"); + std::vector markers; + std::vector> images; + { + std::lock_guard lock(engine.mu); + for (auto& message : messages) { + if (!message.contains("content") || !message.at("content").is_array()) continue; + for (auto& part : message["content"]) { + if (part.value("type", "") != "image_url") continue; + if (images.size() >= 32) throw std::invalid_argument("at most 32 images per request"); + const std::string url = part.at("image_url").at("url").get(); + images.push_back(vision.encode(url)); + markers.push_back("UNBIASED_IMAGE_" + make_id() + "_" + std::to_string(markers.size())); + part = common_json::object(); + part["type"] = "media_marker"; part["text"] = markers.back(); + } + } + } + in.messages = common_chat_msgs_parse_oaicompat(messages); if (body.contains("tools") && body.at("tools").is_array() && body.at("tools").size() > 0) { in.tools = common_chat_tools_parse_oaicompat(body.at("tools")); if (body.contains("tool_choice") && body.at("tool_choice").is_string()) in.tool_choice = common_chat_tool_choice_parse_oaicompat(body.at("tool_choice").get()); - in.parallel_tool_calls = body.value("parallel_tool_calls", false); + const auto caps = common_chat_templates_get_caps(tmpls.get()); + in.parallel_tool_calls = body.value("parallel_tool_calls", caps.at("supports_parallel_tool_calls")); } in.add_generation_prompt = true; in.use_jinja = true; @@ -280,7 +187,39 @@ struct Server { in.chat_template_kwargs["reasoning_effort"] = kw.at("reasoning_effort").dump(); } const common_chat_params cp = common_chat_templates_apply(tmpls.get(), in); - p.ids = common_tokenize(vocab, cp.prompt, /*add_special=*/false, /*parse_special=*/true); + std::string rendered = cp.prompt; + if (images.empty()) { + p.ids = common_tokenize(vocab, rendered, false, true); + } else { + const auto pad = common_tokenize(vocab, "<|image_pad|>", false, true); + const auto literal_pad = common_tokenize(vocab, "<|image_pad|>", false, false); + const auto start = common_tokenize(vocab, "<|vision_start|>", false, true); + const auto end = common_tokenize(vocab, "<|vision_end|>", false, true); + if (pad.size() != 1 || start.size() != 1 || end.size() != 1) + throw std::runtime_error("model does not have the expected image special tokens"); + auto text_ids = [&](const std::string& text) { + for (auto id : common_tokenize(vocab, text, false, true)) { + if (id == pad[0]) p.ids.insert(p.ids.end(), literal_pad.begin(), literal_pad.end()); + else p.ids.push_back(id); + } + }; + size_t offset = 0; rendered.clear(); + for (size_t i = 0; i < images.size(); ++i) { + auto at = cp.prompt.find(markers[i], offset); + if (at == std::string::npos || cp.prompt.find(markers[i], at+markers[i].size()) != std::string::npos) + throw std::invalid_argument("chat template did not preserve each image exactly once"); + auto text = cp.prompt.substr(offset, at-offset); + text_ids(text); rendered += text + "<|vision_start|>"; + p.ids.push_back(start[0]); + p.ids.insert(p.ids.end(), images[i]->tokens, pad[0]); + for (int j = 0; j < images[i]->tokens; ++j) rendered += "<|image_pad|>"; + p.ids.push_back(end[0]); rendered += "<|vision_end|>"; + offset = at + markers[i].size(); + } + auto tail = cp.prompt.substr(offset); text_ids(tail); rendered += tail; + p.images = std::make_shared(); + strata_frontend::write_images(*p.images, images); + } if (p.ids.empty()) { err = "the prompt is empty"; return false; } p.parser = common_chat_parser_params(cp); @@ -332,7 +271,23 @@ struct Server { keys += b; if (keys.find("penalty_last_n") == std::string::npos) keys += " penalty_last_n=64"; } - p.header = "GEN " + std::to_string(max_new) + keys + " "; + p.header = (p.images ? "GENI " : "GEN ") + std::to_string(max_new) + keys + " " + + (p.images ? p.images->path + " " : ""); + // Opt-in provenance capture: the exact first rendered request this + // process serves, including token IDs and the engine sampling header. + if (const char* path = std::getenv("SUGMEOFF_CAPTURE_FIRST_PROMPT")) { + if (FILE* f = std::fopen(path, "wx")) { + common_json capture = common_json::object(); + capture["request"] = body; + capture["rendered_prompt"] = rendered; + capture["token_ids"] = p.ids; + capture["engine_header"] = p.header; + const std::string text = capture.dump_safe(); + if (std::fwrite(text.data(), 1, text.size(), f) != text.size()) + std::fprintf(stderr, "unbiased-strata: prompt capture write failed: %s\n", path); + std::fclose(f); + } + } return true; } @@ -363,6 +318,8 @@ struct Server { GenResult run(const Prepared& p, common_chat_msg& final_msg, const std::function&)>& emit) { std::lock_guard lk(engine.mu); + std::fprintf(stderr, "unbiased-strata: request %s start: prompt=%zu header=%s\n", + p.request_id.c_str(), p.ids.size(), p.header.c_str()); std::string text, pending; common_chat_msg msg; std::vector call_ids; @@ -377,6 +334,16 @@ struct Server { now.role = "assistant"; now.content = text; } + // Partial tool JSON is reparsed and normalized as tokens arrive. + // Escapes and incomplete arguments can change already-parsed text, + // which cannot be retracted from an OpenAI stream. Publish content + // and tool calls once, after the full message is parsed; reasoning + // can still stream. This changes delivery, never generated tokens. + if (partial) { + now.content.clear(); + now.content_parts.clear(); + now.tool_calls.clear(); + } if (now.empty()) return; now.set_tool_call_ids(call_ids, [] { return "call_" + make_id().substr(9); }); const std::vector diffs = common_chat_msg_diff::compute_diffs(msg, now); @@ -395,16 +362,30 @@ struct Server { return client_ok; }); text += pending; - update(false); + try { + update(false); + } catch (const std::exception& ex) { + r.ok = false; + r.error = std::string("response formatter failed: ") + ex.what(); + std::fprintf(stderr, "unbiased-strata: final response formatter failed: %s\n", ex.what()); + } final_msg = msg; if (final_msg.role.empty()) final_msg.role = "assistant"; if (final_msg.tool_calls.empty() && text.find("") != std::string::npos) { // The parser accepts a message with no tool call even when the text holds one it could not // match (see third_party/llama.cpp/common/parsers/qwen3-coder.cpp); say so, with the text. - std::fprintf(stderr, "unbiased-strata: the output contains but no tool call was parsed; " - "the client sees finish=stop. raw-output-begin\n%s\nunbiased-strata: raw-output-end\n", - text.c_str()); + std::fprintf(stderr, "unbiased-strata: request %s: the output contains but no tool call was " + "parsed; the client sees finish=stop. raw-output-begin\n%s\n" + "unbiased-strata: request %s raw-output-end\n", + p.request_id.c_str(), text.c_str(), p.request_id.c_str()); } + if (r.error.find("response formatter failed") == 0) { + std::fprintf(stderr, "unbiased-strata: request %s formatter-input-begin\n%s\n" + "unbiased-strata: request %s formatter-input-end\n", + p.request_id.c_str(), text.c_str(), p.request_id.c_str()); + } + std::fprintf(stderr, "unbiased-strata: request %s end: ok=%d prompt=%lld generated=%lld finish=%s error=%s\n", + p.request_id.c_str(), r.ok ? 1 : 0, r.prompt_n, r.produced, r.finish.c_str(), r.error.c_str()); return r; } @@ -425,6 +406,7 @@ struct Server { return json_error(res, 400, ex.what(), "invalid_request_error"); } const std::string id = make_id(); + prep->request_id = id; const long long created = now_s(); if (!prep->stream) { @@ -561,6 +543,8 @@ bool parse_args(int argc, char** argv, Options& o) { return argv[++i]; }; if (a == "--model") o.model = next("--model"); + else if (a == "--mmproj") o.mmproj = next("--mmproj"); + else if (a == "--vision-tokens") o.vision_tokens = std::atoi(next("--vision-tokens").c_str()); else if (a == "--pack") o.pack = next("--pack"); else if (a == "--mtp") o.mtp = next("--mtp"); else if (a == "--host") o.host = next("--host"); @@ -574,7 +558,7 @@ bool parse_args(int argc, char** argv, Options& o) { for (const char* no : {"--gpus", "--layer-split", "--split-device", "--peer-device", "--peer-slots", "--remote-expert", "--vision", "--batch"}) if (e.rfind(no, 0) == 0) { - std::fprintf(stderr, "unbiased-strata: %s is not supported (single GPU, text only)\n", e.c_str()); + std::fprintf(stderr, "unbiased-strata: %s is not supported here (use --mmproj for image input)\n", e.c_str()); std::exit(2); } o.extra.push_back(e); @@ -609,11 +593,15 @@ int main(int argc, char** argv) { if (!file_exists(f)) { std::fprintf(stderr, "unbiased-strata: missing file: %s\n", f.c_str()); return 2; } if (o.ctx < 1024) { std::fprintf(stderr, "unbiased-strata: --ctx must be at least 1024\n"); return 2; } + if (!o.mmproj.empty() && (!file_exists(o.mmproj) || o.vision_tokens < 16 || o.vision_tokens > 4096)) { + std::fprintf(stderr, "unbiased-strata: --mmproj must exist and --vision-tokens must be 16..4096\n"); return 2; + } // the engine, started first: loading takes minutes, and it must be forked before any thread exists std::vector eargs = { "unbiased-strata", "--engine", "--serve", "--pack", o.pack, "--native", o.model, "--ple-gguf", shard2, "--expert-profile", profile, "--expert-cache", "auto", "--prefill", "auto", "--spec", "4", "--spec-min-p", "0.5", "--mtp", o.mtp, "--max-context", std::to_string(o.ctx), "--ple-io", "ram"}; + if (!o.mmproj.empty()) eargs.push_back("--vision"); if (o.ctx > 8192) { eargs.push_back("--kv"); eargs.push_back("int8"); } if (o.threads <= 0) { o.threads = default_threads(); @@ -640,6 +628,12 @@ int main(int argc, char** argv) { } srv.vocab = llama_model_get_vocab(srv.model); srv.tmpls = common_chat_templates_init(srv.model, ""); + if (!o.mmproj.empty()) { + try { srv.vision.init(o.mmproj, srv.model, o.threads, o.vision_tokens); } + catch (const std::exception& ex) { + std::fprintf(stderr, "unbiased-strata: %s\n", ex.what()); srv.engine.quit(); return 1; + } + } std::fprintf(stderr, "unbiased-strata: loading the model (this takes a few minutes)...\n"); if (!srv.engine.wait_ready(err)) { @@ -656,11 +650,15 @@ int main(int argc, char** argv) { res.set_content(srv.engine.alive() ? "{\"status\":\"ok\"}" : "{\"status\":\"error\"}", "application/json"); }); http.Get("/v1/models", [&](const httplib::Request&, httplib::Response& res) { + if (!srv.engine.alive()) return json_error(res, 503, "the engine is not running", "server_error"); common_json m = common_json::object(); m["id"] = kModelName; m["object"] = "model"; m["owned_by"] = "local"; m["context_length"] = srv.opt.ctx; + m["input_modalities"] = common_json::array(); + m["input_modalities"].push_back("text"); + if (srv.vision.enabled()) m["input_modalities"].push_back("image"); common_json out = common_json::object(); out["object"] = "list"; out["data"] = common_json::array(); @@ -670,6 +668,7 @@ int main(int argc, char** argv) { http.Post("/v1/chat/completions", [&](const httplib::Request& req, httplib::Response& res) { srv.handle_chat(req, res); }); + http.set_payload_max_length(64 * 1024 * 1024); http.set_read_timeout(600, 0); http.set_write_timeout(600, 0); std::signal(SIGINT, on_signal); @@ -681,7 +680,29 @@ int main(int argc, char** argv) { return 1; } std::fprintf(stderr, "unbiased-strata: ready on http://%s:%d (context %lld tokens)\n", o.host.c_str(), o.port, o.ctx); + // The engine watchdog intentionally aborts a stuck child. Exit the HTTP + // parent too so systemd's Restart=on-failure reloads the complete service. + // Do not fork a replacement from this multithreaded HTTP process. + std::atomic shutting_down{false}; + std::thread supervisor([&] { + while (!shutting_down.load()) { + std::string why; + if (srv.engine.reap_exit(why)) { + std::fprintf(stderr, "unbiased-strata: %s; exiting frontend for service restart\n", why.c_str()); + std::fflush(stderr); + std::_Exit(1); + } + if (!srv.engine.alive()) { + std::fprintf(stderr, "unbiased-strata: engine protocol failed; exiting frontend for service restart\n"); + std::fflush(stderr); + std::_Exit(1); + } + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + } + }); http.listen_after_bind(); + shutting_down.store(true); + supervisor.join(); std::fprintf(stderr, "unbiased-strata: stopping\n"); srv.engine.quit(); diff --git a/frontend/vision.hpp b/frontend/vision.hpp new file mode 100644 index 0000000..146cf85 --- /dev/null +++ b/frontend/vision.hpp @@ -0,0 +1,143 @@ +#pragma once +#include "common.h" +#include "gguf.h" +#include "mtmd.h" +#include "mtmd-helper.h" +#include +#include +#include +#include +#include +#include +#include +#include + +namespace strata_frontend { +// Private per-request file, retained through streaming completion/cancellation. +struct ImageFile { + std::string path; + ImageFile() { + char name[] = "/tmp/unbiased-strata-image-XXXXXX"; + int fd = mkstemp(name); + if (fd < 0) throw std::runtime_error("cannot create image embedding file"); + close(fd); path = name; + } + ~ImageFile() { if (!path.empty()) unlink(path.c_str()); } + ImageFile(const ImageFile&) = delete; + ImageFile& operator=(const ImageFile&) = delete; +}; + +inline std::vector image_data(const std::string& url) { + const size_t comma = url.find(','); + if (url.rfind("data:image/", 0) != 0 || comma == std::string::npos || + comma < 7 || url.substr(comma - 7, 7) != ";base64") + throw std::invalid_argument("image_url must contain a base64 data:image URL (PNG, JPEG, BMP or GIF)"); + const std::string data = url.substr(comma + 1); + if (data.empty() || data.size() > 32 * 1024 * 1024 || data.size() % 4) + throw std::invalid_argument("empty, oversized or malformed base64 image"); + const std::string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + std::array table; table.fill(-1); + for (size_t i = 0; i < alphabet.size(); ++i) table[(unsigned char) alphabet[i]] = (int) i; + std::vector out; out.reserve(data.size() / 4 * 3); + for (size_t i = 0; i < data.size(); i += 4) { + int a = table[(unsigned char)data[i]], b = table[(unsigned char)data[i+1]]; + bool p2 = data[i+2] == '=', p3 = data[i+3] == '='; + int c = p2 ? 0 : table[(unsigned char)data[i+2]], d = p3 ? 0 : table[(unsigned char)data[i+3]]; + if (a < 0 || b < 0 || c < 0 || d < 0 || (p2 && !p3) || + ((p2 || p3) && i + 4 != data.size()) || (p2 && (b & 15)) || (!p2 && p3 && (c & 3))) + throw std::invalid_argument("malformed base64 image"); + out.push_back((a << 2) | (b >> 4)); + if (!p2) out.push_back((b << 4) | (c >> 2)); + if (!p3) out.push_back((c << 6) | d); + } + return out; +} +struct EncodedImage { + int32_t tokens, nx, ny, width; + std::vector values; +}; + +// CPU encoder leaves the engine's full VRAM expert cache available. Its callers +// take engine.mu, serializing image encoding and generation just like upstream. +class Vision { + mtmd_context* ctx_ = nullptr; + int width_ = 0; + int max_tokens_ = 1024; + size_t cache_bytes_ = 0; + std::map> cache_; +public: + ~Vision() { if (ctx_) mtmd_free(ctx_); } + bool enabled() const { return ctx_ != nullptr; } + void init(const std::string& path, const llama_model* model, int threads, int max_tokens) { + gguf_init_params gp{true, nullptr}; + auto gg = std::unique_ptr(gguf_init_from_file(path.c_str(), gp), gguf_free); + auto key = gg ? gguf_find_key(gg.get(), "clip.vision.projection_dim") : -1; + if (key < 0) throw std::runtime_error("vision encoder has no projection_dim"); + width_ = (int) gguf_get_val_u32(gg.get(), key); + if (width_ != 2560) throw std::runtime_error("vision projector does not match Flash-Next's 2560 embedding width"); + max_tokens_ = max_tokens; + auto cp = mtmd_context_params_default(); + cp.use_gpu = false; cp.print_timings = false; cp.warmup = false; + cp.n_threads = threads > 0 ? threads : 8; + cp.image_max_tokens = max_tokens; + ctx_ = mtmd_init_from_file(path.c_str(), model, cp); + if (!ctx_ || !mtmd_support_vision(ctx_)) throw std::runtime_error("cannot load vision encoder: " + path); + } + std::shared_ptr encode(const std::string& url) { + if (!ctx_) throw std::invalid_argument("image input requires starting UnbiasedStrata with --mmproj PATH"); + auto bytes = image_data(url); + auto t0 = std::chrono::steady_clock::now(); + auto bw = mtmd_helper_bitmap_init_from_buf(ctx_, bytes.data(), bytes.size(), false, mtmd_helper_init_opt_default()); + std::unique_ptr bitmap(bw.bitmap, mtmd_bitmap_free); + if (bw.video_ctx) mtmd_helper_video_free(bw.video_ctx); + if (!bitmap || mtmd_bitmap_is_audio(bitmap.get())) throw std::invalid_argument("cannot decode image; use PNG, JPEG, BMP or GIF"); + const char* hash = mtmd_bitmap_get_id(bitmap.get()); + if (!hash || !*hash) throw std::runtime_error("image decoder did not supply a content hash"); + std::string id(hash); + auto cached = cache_.find(id); + if (cached != cache_.end()) return cached->second; + auto chunks = std::unique_ptr(mtmd_input_chunks_init(), mtmd_input_chunks_free); + std::string marker = mtmd_default_marker(); + mtmd_input_text txt{marker.c_str(), marker.size(), false, true}; + const mtmd_bitmap* bm[] = {bitmap.get()}; + if (mtmd_tokenize(ctx_, chunks.get(), &txt, bm, 1)) throw std::invalid_argument("image preprocessing failed"); + const mtmd_input_chunk* image = nullptr; + for (size_t i = 0; i < mtmd_input_chunks_size(chunks.get()); ++i) { + auto ch = mtmd_input_chunks_get(chunks.get(), i); + if (mtmd_input_chunk_get_type(ch) == MTMD_INPUT_CHUNK_TYPE_IMAGE) { + if (image) throw std::invalid_argument("multiple image chunks are unsupported for this model"); + image = ch; + } + } + if (!image) throw std::invalid_argument("no image tokens produced"); + size_t n = mtmd_input_chunk_get_n_tokens(image); + if (!n || n > (size_t)max_tokens_) throw std::invalid_argument("image token count exceeds configured limit"); + if (mtmd_encode_chunk(ctx_, image)) throw std::runtime_error("vision encoding failed"); + auto last = mtmd_image_tokens_get_decoder_pos(mtmd_input_chunk_get_tokens_image(image), 0, n-1); + int nx = (int)last.x + 1, ny = (int)last.y + 1; + if ((size_t)nx * ny != n) throw std::runtime_error("image grid is not rectangular"); + auto result = std::make_shared(); + result->tokens = (int32_t)n; result->nx = nx; result->ny = ny; result->width = width_; + auto values = mtmd_get_output_embd(ctx_); + if (!values) throw std::runtime_error("encoder returned no image embeddings"); + result->values.assign(values, values+n*width_); + size_t size = result->values.size()*sizeof(float); + if (cache_bytes_ + size > 128*1024*1024) { cache_.clear(); cache_bytes_ = 0; } + cache_[id] = result; cache_bytes_ += size; + auto ms = std::chrono::duration(std::chrono::steady_clock::now()-t0).count(); + std::fprintf(stderr, "unbiased-strata: encoded image %.0f ms, %d tokens (%dx%d), CPU\n", ms, result->tokens, nx, ny); + return result; + } +}; +inline void write_images(const ImageFile& file, const std::vector>& images) { + auto f = std::unique_ptr(std::fopen(file.path.c_str(), "wb"), std::fclose); + if (!f) throw std::runtime_error("cannot open image embedding file"); + for (auto& im : images) { + int32_t hdr[] = {0x31455653, im->tokens, im->nx, im->ny, im->width}; + if (std::fwrite(hdr, sizeof(hdr), 1, f.get()) != 1 || + std::fwrite(im->values.data(), sizeof(float), im->values.size(), f.get()) != im->values.size()) + throw std::runtime_error("short write to image embedding file"); + } + if (std::fflush(f.get())) throw std::runtime_error("cannot flush image embedding file"); +} +} // namespace strata_frontend diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 085c3d8..35892aa 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -923,6 +923,18 @@ int on_rotational_disk(const std::string& path, std::string& dev) { return -1; } +void thread_wait_channels(std::FILE* f) { + std::error_code ec; + for (const auto& e : std::filesystem::directory_iterator("/proc/self/task", ec)) { + std::ifstream wc(e.path() / "wchan"); + std::string where; + std::getline(wc, where); + std::fprintf(f, " thread %s%s wait channel: %s\n", e.path().filename().string().c_str(), + e.path().filename().string() == std::to_string((long long) ::getpid()) ? " (main)" : "", + where.empty() ? "unavailable" : where.c_str()); + } +} + // #605: the engine's threads in uninterruptible sleep (state D - almost always waiting for the disk), and where // (wchan): 16 threads in blk_io_schedule is a disk that cannot keep up, not a deadlock in the engine void disk_wait_threads(std::FILE* f) { @@ -967,6 +979,7 @@ void stall_report(std::FILE* f, uint64_t layers_during) { if (auto fn = strata::core::diag_verify_fn().load()) fn(f); #if !defined(_WIN32) disk_wait_threads(f); + thread_wait_channels(f); #endif const MemSample m = mem_sample(); std::fprintf(f, " memory: %llu MiB resident, %llu MiB %s, %llu MiB RAM available; %llu %s\n", m.rss_mib, @@ -7140,6 +7153,7 @@ int main(int argc, char** argv) { bool adapt_ok = true; if (!drive.d.usage.empty() && ((rounds + 1) % o.adapt_every) == 0) adapt_thr = std::thread([&] { adapt_ok = adapt(); }); + strata::core::progress_at("commit", p); if (!ver.commit(a + 1, err)) { if (adapt_thr.joinable()) adapt_thr.join(); std::printf("ERR %s\n", err.c_str()); @@ -7151,6 +7165,7 @@ int main(int argc, char** argv) { draft_accepted += a; first_window = false; bool eos = false; + strata::core::progress_at("emit tokens", p); for (int i = 0; i <= a && produced_n < max_new && !eos; ++i) { std::printf("T %d\n", (int) outv[(size_t) i]); strata::core::progress_beat(); @@ -7165,6 +7180,7 @@ int main(int argc, char** argv) { // commit, outv[a] is its row 0) - the drafts extend it on the device as the verify rows will if (hist_n > 0 && mtp.coupled() && !eos && produced_n < max_new) mtp.set_draft_history(consumed.data(), (int64_t) consumed.size(), outv[(size_t) a]); + strata::core::progress_at("MTP draft", p); const bool drafted = eos || produced_n >= max_new || mtp.draft(T, outv.data(), p, a, drafts.data(), err, dprob.data(), (float) req_spec_min_p); { @@ -7173,6 +7189,7 @@ int main(int argc, char** argv) { dt_run += msd(tw0, tw1); dt_commit += msd(tw1, tw2); dt_draft += msd(tw2, tw3); ++dec_windows; dec_T += T; } + strata::core::progress_at("adaptive refill join", p); if (adapt_thr.joinable()) adapt_thr.join(); if (!adapt_ok) { std::printf("ERR an adaptive refill failed\n");