diff --git a/CMakeLists.txt b/CMakeLists.txt index 4649fde..7b51e42 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2147,7 +2147,8 @@ endif() # cpp-httplib) and its image encoder (mtmd) from the same pinned checkout that ggml comes from. ggml is configured # above, so llama.cpp's build reuses those targets. Nothing here downloads: LLAMA_USE_PREBUILT_UI is off and # LLAMA_CURL is a no-op at this pin. -if(STRATA_ENABLE_CUDA AND STRATA_NATIVE_EXPERTS) +option(STRATA_FRONTEND "Build the C++ front end (unbiased-strata); needs no CUDA, so it also builds on a laptop" ON) +if(STRATA_FRONTEND AND STRATA_NATIVE_EXPERTS) set(LLAMA_BUILD_COMMON ON CACHE BOOL "" FORCE) set(LLAMA_BUILD_MTMD ON CACHE BOOL "" FORCE) foreach(_o LLAMA_BUILD_TESTS LLAMA_BUILD_TOOLS LLAMA_BUILD_EXAMPLES LLAMA_BUILD_SERVER LLAMA_BUILD_APP LLAMA_BUILD_UI @@ -2155,6 +2156,34 @@ if(STRATA_ENABLE_CUDA AND STRATA_NATIVE_EXPERTS) set(${_o} OFF CACHE BOOL "" FORCE) endforeach() add_subdirectory(${STRATA_GGML_DIR} ${CMAKE_BINARY_DIR}/llama.cpp EXCLUDE_FROM_ALL) + + # The engine-agnostic files of llama.cpp's tools/server, compiled as they are from the submodule: the HTTP layer, + # the task queue, the task and result types with their OpenAI JSON, request parsing and SSE formatting, the request + # schema, the resumable-stream pipe. server-context.cpp, the part bound to llama_context, is replaced by + # frontend/strata_context.cpp. server-http.cpp wants the web UI's asset table (ui.h, generated by tools/ui at build + # time); frontend/ui_stub provides an empty one. + find_package(Threads REQUIRED) + set(_strata_srv ${STRATA_GGML_DIR}/tools/server) + add_library(strata_llama_server STATIC + ${_strata_srv}/server-http.cpp ${_strata_srv}/server-queue.cpp ${_strata_srv}/server-task.cpp + ${_strata_srv}/server-common.cpp ${_strata_srv}/server-chat.cpp ${_strata_srv}/server-schema.cpp + ${_strata_srv}/server-stream.cpp + frontend/ui_stub/ui.cpp) + target_include_directories(strata_llama_server PUBLIC ${_strata_srv} ${STRATA_GGML_DIR}/tools/mtmd + ${STRATA_GGML_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/frontend/ui_stub) + target_link_libraries(strata_llama_server PUBLIC llama-common llama mtmd cpp-httplib Threads::Threads) + target_compile_features(strata_llama_server PUBLIC cxx_std_17) + + add_executable(unbiased-strata frontend/main.cpp frontend/strata_context.cpp) + target_include_directories(unbiased-strata PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/frontend) + target_link_libraries(unbiased-strata PRIVATE strata_llama_server) + target_compile_features(unbiased-strata PRIVATE cxx_std_20) + + # The engine adapter against the fake engine (frontend/tests/fake-engine.py): no GPU, no model, no llama.cpp. + # `make test` builds and runs it, then frontend/tests/e2e.sh against the binary above. + add_executable(engine_test EXCLUDE_FROM_ALL frontend/tests/engine_test.cpp) + target_include_directories(engine_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/frontend) + target_compile_features(engine_test PRIVATE cxx_std_20) endif() if(STRATA_BUILD_TESTS) diff --git a/Makefile b/Makefile index 087e3ff..7f23910 100644 --- a/Makefile +++ b/Makefile @@ -3,7 +3,8 @@ # # git clone && cd # git submodule update --init -# make build # build/bin/strata, build/bin/strata-poly, build/bin/libstrata_kq.so +# make build # build/bin/{strata,strata-poly,libstrata_kq.so,unbiased-strata} +# make test # the front end against a fake engine; no GPU needed # BUILD_DIR ?= build # CUDA archs: GTX 10 (61), RTX 20 / GTX 16 (75), RTX 30 (86), RTX 40 (89). Any arch below 75 turns on upstream's @@ -13,8 +14,12 @@ CUDA_ARCHS ?= 61;75;86;89 # nvcc: on PATH, else the toolkit's usual place (RunPod images and distro packages differ). NVCC=/path overrides. NVCC ?= $(or $(shell command -v nvcc 2>/dev/null),$(wildcard /usr/local/cuda/bin/nvcc)) ifeq ($(NVCC),) - $(error nvcc not found on PATH or in /usr/local/cuda/bin; install a CUDA 12.x toolkit or set NVCC=/path/to/nvcc) + ifneq ($(filter build configure,$(MAKECMDGOALS)),) + $(error nvcc not found on PATH or in /usr/local/cuda/bin; install a CUDA 12.x toolkit or set NVCC=/path/to/nvcc) + endif endif +# Everything below that runs nvcc is skipped when there is none (a laptop running `make frontend` or `make test`). +ifneq ($(NVCC),) NVCC_ARCHS := $(shell $(NVCC) --list-gpu-arch 2>/dev/null | sed 's/compute_//' | tr '\n' ' ') ifneq ($(NVCC_ARCHS),) CUDA_ARCHS_DROPPED := $(strip $(foreach a,$(subst ;, ,$(CUDA_ARCHS)),$(if $(filter $(firstword $(subst -, ,$(a))),$(NVCC_ARCHS)),,$(a)))) @@ -36,13 +41,14 @@ HOSTCXX ?= $(shell for c in g++-15 g++-14 g++-13 g++-12 g++-11 g++; do p=$$(comm t=$$(mktemp /tmp/strata-hc-XXXXXX.cu) && printf 'int main(){return 0;}\n' > $$t && \ if $(NVCC) -ccbin $$p -c $$t -o /dev/null >/dev/null 2>&1; then rm -f $$t; echo $$p; break; fi; rm -f $$t; done) HOSTCC := $(subst g++,gcc,$(HOSTCXX)) +endif COMPILER_FLAGS := $(if $(HOSTCXX),-DCMAKE_C_COMPILER=$(HOSTCC) -DCMAKE_CXX_COMPILER=$(HOSTCXX) -DCMAKE_CUDA_HOST_COMPILER=$(HOSTCXX),) # capped: inside a container nproc reports the host's CPUs, not the container's quota JOBS ?= $(shell n=$$(nproc 2>/dev/null || echo 4); [ $$n -gt 16 ] && n=16; echo $$n) # what `make build` produces; upstream's `all` also builds about 70 parity and bench programs -TARGETS := strata strata-poly strata_kq llama-common mtmd +TARGETS := strata strata-poly strata_kq unbiased-strata -.PHONY: build configure clean +.PHONY: build configure clean test configure: @test -f third_party/llama.cpp/ggml/CMakeLists.txt || \ @@ -55,7 +61,22 @@ configure: build: configure cmake --build $(BUILD_DIR) -j $(JOBS) --target $(TARGETS) - @echo "built:"; ls -1 $(BUILD_DIR)/bin/strata $(BUILD_DIR)/bin/strata-poly $(BUILD_DIR)/bin/libstrata_kq.so + @echo "built:"; ls -1 $(BUILD_DIR)/bin/strata $(BUILD_DIR)/bin/strata-poly $(BUILD_DIR)/bin/libstrata_kq.so $(BUILD_DIR)/bin/unbiased-strata + +# The front end alone, without CUDA: for a laptop or a CI box. Needs only a C++20 compiler and CMake. +.PHONY: frontend +frontend: + cmake -S . -B $(BUILD_DIR)-frontend -DCMAKE_BUILD_TYPE=Release -DSTRATA_ENABLE_CUDA=OFF -DSTRATA_BUILD_TESTS=OFF \ + -DCMAKE_RUNTIME_OUTPUT_DIRECTORY=$(abspath $(BUILD_DIR))-frontend/bin $(CMAKE_EXTRA) + cmake --build $(BUILD_DIR)-frontend -j $(JOBS) --target unbiased-strata + +# The front end's tests, against a fake engine (frontend/tests/fake-engine.py): the adapter's cases (cancel, drain, +# backpressure, child exit, ERR) and the HTTP surface a coding agent touches (frontend/tests/e2e.sh). Needs python3 +# and curl; no GPU and no model. Runs in the CUDA-free build directory, so it works on the build box and on a laptop. +test: frontend + cmake --build $(BUILD_DIR)-frontend -j $(JOBS) --target engine_test + $(BUILD_DIR)-frontend/engine_test frontend/tests/fake-engine.py + frontend/tests/e2e.sh $(BUILD_DIR)-frontend/bin/unbiased-strata clean: rm -rf $(BUILD_DIR) diff --git a/UPSTREAM.md b/UPSTREAM.md index 24b4d78..02f3e50 100644 --- a/UPSTREAM.md +++ b/UPSTREAM.md @@ -34,9 +34,22 @@ GPU, Pascal or newer, CUDA 12.x), each recorded below with the file, the reason CMake both; here it is CMake only, so a tree configured directly gets it too. - **llama.cpp's libraries for the front end.** A second `add_subdirectory` of the submodule with `LLAMA_BUILD_COMMON` and `LLAMA_BUILD_MTMD` on and tests, tools, examples, server, app, UI, prebuilt UI, - OpenSSL and llguidance off. It reuses the ggml targets configured above. -- **`Makefile`.** `make build` configures once and builds `strata`, `strata-poly`, `strata_kq`, `llama-common` - and `mtmd` into `build/bin/`, not upstream's `all`, which also builds about 70 parity and bench programs. + OpenSSL and llguidance off. It reuses the ggml targets configured above. Gated by `STRATA_FRONTEND` (default on), + not by CUDA, so the front end also builds on a machine without a GPU. +- **The front end, `unbiased-strata`.** Seven of llama.cpp's `tools/server` files are compiled unmodified from the + submodule into a static library (`server-http`, `server-queue`, `server-task`, `server-common`, `server-chat`, + `server-schema`, `server-stream`): the HTTP layer, the task queue, the OpenAI request and result types, SSE + framing, the request schema. The eighth, `server-context.cpp`, is bound to `llama_context` and is replaced by + `frontend/strata_context.cpp`, which runs the engine as a child process over its line protocol (`docs/BACKENDS.md`) + and uses a vocab-only `llama_model` for tokenizing, the chat template and the output parsers. `server-http.cpp` + references the web UI's asset table (`ui.h`, generated by `tools/ui` at build time, which downloads); `frontend/ + ui_stub/` provides an empty one. No patch to llama.cpp was needed for this; the undocumented internal API of + `tools/server` is used as it is at the pinned commit. +- **`Makefile`.** `make build` configures once and builds `strata`, `strata-poly`, `strata_kq` and `unbiased-strata` + into `build/bin/`, not upstream's `all`, which also builds about 70 parity and bench programs. `make frontend` + builds the front end alone without CUDA into `build-frontend/`; `make test` builds and runs the front end's tests + there against a fake engine (`frontend/tests/`): the adapter's cases and the HTTP surface a coding agent touches. + The nvcc check applies only to the `build` and `configure` goals. `CUDA_ARCHS` defaults to `61;75;86;89`; an arch below 75 adds upstream's `STRATA_EXPERIMENTAL_SM60` (upstream's default is `120`, which needs CUDA 13). `PORTABLE=1` gives the AVX2 baseline instead of `-march=native`. One GCC for the C, C++ and nvcc host sides: the Makefile probes `g++-15`, `g++-14`, ... with diff --git a/frontend/engine.hpp b/frontend/engine.hpp new file mode 100644 index 0000000..08716d2 --- /dev/null +++ b/frontend/engine.hpp @@ -0,0 +1,392 @@ +// UnbiasedStrata: the engine as a child process. +// +// The engines (`strata`, `strata-poly`) speak lines over stdin/stdout: `GEN key=value... ` in, +// `T ` per token, `PP`, `RESUME`, `DONE ...`, `ERR ...` out, `STOP` to cancel, `QUIT` to end (docs/BACKENDS.md, +// "How a backend works"). This class owns one such child. It never blocks longer than the caller allows: the server +// loop polls it between tasks so a cancel from a disconnected client is seen within the poll interval. +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace strata_frontend { + +// Reap a dead child: kill(pid, 0) would report a zombie as alive. The pid slot is shared with quit() on another +// thread (the supervisor polls this while a SIGTERM handler shuts down), so it is read once and cleared by +// compare-exchange. Nothing here or in quit() may pass a pid that is not > 0 to kill(): kill(-1, SIGKILL) kills every +// process the user owns (it took out two whole login sessions on 2026-10-17). +inline bool child_running(std::atomic & pid_slot, std::string & why) { + pid_t pid = pid_slot.load(); + if (pid <= 0) { + return false; + } + 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_slot.compare_exchange_strong(pid, -1); + return false; +} + +// One line from the engine, already classified. +struct EngineLine { + enum Kind { NONE, TOKEN, PP, RESUME, REUSED, DONE, ERR, INFO, OTHER, EOF_ } kind = NONE; + std::string raw; + int32_t token = -1; + // PP [ ] + long long pp_done = 0, pp_total = 0; + // RESUME / REUSED + long long n = 0; + // DONE [ ...] + long long produced = 0, prompt_n = 0, draft_accepted = 0, draft_offered = 0, reused = 0; + double prompt_ms = 0, decode_ms = 0; + std::string finish; // stop | length | cancel | nonfinite + std::string message; // ERR text +}; + +class Engine { +public: + Engine() = default; + Engine(const Engine &) = delete; + Engine & operator=(const Engine &) = delete; + ~Engine() { quit(); } + + // fork+exec `executable` with `args` (args[0] is argv[0]). Must be called before any thread exists. + bool start(const std::string & executable, const std::vector & args, std::string & err) { + int to_child[2], from_child[2]; + if (::pipe(to_child) != 0 || ::pipe(from_child) != 0) { + err = std::string("pipe: ") + std::strerror(errno); + return false; + } + const pid_t pid = ::fork(); + if (pid < 0) { + err = std::string("fork: ") + std::strerror(errno); + 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.c_str(), argv.data()); + std::fprintf(stderr, "unbiased-strata: could not start the engine %s: %s\n", executable.c_str(), std::strerror(errno)); + ::_exit(127); + } + pid_ = pid; + ::close(to_child[0]); + ::close(from_child[1]); + in_fd_ = to_child[1]; + out_fd_ = from_child[0]; + alive_ = true; + return true; + } + + // Reads start-up lines until READY. Loading a model takes minutes; `timeout_s` bounds the wait (<= 0: forever). + // `READY [stop]`: the context the engine actually allocated (its VRAM plan may lower the request); + // `stop` means it honours STOP mid-request. INFO lines land in `info`. + bool wait_ready(std::string & err, int timeout_s = 0) { + const int64_t deadline = timeout_s > 0 ? now_ms() + (int64_t) timeout_s * 1000 : 0; + std::string line; + while (true) { + int wait_ms = 1000; + if (deadline) { + const int64_t left = deadline - now_ms(); + if (left <= 0) { + err = "the engine did not become ready within " + std::to_string(timeout_s) + " s"; + return false; + } + wait_ms = (int) std::min(left, 1000); + } + const int rc = read_line(line, wait_ms); + if (rc < 0) { + err = "the engine exited before it was ready (its messages are above)"; + return false; + } + if (rc == 0) { + continue; + } + if (line.rfind("READY", 0) == 0) { + char stop[16] = {0}; + long long ctx = 0; + std::sscanf(line.c_str(), "READY %lld %15s", &ctx, stop); + max_context_ = ctx; + can_stop_ = std::strcmp(stop, "stop") == 0; + ready_ = true; + return true; + } + if (line.rfind("INFO ", 0) == 0) { + parse_info(line.substr(5)); + continue; + } + if (line.rfind("ERR", 0) == 0) { + err = line.size() > 4 ? line.substr(4) : "the engine reported an error"; + return false; + } + if (line.rfind("FATAL", 0) == 0) { + err = line; + return false; + } + // anything else before READY is chatter on stdout; the engine's log is on stderr + } + } + + // Writes one request line. `header` is `GEN key=value...` or `GENI key=value... `. + bool send_request(const std::string & header, const std::vector & ids) { + std::string req = header; + req.reserve(header.size() + ids.size() * 7 + 2); + req += ' '; + for (size_t i = 0; i < ids.size(); ++i) { + if (i) { + req += ','; + } + req += std::to_string(ids[i]); + } + req += '\n'; + busy_ = true; + return send(req); + } + + // Asks the engine to end the current request. Its output continues until a DONE with finish=cancel. + bool stop() { + return send("STOP\n"); + } + + // One classified line, waiting at most `timeout_ms` (0: only what is buffered). Returns false on timeout. + // kind == EOF_ when the engine closed its stdout (it exited). + bool next_line(EngineLine & out, int timeout_ms) { + std::string line; + const int rc = read_line(line, timeout_ms); + if (rc == 0) { + return false; + } + out = EngineLine{}; + out.raw = line; + if (rc < 0) { + out.kind = EngineLine::EOF_; + return true; + } + classify(line, out); + if (out.kind == EngineLine::DONE || out.kind == EngineLine::ERR) { + busy_ = false; + } + return true; + } + + // One command between requests with a one-line reply whose first word is `reply_prefix` (`STATS`, `VRAM`). + bool command(const std::string & line, const char * reply_prefix, std::string & reply, std::string & err, int timeout_ms = 5000) { + if (!alive_) { err = "the engine is not running"; return false; } + if (!send(line + "\n")) { err = "the engine is not running"; return false; } + std::string got; + const int64_t deadline = now_ms() + timeout_ms; + while (true) { + const int64_t left = deadline - now_ms(); + if (left <= 0) { err = "no reply from the engine"; return false; } + const int rc = read_line(got, (int) left); + if (rc < 0) { err = "the engine exited"; return false; } + if (rc == 0) { continue; } + if (got.rfind(reply_prefix, 0) == 0) { reply = got; return true; } + if (got.rfind("ERR", 0) == 0) { err = got.size() > 4 ? got.substr(4) : "the engine reported an error"; return false; } + } + } + + // Stop the engine: QUIT, up to 10 s for it to leave, then SIGKILL. Safe against reap_exit() on another thread. + void quit() { + // Take the pid out of the shared slot first: from here only this call owns the child, and kill() below + // targets this positive local copy, never the slot (which reads -1 once the supervisor has reaped it). + const pid_t pid = pid_.exchange(-1); + if (pid > 0) { + send("QUIT\n"); + int status = 0; + pid_t reaped = 0; + for (int i = 0; i < 100 && (reaped = ::waitpid(pid, &status, WNOHANG)) == 0; ++i) { + ::usleep(100 * 1000); + } + if (reaped == 0) { // still running; -1 means another thread already reaped it + ::kill(pid, SIGKILL); + ::waitpid(pid, &status, 0); + } + } + if (in_fd_ >= 0) { ::close(in_fd_); in_fd_ = -1; } + if (out_fd_ >= 0) { ::close(out_fd_); out_fd_ = -1; } + alive_ = false; + } + + // Non-blocking: has the child exited? `why` names the signal or code. + bool reap_exit(std::string & why) { + if (child_running(pid_, why)) { + return false; + } + alive_ = false; + return true; + } + + bool alive() const { return alive_; } + bool busy() const { return busy_; } + bool ready() const { return ready_; } + bool can_stop() const { return can_stop_; } + long long max_context() const { return max_context_; } + const std::map & info() const { return info_; } + pid_t pid() const { return pid_; } + + static int64_t now_ms() { + struct timespec ts; + ::clock_gettime(CLOCK_MONOTONIC, &ts); + return (int64_t) ts.tv_sec * 1000 + ts.tv_nsec / 1000000; + } + +private: + bool send(const std::string & s) { + if (in_fd_ < 0) { + return false; + } + size_t off = 0; + while (off < s.size()) { + const ssize_t n = ::write(in_fd_, s.data() + off, s.size() - off); + if (n < 0 && errno == EINTR) { + continue; + } + if (n <= 0) { + alive_ = false; + return false; + } + off += (size_t) n; + } + return true; + } + + // 1: a line; 0: timeout; -1: EOF/error + int read_line(std::string & line, int timeout_ms) { + const int64_t deadline = now_ms() + timeout_ms; + while (true) { + const size_t nl = buf_.find('\n'); + if (nl != std::string::npos) { + line.assign(buf_, 0, nl); + buf_.erase(0, nl + 1); + while (!line.empty() && line.back() == '\r') { + line.pop_back(); + } + return 1; + } + if (out_fd_ < 0) { + return -1; + } + int wait = timeout_ms <= 0 ? 0 : (int) std::max(0, deadline - now_ms()); + struct pollfd pfd = { out_fd_, POLLIN, 0 }; + const int pr = ::poll(&pfd, 1, wait); + if (pr < 0) { + if (errno == EINTR) { + continue; + } + alive_ = false; + return -1; + } + if (pr == 0) { + return 0; + } + char chunk[65536]; + const ssize_t n = ::read(out_fd_, chunk, sizeof chunk); + if (n < 0 && errno == EINTR) { + continue; + } + if (n <= 0) { + // EOF: the engine closed stdout. Hand out what is buffered without a newline, then -1. + if (!buf_.empty()) { + line.swap(buf_); + buf_.clear(); + return 1; + } + alive_ = false; + return -1; + } + buf_.append(chunk, (size_t) n); + } + } + + void parse_info(const std::string & kv) { + size_t i = 0; + while (i < kv.size()) { + while (i < kv.size() && kv[i] == ' ') ++i; + const size_t j = kv.find(' ', i); + const std::string tok = kv.substr(i, j == std::string::npos ? std::string::npos : j - i); + const size_t eq = tok.find('='); + if (eq != std::string::npos) { + info_[tok.substr(0, eq)] = tok.substr(eq + 1); + } + if (j == std::string::npos) break; + i = j + 1; + } + } + + static void classify(const std::string & line, EngineLine & out) { + if (line.size() > 2 && line[0] == 'T' && line[1] == ' ') { + out.kind = EngineLine::TOKEN; + out.token = (int32_t) std::atoi(line.c_str() + 2); + } else if (line.rfind("DONE ", 0) == 0) { + char finish[32] = {0}; + // DONE ... + const int got = std::sscanf(line.c_str(), "DONE %lld %lld %lf %lf %31s %lld %lld %lld", &out.produced, &out.prompt_n, + &out.prompt_ms, &out.decode_ms, finish, &out.draft_accepted, &out.draft_offered, &out.reused); + out.kind = EngineLine::DONE; + out.finish = got >= 5 ? finish : "stop"; + } else if (line.rfind("PP ", 0) == 0) { + out.kind = EngineLine::PP; + std::sscanf(line.c_str(), "PP %lld %lld", &out.pp_done, &out.pp_total); + } else if (line.rfind("RESUME ", 0) == 0) { + out.kind = EngineLine::RESUME; + out.n = std::atoll(line.c_str() + 7); + } else if (line.rfind("REUSED ", 0) == 0) { + out.kind = EngineLine::REUSED; + out.n = std::atoll(line.c_str() + 7); + } else if (line.rfind("ERR", 0) == 0) { + out.kind = EngineLine::ERR; + out.message = line.size() > 4 ? line.substr(4) : "the engine reported an error"; + } else if (line.rfind("FATAL", 0) == 0) { + out.kind = EngineLine::ERR; + out.message = line; + } else if (line.rfind("INFO ", 0) == 0 || line.rfind("WARN ", 0) == 0) { + out.kind = EngineLine::INFO; + } else { + out.kind = EngineLine::OTHER; + } + } + + std::atomic pid_{-1}; + int in_fd_ = -1; + int out_fd_ = -1; + std::string buf_; + std::atomic alive_{false}; + bool busy_ = false; + bool ready_ = false; + bool can_stop_ = false; + long long max_context_ = 0; + std::map info_; +}; + +} // namespace strata_frontend diff --git a/frontend/main.cpp b/frontend/main.cpp new file mode 100644 index 0000000..ed35bcf --- /dev/null +++ b/frontend/main.cpp @@ -0,0 +1,225 @@ +// UnbiasedStrata: the front end's program. Mirrors llama.cpp's tools/server/server.cpp without router mode, MCP, +// server-side tools, the web UI and model downloads. +// +// unbiased-strata --engine build/bin/strata-poly -m model.gguf [llama-server options] -- +// +// Options before `--` are llama-server's (common_params_parse): -m/--model gives the GGUF the vocabulary and chat +// template are read from, --host/--port/--api-key/--threads-http the listener, --temp/--top-k/... the sampling +// defaults, --reasoning-format/--chat-template-kwargs/--jinja the chat handling. Options after `--` go to the engine +// as they are; `--serve` is added. The engine's READY line gives the context size. + +#include "strata_context.hpp" + +#include "arg.h" +#include "common.h" +#include "llama.h" +#include "log.h" +#include "server-common.h" +#include "server-stream.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace { + +std::function shutdown_handler; +std::atomic_flag is_terminating = ATOMIC_FLAG_INIT; + +void signal_handler(int signal) { + if (is_terminating.test_and_set()) { + std::fprintf(stderr, "Received second interrupt, terminating immediately.\n"); + std::exit(1); + } + if (shutdown_handler) { + shutdown_handler(signal); + } +} + +void usage() { + std::fprintf(stderr, + "usage: unbiased-strata --engine -m [llama-server options] -- \n" + "\n" + " --engine PATH the engine binary; a bare name is looked up beside this program\n" + " -m, --model FILE the GGUF the vocabulary and chat template are read from (no tensors are loaded)\n" + " --host, --port, --api-key, --threads-http, --temp, --top-k, --top-p, --min-p, --reasoning-format,\n" + " --chat-template-kwargs, --alias ... llama-server options (see llama-server --help)\n" + " -- everything after it is passed to the engine; --serve is added\n" + "\n" + "example (Qwen3.6-35B-A3B from its GGUF):\n" + " unbiased-strata --engine strata-poly -m Qwen3.6-35B-A3B-UD-Q3_K_M.gguf --port 8080 \\\n" + " -- --model Qwen3.6-35B-A3B-UD-Q3_K_M.gguf --max-context 32768\n"); +} + +std::string self_dir() { + char buf[4096]; + const ssize_t n = ::readlink("/proc/self/exe", buf, sizeof buf - 1); + if (n <= 0) { + return "."; + } + buf[n] = 0; + std::string p(buf); + const size_t slash = p.find_last_of('/'); + return slash == std::string::npos ? "." : p.substr(0, slash); +} + +bool file_exists(const std::string & p) { + return ::access(p.c_str(), X_OK) == 0; +} + +} // namespace + +int main(int argc, char ** argv) { + std::setlocale(LC_NUMERIC, "C"); +#ifndef _WIN32 + signal(SIGPIPE, SIG_IGN); +#endif + + // split: ours (--engine), llama-server's, and after `--` the engine's + std::string engine_exe; + std::vector engine_args; + std::vector llama_argv; + llama_argv.push_back(argv[0]); + for (int i = 1; i < argc; ++i) { + const std::string a = argv[i]; + if (a == "--") { + for (++i; i < argc; ++i) { + engine_args.push_back(argv[i]); + } + break; + } + if (a == "--engine") { + if (i + 1 >= argc) { usage(); return 2; } + engine_exe = argv[++i]; + continue; + } + if (a.rfind("--engine=", 0) == 0) { + engine_exe = a.substr(9); + continue; + } + llama_argv.push_back(argv[i]); + } + if (engine_exe.empty()) { + usage(); + return 2; + } + if (engine_exe.find('/') == std::string::npos) { + const std::string beside = self_dir() + "/" + engine_exe; + if (file_exists(beside)) { + engine_exe = beside; + } + } + if (!file_exists(engine_exe)) { + std::fprintf(stderr, "unbiased-strata: engine not found or not executable: %s\n", engine_exe.c_str()); + return 2; + } + + common_params params; + common_init(); + server_stream_session_manager_start(); + + if (!common_params_parse((int) llama_argv.size(), llama_argv.data(), params, LLAMA_EXAMPLE_SERVER)) { + return 1; + } + if (params.model.path.empty()) { + std::fprintf(stderr, "unbiased-strata: -m is required (the vocabulary and chat template come from it)\n"); + return 2; + } + if (!params.mmproj.path.empty()) { + std::fprintf(stderr, "unbiased-strata: --mmproj (images) is not in this build yet; see PLAN.md step 8\n"); + return 2; + } + auto model_name = params.model.get_name(); + if (params.model_alias.empty() && !model_name.empty()) { + params.model_alias.insert(model_name); + } + + llama_backend_init(); + llama_numa_init(params.numa); + + strata_context ctx_server; + server_http_context ctx_http; + if (!ctx_http.init(params)) { + SRV_ERR("%s", "failed to initialize HTTP server\n"); + return 1; + } + + // routes first (handlers are not called until is_ready), then the engine (forked before any thread exists), + // then the HTTP thread, which answers /health with 503 while the engine loads + ctx_server.init_routes(ctx_http); + + std::string err; + if (!ctx_server.start_engine(params, engine_exe, engine_args, err)) { + SRV_ERR("could not start the engine: %s\n", err.c_str()); + return 1; + } + + auto clean_up = [&]() { + SRV_INF("%s", "cleaning up before exit...\n"); + server_stream_session_manager_stop(); + ctx_http.stop(); + ctx_server.terminate(); + llama_backend_free(); + }; + + if (!ctx_http.start()) { + clean_up(); + SRV_ERR("%s", "exiting due to HTTP server error\n"); + return 1; + } + + if (!ctx_server.load(params, err)) { + SRV_ERR("%s\n", err.c_str()); + clean_up(); + if (ctx_http.thread.joinable()) { + ctx_http.thread.join(); + } + return 1; + } + ctx_http.is_ready.store(true); + SRV_INF("listening on %s, context %lld tokens\n", ctx_http.listening_address.c_str(), ctx_server.n_ctx()); + + shutdown_handler = [&](int) { + ctx_server.terminate(); + }; + struct sigaction sigint_action; + sigint_action.sa_handler = signal_handler; + sigemptyset(&sigint_action.sa_mask); + sigint_action.sa_flags = 0; + sigaction(SIGINT, &sigint_action, NULL); + sigaction(SIGTERM, &sigint_action, NULL); + + // the engine's exit ends this process too, with a non-zero code, so a unit with Restart=on-failure brings both + // back. A replacement engine is not forked from this multithreaded process (UnbiasedStrata 1 main.cpp:873). + std::atomic engine_died{false}; + std::atomic stop_supervisor{false}; + std::thread supervisor([&]() { + std::string why; + while (!stop_supervisor) { + if (ctx_server.engine_exited(why)) { + SRV_ERR("%s; shutting down so the service manager can restart\n", why.c_str()); + engine_died = true; + ctx_server.terminate(); + return; + } + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + } + }); + + ctx_server.start_loop(); // blocks until terminate() + + stop_supervisor = true; + supervisor.join(); + clean_up(); + if (ctx_http.thread.joinable()) { + ctx_http.thread.join(); + } + return engine_died ? 1 : 0; +} diff --git a/frontend/strata_context.cpp b/frontend/strata_context.cpp new file mode 100644 index 0000000..5b0c22b --- /dev/null +++ b/frontend/strata_context.cpp @@ -0,0 +1,1095 @@ +// UnbiasedStrata: the server context with a Strata engine behind it. See strata_context.hpp. +// +// Where a function here mirrors one in llama.cpp's tools/server/server-context.cpp it says so; those are the places +// to look when the submodule pin moves. + +#include "strata_context.hpp" +#include "engine.hpp" + +#include "server-common.h" +#include "server-task.h" +#include "server-queue.h" +#include "server-schema.h" +#include "server-stream.h" + +#include "build-info.h" +#include "chat.h" +#include "common.h" +#include "llama.h" +#include "log.h" + +#include +#include +#include +#include +#include +#include + +using strata_frontend::Engine; +using strata_frontend::EngineLine; + +namespace { + +// how long update_slots() waits for an engine line before returning to the queue (which then sees cancels) +constexpr int ENGINE_POLL_MS = 20; + +// the engine keeps this many context slots back; a prompt plus max_new may not reach the context (UnbiasedStrata 1, +// REGINA-112: every request without max_tokens got a 500 until the front end counted it) +constexpr int ENGINE_CONTEXT_RESERVE = 8; + +// mirrors server_slot in server-context.cpp, for the one slot the engine is +struct Slot { + std::unique_ptr task; + + bool started = false; // GEN written + bool cancelled = false; // the client went away: STOP sent, output is drained, no final result + bool stop_sent = false; // STOP sent for our own reason (stop string, limit); the final result is still sent + + std::string generated_text; + llama_tokens generated_tokens; + size_t n_sent_text = 0; + + server_slot_stats stats; + stop_type stop = STOP_TYPE_NONE; + std::string stopping_word; + bool has_new_line = false; + bool truncated = false; + bool has_next_token = true; + + int32_t n_predict = -1; + + bool active() const { return task != nullptr; } + + void release() { + *this = Slot{}; + } + + bool has_budget() const { + return n_predict < 0 || (int32_t) stats.n_gen < n_predict; + } + + // mirrors server_slot::find_stopping_strings + size_t find_stopping_strings(const std::string & text, const size_t last_token_size, bool is_full_stop) const { + size_t stop_pos = std::string::npos; + for (const std::string & word : task->params.antiprompt) { + size_t pos; + if (is_full_stop) { + const size_t tmp = word.size() + last_token_size; + const size_t from_pos = text.size() > tmp ? text.size() - tmp : 0; + pos = text.find(word, from_pos); + } else { + pos = string_find_partial_stop(text, word); + } + if (pos != std::string::npos && (stop_pos == std::string::npos || pos < stop_pos)) { + if (is_full_stop) { + const_cast(this)->stop = STOP_TYPE_WORD; + const_cast(this)->stopping_word = word; + const_cast(this)->has_next_token = false; + } + stop_pos = pos; + } + } + return stop_pos; + } +}; + +// mirrors server_res_generator in server-context.cpp +struct res_generator : server_res_spipe { + server_response_reader rd; + res_generator(server_queue & queue_tasks, server_response & queue_results) + : rd(queue_tasks, queue_results, /* polling_interval_seconds */ 1) {} + void ok(const json & response_data) { + status = 200; + data = safe_json_to_str(response_data); + } + void error(const json & error_data) { + status = json_value(error_data, "code", 500); + data = safe_json_to_str({{ "error", error_data }}); + } +}; + +// mirrors ex_wrapper in server.cpp: a handler never throws; an exception becomes an error response +server_http_context::handler_t ex_wrapper(server_http_context::handler_t func) { + return [func = std::move(func)](const server_http_req & req) -> server_http_res_ptr { + std::string message; + error_type error; + try { + return func(req); + } catch (const std::invalid_argument & e) { + error = ERROR_TYPE_INVALID_REQUEST; + message = e.what(); + } catch (const std::exception & e) { + error = ERROR_TYPE_SERVER; + message = e.what(); + } catch (...) { + error = ERROR_TYPE_SERVER; + message = "unknown error"; + } + auto res = std::make_unique(); + res->status = 500; + try { + json error_data = format_error_response(message, error); + res->status = json_value(error_data, "code", 500); + res->data = safe_json_to_str({{ "error", error_data }}); + SRV_WRN("got exception: %s\n", res->data.c_str()); + } catch (const std::exception & e) { + SRV_ERR("got another exception: %s | while handling exception: %s\n", e.what(), message.c_str()); + res->data = "Internal Server Error"; + } + return res; + }; +} + +std::string file_stem(const std::string & path) { + const size_t slash = path.find_last_of('/'); + std::string name = slash == std::string::npos ? path : path.substr(slash + 1); + const size_t dot = name.rfind(".gguf"); + if (dot != std::string::npos) { + name.erase(dot); + } + return name; +} + +} // namespace + +struct strata_context_impl { + common_params params; + + llama_model * model = nullptr; + const llama_vocab * vocab = nullptr; + + // images arrive in step 8 of PLAN.md: until then mctx stays null and image_url parts are refused by + // oaicompat_chat_params_parse with llama.cpp's own message + mtmd_context * mctx = nullptr; + mtmd_helper_init_opt init_opt{}; + + server_chat_params chat_params; + std::map chat_caps; + std::vector logit_bias_eog; // empty: the engine applies logit bias itself + + std::string model_name; + std::string model_path; + + server_queue queue_tasks; + server_response queue_results; + + Engine engine; + std::string engine_exe; + std::vector engine_args; + bool engine_is_poly = false; + long long n_ctx = 0; + std::atomic engine_dead{false}; + + Slot slot; + + // ---- queue callbacks ------------------------------------------------------------------------------------------- + + void send_error(int id_task, const std::string & error, enum error_type type, int32_t n_prompt_tokens = 0) { + SRV_ERR("task id = %d, error: %s\n", id_task, error.c_str()); + auto res = std::make_unique(); + res->id = id_task; + res->err_type = type; + res->err_msg = error; + res->n_prompt_tokens = n_prompt_tokens; + res->n_ctx = (int32_t) n_ctx; + queue_results.send(std::move(res)); + } + + void send_error(const server_task & task, const std::string & error, enum error_type type) { + send_error(task.id, error, type, task.n_tokens()); + } + + // mirrors process_single_task in server-context.cpp, for the task types this front end has + bool process_new_task(server_task && task, bool is_yielding) { + (void) is_yielding; // never yields: the engine is not driven from this process + switch (task.type) { + case SERVER_TASK_TYPE_COMPLETION: + if (slot.active()) { + queue_tasks.defer(std::move(task)); + return true; + } + launch(std::move(task)); + return true; + + case SERVER_TASK_TYPE_CANCEL: + if (slot.active() && slot.task->id == task.id_target) { + cancel_current(); + } + return true; + + case SERVER_TASK_TYPE_NEXT_RESPONSE: + return true; + + case SERVER_TASK_TYPE_METRICS: { + auto res = std::make_unique(); + res->id = task.id; + res->n_processing_slots = slot.active() ? 1 : 0; + res->n_tasks_deferred = (int) queue_tasks.queue_tasks_deferred_size(); + res->metrics = metrics; + queue_results.send(std::move(res)); + return true; + } + + default: + send_error(task, "this request type is not supported by this server", ERROR_TYPE_NOT_SUPPORTED); + return true; + } + } + + // mirrors update_slots in server-context.cpp: called by the queue after each round of tasks + void update_slots() { + if (!slot.active()) { + return; + } + // keep the loop coming back while a request runs + { + server_task task(SERVER_TASK_TYPE_NEXT_RESPONSE); + task.id = queue_tasks.get_new_id(); + queue_tasks.post(std::move(task)); + } + + // read what the engine has, for a bounded time, so a cancel posted meanwhile is seen within ENGINE_POLL_MS + const int64_t until = Engine::now_ms() + ENGINE_POLL_MS; + EngineLine line; + while (slot.active()) { + const int left = (int) (until - Engine::now_ms()); + if (!engine.next_line(line, std::max(left, 0))) { + break; // nothing more right now + } + handle_line(line); + if (left <= 0) { + break; + } + } + } + + // ---- one request -------------------------------------------------------------------------------------------- + + // mirrors launch_slot_with_task + void launch(server_task && task) { + slot.release(); + slot.task = std::make_unique(std::move(task)); + const server_task & t = *slot.task; + + if (!engine.alive()) { + send_error(t, "the engine is not running", ERROR_TYPE_UNAVAILABLE); + slot.release(); + return; + } + + const int32_t n_prompt = t.n_tokens(); + if (n_prompt == 0) { + send_error(t, "the prompt is empty", ERROR_TYPE_INVALID_REQUEST); + slot.release(); + return; + } + if (t.tokens.has_mtmd) { + // step 8: image rows through GENI + send_error(t, "images are not supported by this build yet", ERROR_TYPE_NOT_SUPPORTED); + slot.release(); + return; + } + const long long room = n_ctx - n_prompt - ENGINE_CONTEXT_RESERVE; + if (room <= 0) { + send_error(t, string_format("the request exceeds the available context size: %d prompt tokens, context %lld (%d kept back)", + n_prompt, n_ctx, ENGINE_CONTEXT_RESERVE), ERROR_TYPE_EXCEED_CONTEXT_SIZE); + slot.release(); + return; + } + // n_predict: -1 and anything past the context become what is left, as llama-server does + slot.n_predict = t.params.n_predict; + if (slot.n_predict < 0 || slot.n_predict > room) { + if (slot.n_predict > room) { + SRV_WRN("n_predict %d exceeds the room left in the context, lowered to %lld\n", slot.n_predict, room); + } + slot.n_predict = (int32_t) room; + } + if (!t.params.sampling.grammar.grammar.empty()) { + // the engine samples inside its own process and exposes no logits: a grammar (tools, json_schema, + // tool_choice=required) cannot constrain it. Same as upstream PolyStrata. The parser still runs on the output. + SRV_WRN("task %d: a grammar was requested (%zu chars); this engine does not constrain sampling, parsing only\n", + t.id, t.params.sampling.grammar.grammar.size()); + } + + const std::string header = gen_header(t, slot.n_predict); + if (!engine.send_request(header, t.tokens.get_text_tokens())) { + send_error(t, "the engine is not running", ERROR_TYPE_UNAVAILABLE); + slot.release(); + return; + } + slot.started = true; + slot.stats.update_prompt_start(); + SRV_INF("task %d: %s prompt=%d n_predict=%d\n", t.id, header.c_str(), n_prompt, slot.n_predict); + + if (t.params.stream) { + // the HTTP side sends the 200 and the stream headers on this, before the first token + send_partial_response(completion_token_output{}, /* is_progress */ false, /* is_begin */ true); + } + } + + // `GEN key=value...` from the request's sampling parameters. Absent keys mean greedy to the engine + // (generate.cpp: "Absent = greedy"), so temperature <= 0 sends none of them. + std::string gen_header(const server_task & t, int32_t max_new) const { + const auto & s = t.params.sampling; + std::string h = "GEN " + std::to_string(max_new); + char b[128]; + if (s.temp > 0.0f) { + std::snprintf(b, sizeof b, " temperature=%g", (double) s.temp); h += b; + if (s.top_p > 0.0f && s.top_p < 1.0f) { std::snprintf(b, sizeof b, " top_p=%g", (double) s.top_p); h += b; } + // strata's sampled path takes top_k in 1..64; 0 means "whole vocabulary" to llama.cpp + int32_t top_k = s.top_k <= 0 ? 64 : std::min(s.top_k, 64); + std::snprintf(b, sizeof b, " top_k=%d", top_k); h += b; + if (s.min_p > 0.0f) { std::snprintf(b, sizeof b, " min_p=%g", (double) s.min_p); h += b; } + if (s.seed != LLAMA_DEFAULT_SEED) { std::snprintf(b, sizeof b, " seed=%u", s.seed); h += b; } + } + const bool penalties = s.penalty_repeat != 1.0f || s.penalty_freq != 0.0f || s.penalty_present != 0.0f; + if (penalties && s.penalty_last_n != 0) { + std::snprintf(b, sizeof b, " penalty_last_n=%d penalty_repeat=%g penalty_freq=%g penalty_present=%g", + s.penalty_last_n < 0 ? (int) n_ctx : s.penalty_last_n, + (double) s.penalty_repeat, (double) s.penalty_freq, (double) s.penalty_present); + h += b; + } + if (!s.logit_bias.empty() && !engine_is_poly) { + std::string lb = " logit_bias="; + for (size_t i = 0; i < s.logit_bias.size(); ++i) { + if (i) lb += ','; + std::snprintf(b, sizeof b, "%d:%g", s.logit_bias[i].token, (double) s.logit_bias[i].bias); + lb += b; + } + h += lb; + } + return h; + } + + void cancel_current() { + if (!slot.active() || slot.cancelled) { + return; + } + SRV_INF("task %d: cancelled by the client, stopping the engine's request\n", slot.task->id); + slot.cancelled = true; + if (!engine.stop()) { + // the engine is gone; the supervisor will report it + slot.release(); + } + } + + void handle_line(const EngineLine & line) { + switch (line.kind) { + case EngineLine::TOKEN: + if (!slot.cancelled && slot.has_next_token) { + on_token(line.token); + } + break; + + case EngineLine::RESUME: + slot.stats.n_prompt_cached = (uint64_t) line.n; + break; + + case EngineLine::PP: + if (!slot.cancelled && slot.task->params.stream && slot.task->params.return_progress) { + send_partial_response(completion_token_output{}, /* is_progress */ true, false, line.pp_done); + } + break; + + case EngineLine::DONE: + on_done(line); + break; + + case EngineLine::ERR: + SRV_ERR("task %d: engine: %s\n", slot.task->id, line.message.c_str()); + if (!slot.cancelled) { + send_error(*slot.task, "engine: " + line.message, ERROR_TYPE_SERVER); + } + finish_slot(); + break; + + case EngineLine::EOF_: + SRV_ERR("%s", "the engine closed its output during a request\n"); + if (!slot.cancelled) { + send_error(*slot.task, "the engine exited during the request", ERROR_TYPE_UNAVAILABLE); + } + finish_slot(); + engine_dead = true; + queue_tasks.terminate(); + break; + + case EngineLine::INFO: + LOG_INF("engine: %s\n", line.raw.c_str()); + break; + + case EngineLine::REUSED: + case EngineLine::OTHER: + case EngineLine::NONE: + break; + } + } + + bool accept_special_token(llama_token token) const { + return params.special || + slot.task->params.sampling.preserved_tokens.find(token) != slot.task->params.sampling.preserved_tokens.end(); + } + + // mirrors post_decode + process_token in server-context.cpp + void on_token(llama_token tok) { + if (slot.stats.n_gen == 0) { + slot.stats.update_prompt_last(); + } + slot.stats.n_gen++; + slot.stats.update_gen_last(); + + completion_token_output result; + result.tok = tok; + result.prob = 1.0f; + result.text_to_send = common_token_to_piece(vocab, tok, accept_special_token(tok)); + + const std::string token_str = result.text_to_send; + slot.generated_text += token_str; + if (slot.task->params.return_tokens) { + slot.generated_tokens.push_back(tok); + } + slot.has_next_token = true; + + const bool incomplete = validate_utf8(slot.generated_text) < slot.generated_text.size(); + + if (!incomplete) { + size_t pos = std::min(slot.n_sent_text, slot.generated_text.size()); + const std::string str_test = slot.generated_text.substr(pos); + bool send_text = true; + + size_t stop_pos = slot.find_stopping_strings(str_test, token_str.size(), true); + if (stop_pos != std::string::npos) { + slot.generated_text.erase(slot.generated_text.begin() + pos + stop_pos, slot.generated_text.end()); + pos = std::min(slot.n_sent_text, slot.generated_text.size()); + } else if (slot.has_next_token && !llama_vocab_is_eog(vocab, tok)) { + stop_pos = slot.find_stopping_strings(str_test, token_str.size(), false); + send_text = stop_pos == std::string::npos; + } + + if (send_text) { + result.text_to_send = slot.generated_text.substr(pos, std::string::npos); + slot.n_sent_text += result.text_to_send.size(); + } else { + result.text_to_send = ""; + } + if (slot.task->params.stream) { + send_partial_response(result, false, false); + } + } + + if (slot.stats.n_gen > 0 && slot.has_next_token && !slot.has_budget()) { + slot.stop = STOP_TYPE_LIMIT; + slot.has_next_token = false; + } + if (result.text_to_send.find('\n') != std::string::npos) { + slot.has_new_line = true; + } + if (llama_vocab_is_eog(vocab, tok)) { + slot.stop = STOP_TYPE_EOS; + slot.has_next_token = false; + } + + // a stop the engine does not know about (stop string, our limit): tell it, keep draining to its DONE + if (!slot.has_next_token && slot.stop != STOP_TYPE_EOS && !slot.stop_sent) { + slot.stop_sent = true; + engine.stop(); + } + } + + void on_done(const EngineLine & d) { + if (!slot.active()) { + return; + } + const server_task & t = *slot.task; + // the engine's own clock: prompt and decode times as it measured them + SRV_INF("task %d: DONE produced=%lld prompt=%lld prompt_ms=%.1f decode_ms=%.1f finish=%s drafts=%lld/%lld reused=%lld\n", + t.id, d.produced, d.prompt_n, d.prompt_ms, d.decode_ms, d.finish.c_str(), d.draft_accepted, d.draft_offered, d.reused); + + if (d.prompt_n != (long long) t.n_tokens()) { + // the engine answered for another prompt: never pass that off as this request's reply + SRV_ERR("task %d: engine prompt size mismatch: sent %d, engine reports %lld; refusing the response\n", t.id, t.n_tokens(), d.prompt_n); + if (!slot.cancelled) { + send_error(t, "engine response prompt size mismatch", ERROR_TYPE_SERVER); + } + finish_slot(); + return; + } + + slot.stats.n_prompt_cached = (uint64_t) std::max(d.reused, (long long) slot.stats.n_prompt_cached); + slot.stats.n_prompt_processed = (uint64_t) std::max(0, d.prompt_n - (long long) slot.stats.n_prompt_cached); + slot.stats.n_draft_tokens = (uint64_t) d.draft_offered; + slot.stats.n_draft_accepted = (uint64_t) d.draft_accepted; + if (slot.stats.t_prompt_last == 0) { + slot.stats.update_prompt_last(); + } + if (slot.stats.t_gen_last == 0 && slot.stats.n_gen > 0) { + slot.stats.update_gen_last(); + } + + if (slot.cancelled) { + finish_slot(); + return; + } + if (d.finish == "nonfinite") { + send_error(t, "the engine produced non-finite logits", ERROR_TYPE_SERVER); + finish_slot(); + return; + } + if (slot.stop == STOP_TYPE_NONE) { + if (d.finish == "length") { + slot.stop = STOP_TYPE_LIMIT; + slot.truncated = false; + } else { + slot.stop = STOP_TYPE_EOS; + } + } + send_final_response(); + finish_slot(); + } + + void finish_slot() { + slot.release(); + queue_tasks.pop_deferred_task(-1); + } + + // mirrors send_partial_response in server-context.cpp + void send_partial_response(const completion_token_output & tkn, bool is_progress, bool is_begin, long long pp_done = 0) { + auto res = std::make_unique(); + const server_task & t = *slot.task; + + res->id = t.id; + res->index = t.index; + + if (is_progress) { + res->is_progress = true; + res->progress.total = t.n_tokens(); + res->progress.cache = (int32_t) slot.stats.n_prompt_cached; + res->progress.processed = (int32_t) pp_done; + res->progress.time_ms = slot.stats.t_elapsed_us() / 1000; + } + if (is_begin) { + res->is_begin = true; + } else { + res->content = tkn.text_to_send; + res->tokens = { tkn.tok }; + } + + res->n_decoded = (int32_t) slot.stats.n_gen; + res->n_prompt_tokens = t.n_tokens(); + res->n_prompt_tokens_cache = (int32_t) slot.stats.n_prompt_cached; + res->post_sampling_probs = t.params.post_sampling_probs; + + res->verbose = t.params.verbose; + res->res_type = t.params.res_type; + res->oaicompat_model = t.params.oaicompat_model; + res->oaicompat_cmpl_id = t.params.oaicompat_cmpl_id; + + if (slot.stop != STOP_TYPE_NONE || t.params.timings_per_token) { + res->stats = slot.stats; + } + queue_results.send(std::move(res)); + } + + // mirrors send_final_response in server-context.cpp + void send_final_response() { + auto res = std::make_unique(); + server_task & t = *slot.task; + + res->id = t.id; + res->id_slot = 0; + res->index = t.index; + + if (t.params.stream) { + res->content = ""; + res->tokens = llama_tokens{}; + } else { + res->content = std::move(slot.generated_text); + res->tokens = std::move(slot.generated_tokens); + } + res->stats = slot.stats; + res->prompt = tokens_to_str(vocab, t.tokens.get_text_tokens()); + res->response_fields = std::move(t.params.response_fields); + + res->truncated = slot.truncated; + res->n_decoded = (int32_t) slot.stats.n_gen; + res->n_prompt_tokens = t.n_tokens(); + res->n_prompt_tokens_cache = (int32_t) slot.stats.n_prompt_cached; + res->n_tokens_cached = t.n_tokens() + (int32_t) slot.stats.n_gen; + res->has_new_line = slot.has_new_line; + res->stopping_word = slot.stopping_word; + res->stop = slot.stop; + res->post_sampling_probs = t.params.post_sampling_probs; + + res->verbose = t.params.verbose; + res->stream = t.params.stream; + res->include_usage = t.params.include_usage; + res->res_type = t.params.res_type; + res->oaicompat_model = t.params.oaicompat_model; + res->oaicompat_cmpl_id = t.params.oaicompat_cmpl_id; + + res->generation_params = t.params; + + // cumulative server metrics + metrics.add_prompt(slot.stats.n_prompt_processed, (uint64_t) std::max(0, slot.stats.t_prompt_ms() * 1000)); + metrics.add_prompt_cached(slot.stats.n_prompt_cached); + metrics.predict.add(slot.stats.n_gen, slot.stats.n_gen_steps(), (uint64_t) slot.stats.t_gen_us()); + metrics.n_draft_tokens += slot.stats.n_draft_tokens; + metrics.n_draft_accepted += slot.stats.n_draft_accepted; + + queue_results.send(std::move(res)); + } + + server_metrics metrics; + + // ---- routes ---------------------------------------------------------------------------------------------------- + + std::unique_ptr create_response() { + return std::make_unique(queue_tasks, queue_results); + } + + json model_info_json() const { + json modalities = json::array({"text"}); + if (chat_params.allow_image) { + modalities.push_back("image"); + } + return json { + {"id", model_name}, + {"object", "model"}, + {"created", std::time(0)}, + {"owned_by", "unbiasedstrata"}, + {"context_length", n_ctx}, + {"input_modalities", modalities}, + {"meta", { + {"vocab_type", llama_vocab_type(vocab)}, + {"n_vocab", llama_vocab_n_tokens(vocab)}, + {"n_ctx", n_ctx}, + {"engine", engine_is_poly ? "strata-poly" : "strata"}, + }}, + }; + } + + // mirrors handle_completions_impl in server-context.cpp without the parts the engine has no use for + // (n_cmpl > 1, prompt logging, message spans for checkpoints) + std::unique_ptr handle_completions(const server_http_req & req, const json & data, + const std::vector & files, task_response_type res_type) { + auto res = create_response(); + auto completion_id = gen_chatcmplid(); + auto & rd = res->rd; + + res->set_req(&req); + + int32_t sse_ping_interval = params.sse_ping_interval; + + try { + const auto & prompt = data.at("prompt"); + + std::vector inputs; + if (res_type != TASK_RESPONSE_TYPE_NONE && mctx != nullptr) { + inputs.push_back(process_mtmd_prompt(mctx, prompt.get(), files, init_opt)); + } else { + inputs = tokenize_input_prompts(vocab, mctx, prompt, true, true, init_opt); + } + if (inputs.size() != 1) { + throw std::invalid_argument("this server takes one prompt per request"); + } + + server_task task = server_task(SERVER_TASK_TYPE_COMPLETION); + task.id = rd.get_new_id(); + task.tokens = std::move(inputs[0]); + task.params = server_schema::eval_llama_cmpl_schema(vocab, params, logit_bias_eog, data); + if (task.params.n_cmpl > 1) { + throw std::invalid_argument("n > 1 is not supported by this server"); + } + sse_ping_interval = task.params.sse_ping_interval; + + task.params.res_type = res_type; + task.params.oaicompat_cmpl_id = completion_id; + task.params.oaicompat_model = model_name; + + std::vector tasks; + tasks.push_back(std::move(task)); + rd.post_tasks(std::move(tasks)); + } catch (const std::exception & e) { + res->error(format_error_response(e.what(), ERROR_TYPE_INVALID_REQUEST)); + return res; + } + + const bool stream = json_value(data, "stream", false); + + if (!stream) { + auto all_results = rd.wait_for_all(req.should_stop); + if (all_results.is_terminated) { + return res; // connection closed + } else if (all_results.error) { + res->error(all_results.error->to_json()); + return res; + } else { + GGML_ASSERT(all_results.results.size() == 1); + GGML_ASSERT(dynamic_cast(all_results.results[0].get()) != nullptr); + res->ok(all_results.results[0]->to_json()); + } + return res; + } + + // streaming: the first error is a plain (non-stream) error response, as OpenAI does + auto first_result = rd.next(req.should_stop); + if (first_result == nullptr) { + GGML_ASSERT(req.should_stop()); + return res; + } + if (first_result->is_error()) { + res->error(first_result->to_json()); + return res; + } + GGML_ASSERT( + dynamic_cast(first_result.get()) != nullptr || + dynamic_cast (first_result.get()) != nullptr + ); + + json first_result_json = first_result->to_json(); + if (first_result_json == nullptr) { + res->data = ""; // headers and status only + } else if (res_type == TASK_RESPONSE_TYPE_ANTHROPIC) { + res->data = format_anthropic_sse(first_result_json); + } else if (res_type == TASK_RESPONSE_TYPE_OAI_RESP) { + res->data = format_oai_resp_sse(first_result_json); + } else { + res->data = format_oai_sse(first_result_json); + } + res->status = 200; + res->content_type = "text/event-stream"; + res->set_next([res_this = res.get(), res_type, sse_ping_interval](std::string & output) -> bool { + static auto format_error = [](task_response_type res_type, const json & res_json) { + if (res_type == TASK_RESPONSE_TYPE_ANTHROPIC) { + return format_anthropic_sse({{"event", "error"}, {"data", res_json}}); + } + return format_oai_sse(json {{ "error", res_json }}); + }; + auto effective_should_stop = [&res_this]() { return res_this->should_stop(); }; + + try { + if (effective_should_stop()) { + return false; + } + if (!res_this->data.empty()) { + output = std::move(res_this->data); + res_this->data.clear(); + return true; + } + server_response_reader & rd = res_this->rd; + if (!rd.has_next()) { + switch (res_type) { + case TASK_RESPONSE_TYPE_NONE: + case TASK_RESPONSE_TYPE_OAI_RESP: + case TASK_RESPONSE_TYPE_ANTHROPIC: + output = ""; + break; + default: + output = "data: [DONE]\n\n"; + break; + } + return false; + } + bool timeout = false; + int64_t start_time = ggml_time_ms(); + auto result = rd.next([&timeout, &start_time, sse_ping_interval, &effective_should_stop]() { + if (effective_should_stop()) { + return true; + } + if (sse_ping_interval > 0 && ggml_time_ms() - start_time > (int64_t) sse_ping_interval * 1000) { + timeout = true; + return true; + } + return false; + }); + if (timeout) { + // a client with an idle timeout (pi: 5 minutes) stays attached; a client that is gone fails this write + output = ":\n\n"; + return true; + } + if (result == nullptr) { + GGML_ASSERT(effective_should_stop()); + return false; + } + if (result->is_error()) { + output = format_error(res_type, result->to_json()); + return false; + } + GGML_ASSERT( + dynamic_cast(result.get()) != nullptr || + dynamic_cast(result.get()) != nullptr + ); + json res_json = result->to_json(); + if (res_type == TASK_RESPONSE_TYPE_ANTHROPIC) { + output = format_anthropic_sse(res_json); + } else if (res_type == TASK_RESPONSE_TYPE_OAI_RESP) { + output = format_oai_resp_sse(res_json); + } else { + output = format_oai_sse(res_json); + } + return true; + } catch (const std::exception & e) { + output = format_error(res_type, format_error_response(e.what(), ERROR_TYPE_SERVER)); + return false; + } + }); + return res; + } +}; + +// ---- strata_context ------------------------------------------------------------------------------------------------- + +strata_context::strata_context() : impl(std::make_unique()) {} +strata_context::~strata_context() = default; + +bool strata_context::start_engine(const common_params & params, const std::string & engine_exe, + const std::vector & engine_args, std::string & err) { + impl->params = params; + impl->engine_exe = engine_exe; + impl->engine_args = engine_args; + impl->engine_is_poly = engine_exe.find("strata-poly") != std::string::npos; + + std::vector argv; + argv.push_back(engine_exe); + argv.push_back("--serve"); + for (const auto & a : engine_args) { + argv.push_back(a); + } + return impl->engine.start(engine_exe, argv, err); +} + +bool strata_context::load(common_params & params, std::string & err) { + auto & I = *impl; + I.params = params; + + // the vocabulary and the chat template, from the GGUF's metadata; no tensor is read + llama_model_params mparams = llama_model_default_params(); + mparams.vocab_only = true; + I.model = llama_model_load_from_file(params.model.path.c_str(), mparams); + if (I.model == nullptr) { + err = "could not read the vocabulary from " + params.model.path; + return false; + } + I.vocab = llama_model_get_vocab(I.model); + I.model_path = params.model.path; + I.model_name = params.model_alias.empty() ? file_stem(params.model.path) : *params.model_alias.begin(); + + // mirrors the chat template setup in server_context_impl::load_model + { + common_chat_templates_ptr chat_templates; + bool enable_thinking = false; + try { + chat_templates = common_chat_templates_init(I.model, params.chat_template); + LOG_INF("chat template, example_format: '%s'\n", + common_chat_format_example(chat_templates.get(), params.use_jinja, params.default_template_kwargs).c_str()); + const bool template_supports_thinking = params.use_jinja && common_chat_templates_support_enable_thinking(chat_templates.get()); + enable_thinking = params.enable_reasoning != 0 && template_supports_thinking; + LOG_INF("chat template, thinking = %d\n", enable_thinking); + } catch (const std::exception & e) { + err = std::string("chat template parsing error: ") + e.what(); + return false; + } + I.chat_params = { + /* use_jinja */ params.use_jinja, + /* prefill_assistant */ params.prefill_assistant, + /* reasoning_format */ params.reasoning_format, + /* chat_template_kwargs */ params.default_template_kwargs, + /* tmpls */ std::move(chat_templates), + /* allow_image */ false, + /* allow_audio */ false, + /* allow_video */ false, + /* enable_thinking */ enable_thinking, + /* reasoning_budget */ -1, // needs a sampler the engine does not expose + /* reasoning_budget_msg */ std::string(), + /* media_path */ params.media_path, + /* force_pure_content */ params.force_pure_content_parser + }; + I.chat_caps = common_chat_templates_get_caps(I.chat_params.tmpls.get()); + } + + // the engine: READY carries the context it allocated + LOG_INF("waiting for the engine (%s) to load\n", I.engine_exe.c_str()); + std::string eerr; + if (!I.engine.wait_ready(eerr, /* timeout_s */ 3600)) { + err = "engine: " + eerr; + return false; + } + I.n_ctx = I.engine.max_context() > 0 ? I.engine.max_context() : params.n_ctx; + if (I.n_ctx <= 0) { + err = "the engine did not report its context size and -c was not given"; + return false; + } + if (!I.engine.can_stop()) { + LOG_WRN("%s", "the engine does not honour STOP: a cancelled request runs to its end\n"); + } + for (const auto & kv : I.engine.info()) { + LOG_INF("engine info: %s=%s\n", kv.first.c_str(), kv.second.c_str()); + } + LOG_INF("engine ready: context %lld tokens, model %s\n", I.n_ctx, I.model_name.c_str()); + + I.queue_tasks.on_new_task([this](server_task && task, bool is_yielding) { + return impl->process_new_task(std::move(task), is_yielding); + }); + I.queue_tasks.on_update_slots([this]() { + impl->update_slots(); + }); + I.metrics.init(); + return true; +} + +void strata_context::start_loop() { + impl->queue_tasks.start_loop(); +} + +void strata_context::terminate() { + impl->queue_tasks.terminate(); + impl->queue_results.terminate(); + impl->engine.quit(); + if (impl->model) { + llama_model_free(impl->model); + impl->model = nullptr; + } +} + +bool strata_context::engine_exited(std::string & why) { + if (impl->engine_dead) { + why = "the engine closed its output"; + return true; + } + return impl->engine.reap_exit(why); +} + +bool strata_context::engine_alive() const { + return impl->engine.alive() && !impl->engine_dead; +} + +long long strata_context::n_ctx() const { + return impl->n_ctx; +} + +void strata_context::init_routes(server_http_context & http) { + strata_context_impl * I = impl.get(); + + auto get_health = [I](const server_http_req &) { + auto res = I->create_response(); + if (!I->engine.alive() || I->engine_dead) { + res->error(format_error_response("the engine is not running", ERROR_TYPE_UNAVAILABLE)); + return res; + } + res->ok({{"status", "ok"}, {"busy", I->slot.active()}}); + return res; + }; + + auto get_models = [I](const server_http_req &) { + auto res = I->create_response(); + res->ok(json { + {"object", "list"}, + {"data", json::array({ I->model_info_json() })}, + }); + return res; + }; + + auto get_props = [I](const server_http_req &) { + auto res = I->create_response(); + json caps = json::object(); + for (const auto & kv : I->chat_caps) { + caps[kv.first] = kv.second; + } + res->ok(json { + {"default_generation_settings", {{"n_ctx", I->n_ctx}}}, + {"total_slots", 1}, + {"model_path", I->model_path}, + {"model_alias", I->model_name}, + {"modalities", {{"vision", I->chat_params.allow_image}, {"audio", false}}}, + {"chat_template", common_chat_templates_source(I->chat_params.tmpls.get())}, + {"chat_template_caps", caps}, + {"build_info", std::string(llama_build_info())}, + {"engine", I->engine_is_poly ? "strata-poly" : "strata"}, + }); + return res; + }; + + auto post_chat_completions = [I](const server_http_req & req) { + std::vector files; + json body = json::parse(req.body); + json body_parsed = oaicompat_chat_params_parse(body, I->chat_params, files); + return I->handle_completions(req, body_parsed, files, TASK_RESPONSE_TYPE_OAI_CHAT); + }; + + auto post_completions_oai = [I](const server_http_req & req) { + std::vector files; + const json body = json::parse(req.body); + return I->handle_completions(req, body, files, TASK_RESPONSE_TYPE_OAI_CMPL); + }; + + auto post_completions = [I](const server_http_req & req) { + std::vector files; + const json body = json::parse(req.body); + return I->handle_completions(req, body, files, TASK_RESPONSE_TYPE_NONE); + }; + + auto post_apply_template = [I](const server_http_req & req) { + auto res = I->create_response(); + std::vector files; + json body = json::parse(req.body); + json data = oaicompat_chat_params_parse(body, I->chat_params, files); + res->ok({{ "prompt", std::move(data.at("prompt")) }}); + return res; + }; + + auto post_tokenize = [I](const server_http_req & req) { + auto res = I->create_response(); + const json body = json::parse(req.body); + json tokens_response = json::array(); + if (body.count("content") != 0) { + const bool add_special = json_value(body, "add_special", false); + const bool parse_special = json_value(body, "parse_special", true); + const bool with_pieces = json_value(body, "with_pieces", false); + llama_tokens tokens = tokenize_mixed(I->vocab, body.at("content"), add_special, parse_special); + if (with_pieces) { + for (const auto & token : tokens) { + std::string piece = common_token_to_piece(I->vocab, token); + json piece_json; + if (is_valid_utf8(piece)) { + piece_json = piece; + } else { + piece_json = json::array(); + for (unsigned char c : piece) { + piece_json.push_back(static_cast(c)); + } + } + tokens_response.push_back({{"id", token}, {"piece", piece_json}}); + } + } else { + tokens_response = tokens; + } + } + res->ok(json{{"tokens", std::move(tokens_response)}}); + return res; + }; + + auto post_detokenize = [I](const server_http_req & req) { + auto res = I->create_response(); + const json body = json::parse(req.body); + std::string content; + if (body.count("tokens") != 0) { + const llama_tokens tokens = body.at("tokens").get(); + content = tokens_to_str(I->vocab, tokens); + } + res->ok(json{{"content", std::move(content)}}); + return res; + }; + + http.get ("/health", ex_wrapper(get_health)); + http.get ("/v1/health", ex_wrapper(get_health)); + http.get ("/props", ex_wrapper(get_props)); + http.get ("/models", ex_wrapper(get_models)); + http.get ("/v1/models", ex_wrapper(get_models)); + http.post("/completion", ex_wrapper(post_completions)); + http.post("/completions", ex_wrapper(post_completions)); + http.post("/v1/completions", ex_wrapper(post_completions_oai)); + http.post("/chat/completions", ex_wrapper(post_chat_completions)); + http.post("/v1/chat/completions", ex_wrapper(post_chat_completions)); + http.post("/tokenize", ex_wrapper(post_tokenize)); + http.post("/detokenize", ex_wrapper(post_detokenize)); + http.post("/apply-template", ex_wrapper(post_apply_template)); +} diff --git a/frontend/strata_context.hpp b/frontend/strata_context.hpp new file mode 100644 index 0000000..508dee6 --- /dev/null +++ b/frontend/strata_context.hpp @@ -0,0 +1,46 @@ +// UnbiasedStrata: the server context with a Strata engine behind it. +// +// This is the fork's replacement for llama.cpp's tools/server/server-context.cpp. Everything around it is llama.cpp's +// own, compiled unmodified from the submodule: the HTTP layer (server-http), the task queue and response reader +// (server-queue), the task and result types with their OpenAI/Anthropic/Responses JSON (server-task), request parsing, +// tokenization helpers and SSE formatting (server-common), the request schema (server-schema). What this file adds is +// the part that llama.cpp does with llama_context, llama_batch and common_sampler and that the engine does inside +// its own process: run one request at a time through `strata`/`strata-poly`, turn its `T ` lines into partial +// results, and its `DONE` line into the final one. +#pragma once + +#include "server-http.h" + +#include +#include +#include + +struct common_params; +struct strata_context_impl; + +struct strata_context { + std::unique_ptr impl; + + strata_context(); + ~strata_context(); + + // Registers the HTTP routes on `http`. Handlers run only once http.is_ready is set, after load(). + void init_routes(server_http_context & http); + + // fork+exec the engine. Call before any thread exists (before http.start()). + bool start_engine(const common_params & params, const std::string & engine_exe, const std::vector & engine_args, std::string & err); + + // Loads the vocabulary and chat template from the GGUF (vocab only, no tensors) and waits for the engine's READY. + bool load(common_params & params, std::string & err); + + // Blocks the calling thread running the task loop until terminate(). + void start_loop(); + void terminate(); + + // Non-blocking: true once the engine process has exited; `why` names the signal or exit code. + bool engine_exited(std::string & why); + bool engine_alive() const; + + // the context the engine allocated (READY line) + long long n_ctx() const; +}; diff --git a/frontend/tests/e2e.sh b/frontend/tests/e2e.sh new file mode 100755 index 0000000..abbddb8 --- /dev/null +++ b/frontend/tests/e2e.sh @@ -0,0 +1,83 @@ +#!/usr/bin/env bash +# UnbiasedStrata: the front end end to end against the fake engine, with a vocabulary-only GGUF from llama.cpp's +# own test models (no GPU, no weights). Checks the HTTP surface a coding agent touches: /health, /v1/models, +# a non-streaming chat completion, a streaming one, a client that disconnects mid-stream, and an engine error. +# +# frontend/tests/e2e.sh [model.gguf] +set -u +BIN=${1:?usage: e2e.sh [model.gguf]} +HERE=$(cd "$(dirname "$0")" && pwd) +ROOT=$(cd "$HERE/../.." && pwd) +MODEL=${2:-$ROOT/third_party/llama.cpp/models/ggml-vocab-qwen35.gguf} +PORT=${PORT:-18931} +URL=http://127.0.0.1:$PORT +LOG=$(mktemp "${TMPDIR:-/tmp}/us2-e2e-XXXXXX") # no suffix after the Xs: BSD mktemp rejects it +fail=0 +check() { if [ "$1" = 0 ]; then echo "ok $2"; else echo "FAIL $2"; fail=1; fi; } +# j EXPR: evaluate a Python expression over the JSON on stdin (bound to `d`); the test needs python3 anyway, not jq. +j() { python3 -c 'import json,sys; d=json.load(sys.stdin); r=eval(sys.argv[1]); print(json.dumps(r) if isinstance(r,(dict,list)) else ("true" if r is True else "false" if r is False else "null" if r is None else r))' "$1" 2>/dev/null; } + +# tokens the fake engine emits: FAKE_TOKENS so the reply does not depend on the template's special tokens +export FAKE_TOKENS="${FAKE_TOKENS:-9707,11,1879,0}" # "Hello, world!" in the Qwen vocabulary +export FAKE_DELAY_MS=${FAKE_DELAY_MS:-0} + +"$BIN" --engine "$HERE/fake-engine.py" -m "$MODEL" --host 127.0.0.1 --port "$PORT" --alias fake -- --max-context 4096 > "$LOG" 2>&1 & +PID=$! +trap 'kill $PID 2>/dev/null; wait $PID 2>/dev/null' EXIT + +for i in $(seq 1 100); do + if curl -s -o /dev/null -w '%{http_code}' "$URL/health" 2>/dev/null | grep -q 200; then break; fi + if ! kill -0 $PID 2>/dev/null; then echo "FAIL server exited early"; cat "$LOG"; exit 1; fi + sleep 0.2 +done + +# /health and /v1/models +h=$(curl -s "$URL/health"); check $([ "$(echo "$h" | j 'd["status"]')" = ok ] && echo 0 || echo 1) "/health: $h" +m=$(curl -s "$URL/v1/models"); check $([ "$(echo "$m" | j 'd["data"][0]["id"]')" = fake ] && echo 0 || echo 1) "/v1/models id: $(echo "$m" | j '{k: d["data"][0].get(k) for k in ("id", "context_length")}')" + +# non-streaming chat +r=$(curl -s "$URL/v1/chat/completions" -H 'content-type: application/json' -d '{"model":"fake","messages":[{"role":"user","content":"Say hello"}],"max_tokens":32,"temperature":0}') +content=$(echo "$r" | j 'd["choices"][0]["message"]["content"]') +check $([ "$content" = "Hello, world!" ] && echo 0 || echo 1) "chat content: $(echo "$r" | j '{"content": d["choices"][0]["message"]["content"], "finish": d["choices"][0]["finish_reason"], "usage": d["usage"]}')" +check $([ "$(echo "$r" | j 'd["choices"][0]["finish_reason"]')" = stop ] && echo 0 || echo 1) "finish_reason stop" +check $([ "$(echo "$r" | j 'd["usage"]["completion_tokens"]')" = 4 ] && echo 0 || echo 1) "usage.completion_tokens 4" + +# streaming chat: role chunk, content deltas, finish chunk, [DONE] +s=$(curl -s -N "$URL/v1/chat/completions" -H 'content-type: application/json' -d '{"model":"fake","stream":true,"messages":[{"role":"user","content":"Say hello"}],"max_tokens":32}') +n_data=$(echo "$s" | grep -c '^data: {') +joined=$(echo "$s" | grep '^data: {' | sed 's/^data: //' | python3 -c 'import json,sys; print("".join((json.loads(l)["choices"][0]["delta"].get("content") or "") for l in sys.stdin if l.strip()), end="")') +check $([ "$joined" = "Hello, world!" ] && echo 0 || echo 1) "stream deltas join to the content ($n_data chunks)" +check $(echo "$s" | grep -q '^data: \[DONE\]' && echo 0 || echo 1) "stream ends with [DONE]" +check $([ "$(echo "$s" | grep '^data: {' | tail -1 | sed 's/^data: //' | j 'd["choices"][0]["finish_reason"]')" = stop ] && echo 0 || echo 1) "stream finish_reason stop" + +# a client that disconnects mid-stream: the engine is told to stop and the next request is clean. The fake engine +# reads its env once at start, so this needs a second server whose engine streams a long reply slowly (token 9707, +# "Hello": a raw byte token would not survive the chat parser on the follow-up request). +SLOW_PORT=$((PORT + 1)); SLOW_URL=http://127.0.0.1:$SLOW_PORT; SLOW_LOG=$(mktemp "${TMPDIR:-/tmp}/us2-e2e-slow-XXXXXX") +FAKE_N_TOKENS=100000 FAKE_TOKEN_ID=9707 FAKE_DELAY_MS=10 "$BIN" --engine "$HERE/fake-engine.py" -m "$MODEL" --host 127.0.0.1 --port "$SLOW_PORT" --alias fake -- --max-context 4096 > "$SLOW_LOG" 2>&1 & +SLOW_PID=$! +trap 'kill $PID $SLOW_PID 2>/dev/null; wait $PID $SLOW_PID 2>/dev/null; rm -f "$LOG" "$SLOW_LOG" "$BIG"' EXIT +for i in $(seq 1 100); do + if curl -s -o /dev/null -w '%{http_code}' "$SLOW_URL/health" 2>/dev/null | grep -q 200; then break; fi + if ! kill -0 $SLOW_PID 2>/dev/null; then echo "FAIL slow server exited early"; cat "$SLOW_LOG"; exit 1; fi + sleep 0.2 +done +curl -s -N --max-time 1 "$SLOW_URL/v1/chat/completions" -H 'content-type: application/json' -d '{"model":"fake","stream":true,"messages":[{"role":"user","content":"x"}],"max_tokens":4000}' > /dev/null 2>&1 +sleep 0.5 +r2=$(curl -s --max-time 10 "$SLOW_URL/v1/chat/completions" -H 'content-type: application/json' -d '{"model":"fake","messages":[{"role":"user","content":"again"}],"max_tokens":8}') +check $([ "$(echo "$r2" | j 'd["usage"]["completion_tokens"]')" = 8 ] && [ "$(echo "$r2" | j 'd["choices"][0]["finish_reason"]')" = length ] && echo 0 || echo 1) "request after a disconnected stream: $(echo "$r2" | j '{"finish": d["choices"][0]["finish_reason"], "usage": d["usage"]["completion_tokens"]}')" +check $(grep -q "cancelled by the client" "$SLOW_LOG" && echo 0 || echo 1) "server logged the cancel" + +# a prompt that exceeds the context is refused with 400, not 500 +big=$(python3 -c 'print("word " * 5000)') +BIG=$(mktemp "${TMPDIR:-/tmp}/us2-e2e-big-XXXXXX") +code=$(curl -s -o "$BIG" -w '%{http_code}' "$URL/v1/chat/completions" -H 'content-type: application/json' -d "{\"model\":\"fake\",\"messages\":[{\"role\":\"user\",\"content\":\"$big\"}]}") +check $([ "$code" = 400 ] && echo 0 || echo 1) "oversize prompt -> $code: $(j 'd["error"]["type"]' < "$BIG")" + +# tokenize / detokenize round trip +t=$(curl -s "$URL/tokenize" -H 'content-type: application/json' -d '{"content":"Hello, world!"}' | j 'd["tokens"]') +d=$(curl -s "$URL/detokenize" -H 'content-type: application/json' -d "{\"tokens\":$t}" | j 'd["content"]') +check $([ "$d" = "Hello, world!" ] && echo 0 || echo 1) "tokenize/detokenize round trip: $t" + +if [ $fail = 0 ]; then echo "e2e: all checks passed"; else echo "--- server log"; tail -40 "$LOG"; echo "--- slow server log"; tail -20 "$SLOW_LOG"; fi +exit $fail diff --git a/frontend/tests/engine_test.cpp b/frontend/tests/engine_test.cpp new file mode 100644 index 0000000..bb1c7b9 --- /dev/null +++ b/frontend/tests/engine_test.cpp @@ -0,0 +1,162 @@ +// UnbiasedStrata: the engine adapter against the fake engine (frontend/tests/fake-engine.py). No GPU, no model. +// +// c++ -std=c++20 -I frontend frontend/tests/engine_test.cpp -o engine_test && ./engine_test frontend/tests/fake-engine.py +// +// Cases, each the shape of a bug UnbiasedStrata 1 met: +// 1. READY parsed: context and the stop capability +// 2. a request: tokens come back, DONE carries the counts, the adapter is idle afterwards +// 3. cancel: STOP mid-request, the rest is drained to DONE finish=cancel, the next request is clean +// 4. backpressure: a 100k-token burst the caller abandons does not fill the pipe for ever (drain to DONE) +// 5. ERR: a refused request leaves the adapter usable +// 6. the engine dies mid-request: EOF is reported, reap_exit names the exit code +// 7. a DONE whose prompt size does not match is visible to the caller (the context refuses such a reply) +#include "engine.hpp" + +#include +#include +#include +#include + +using strata_frontend::Engine; +using strata_frontend::EngineLine; + +static int failures = 0; +#define CHECK(cond) do { if (!(cond)) { std::fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, #cond); ++failures; } } while (0) + +struct Run { + std::vector tokens; + EngineLine done; + bool got_done = false, got_err = false, got_eof = false; + std::string err; +}; + +// read until DONE/ERR/EOF; `cancel_after` tokens -> send STOP; `abandon_after` tokens -> stop reading tokens into +// the vector (the caller is "gone") but keep draining +static Run run(Engine & e, int cancel_after = -1, int timeout_ms = 5000) { + Run r; + EngineLine line; + const int64_t deadline = Engine::now_ms() + timeout_ms; + while (Engine::now_ms() < deadline) { + if (!e.next_line(line, 50)) continue; + switch (line.kind) { + case EngineLine::TOKEN: + r.tokens.push_back(line.token); + if (cancel_after >= 0 && (int) r.tokens.size() == cancel_after) e.stop(); + break; + case EngineLine::DONE: r.done = line; r.got_done = true; return r; + case EngineLine::ERR: r.err = line.message; r.got_err = true; return r; + case EngineLine::EOF_: r.got_eof = true; return r; + default: break; + } + } + std::fprintf(stderr, "FAIL: timed out waiting for DONE\n"); + ++failures; + return r; +} + +static bool start(Engine & e, const std::string & script, const std::vector> & env) { + for (auto & kv : env) ::setenv(kv.first.c_str(), kv.second.c_str(), 1); + std::string err; + const bool ok = e.start(script, {script}, err) && e.wait_ready(err, 10); + for (auto & kv : env) ::unsetenv(kv.first.c_str()); + if (!ok) std::fprintf(stderr, "start: %s\n", err.c_str()); + return ok; +} + +int main(int argc, char ** argv) { + if (argc < 2) { std::fprintf(stderr, "usage: engine_test \n"); return 2; } + const std::string script = argv[1]; + + // 1 + 2: READY, one request echoing the prompt + { + Engine e; + CHECK(start(e, script, {{"FAKE_CONTEXT", "2048"}})); + CHECK(e.ready()); + CHECK(e.max_context() == 2048); + CHECK(e.can_stop()); + CHECK(e.info().count("engine") && e.info().at("engine") == "fake"); + CHECK(e.send_request("GEN 10 temperature=0.6", {5, 6, 7})); + CHECK(e.busy()); + Run r = run(e); + CHECK(r.got_done); + CHECK((r.tokens == std::vector{5, 6, 7})); + CHECK(r.done.produced == 3 && r.done.prompt_n == 3 && r.done.finish == "stop"); + CHECK(!e.busy()); + // max_new caps it + CHECK(e.send_request("GEN 2", {1, 2, 3, 4})); + r = run(e); + CHECK(r.got_done && r.tokens.size() == 2 && r.done.finish == "length"); + e.quit(); + CHECK(!e.alive()); + } + + // 3: cancel mid-request, then a clean next request + { + Engine e; + CHECK(start(e, script, {{"FAKE_N_TOKENS", "1000"}, {"FAKE_DELAY_MS", "2"}})); + CHECK(e.send_request("GEN 1000", {1})); + Run r = run(e, /* cancel_after */ 5); + CHECK(r.got_done); + CHECK(r.done.finish == "cancel"); + CHECK(r.tokens.size() < 1000); + CHECK(e.send_request("GEN 3", {9})); + r = run(e); + CHECK(r.got_done && r.done.finish == "length" && r.tokens.size() == 3); + e.quit(); + } + + // 4: a burst the caller abandons; the pipe would hold ~64 KB, the burst is ~700 KB + { + Engine e; + CHECK(start(e, script, {{"FAKE_N_TOKENS", "100000"}})); + CHECK(e.send_request("GEN 100000", {1})); + Run r = run(e, /* cancel_after */ 1, /* timeout */ 30000); + CHECK(r.got_done); + // FAKE_N_TOKENS still applies, so the reply is one token of id 100 cut by max_new; what matters is + // that nothing of the abandoned burst leaks into it + CHECK(e.send_request("GEN 1", {2})); + r = run(e); + CHECK(r.got_done && r.tokens.size() == 1 && r.done.finish == "length"); + e.quit(); + } + + // 5: ERR leaves the adapter usable + { + Engine e; + CHECK(start(e, script, {{"FAKE_ERR", "prompt too long"}})); + CHECK(e.send_request("GEN 1", {1})); + Run r = run(e); + CHECK(r.got_err && r.err == "prompt too long"); + CHECK(!e.busy()); + CHECK(e.alive()); + e.quit(); + } + + // 6: the engine dies mid-request + { + Engine e; + CHECK(start(e, script, {{"FAKE_N_TOKENS", "50"}, {"FAKE_DIE_AFTER", "3"}})); + CHECK(e.send_request("GEN 50", {1})); + Run r = run(e); + CHECK(r.got_eof); + CHECK(r.tokens.size() == 3); + std::string why; + for (int i = 0; i < 50 && !e.reap_exit(why); ++i) ::usleep(10 * 1000); + CHECK(why == "engine exited with code 3"); + CHECK(!e.alive()); + } + + // 7: prompt size mismatch is visible + { + Engine e; + CHECK(start(e, script, {{"FAKE_PROMPT_N", "99"}})); + CHECK(e.send_request("GEN 5", {1, 2})); + Run r = run(e); + CHECK(r.got_done && r.done.prompt_n == 99); + e.quit(); + } + + if (failures) { std::fprintf(stderr, "%d failure(s)\n", failures); return 1; } + std::printf("engine_test: 7 cases passed\n"); + return 0; +} diff --git a/frontend/tests/fake-engine.py b/frontend/tests/fake-engine.py new file mode 100755 index 0000000..6ee7378 --- /dev/null +++ b/frontend/tests/fake-engine.py @@ -0,0 +1,109 @@ +#!/usr/bin/env python3 +"""A stand-in for strata / strata-poly that speaks the line protocol (docs/BACKENDS.md), for tests without a GPU. + + GEN [key=value ...] -> T per token, then DONE + STOP -> the current request ends with finish=cancel + QUIT -> exit 0 + +Environment variables choose the answers, so one script covers the cases: + FAKE_TOKENS comma-separated ids to emit (default: the prompt ids echoed back, capped by max_new) + FAKE_N_TOKENS emit this many tokens of id FAKE_TOKEN_ID instead (burst tests) + FAKE_TOKEN_ID the id used by FAKE_N_TOKENS (default 100) + FAKE_DELAY_MS sleep this long between tokens (default 0) + FAKE_CONTEXT the context in the READY line (default 4096) + FAKE_ERR if set, answer every GEN with "ERR " instead + FAKE_DIE_AFTER if set, exit 3 after emitting this many tokens of the first request + FAKE_NO_STOP if set, READY without "stop": STOP is ignored and the request runs to its end + FAKE_PROMPT_N if set, lie about the prompt size in DONE (mismatch test) +""" +import os +import select +import sys +import time + +out = sys.stdout + + +def say(s): + out.write(s + "\n") + out.flush() + + +env = os.environ.get +say("INFO engine=fake batch_slots=0") +say("READY %s%s" % (env("FAKE_CONTEXT", "4096"), "" if env("FAKE_NO_STOP") else " stop")) + +first = True +pending = [] # lines read while checking for STOP that are not STOP/QUIT + + +def readline(): + if pending: + return pending.pop(0) + line = sys.stdin.readline() + if line == "": + sys.exit(0) + return line.rstrip("\n") + + +def stop_requested(): + """Consume what is readable now; True if a STOP was among it.""" + stop = False + while select.select([sys.stdin], [], [], 0)[0]: + line = sys.stdin.readline() + if line == "": + sys.exit(0) + line = line.rstrip("\n") + if line == "STOP": + stop = True + elif line == "QUIT": + sys.exit(0) + else: + pending.append(line) + return stop + + +while True: + line = readline() + if line == "QUIT": + sys.exit(0) + if line == "STOP" or line == "": + continue + parts = line.split() + if parts[0] not in ("GEN", "GENI") or len(parts) < 3: + say("ERR expected: GEN ") + continue + max_new = int(parts[1]) + prompt = [int(x) for x in parts[-1].split(",") if x] + prompt_n = len(prompt) + if env("FAKE_ERR"): + say("ERR " + env("FAKE_ERR")) + continue + say("RESUME 0") + say("PP %d %d 1 1000" % (prompt_n, prompt_n)) + if env("FAKE_N_TOKENS"): + tokens = [int(env("FAKE_TOKEN_ID", "100"))] * int(env("FAKE_N_TOKENS")) + elif env("FAKE_TOKENS"): + tokens = [int(x) for x in env("FAKE_TOKENS").split(",") if x] + else: + tokens = prompt + delay = float(env("FAKE_DELAY_MS", "0")) / 1000.0 + die_after = int(env("FAKE_DIE_AFTER", "0") or 0) + produced = 0 + finish = "stop" + for t in tokens: + if produced >= max_new: + finish = "length" + break + if stop_requested() and not env("FAKE_NO_STOP"): + finish = "cancel" + break + say("T %d" % t) + produced += 1 + if die_after and first and produced >= die_after: + sys.exit(3) + if delay: + time.sleep(delay) + first = False + # DONE + say("DONE %d %s 12.5 %.1f %s 0 0 0" % (produced, env("FAKE_PROMPT_N", str(prompt_n)), produced * 10.0, finish)) diff --git a/frontend/ui_stub/ui.cpp b/frontend/ui_stub/ui.cpp new file mode 100644 index 0000000..166cbf8 --- /dev/null +++ b/frontend/ui_stub/ui.cpp @@ -0,0 +1,16 @@ +// UnbiasedStrata: the empty UI asset table (see ui.h). +#include "ui.h" + +const llama_ui_asset * llama_ui_find_asset(const std::string & name) { + (void) name; + return nullptr; +} + +const std::array & llama_ui_get_assets() { + static const std::array empty{}; + return empty; +} + +bool llama_ui_use_gzip() { + return false; +} diff --git a/frontend/ui_stub/ui.h b/frontend/ui_stub/ui.h new file mode 100644 index 0000000..277a91a --- /dev/null +++ b/frontend/ui_stub/ui.h @@ -0,0 +1,19 @@ +// UnbiasedStrata: stands in for the ui.h that llama.cpp's tools/ui generates at build time. tools/server/server-http.cpp +// includes it to serve the web UI's embedded assets; this fork ships no UI, so the asset table is empty and every +// lookup misses. Same declarations as tools/ui/ui.h.in with N_ASSETS = 0 and LLAMA_UI_HAS_ASSETS undefined. +#pragma once + +#include +#include + +struct llama_ui_asset { + std::string name; + const unsigned char * data; + std::size_t size; + std::string etag; + std::string type; +}; + +const llama_ui_asset * llama_ui_find_asset(const std::string & name); +bool llama_ui_use_gzip(); +const std::array & llama_ui_get_assets();