diff --git a/common/arg.cpp b/common/arg.cpp index 4353464d2847..56b19576fe07 100644 --- a/common/arg.cpp +++ b/common/arg.cpp @@ -1714,6 +1714,21 @@ common_params_context common_params_parser_init(common_params & params, llama_ex params.cache_ram_mib = value; } ).set_env("LLAMA_ARG_CACHE_RAM").set_examples({LLAMA_EXAMPLE_SERVER, LLAMA_EXAMPLE_CLI})); + add_opt(common_arg( + {"--cache-disk"}, "DIR", + "a disk tier for the prompt cache: an entry evicted from --cache-ram is written here instead of dropped, " + "and read back when a prompt matches it (default: none)", + [](common_params & params, const std::string & value) { + params.cache_disk_dir = value; + } + ).set_env("LLAMA_ARG_CACHE_DISK").set_examples({LLAMA_EXAMPLE_SERVER})); + add_opt(common_arg( + {"--cache-disk-mib"}, "N", + string_format("the prompt cache disk tier's size limit in MiB (default: %d, 0 - no limit)", params.cache_disk_mib), + [](common_params & params, int value) { + params.cache_disk_mib = value; + } + ).set_env("LLAMA_ARG_CACHE_DISK_MIB").set_examples({LLAMA_EXAMPLE_SERVER})); add_opt(common_arg( {"-kvu", "--kv-unified"}, {"-no-kvu", "--no-kv-unified"}, diff --git a/common/common.h b/common/common.h index f57bafb83295..9ef7d388efce 100644 --- a/common/common.h +++ b/common/common.h @@ -625,6 +625,8 @@ struct common_params { int32_t n_ctx_checkpoints = 32; // max number of context checkpoints per slot int32_t checkpoint_min_step = 8192; // minimum spacing between context checkpoints int32_t cache_ram_mib = 8192; // -1 = no limit, 0 - disable, 1 = 1 MiB, etc. + std::string cache_disk_dir; // the prompt cache's disk tier, empty = none + int32_t cache_disk_mib = 0; // the disk tier's size limit in MiB, 0 = no limit std::string hostname = "127.0.0.1"; std::string public_path = ""; // NOLINT diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 4e1fd12b03dc..10ba8253c36f 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -1,6 +1,12 @@ llama_add_compile_flags() # Model-free scheduling validator: compile the same traversal used by server-context. +# Model-free: the disk tier's instance custody and bounded reads (llama.cpp#124). +add_executable(test-server-spill-dir test-server-spill-dir.cpp ../tools/server/server-spill-dir.cpp) +target_compile_features(test-server-spill-dir PRIVATE cxx_std_17) +add_test(NAME test-server-spill-dir COMMAND test-server-spill-dir) +set_tests_properties(test-server-spill-dir PROPERTIES LABELS "main") + add_executable(test-server-prefill test-server-prefill.cpp) target_compile_features(test-server-prefill PRIVATE cxx_std_17) add_test(NAME test-server-prefill COMMAND test-server-prefill) diff --git a/tests/test-server-spill-dir.cpp b/tests/test-server-spill-dir.cpp new file mode 100644 index 000000000000..54b1c82da564 --- /dev/null +++ b/tests/test-server-spill-dir.cpp @@ -0,0 +1,83 @@ +// what this catches: the prompt cache's disk tier deleting another engine's files (Codex's review of +// llama.cpp#124: two owners of one --cache-disk DIR deleted each other's spills), sweeping a live owner's +// directory, touching files that are not instance directories, and sizing a read from a corrupt file's own +// length claim (an out-of-memory). Model-free. +#include "../tools/server/server-spill-dir.h" + +#include +#include +#include +#include +#include +#include + +namespace fs = std::filesystem; + +static void require(bool condition, const char * message) { + if (!condition) { + std::cerr << "FAILED: " << message << '\n'; + std::exit(1); + } +} + +static void two_owners_never_touch_each_other() { + const fs::path base = fs::temp_directory_path() / ("spill-dir-test-" + std::to_string(std::rand())); + fs::remove_all(base); + fs::create_directories(base); + { std::ofstream(base / "foreign.state") << "not ours"; } // a file in DIR that is no instance's + fs::create_directories(base / "notes"); // a directory that is no instance's + // an abandoned instance: its final marker exists and nobody holds its lock + fs::create_directories(base / "instance-1-1"); + { std::ofstream(base / "instance-1-1.owner") << ""; } + { std::ofstream(base / "instance-1-1" / "0.state") << "stale"; } + // an instance directory with NO marker (a claim before its marker, or anything unproven): untouched, + // and a sweeper never creates a marker for it (Codex on #124) + fs::create_directories(base / "instance-2-2"); + // a claim in progress: its .tmp marker exists (a live owner would hold it): never judged + { std::ofstream(base / "instance-3-3.owner.tmp") << ""; } + + std::error_code ec; + auto a = std::make_unique(); + require(a->claim(base, ec) == 1 && a->ok(), "the first owner claims its directory and sweeps the one abandoned instance"); + { std::ofstream(a->path() / "0.state") << "a's spill"; } + server_spill_dir b; + require(b.claim(base, ec) == 0 && b.ok(), "a second live owner sweeps nothing: the first one's marker is locked"); + require(a->path() != b.path(), "each owner has its own directory"); + require(fs::exists(a->path() / "0.state"), "the second owner never deletes the first owner's spill"); + require(fs::exists(base / "foreign.state") && fs::exists(base / "notes"), "nothing that is not an instance is touched"); + require(!fs::exists(base / "instance-1-1") && !fs::exists(base / "instance-1-1.owner"), "an abandoned instance and its marker are swept"); + require(fs::exists(base / "instance-2-2") && !fs::exists(base / "instance-2-2.owner"), + "a directory without a marker is never swept, and no sweeper creates a marker for it"); + require(fs::exists(base / "instance-3-3.owner.tmp"), "a claim in progress (.tmp) is never judged"); + const fs::path a_dir = a->path(); + a.reset(); + require(!fs::exists(a_dir), "an owner's directory leaves with it"); + require(b.ok() && fs::exists(b.path()), "and the other owner's stays"); + fs::remove_all(base); +} + +static void a_corrupt_length_is_refused_before_allocation() { + const fs::path p = fs::temp_directory_path() / ("spill-block-" + std::to_string(std::rand())); + { + FILE * f = std::fopen(p.string().c_str(), "wb"); + require(server_spill_write_block(f, std::vector(1000, 7)), "write a block"); + const uint64_t lie = 1ull << 62; // a corrupt length: far beyond the file + std::fwrite(&lie, sizeof(lie), 1, f); + std::fclose(f); + } + FILE * f = std::fopen(p.string().c_str(), "rb"); + uint64_t remaining = fs::file_size(p); + std::vector block; + require(server_spill_read_block(f, block, remaining) && block.size() == 1000 && block[999] == 7, "a sound block reads back"); + require(!server_spill_read_block(f, block, remaining), "a length beyond the file is refused"); + require(block.size() == 1000, "and nothing was resized from its claim"); + std::fclose(f); + fs::remove(p); +} + +int main() { + two_owners_never_touch_each_other(); + a_corrupt_length_is_refused_before_allocation(); + std::cout << "test-server-spill-dir: ok\n"; + return 0; +} diff --git a/tools/server/CMakeLists.txt b/tools/server/CMakeLists.txt index 67fb03964d7c..600489c90b13 100644 --- a/tools/server/CMakeLists.txt +++ b/tools/server/CMakeLists.txt @@ -8,6 +8,7 @@ add_library(${TARGET} STATIC server-chat.cpp server-chat.h server-task.cpp + server-spill-dir.cpp server-task.h server-queue.cpp server-queue.h diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index ba7b2093053a..357d5cd75881 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -317,7 +317,9 @@ struct server_slot { server_prompt prompt; - bool prompt_save(server_prompt_cache & prompt_cache) const { + // `next` / `next_lora`: the request about to load from the cache after this save, when there is one + bool prompt_save(server_prompt_cache & prompt_cache, const server_tokens * next = nullptr, + const lora_active_set * next_lora = nullptr) const { if (prompt.tokens.size() == 0) { return false; } @@ -330,7 +332,7 @@ struct server_slot { SRV_TRC(" - saving prompt with length %d, total state size = %.3f MiB (draft: %.3f MiB)\n", (int) prompt.tokens.size(), cur_size / (1024.0 * 1024.0), cur_size_dft / (1024.0 * 1024.0)); - auto * cur = prompt_cache.alloc(prompt, lora_active(lora), cur_size_tgt, cur_size_dft); + auto * cur = prompt_cache.alloc(prompt, lora_active(lora), cur_size_tgt, cur_size_dft, next, next_lora); if (cur == nullptr) { return false; } @@ -1553,6 +1555,11 @@ struct server_context_impl { SRV_TRC("%s", "use `--cache-ram 0` to disable the prompt cache\n"); prompt_cache = std::make_unique(params_base.cache_ram_mib, n_ctx); + if (!params_base.cache_disk_dir.empty() && !prompt_cache->set_disk(params_base.cache_disk_dir, params_base.cache_disk_mib, page_io.get(), &page_io_bytes, + server_test_faults::enabled ? server_test_faults::from_env().page_io_gate : std::string())) { + SRV_ERR("%s", "the prompt cache disk tier could not be set up, refusing to start without it\n"); + return false; + } } else { SRV_TRC("%s", "prompt cache is disabled - use `--cache-ram N` to enable it\n"); } @@ -1847,10 +1854,10 @@ struct server_context_impl { const int64_t t_start = ggml_time_us(); - ret->prompt_save(*prompt_cache); - const auto task_lora = task.params.lora.empty() ? params_base.lora_adapters : construct_lora_list(task.params.lora); + const auto next_lora = lora_active(task_lora); + ret->prompt_save(*prompt_cache, &task.tokens, &next_lora); if (!ret->prompt_load(*prompt_cache, task.tokens, task_lora)) { ret->prompt_clear(); } diff --git a/tools/server/server-page-io.h b/tools/server/server-page-io.h index fb1d6cc8ce57..b0db047e37fb 100644 --- a/tools/server/server-page-io.h +++ b/tools/server/server-page-io.h @@ -176,6 +176,17 @@ class server_page_admission { return false; } + // Admits `bytes` now or refuses: never parks (a caller that cannot wait, e.g. a prompt-cache spill + // that must free RAM now, drops instead of queueing behind the budget). + bool try_admit(uint64_t bytes) { + std::lock_guard lock(m); + if (closed || !waiting.empty() || !fits(bytes)) { + return false; + } + in_flight += bytes; + return true; + } + void release(uint64_t bytes) { std::vector> run; { diff --git a/tools/server/server-spill-dir.cpp b/tools/server/server-spill-dir.cpp new file mode 100644 index 000000000000..ba2fb90cd5b5 --- /dev/null +++ b/tools/server/server-spill-dir.cpp @@ -0,0 +1,63 @@ +// The disk tier's only platform-specific lines (server-spill-dir.h): an exclusive file lock and the process +// id. Logic lives in the header; this file holds just the OS calls. +#include "server-spill-dir.h" + +#if defined(_WIN32) +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#else +#include +#include +#include +#endif + +bool server_owner_lock::try_take(const std::filesystem::path & path, bool create) { + release(); +#if defined(_WIN32) + // no read/write sharing: a second open of a file another process holds open fails (delete sharing + // lets the owner rename its own marker) + HANDLE h = CreateFileW(path.wstring().c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_DELETE, nullptr, + create ? CREATE_NEW : OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + if (h == INVALID_HANDLE_VALUE) { + return false; + } + handle = (intptr_t) h; + return true; +#else + const int fd = ::open(path.c_str(), O_RDWR | O_CLOEXEC | (create ? (O_CREAT | O_EXCL) : 0), 0600); + if (fd < 0) { + return false; + } + if (::flock(fd, LOCK_EX | LOCK_NB) != 0) { + ::close(fd); + return false; + } + handle = fd; + return true; +#endif +} + +void server_owner_lock::release() { + if (handle == -1) { + return; + } +#if defined(_WIN32) + CloseHandle((HANDLE) handle); +#else + ::close((int) handle); // closing releases the flock +#endif + handle = -1; +} + +uint64_t server_process_id() { +#if defined(_WIN32) + return (uint64_t) GetCurrentProcessId(); +#else + return (uint64_t) ::getpid(); +#endif +} diff --git a/tools/server/server-spill-dir.h b/tools/server/server-spill-dir.h new file mode 100644 index 000000000000..1d8f323b81a6 --- /dev/null +++ b/tools/server/server-spill-dir.h @@ -0,0 +1,154 @@ +#pragma once + +// Continuum fork: the prompt cache's disk tier keeps its files in a directory this engine instance owns +// (Codex's review of llama.cpp#124: two engines sharing one --cache-disk DIR deleted each other's files). +// +// - Each instance writes only under DIR/instance--/, and holds an exclusive lock on its +// `.owner` file there for as long as it lives (the OS releases it if the process dies). +// - At start, an instance removes only instance directories whose `.owner` lock it can take: their owner +// is gone. A live owner's directory, and anything else in DIR, is never touched. +// - Spill files hold length-prefixed blocks; a read checks every length against the bytes left in the +// file BEFORE allocating, so a corrupt or truncated file is refused, never an out-of-memory. +// +// The OS lock is the only platform-specific part (server_owner_lock below). + +#include +#include +#include +#include +#include +#include +#include + + +// An exclusive, non-blocking lock on one file, released when this object or its process ends. The OS calls +// live in server-spill-dir.cpp: this header includes no platform header (Codex on #124: windows.h here +// pulled winsock.h in ahead of Winsock2 for every includer). +class server_owner_lock { +public: + server_owner_lock() = default; + server_owner_lock(const server_owner_lock &) = delete; + server_owner_lock & operator=(const server_owner_lock &) = delete; + ~server_owner_lock() { release(); } + + // true when this process now holds the lock on `path`. `create`: make the file (exclusively: it + // must not exist yet); otherwise open only an existing file, never creating a marker for anyone. + bool try_take(const std::filesystem::path & path, bool create); + void release(); + +private: + intptr_t handle = -1; // a POSIX descriptor or a Windows HANDLE; -1 = none +}; + +// This process's id (server-spill-dir.cpp). +uint64_t server_process_id(); + +// The instance directory's protocol. The marker is published before the directory and only while +// locked, so a sweeper can never see a live owner unlocked (Codex on #124: a claim raced a sweep): +// owner: create .owner.tmp exclusively, lock it, rename it to .owner (atomic; the lock +// stays on the open file), then create /; +// sweeper: for each final .owner (never a .tmp, never anything else), open it WITHOUT creating +// and try the lock; taken means its owner is gone: remove /, then the marker. A +// directory without a marker, a .tmp, or any other file is never touched. +class server_spill_dir { +public: + // Claims an instance directory under `base` and sweeps instances whose owner is gone. Returns the + // number swept; `ok()` says whether this instance holds its directory. + size_t claim(const std::filesystem::path & base, std::error_code & ec) { + std::filesystem::create_directories(base, ec); + if (ec) { + return 0; + } + const auto ns = std::chrono::steady_clock::now().time_since_epoch().count(); + const std::string name = "instance-" + std::to_string(server_process_id()) + "-" + std::to_string(ns); + const auto tmp = base / (name + ".owner.tmp"); + const auto marker = base / (name + ".owner"); + if (!owner.try_take(tmp, /*create=*/true)) { + return 0; + } + std::filesystem::rename(tmp, marker, ec); + if (ec) { + owner.release(); + std::error_code rm; + std::filesystem::remove(tmp, rm); + return 0; + } + dir = base / name; + std::filesystem::create_directories(dir, ec); + if (ec) { + owner.release(); + std::error_code rm; + std::filesystem::remove(marker, rm); + dir.clear(); + return 0; + } + owner_marker = marker; + // collect first: removing entries while iterating the same directory is unspecified + std::vector markers; + for (const auto & entry : std::filesystem::directory_iterator(base, ec)) { + markers.push_back(entry.path()); + } + size_t swept = 0; + for (const auto & path : markers) { + const auto file = path.filename().string(); + const std::string suffix = ".owner"; + if (file.rfind("instance-", 0) != 0 || file.size() <= suffix.size() || + file.compare(file.size() - suffix.size(), suffix.size(), suffix) != 0 || path == marker) { + continue; // only a final owner marker names an instance a sweeper may judge + } + server_owner_lock probe; + if (!probe.try_take(path, /*create=*/false)) { + continue; // a live owner holds it (or it vanished meanwhile) + } + const auto instance = base / file.substr(0, file.size() - suffix.size()); + std::error_code rm; + std::filesystem::remove_all(instance, rm); + if (!rm) { + std::filesystem::remove(path, rm); // the marker last: a crash in between is swept again + swept += rm ? 0 : 1; + } + } + return swept; + } + + bool ok() const { return !dir.empty(); } + const std::filesystem::path & path() const { return dir; } + + ~server_spill_dir() { + if (ok()) { + std::error_code ec; + std::filesystem::remove_all(dir, ec); // this instance's files leave with it + std::filesystem::remove(owner_marker, ec); + owner.release(); + } + } + +private: + std::filesystem::path dir; + std::filesystem::path owner_marker; + server_owner_lock owner; +}; + +// Length-prefixed blocks. `remaining` is the bytes left in the file; a length beyond it is refused +// before anything is allocated. +inline bool server_spill_write_block(FILE * f, const std::vector & data) { + const uint64_t n = data.size(); + return fwrite(&n, sizeof(n), 1, f) == 1 && (n == 0 || fwrite(data.data(), 1, n, f) == n); +} + +inline bool server_spill_read_block(FILE * f, std::vector & data, uint64_t & remaining) { + uint64_t n = 0; + if (remaining < sizeof(n) || fread(&n, sizeof(n), 1, f) != 1) { + return false; + } + remaining -= sizeof(n); + if (n > remaining) { + return false; // a corrupt or truncated file: refused, never sized from its own claim + } + data.resize(n); + if (n != 0 && fread(data.data(), 1, n, f) != n) { + return false; + } + remaining -= n; + return true; +} diff --git a/tools/server/server-task.cpp b/tools/server/server-task.cpp index e502d728cda1..299d6fadac65 100644 --- a/tools/server/server-task.cpp +++ b/tools/server/server-task.cpp @@ -1,4 +1,5 @@ #include "server-task.h" +#include "server-test-faults.h" #include "build-info.h" #include "server-chat.h" @@ -10,6 +11,11 @@ #include "speculative.h" #include "server-common.h" +#include +#include +#include +#include + #include // @@ -1747,7 +1753,9 @@ json learn_outcome::to_json() const { // server_prompt_cache // size_t server_prompt_cache::size() const { - size_t res = 0; + // resident bytes plus spills whose write has not landed (their entries' vectors are empty while the + // bytes sit in the write's buffer; an erased entry's in-flight bytes still count until it lands) + size_t res = (size_t) spill_in_flight->load(std::memory_order_relaxed); for (const auto & state : states) { res += state.size(); @@ -1756,17 +1764,292 @@ size_t server_prompt_cache::size() const { return res; } +size_t server_prompt_cache::disk_size() const { + size_t res = 0; + + for (const auto & state : states) { + res += state.spill_size; + } + + return res; +} + size_t server_prompt_cache::n_tokens() const { size_t res = 0; for (const auto & state : states) { - res += state.prompt.n_tokens(); + if (!state.spilled()) { + res += state.prompt.n_tokens(); + } } return res; } -server_prompt_cache_state * server_prompt_cache::alloc(const server_prompt & prompt, const lora_active_set & lora, size_t state_size_tgt, size_t state_size_dft) { +server_prompt_cache::~server_prompt_cache() = default; // spill_dir removes this instance's directory + +bool server_prompt_cache::set_disk(const std::string & dir, int32_t limit_mib, server_page_io_pool * pool, + server_page_admission * admission_, std::string io_gate_) { + std::error_code ec; + const size_t swept = spill_dir.claim(dir, ec); + if (!spill_dir.ok() || pool == nullptr || admission_ == nullptr) { + SRV_ERR("prompt cache disk tier: cannot claim an instance directory under %s: %s\n", dir.c_str(), + ec ? ec.message().c_str() : (pool ? "its owner lock is held" : "no page-io pool")); + return false; + } + disk_dir = spill_dir.path().string(); + io = pool; + admission = admission_; + io_gate = std::move(io_gate_); + disk_limit = 1024ull*1024ull*(limit_mib < 0 ? 0 : limit_mib); + SRV_INF("prompt cache disk tier: %s, size limit: %d MiB (%zu abandoned instance directories swept)\n", + disk_dir.c_str(), limit_mib, swept); + return true; +} + +bool server_prompt_cache::spill(server_prompt_cache_state & state) { + if (disk_dir.empty() || state.spilled()) { + return false; + } + const size_t bytes = state.size(); + if (disk_limit > 0 && bytes > disk_limit) { + return false; + } + while (disk_limit > 0 && disk_size() + bytes > disk_limit) { + auto oldest = std::find_if(states.begin(), states.end(), [](const server_prompt_cache_state & s) { return s.spilled(); }); + if (oldest == states.end()) { + break; + } + SRV_WRN(" - disk tier full, removing oldest spilled entry (size = %.3f MiB)\n", oldest->spill_size / (1024.0 * 1024.0)); + erase(oldest); + } + + // admitted against the one page-IO budget before anything moves, never parked: a spill that does not + // fit beside the bytes in flight is refused and the entry is dropped (as with no disk tier), so a slow + // or paused disk can never stack spills past the budget (Codex on #124) + if (!admission->try_admit(bytes)) { + SRV_WRN(" - disk tier: %.3f MiB does not fit the page-IO budget beside the bytes in flight; the entry is dropped\n", + bytes / (1024.0 * 1024.0)); + return false; + } + // the task loop only MOVES the bytes into the spill buffer; the file is written on the page-io pool + const std::string path = disk_dir + "/" + std::to_string(spill_seq++) + ".state"; + auto buf = std::make_shared(); + buf->reservation.hold(admission, bytes); + buf->counted = spill_in_flight; + buf->bytes = bytes; + spill_in_flight->fetch_add(bytes, std::memory_order_relaxed); + buf->blocks.reserve(2 + 3 * state.prompt.checkpoints.size()); + buf->blocks.push_back(std::move(state.data.main)); + buf->blocks.push_back(std::move(state.data.drft)); + for (auto & ckpt : state.prompt.checkpoints) { + buf->blocks.push_back(std::move(ckpt.data_tgt)); + buf->blocks.push_back(std::move(ckpt.data_dft)); + buf->blocks.push_back(std::move(ckpt.data_spec)); + } + state.data.main = {}; + state.data.drft = {}; + for (auto & ckpt : state.prompt.checkpoints) { + ckpt.data_tgt = {}; + ckpt.data_dft = {}; + ckpt.data_spec = {}; + } + state.spill_path = path; + state.spill_size = bytes; + state.spilling = buf; + + const int n_tokens = state.prompt.n_tokens(); + io->submit(path, [buf, path, bytes, n_tokens, gate = io_gate] { + if constexpr (server_test_faults::enabled) { + server_test_faults::hold(gate); // a test holds spill writes as it holds page IO + } + int expected = server_spill_buffer::queued; + if (!buf->status.compare_exchange_strong(expected, server_spill_buffer::writing, std::memory_order_acq_rel)) { + return; // claimed: the entry was restored before this write started; its blocks went back to it + } + const auto t0 = std::chrono::steady_clock::now(); + FILE * f = fopen(path.c_str(), "wb"); + bool ok = f != nullptr; + for (const auto & block : buf->blocks) { + ok = ok && server_spill_write_block(f, block); + } + ok = (f == nullptr || fclose(f) == 0) && ok; + if (!ok) { + std::error_code ec; + std::filesystem::remove(path, ec); + SRV_ERR("prompt cache disk tier: failed writing %s; the entry stays in RAM\n", path.c_str()); + } else { + const double ms = std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); + SRV_INF(" - spilled prompt cache entry to disk: %d tokens, %.3f MiB in %.1f ms (page-io pool)\n", + n_tokens, bytes / (1024.0 * 1024.0), ms); + } + buf->status.store(ok ? server_spill_buffer::written : server_spill_buffer::failed, std::memory_order_release); + // the bytes stay charged until the buffer itself is freed (its destructor): when this job lets + // go and the entry is reaped or erased, whichever is last + }); + return true; +} + +void server_prompt_cache::reap_spills() { + for (auto & state : states) { + if (!state.spilling) { + continue; + } + const int status = state.spilling->status.load(std::memory_order_acquire); + if (status == server_spill_buffer::written) { + state.spilling.reset(); // written: the RAM copy goes + } else if (status == server_spill_buffer::failed) { + // the write failed: the bytes come back and the entry stays resident + auto & blocks = state.spilling->blocks; + size_t b = 0; + state.data.main = std::move(blocks[b++]); + state.data.drft = std::move(blocks[b++]); + for (auto & ckpt : state.prompt.checkpoints) { + ckpt.data_tgt = std::move(blocks[b++]); + ckpt.data_dft = std::move(blocks[b++]); + ckpt.data_spec = std::move(blocks[b++]); + } + state.spilling.reset(); + state.spill_path.clear(); + state.spill_size = 0; + } + } +} + +bool server_prompt_cache::unspill(server_prompt_cache_state & state) { + if (!state.spilled()) { + return true; + } + const auto t0 = std::chrono::steady_clock::now(); + if (state.spilling) { + // its bytes are still in RAM, never read back from disk. A write not started yet is claimed and the + // blocks MOVE back (no copy; the worker skips the write). A write running or landed keeps its buffer + // (the worker may be reading it): load() applies the KV from it by reference, and only the + // checkpoints, which the slot must own, are copied (Codex on #124: no full deep copy). + auto & buf = *state.spilling; + int expected = server_spill_buffer::queued; + const bool took = buf.status.compare_exchange_strong(expected, server_spill_buffer::claimed, std::memory_order_acq_rel); + auto & blocks = buf.blocks; + size_t b = 2; // main and drft stay in the buffer unless taken + if (took) { + state.data.main = std::move(blocks[0]); + state.data.drft = std::move(blocks[1]); + } + for (auto & ckpt : state.prompt.checkpoints) { + if (took) { + ckpt.data_tgt = std::move(blocks[b++]); + ckpt.data_dft = std::move(blocks[b++]); + ckpt.data_spec = std::move(blocks[b++]); + } else { + ckpt.data_tgt = blocks[b++]; + ckpt.data_dft = blocks[b++]; + ckpt.data_spec = blocks[b++]; + } + } + if (took) { + state.spilling.reset(); // the moved-from buffer is empty; its charge is released with it + } + // else: load() reads main/drft from state.spilling and drops it after applying them + // the file is removed after its write, in order, on the pool + const std::string path = state.spill_path; + io->submit(path, [path] { std::error_code rm; std::filesystem::remove(path, rm); }); + const size_t bytes = state.spill_size; + state.spill_path.clear(); + state.spill_size = 0; + const double ms = std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); + SRV_INF(" - restored prompt cache entry from its in-flight spill: %d tokens, %.3f MiB in %.1f ms\n", + state.prompt.n_tokens(), bytes / (1024.0 * 1024.0), ms); + return true; + } + FILE * f = fopen(state.spill_path.c_str(), "rb"); + if (f == nullptr) { + SRV_ERR("prompt cache disk tier: cannot open %s\n", state.spill_path.c_str()); + return false; + } + // the file must be exactly what this instance admitted when it spilled: the state's bytes plus one + // 8-byte length per block; anything else is refused before a single block is read or allocated + // (Codex on #124: the file size alone could exceed the admitted state) + const uint64_t n_blocks = 2 + 3 * (uint64_t) state.prompt.checkpoints.size(); + const uint64_t expected = (uint64_t) state.spill_size + n_blocks * sizeof(uint64_t); + std::error_code size_ec; + const uint64_t file_bytes = std::filesystem::file_size(state.spill_path, size_ec); + uint64_t remaining = expected; + bool ok = !size_ec && file_bytes == expected && + server_spill_read_block(f, state.data.main, remaining) && server_spill_read_block(f, state.data.drft, remaining); + for (auto & ckpt : state.prompt.checkpoints) { + ok = ok && server_spill_read_block(f, ckpt.data_tgt, remaining) && server_spill_read_block(f, ckpt.data_dft, remaining) && + server_spill_read_block(f, ckpt.data_spec, remaining); + } + fclose(f); + if (!ok || remaining != 0) { + SRV_ERR("prompt cache disk tier: %s is corrupt or truncated; the entry is dropped\n", state.spill_path.c_str()); + return false; + } + std::error_code ec; + std::filesystem::remove(state.spill_path, ec); + const size_t bytes = state.spill_size; + state.spill_path.clear(); + state.spill_size = 0; + + const double ms = std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); + SRV_INF(" - restored prompt cache entry from disk: %d tokens, %.3f MiB in %.1f ms\n", + state.prompt.n_tokens(), bytes / (1024.0 * 1024.0), ms); + return true; +} + +std::list::iterator server_prompt_cache::erase(std::list::iterator it) { + if (it->spilled()) { + // ordered after any write of the same file on the pool, so a writer never recreates it + const std::string path = it->spill_path; + io->submit(path, [path] { std::error_code rm; std::filesystem::remove(path, rm); }); + } + return states.erase(it); +} + +bool server_prompt_cache::evict_oldest_resident() { + // a state larger than the whole RAM tier leaves first: it cannot stay, so evicting older + // states for it would only push them to disk as well + auto oldest = std::find_if(states.begin(), states.end(), [this](const server_prompt_cache_state & s) { + return !s.spilled() && &s != keep && limit_size > 0 && s.size() > limit_size; + }); + if (oldest == states.end()) { + oldest = std::find_if(states.begin(), states.end(), [this](const server_prompt_cache_state & s) { return !s.spilled() && &s != keep; }); + } + if (oldest == states.end()) { + return false; + } + if (spill(*oldest)) { + return true; + } + SRV_WRN(" - making room for prompt cache entry, removing oldest entry (size = %.3f MiB)\n", + oldest->size() / (1024.0 * 1024.0)); + erase(oldest); + return true; +} + +const server_prompt_cache_state * server_prompt_cache::leaving(const server_tokens & next, const lora_active_set & lora) const { + const server_prompt_cache_state * best = nullptr; + int lcp_best = 0; + for (const auto & s : states) { + if (s.lora != lora || s.prompt.tokens.size() == 0) { + continue; + } + const int lcp = s.prompt.tokens.get_common_prefix(next); + if (float(lcp) / s.prompt.tokens.size() >= 0.25f && lcp > lcp_best) { // load()'s "don't trash" floor + lcp_best = lcp; + best = &s; + } + } + return best; +} + +server_prompt_cache_state * server_prompt_cache::alloc(const server_prompt & prompt, const lora_active_set & lora, size_t state_size_tgt, size_t state_size_dft, + const server_tokens * next, const lora_active_set * next_lora) { + reap_spills(); + // the resident the incoming request is about to load: evicting it to make room for this save would push + // the very mind arriving to disk and refuse the one leaving (two minds, a tier that holds one) + keep = next != nullptr && next_lora != nullptr ? leaving(*next, *next_lora) : nullptr; + struct keep_reset { const server_prompt_cache_state *& k; ~keep_reset() { k = nullptr; } } keep_reset_ { keep }; // first check if the current state is contained fully in the cache for (auto it = states.begin(); it != states.end(); ++it) { if (it->lora != lora) { @@ -1788,8 +2071,10 @@ server_prompt_cache_state * server_prompt_cache::alloc(const server_prompt & pro const size_t state_size_new = state_size_tgt + state_size_dft + checkpoints_size; - // skip over-limit entries to avoid disturbing the cache - if (limit_size > 0 && state_size_new > limit_size) { + // skip over-limit entries to avoid disturbing the cache; with a disk tier that can hold it, + // the entry is taken and `update` spills it once the caller has filled it + const bool disk_holds = !disk_dir.empty() && (disk_limit == 0 || state_size_new <= disk_limit); + if (limit_size > 0 && state_size_new > limit_size && !disk_holds) { SRV_WRN(" - prompt state size %.3f MiB exceeds cache size limit %.3f MiB, skipping\n", state_size_new / (1024.0 * 1024.0), limit_size / (1024.0 * 1024.0)); return nullptr; @@ -1802,19 +2087,27 @@ server_prompt_cache_state * server_prompt_cache::alloc(const server_prompt & pro if (it->lora == lora && len == (int) it->prompt.tokens.size()) { SRV_TRC(" - removing obsolete cached prompt with length %d\n", len); - it = states.erase(it); + it = erase(it); } else { ++it; } } if (limit_size > 0) { - // make room before allocating the new vectors to avoid breaching the limit - while (!states.empty() && size() + state_size_new > limit_size) { - SRV_WRN(" - making room for prompt cache entry, removing oldest entry (size = %.3f MiB)\n", - states.front().size() / (1024.0 * 1024.0)); - - states.pop_front(); + // make room before allocating the new vectors to avoid breaching the limit; an entry + // larger than the whole RAM tier goes to disk itself in `update`, displacing nothing + // The protected entry leaves with the load that follows this save (update() restores the cap right + // after if it does not), so it counts as gone: the swap holds both for that moment, bounded by one entry. + const size_t room_needed = state_size_new > limit_size ? 0 : state_size_new; + auto kept = [this] { return keep != nullptr ? keep->size() : 0; }; + while (size() - kept() + room_needed > limit_size && evict_oldest_resident()) { + } + // every other resident evicted and still over: bytes in flight to disk hold the rest, so this entry is + // not cached rather than breaching the cap (Codex on #124: cap 100, 80 in flight, a new 50) + if (size() - kept() + room_needed > limit_size) { + SRV_WRN(" - prompt state of %.3f MiB not cached: %.3f MiB in flight to disk leave no room under the %.3f MiB limit\n", + state_size_new / (1024.0 * 1024.0), size() / (1024.0 * 1024.0), limit_size / (1024.0 * 1024.0)); + return nullptr; } } @@ -1847,23 +2140,26 @@ server_prompt_cache_state * server_prompt_cache::alloc(const server_prompt & pro /*.drft =*/ std::move(state_data_dft), }, /*.lora =*/ lora, + /*.spill_path =*/ {}, // resident in RAM until the disk tier spills it + /*.spill_size =*/ 0, + /*.spilling =*/ nullptr, }); return &states.back(); } void server_prompt_cache::evict_lora(const llama_adapter_lora * adapter) { - states.remove_if([adapter](const server_prompt_cache_state & state) { - for (const auto & [ptr, scale] : state.lora) { - if (ptr == adapter) { - return true; - } + for (auto it = states.begin(); it != states.end();) { + bool uses = false; + for (const auto & [ptr, scale] : it->lora) { + uses = uses || ptr == adapter; } - return false; - }); + it = uses ? erase(it) : std::next(it); + } } bool server_prompt_cache::load(server_prompt & prompt, const lora_active_set & lora, const server_tokens & tokens_new, llama_context * ctx_tgt, llama_context * ctx_dft, int32_t id_slot) { + reap_spills(); const int lcp_best = prompt.tokens.get_common_prefix(tokens_new); float f_keep_best = prompt.tokens.size() > 0 ? float(lcp_best) / prompt.tokens.size() : -1.0f; // empty slot: any cache entry wins @@ -1901,8 +2197,16 @@ bool server_prompt_cache::load(server_prompt & prompt, const lora_active_set & l if (it_best != states.end()) { SRV_TRC(" - found better prompt with f_keep = %.3f, f_sim = %.3f\n", f_keep_best, f_sim_best); + if (!unspill(*it_best)) { + erase(it_best); + return false; + } + + // the KV comes from the entry's own vectors, or by reference from its in-flight spill's buffer + const auto & src_main = it_best->spilling ? it_best->spilling->blocks[0] : it_best->data.main; + const auto & src_drft = it_best->spilling ? it_best->spilling->blocks[1] : it_best->data.drft; { - auto & data = it_best->data.main; + const auto & data = src_main; const size_t size = data.size(); const size_t n = llama_state_seq_set_data_ext(ctx_tgt, data.data(), size, id_slot, 0); @@ -1911,13 +2215,10 @@ bool server_prompt_cache::load(server_prompt & prompt, const lora_active_set & l return false; } - - data.clear(); - data.shrink_to_fit(); } { - auto & data = it_best->data.drft; + const auto & data = src_drft; if (!data.empty()) { GGML_ASSERT(ctx_dft); @@ -1929,11 +2230,11 @@ bool server_prompt_cache::load(server_prompt & prompt, const lora_active_set & l return false; } - - data.clear(); - data.shrink_to_fit(); } } + std::vector().swap(it_best->data.main); + std::vector().swap(it_best->data.drft); + it_best->spilling.reset(); // applied: the write (if running) keeps the buffer alive until it finishes prompt = std::move(it_best->prompt); @@ -1944,11 +2245,9 @@ bool server_prompt_cache::load(server_prompt & prompt, const lora_active_set & l } void server_prompt_cache::update() { + reap_spills(); if (limit_size > 0) { - while (!states.empty() && size() > limit_size) { - SRV_WRN(" - cache size limit reached, removing oldest entry (size = %.3f MiB)\n", states.front().size() / (1024.0 * 1024.0)); - - states.pop_front(); + while (size() > limit_size && evict_oldest_resident()) { } } @@ -1959,16 +2258,13 @@ void server_prompt_cache::update() { const size_t limit_tokens_cur = limit_size > 0 ? std::max(limit_tokens, limit_size/size_per_token) : limit_tokens; if (limit_tokens > 0) { - while (!states.empty() && n_tokens() > limit_tokens_cur) { - SRV_WRN(" - cache token limit (%zu, est: %zu) reached, removing oldest entry (size = %.3f MiB)\n", - limit_tokens, limit_tokens_cur, states.front().size() / (1024.0 * 1024.0)); - - states.pop_front(); + while (n_tokens() > limit_tokens_cur && evict_oldest_resident()) { } } - SRV_TRC(" - cache state: %zu prompts, %.3f MiB (limits: %.3f MiB, %zu tokens, %zu est)\n", - states.size(), size() / (1024.0 * 1024.0), limit_size / (1024.0 * 1024.0), limit_tokens, limit_tokens_cur); + SRV_TRC(" - cache state: %zu prompts, %.3f MiB in RAM, %.3f MiB on disk (limits: %.3f MiB, %.3f MiB on disk, %zu tokens, %zu est)\n", + states.size(), size() / (1024.0 * 1024.0), disk_size() / (1024.0 * 1024.0), limit_size / (1024.0 * 1024.0), + disk_limit / (1024.0 * 1024.0), limit_tokens, limit_tokens_cur); for (const auto & state : states) { SRV_TRC(" - prompt %p: %7d tokens, checkpoints: %2zu, %9.3f MiB\n", diff --git a/tools/server/server-task.h b/tools/server/server-task.h index c757135afcc0..ec3605e9231e 100644 --- a/tools/server/server-task.h +++ b/tools/server/server-task.h @@ -9,9 +9,12 @@ #include #include #include +#include // TODO: prevent including the whole server-common.h as we only use server_tokens #include "server-common.h" +#include "server-page-io.h" +#include "server-spill-dir.h" struct server_page_job; // server-page-job.h: one page switch between the task loop and its file IO @@ -773,6 +776,36 @@ struct server_prompt_data { } }; +// A spill in flight: the state's bytes in file order (sequence state main, draft; then each checkpoint's +// target, draft, speculative). `status`: 0 writing, 1 written, -1 failed. +struct server_spill_buffer { + // status: queued -> writing -> written | failed; or queued -> claimed (the entry was restored before its + // write started: the loop took the blocks back by move and the worker skips the write) + enum : int { queued = 0, written = 1, failed = -1, writing = 2, claimed = 3 }; + std::vector> blocks; + std::atomic status{queued}; + // Its bytes stay charged (to the one page-IO budget and to the RAM tier's count) for exactly as long + // as they exist: released here, when the last owner (the write, or the entry until it is reaped or + // erased) lets the buffer go, never at the write's completion while the bytes are still in RAM + // (Codex on #124). + server_page_reservation reservation; + std::shared_ptr> counted; + uint64_t bytes = 0; + + server_spill_buffer() = default; + server_spill_buffer(const server_spill_buffer &) = delete; + server_spill_buffer & operator=(const server_spill_buffer &) = delete; + ~server_spill_buffer() { + // the bytes are freed first: a release can admit queued page IO, which must find the RAM already free + // (Codex on #124) + std::vector>().swap(blocks); + reservation.release(); + if (counted) { + counted->fetch_sub(bytes, std::memory_order_relaxed); + } + } +}; + struct server_prompt_cache_state { server_prompt prompt; server_prompt_data data; @@ -780,6 +813,21 @@ struct server_prompt_cache_state { // the adapters the state was computed under; restored only into the same set lora_active_set lora; + // set while the state's bytes (its sequence state and its checkpoints' data) live in this + // file instead of RAM; its tokens and checkpoint positions stay in RAM, so a lookup still + // matches it without touching the disk + std::string spill_path; + size_t spill_size = 0; + + // while its file is being written on the page-io pool: the bytes, moved out of this state (never + // copied), read by the write and by a lookup that matches before the write lands + std::shared_ptr spilling; + + bool spilled() const { + return !spill_path.empty(); + } + + // bytes held in RAM: a spilled state holds none size_t size() const { size_t res = data.size(); @@ -805,11 +853,66 @@ struct server_prompt_cache { // in tokens, 0 = no limit size_t limit_tokens = 0; + // the disk tier: when set, a state evicted from RAM is written here instead of dropped, and + // a lookup that matches it reads it back; empty = no disk tier + std::string disk_dir; + + // in bytes, 0 = no limit + size_t disk_limit = 0; + + uint64_t spill_seq = 0; + + // this instance's directory under the configured one (server-spill-dir.h: another engine's files are + // never touched), and the pool its files are written on (the task loop only moves the bytes) + server_spill_dir spill_dir; + server_page_io_pool * io = nullptr; + server_page_admission * admission = nullptr; + // RAM still held by spills whose write has not landed, entries erased meanwhile included: the + // RAM tier counts it (size()) so eviction never believes it free early (Codex on #124) + std::shared_ptr> spill_in_flight = std::make_shared>(0); + // a test hook: the page-IO gate (server-test-faults.h), so a test pauses spill writes like page IO + std::string io_gate; + + ~server_prompt_cache(); + + // enable the disk tier under `dir` (this instance's own directory; instance directories whose owner + // is gone are swept), writing on `pool` + bool set_disk(const std::string & dir, int32_t limit_mib, server_page_io_pool * pool, server_page_admission * admission, + std::string io_gate); + + // on the task loop: drop the bytes of spills whose write landed, and keep resident the ones whose + // write failed + void reap_spills(); + + // bytes held in RAM, by resident states only size_t size() const; + // bytes held on disk, by spilled states + size_t disk_size() const; + + // tokens of the resident states (the RAM tier's token limit) size_t n_tokens() const; - server_prompt_cache_state * alloc(const server_prompt & prompt, const lora_active_set & lora, size_t state_size_main, size_t state_size_drft); + // move the state's bytes to a file; false leaves it resident + bool spill(server_prompt_cache_state & state); + + // read a spilled state's bytes back into RAM and remove its file + bool unspill(server_prompt_cache_state & state); + + // the resident the incoming request will load (load()'s own choice, by the same cheap prefix test) + const server_prompt_cache_state * leaving(const server_tokens & next, const lora_active_set & lora) const; + const server_prompt_cache_state * keep = nullptr; // set only for the duration of one alloc + + // remove a state, and its file if it has one + std::list::iterator erase(std::list::iterator it); + + // make room in RAM: the oldest resident state goes to disk, or is dropped without a disk tier + bool evict_oldest_resident(); + + // `next`: the tokens of the request about to load from this cache (nullptr when none). The resident that + // request will take is never evicted to make room for this save: it is leaving the cache anyway. + server_prompt_cache_state * alloc(const server_prompt & prompt, const lora_active_set & lora, size_t state_size_main, size_t state_size_drft, + const server_tokens * next = nullptr, const lora_active_set * next_lora = nullptr); bool load(server_prompt & prompt, const lora_active_set & lora, const server_tokens & tokens_new, llama_context * ctx_tgt, llama_context * ctx_dft, int32_t id_slot);