diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 51d135ab9a1b..c23333b44458 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -182,6 +182,8 @@ endif () llama_build(test-recurrent-state-rollback.cpp) llama_build_and_test(test-sampler-penalties.cpp) +llama_build(test-server-lanes.cpp) # needs -m : laned sampling picks the serial tokens; the step's us serial vs laned +target_compile_features(test-server-lanes PRIVATE cxx_std_20) llama_build(test-sampler-coarse.cpp) # needs -m : ballpark sampling picks exactly the full path's token llama_build_and_test(test-server-view-end.cpp) diff --git a/tests/test-server-lanes.cpp b/tests/test-server-lanes.cpp new file mode 100644 index 000000000000..42f8ee6fb651 --- /dev/null +++ b/tests/test-server-lanes.cpp @@ -0,0 +1,184 @@ +// what this catches: sampling one step's sequences on the lanes (server-lanes.h, CONTINUUM-ENGINE 4.7.14) +// choosing a different token than sampling them one after another, a lane run that loses or repeats a +// job, a job exception that does not reach the caller; and it reports the step's sampling time serial vs +// laned on real logits (needs -m ; the receipt is the per-step microseconds it prints). +#include "../tools/server/server-lanes.h" + +#include "arg.h" +#include "common.h" +#include "llama.h" +#include "sampling.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static void require(bool condition, const char * message) { + if (!condition) { + std::fprintf(stderr, "FAILED: %s\n", message); + std::exit(1); + } +} + +static double now_us() { + return std::chrono::duration(std::chrono::steady_clock::now().time_since_epoch()).count(); +} + +// the lanes alone: every job once, any count, exceptions carried back +static void lanes_run_every_job_once() { + server_lanes lanes(5); + for (size_t n : { (size_t) 1, (size_t) 2, (size_t) 6, (size_t) 64, (size_t) 1000 }) { + for (int rep = 0; rep < 200; ++rep) { + std::vector> hits(n); + lanes.run(n, [&](size_t i) { hits[i].fetch_add(1, std::memory_order_relaxed); }); + for (auto & h : hits) { + require(h.load() == 1, "every job runs exactly once"); + } + } + } + bool caught = false; + try { + lanes.run(6, [](size_t i) { if (i == 3) { throw std::runtime_error("job 3"); } }); + } catch (const std::runtime_error & e) { + caught = std::string(e.what()) == "job 3"; + } + require(caught, "a job's exception reaches the caller"); + std::atomic after{0}; + lanes.run(6, [&](size_t) { after++; }); + require(after.load() == 6, "the lanes run normally after a failed run"); +} + +// regressions for Codex's review of #125: a stop signalled before a lane's first wait was missed (the +// join hung); and a lane holding an earlier run's claim word could claim against the next run's jobs +static void lanes_never_hang_and_never_cross_runs() { + for (int i = 0; i < 2000; ++i) { + server_lanes lanes(5); // destroyed at once: a lane may not have reached its first wait yet + } + server_lanes lanes(5); + std::vector> hits(8); + for (int run = 0; run < 50000; ++run) { + const size_t n = 2 + (size_t) (run % 6); + for (size_t i = 0; i < n; ++i) { + hits[i].store(0, std::memory_order_relaxed); + } + lanes.run(n, [&](size_t i) { hits[i].fetch_add(1, std::memory_order_relaxed); }); + for (size_t i = 0; i < n; ++i) { + require(hits[i].load() == 1, "back to back, every job of every run runs exactly once"); + } + } +} + +// what this catches: a lane thread that fails to start after others did destroyed joinable threads +// (std::terminate); the started lanes must be stopped and joined and the error reach the caller +static void lanes_failed_start_joins_the_started() { + size_t started = 0; + bool threw = false; + try { + server_lanes lanes(4, [&](std::function f) { + if (started == 2) { + throw std::system_error(std::make_error_code(std::errc::resource_unavailable_try_again)); + } + ++started; + return std::thread(std::move(f)); + }); + } catch (const std::system_error &) { + threw = true; + } + require(threw && started == 2, "a failed lane start reaches the caller after the started lanes are joined"); +} + +int main(int argc, char ** argv) { + lanes_failed_start_joins_the_started(); + lanes_run_every_job_once(); + lanes_never_hang_and_never_cross_runs(); + + common_params params; + if (!common_params_parse(argc, argv, params, LLAMA_EXAMPLE_COMMON)) { + return 1; + } + const int n_seq = 6; + params.n_parallel = n_seq; + params.kv_unified = true; + common_init(); + llama_backend_init(); + auto init = common_init_from_params(params); + llama_model * model = init->model(); + llama_context * ctx = init->context(); + require(model && ctx, "model loads"); + const llama_vocab * vocab = llama_model_get_vocab(model); + + // one decode of six sequences, one output row each: the shape of a serving step + const char * topics[n_seq] = { "the ledger", "a merge queue", "a kv cache", "the grid", "a resident", "a checkpoint" }; + llama_batch batch = llama_batch_init(512, 0, n_seq); + std::vector out_idx(n_seq); + for (int s = 0; s < n_seq; ++s) { + const auto toks = common_tokenize(vocab, std::string("Write about ") + topics[s] + ".", true, true); + for (size_t i = 0; i < toks.size(); ++i) { + const bool last = i + 1 == toks.size(); + if (last) { + out_idx[s] = batch.n_tokens; + } + common_batch_add(batch, toks[i], (llama_pos) i, { s }, last); + } + } + require(llama_decode(ctx, batch) == 0, "decode"); + + common_params_sampling sp; + sp.top_k = 40; + sp.penalty_last_n = 256; + sp.penalty_repeat = 1.1f; + std::vector base(n_seq); + for (int s = 0; s < n_seq; ++s) { + base[s] = common_sampler_init(model, sp); + } + std::vector rows(n_seq); + for (int s = 0; s < n_seq; ++s) { + rows[s] = common_sampler_row_ith(ctx, out_idx[s]); + } + + server_lanes lanes(n_seq - 1); + const int reps = 400; + double t_serial = 0, t_laned = 0; + std::vector a(n_seq), b(n_seq); + for (int rep = 0; rep < reps; ++rep) { + std::vector s1(n_seq), s2(n_seq); + for (int s = 0; s < n_seq; ++s) { + s1[s] = common_sampler_clone(base[s]); + s2[s] = common_sampler_clone(base[s]); + } + // alternate which goes first, so neither always meets a warm or cold cache + auto serial = [&] { + const double t0 = now_us(); + for (int s = 0; s < n_seq; ++s) { + a[s] = common_sampler_sample_row(s1[s], rows[s]); + } + t_serial += now_us() - t0; + }; + auto laned = [&] { + const double t0 = now_us(); + lanes.run(n_seq, [&](size_t s) { b[s] = common_sampler_sample_row(s2[s], rows[s]); }); + t_laned += now_us() - t0; + }; + if (rep % 2 == 0) { serial(); laned(); } else { laned(); serial(); } + for (int s = 0; s < n_seq; ++s) { + require(a[s] == b[s], "a laned sample picks exactly the serial token"); + common_sampler_free(s1[s]); + common_sampler_free(s2[s]); + } + } + std::printf("one step, %d sequences, %d reps: serial %.1f us/step, laned (%zu lanes) %.1f us/step, %.2fx\n", + n_seq, reps, t_serial / reps, lanes.size(), t_laned / reps, t_serial / t_laned); + + for (auto * s : base) { + common_sampler_free(s); + } + llama_batch_free(batch); + std::printf("test-server-lanes: ok\n"); + return 0; +} diff --git a/tools/server/CMakeLists.txt b/tools/server/CMakeLists.txt index 67fb03964d7c..e19fa5847231 100644 --- a/tools/server/CMakeLists.txt +++ b/tools/server/CMakeLists.txt @@ -33,6 +33,9 @@ endif() target_include_directories(${TARGET} PRIVATE ../mtmd) target_include_directories(${TARGET} PRIVATE ${CMAKE_SOURCE_DIR}) target_link_libraries(${TARGET} PUBLIC llama-common mtmd ${CMAKE_THREAD_LIBS_INIT}) +# Continuum fork: the server is C++20 (atomic wait/notify for the sampling lanes, CONTINUUM-ENGINE 4.7.14); +# PUBLIC so every target that includes the server's headers compiles them as written +target_compile_features(${TARGET} PUBLIC cxx_std_20) # the faults tools/server/tests inject (server-test-faults.h); only the server test build sets it option(LLAMA_SERVER_TEST_FAULTS "llama-server: compile in the test fault injection (tests only, never a release)" OFF) @@ -69,4 +72,4 @@ add_executable(${TARGET} main.cpp) install(TARGETS ${TARGET} RUNTIME) target_link_libraries(${TARGET} PRIVATE llama-server-impl) -target_compile_features(${TARGET} PRIVATE cxx_std_17) +target_compile_features(${TARGET} PRIVATE cxx_std_20) diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index 1745c8cca2c2..bb8495f89420 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -1,5 +1,6 @@ #include #include "server-context.h" +#include "server-lanes.h" #include "server-view-end.h" #include "../../src/llama-ext.h" #include "server-train.h" @@ -376,6 +377,14 @@ struct server_slot { common_sampler_ptr smpl; + // Continuum fork (CONTINUUM-ENGINE 4.7.14): this step's sample, made on a lane before the loop that + // emits it; a sampling error is carried here and raised in this slot's own step + bool presampled = false; + llama_token presampled_id = LLAMA_TOKEN_NULL; + common_sampler_ptr presampled_save; // the speculative save point, cloned before the verify + std::vector presampled_accepted; // the speculative verify's accepted tokens + std::string presample_error; + llama_token sampled; // in speculative mode, this is the last accepted token // for TTS models, this is the embd generated from prev step, decode this to generate next hidden state @@ -985,6 +994,10 @@ struct server_context_impl { // whether any configured drafter reads the prompt's tokens (the n-gram family); set at load bool spec_reads_prompt = false; + // the lanes one step's slots sample on at once (CONTINUUM-ENGINE 4.7.14); sized at load from the + // slot count and the cores the OS reports, never more lanes than slots + std::unique_ptr sample_lanes; + common_init_result_ptr llama_init; llama_context * ctx_tgt = nullptr; @@ -1420,6 +1433,12 @@ struct server_context_impl { n_swa = params_base.swa_full ? 0 : llama_model_n_swa(model_tgt); + { + const size_t cores = std::max(1, std::thread::hardware_concurrency()); + const size_t workers = std::min(params_base.n_parallel > 1 ? params_base.n_parallel - 1 : 0, cores - 1); + sample_lanes = std::make_unique(workers); + } + spec_reads_prompt = std::any_of(params_base.speculative.types.begin(), params_base.speculative.types.end(), [](common_speculative_type t) { return t == COMMON_SPECULATIVE_TYPE_NGRAM_SIMPLE || t == COMMON_SPECULATIVE_TYPE_NGRAM_MAP_K || @@ -4367,6 +4386,71 @@ struct server_context_impl { return true; } + // Continuum fork (CONTINUUM-ENGINE 4.7.14): every slot that samples in this view samples at once. + // Gather on this thread (one synchronize; a row is raw pointers into the context's outputs, so + // sampling from it never calls into the context), sample on the lanes (each slot's sampler is its + // own state), and the loops in post_decode then emit in slot order exactly as before. Same tokens: + // each sampler sees the same rows and its own RNG in the same order. + void presample(int32_t off, int32_t n_batch_tokens) { + auto inside = [&](int32_t idx) { return idx >= off && idx < off + n_batch_tokens; }; + struct sample_job { + server_slot * slot; + bool verify; // speculative verify (MTP), else one plain sample + std::vector rows; + }; + std::vector jobs; + for (auto & slot : slots) { + slot.presampled = false; + slot.presample_error.clear(); + if (!slot.task) { + continue; + } + const bool drafting = slot.can_speculate() && !slot.spec_draft.empty(); + if (slot.state == SLOT_STATE_GENERATING && drafting && !slot.spec_i_batch.empty()) { + GGML_ASSERT(slot.spec_i_batch.size() == slot.spec_draft.size() + 1); + jobs.push_back({ &slot, true, {} }); + continue; + } + if (!inside(slot.i_batch) || drafting) { + continue; + } + const bool done_prompt = slot.state == SLOT_STATE_DONE_PROMPT && + slot.task->type != SERVER_TASK_TYPE_EMBEDDING && slot.task->type != SERVER_TASK_TYPE_RERANK; + if (slot.state == SLOT_STATE_GENERATING || done_prompt) { + jobs.push_back({ &slot, false, {} }); + } + } + if (jobs.empty()) { + return; + } + for (auto & job : jobs) { + if (job.verify) { + for (const int idx : job.slot->spec_i_batch) { + job.rows.push_back(common_sampler_row_ith(ctx_tgt, idx)); + } + } else { + job.rows.push_back(common_sampler_row_ith(ctx_tgt, job.slot->i_batch - off)); + } + } + scoped_timer timer(t_sampl, n_sampl); + sample_lanes->run(jobs.size(), [&](size_t j) { + auto & job = jobs[j]; + auto & slot = *job.slot; + try { + if (job.verify) { + slot.presampled_save.reset(common_sampler_clone(slot.smpl.get())); + slot.presampled_accepted = common_sampler_sample_and_accept_rows(slot.smpl.get(), job.rows, slot.spec_draft); + } else { + slot.presampled_id = common_sampler_sample_row(slot.smpl.get(), job.rows[0]); + common_sampler_accept(slot.smpl.get(), slot.presampled_id, true); + } + slot.presampled = true; + } catch (const std::exception & e) { + slot.presample_error = e.what(); // raised in this slot's own step, as the serial path did + } + }); + } + void post_decode(int32_t n_batch_tokens, int32_t off, llama_batch & batch_view) { // for checking if a given batch index is inside batch_view auto is_inside_view = [&](int32_t idx) { @@ -4383,6 +4467,8 @@ struct server_context_impl { } }); + presample(off, n_batch_tokens); + auto accept_special_token = [&](server_slot & slot, llama_token token) { return params_base.special || slot.task->params.sampling.preserved_tokens.find(token) != slot.task->params.sampling.preserved_tokens.end(); @@ -4436,16 +4522,16 @@ struct server_context_impl { // shifted according to the current sub-batch const int tok_idx = slot.i_batch - off; - llama_token id; - { - scoped_timer timer(t_sampl, n_sampl); - id = common_sampler_sample(slot.smpl.get(), slot.ctx_tgt, tok_idx); + // sampled and accepted on a lane by presample(); the predicate there mirrors this loop + if (!slot.presample_error.empty()) { + throw std::runtime_error(std::exchange(slot.presample_error, {})); } + GGML_ASSERT(slot.presampled && "presample() must cover every slot this loop samples"); + const llama_token id = slot.presampled_id; + slot.presampled = false; slot.i_batch = -1; - common_sampler_accept(slot.smpl.get(), id, true); - // here we have synchronized the llama_context (due to the sampling above), so we can do time measurement const int64_t t_now = ggml_time_us(); @@ -4498,10 +4584,14 @@ struct server_context_impl { // verify and try to accept the draft { - common_sampler_ptr smpl_save(common_sampler_clone(slot.smpl.get())); - - GGML_ASSERT(slot.spec_i_batch.size() == n_draft + 1); - auto accepted = common_sampler_sample_and_accept_n(slot.smpl.get(), slot.ctx_tgt, slot.spec_i_batch, slot.spec_draft); + // cloned, verified and accepted on a lane by presample() + if (!slot.presample_error.empty()) { + throw std::runtime_error(std::exchange(slot.presample_error, {})); + } + GGML_ASSERT(slot.presampled && "presample() must cover every slot this loop verifies"); + slot.presampled = false; + common_sampler_ptr smpl_save = std::move(slot.presampled_save); + auto accepted = std::move(slot.presampled_accepted); slot.spec_i_batch.clear(); GGML_ASSERT(accepted.size() >= 1); diff --git a/tools/server/server-lanes.h b/tools/server/server-lanes.h new file mode 100644 index 000000000000..21398ac17c8f --- /dev/null +++ b/tools/server/server-lanes.h @@ -0,0 +1,183 @@ +#pragma once + +// Continuum fork: a fixed set of lanes that run one step's independent jobs at once (CONTINUUM-ENGINE +// 4.7.14). Built for jobs of tens to hundreds of microseconds, every few milliseconds: +// - a job is claimed lock-free from one 64-bit word (run id << 32 | next index), so a lane finishing an +// earlier run can never claim in a new one; +// - each lane has its own wake word: a run wakes only as many lanes as it has jobs beyond the caller's, +// with an atomic notify (a futex: __ulock on macOS), never a mutex and condition variable; +// - the caller is a lane and never sleeps: it runs jobs, then spins on the done count for the last few +// microseconds of the slowest lane (no syscall, no core clocking down before the next GPU submit); +// - an idle lane sleeps on its wake word and burns nothing. +// A job's exception is carried back to the caller. + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(__APPLE__) +#include +#endif + +// The one OS-specific line: lanes run where the step's latency is decided (macOS: performance cores). +inline void server_lane_priority() { +#if defined(__APPLE__) + pthread_set_qos_class_self_np(QOS_CLASS_USER_INTERACTIVE, 0); +#endif +} + +class server_lanes { +public: + // `spawn` starts one lane's thread (std::thread by default; a test injects a failure). If starting any + // lane throws, the lanes already started are stopped and joined before the exception leaves, so no + // joinable std::thread is ever destroyed (Codex on #129: that is std::terminate). + using spawn_fn = std::function)>; + + explicit server_lanes(size_t n_workers, const spawn_fn & spawn = [](std::function f) { return std::thread(std::move(f)); }) + : lanes(n_workers) { + try { + for (size_t i = 0; i < n_workers; ++i) { + lanes[i].thread = spawn([this, i] { work(lanes[i]); }); + } + } catch (...) { + shutdown(); + throw; + } + } + + server_lanes(const server_lanes &) = delete; + server_lanes & operator=(const server_lanes &) = delete; + + ~server_lanes() { shutdown(); } + + size_t size() const { return lanes.size() + 1; } + + // Run fn(i) for every i in [0, n) across the caller and up to n - 1 lanes; return when all have run. + // The first job exception is rethrown here. + void run(size_t n, const std::function & fn) { + if (n == 0) { + return; + } + const size_t helpers = std::min(n - 1, lanes.size()); + if (helpers == 0) { + for (size_t i = 0; i < n; ++i) { + fn(i); + } + return; + } + done.store(0, std::memory_order_relaxed); + failure = nullptr; + // one immutable record per run, published BEFORE the run's claim word: a lane claims only when the + // word's run id matches the record's, so a word from an earlier run can never pair with this + // run's jobs or bounds (Codex on #125) + run_record & rec = runs[++run_id % 2]; + rec.fn.store(&fn, std::memory_order_relaxed); + rec.n.store(n, std::memory_order_relaxed); + rec.id.store(run_id, std::memory_order_release); + record.store(&rec, std::memory_order_release); + next.store(run_id << 32, std::memory_order_release); + for (size_t i = 0; i < helpers; ++i) { + lanes[i].wake.fetch_add(1, std::memory_order_release); + lanes[i].wake.notify_one(); + } + take(); + while (done.load(std::memory_order_acquire) != n) { + std::this_thread::yield(); // the slowest lane's last microseconds; the caller never sleeps + } + if (failure) { + std::rethrow_exception(failure); + } + } + +private: + // stop every started lane, wake it, and join it; lanes never started have no thread + void shutdown() { + stop.store(true, std::memory_order_release); + for (auto & lane : lanes) { + lane.wake.fetch_add(1, std::memory_order_release); + lane.wake.notify_one(); + } + for (auto & lane : lanes) { + if (lane.thread.joinable()) { + lane.thread.join(); + } + } + } + + struct lane { + std::thread thread; + std::atomic wake{0}; + }; + + // claim and run the current run's jobs until none are left + void take() { + uint64_t claim = next.load(std::memory_order_acquire); + while (true) { + // read after the claim word: a word of run r implies run r's record is published (it was + // stored first, with release), so a mismatch can only mean the word is stale + const run_record * run = record.load(std::memory_order_acquire); + const size_t i = (size_t) (claim & 0xffffffffu); + if (run == nullptr || (claim >> 32) != run->id.load(std::memory_order_acquire) || + i >= run->n.load(std::memory_order_relaxed)) { + return; // no run, a stale word, or this run's jobs are all claimed + } + if (!next.compare_exchange_weak(claim, claim + 1, std::memory_order_acq_rel, std::memory_order_acquire)) { + continue; // another lane claimed it, or a new run began: `claim` holds the current word + } + try { + (*run->fn.load(std::memory_order_relaxed))(i); + } catch (...) { + std::lock_guard lock(failure_mutex); + if (!failure) { + failure = std::current_exception(); + } + } + done.fetch_add(1, std::memory_order_acq_rel); + claim = next.load(std::memory_order_acquire); + } + } + + void work(lane & self) { + server_lane_priority(); + // from 0, never from a load at start: a wake (or the destructor's) that came before this thread + // ran is still seen; and stop is checked before every sleep (Codex on #125: a stop signalled before + // the first wait was missed, and the join hung) + uint64_t seen = 0; + while (true) { + if (stop.load(std::memory_order_acquire)) { + return; + } + self.wake.wait(seen, std::memory_order_acquire); + seen = self.wake.load(std::memory_order_acquire); + if (stop.load(std::memory_order_acquire)) { + return; + } + take(); + } + } + + std::vector lanes; + std::atomic stop{false}; + std::atomic next{0}; + uint64_t run_id = 0; // the caller's only + std::atomic done{0}; + struct run_record { + std::atomic id{0}; + std::atomic *> fn{nullptr}; + std::atomic n{0}; + }; + // two records alternate. A record is rewritten only two runs later, after its run's every job was + // done; a lane that was descheduled across that can read mixed fields, but its claim word is then two + // runs stale and its compare-exchange fails, so it never runs a job. The fields are atomic so that + // read is never a data race. + run_record runs[2]; + std::atomic record{nullptr}; + std::mutex failure_mutex; // only when a job throws + std::exception_ptr failure; +}; diff --git a/tools/server/server-tools.cpp b/tools/server/server-tools.cpp index 12e9dbb8cfa9..6a8a68dad8df 100644 --- a/tools/server/server-tools.cpp +++ b/tools/server/server-tools.cpp @@ -99,7 +99,8 @@ enum class list_kind { // a narrow path uses the active code page on Windows, so every crossing between // a std::string (always UTF-8 here) and fs::path is converted explicitly static fs::path path_from_utf8(const std::string & s) { - return fs::u8path(s); + // C++20: a path built from char8_t is UTF-8 by type (u8path is deprecated) + return fs::path(std::u8string(reinterpret_cast(s.data()), s.size())); } // '/' separators on every platform: Windows accepts them, the web UI needs them