diff --git a/common/sampling.cpp b/common/sampling.cpp index b4d6584e5bde..252b49fecf74 100644 --- a/common/sampling.cpp +++ b/common/sampling.cpp @@ -227,30 +227,27 @@ struct common_sampler { llama_sampler_reset(chain); } - void set_logits(struct llama_context * ctx, int idx, bool coarse = false) { - const float * sampled_probs = llama_get_sampled_probs_ith (ctx, idx); - const float * sampled_logits = llama_get_sampled_logits_ith (ctx, idx); - const llama_token * sampled_ids = llama_get_sampled_candidates_ith(ctx, idx); + void set_logits(const common_sampler_row & row, bool coarse = false) { + const float * sampled_probs = row.sampled_probs; + const float * sampled_logits = row.sampled_logits; + const llama_token * sampled_ids = row.sampled_ids; - const llama_model * model = llama_get_model(ctx); - const llama_vocab * vocab = llama_model_get_vocab(model); - - const int n_vocab = llama_vocab_n_tokens(vocab); + const int n_vocab = row.n_vocab; if (sampled_probs) { - const uint32_t sampled_probs_count = llama_get_sampled_probs_count_ith(ctx, idx); + const uint32_t sampled_probs_count = row.n_sampled_probs; cur.resize(sampled_probs_count); for (uint32_t i = 0; i < sampled_probs_count; ++i) { cur[i] = llama_token_data{sampled_ids[i], sampled_logits[i], sampled_probs[i]}; } } else if (sampled_logits) { - const uint32_t sampled_logits_count = llama_get_sampled_logits_count_ith(ctx, idx); + const uint32_t sampled_logits_count = row.n_sampled_logits; cur.resize(sampled_logits_count); for (uint32_t i = 0; i < sampled_logits_count; i++) { cur[i] = llama_token_data{sampled_ids[i], sampled_logits[i], 0.0f}; } } else { - const auto * logits = llama_get_logits_ith(ctx, idx); + const auto * logits = row.logits; GGML_ASSERT(logits != nullptr); if (coarse && coarse_cap > 0 && coarse_cap < (size_t) n_vocab) { coarse_candidates(logits, n_vocab); @@ -758,9 +755,30 @@ struct llama_sampler * common_sampler_get(const struct common_sampler * gsmpl) { return gsmpl->chain; } -llama_token common_sampler_sample(struct common_sampler * gsmpl, struct llama_context * ctx, int idx, bool grammar_first) { +common_sampler_row common_sampler_row_ith(struct llama_context * ctx, int idx) { llama_synchronize(ctx); + common_sampler_row row; + row.sampled_probs = llama_get_sampled_probs_ith (ctx, idx); + row.sampled_logits = llama_get_sampled_logits_ith (ctx, idx); + row.sampled_ids = llama_get_sampled_candidates_ith(ctx, idx); + if (row.sampled_probs) { + row.n_sampled_probs = llama_get_sampled_probs_count_ith(ctx, idx); + } else if (row.sampled_logits) { + row.n_sampled_logits = llama_get_sampled_logits_count_ith(ctx, idx); + } else { + row.logits = llama_get_logits_ith(ctx, idx); + } + row.sampled_token = llama_get_sampled_token_ith(ctx, idx); + row.n_vocab = llama_vocab_n_tokens(llama_model_get_vocab(llama_get_model(ctx))); + return row; +} + +llama_token common_sampler_sample(struct common_sampler * gsmpl, struct llama_context * ctx, int idx, bool grammar_first) { + return common_sampler_sample_row(gsmpl, common_sampler_row_ith(ctx, idx), grammar_first); +} + +llama_token common_sampler_sample_row(struct common_sampler * gsmpl, const common_sampler_row & row, bool grammar_first) { // start measuring sampling time after the llama_context synchronization in order to not measure any ongoing async operations const auto tm = gsmpl->tm(); @@ -775,12 +793,12 @@ llama_token common_sampler_sample(struct common_sampler * gsmpl, struct llama_co // FORCING (it sets every candidate but the forced token to -inf, and the forced token need not be in // a ballpark subset); a grammar rejection below resamples over the full array const bool forcing = rbudget && common_reasoning_budget_get_state(rbudget) == REASONING_BUDGET_FORCING; - gsmpl->set_logits(ctx, idx, /*coarse=*/!forcing && !(grammar_first && grammar_should_apply(gsmpl))); + gsmpl->set_logits(row, /*coarse=*/!forcing && !(grammar_first && grammar_should_apply(gsmpl))); // Check if a backend sampler has already sampled a token in which case we // return that token id directly. { - id = llama_get_sampled_token_ith(ctx, idx); + id = row.sampled_token; if (id != LLAMA_TOKEN_NULL) { LOG_DBG("%s: Backend sampler selected token: '%d'. Will not run any CPU samplers\n", __func__, id); @@ -829,7 +847,7 @@ llama_token common_sampler_sample(struct common_sampler * gsmpl, struct llama_co // resampling: // if the token is not valid, sample again, but first apply the grammar sampler and then the sampling chain - gsmpl->set_logits(ctx, idx); + gsmpl->set_logits(row); llama_sampler_apply(rbudget, &cur_p); @@ -847,14 +865,23 @@ llama_token common_sampler_sample(struct common_sampler * gsmpl, struct llama_co } std::vector common_sampler_sample_and_accept_n(struct common_sampler * gsmpl, struct llama_context * ctx, const std::vector & idxs, const llama_tokens & draft, bool grammar_first) { - GGML_ASSERT(idxs.size() == draft.size() + 1 && "idxs.size() must be draft.size() + 1"); + std::vector rows; + rows.reserve(idxs.size()); + for (const int idx : idxs) { + rows.push_back(common_sampler_row_ith(ctx, idx)); + } + return common_sampler_sample_and_accept_rows(gsmpl, rows, draft, grammar_first); +} + +std::vector common_sampler_sample_and_accept_rows(struct common_sampler * gsmpl, const std::vector & rows, const llama_tokens & draft, bool grammar_first) { + GGML_ASSERT(rows.size() == draft.size() + 1 && "rows.size() must be draft.size() + 1"); std::vector result; - result.reserve(idxs.size()); + result.reserve(rows.size()); size_t i = 0; for (; i < draft.size(); i++) { - const llama_token id = common_sampler_sample(gsmpl, ctx, idxs[i], grammar_first); + const llama_token id = common_sampler_sample_row(gsmpl, rows[i], grammar_first); common_sampler_accept(gsmpl, id, true); @@ -866,7 +893,7 @@ std::vector common_sampler_sample_and_accept_n(struct common_sample } if (i == draft.size()) { - const llama_token id = common_sampler_sample(gsmpl, ctx, idxs[i], grammar_first); + const llama_token id = common_sampler_sample_row(gsmpl, rows[i], grammar_first); common_sampler_accept(gsmpl, id, true); diff --git a/common/sampling.h b/common/sampling.h index ac66a4bacccd..e1eb3ffd41ad 100644 --- a/common/sampling.h +++ b/common/sampling.h @@ -71,6 +71,28 @@ struct llama_sampler * common_sampler_get(const struct common_sampler * gsmpl); // llama_token common_sampler_sample(struct common_sampler * gsmpl, struct llama_context * ctx, int idx, bool grammar_first = false); +// One output row's sampling input, gathered from the context by the thread that owns it. Sampling from a +// row reads no context state, so the rows of one decode step sample on many lanes at once (continuum +// CONTINUUM-ENGINE 4.7.14). common_sampler_row_ith synchronizes the context first. +struct common_sampler_row { + const float * logits = nullptr; + const float * sampled_probs = nullptr; + const float * sampled_logits = nullptr; + const llama_token * sampled_ids = nullptr; + uint32_t n_sampled_probs = 0; + uint32_t n_sampled_logits = 0; + llama_token sampled_token = LLAMA_TOKEN_NULL; // a backend sampler's choice, if any + int32_t n_vocab = 0; +}; + +common_sampler_row common_sampler_row_ith(struct llama_context * ctx, int idx); + +// common_sampler_sample over a gathered row: touches only `gsmpl` +llama_token common_sampler_sample_row(struct common_sampler * gsmpl, const common_sampler_row & row, bool grammar_first = false); + +// common_sampler_sample_and_accept_n over gathered rows (rows.size() == draft.size() + 1): touches only `gsmpl` +std::vector common_sampler_sample_and_accept_rows(struct common_sampler * gsmpl, const std::vector & rows, const llama_tokens & draft, bool grammar_first = false); + // generalized version of common_sampler_sample // // will cross-reference the sampled tokens with a batch of draft tokens and accept those that match diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 192cb1b63e46..fec30b164427 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 # GGML_TENSOR_FLAG_GRAD: a leaf whose gradient the backward computes, never optimized (the walk reads the cached prefix K/V gradient) diff --git a/tests/test-server-lanes.cpp b/tests/test-server-lanes.cpp new file mode 100644 index 000000000000..7b1b00220e5f --- /dev/null +++ b/tests/test-server-lanes.cpp @@ -0,0 +1,142 @@ +// 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 + +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"); +} + +int main(int argc, char ** argv) { + lanes_run_every_job_once(); + + 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 ff006fd0abe1..b810c802c2cf 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 "../../src/llama-ext.h" #include "server-train.h" #include "server-adapter-file.h" @@ -375,6 +376,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 @@ -984,6 +993,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; @@ -1419,6 +1432,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 || @@ -4366,6 +4385,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) { @@ -4382,6 +4466,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(); @@ -4435,16 +4521,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(); @@ -4497,10 +4583,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..7085c84c99d4 --- /dev/null +++ b/tools/server/server-lanes.h @@ -0,0 +1,144 @@ +#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: + explicit server_lanes(size_t n_workers) : lanes(n_workers) { + for (size_t i = 0; i < n_workers; ++i) { + lanes[i].thread = std::thread([this, i] { work(lanes[i]); }); + } + } + + server_lanes(const server_lanes &) = delete; + server_lanes & operator=(const server_lanes &) = delete; + + ~server_lanes() { + 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) { + lane.thread.join(); + } + } + + 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; + } + job.store(&fn, std::memory_order_relaxed); + n_jobs.store(n, std::memory_order_relaxed); + done.store(0, std::memory_order_relaxed); + failure = nullptr; + // published with this release: job and n_jobs are visible to whoever claims in this run + 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: + 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) { + const size_t i = (size_t) (claim & 0xffffffffu); + // a lane holding an older word may read a newer n_jobs here; its compare-exchange then fails + if ((claim >> 32) == 0 || i >= n_jobs.load(std::memory_order_relaxed)) { + return; + } + 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 { + (*job.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(); + uint64_t seen = self.wake.load(std::memory_order_acquire); + while (true) { + 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}; + std::atomic n_jobs{0}; + std::atomic *> job{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