diff --git a/CMakeLists.txt b/CMakeLists.txt index 5460231b..a8f101cb 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1539,6 +1539,11 @@ if(STRATA_BUILD_TESTS) target_link_libraries(direct_file_async_test PRIVATE Threads::Threads) add_test(NAME direct_file_async_test COMMAND direct_file_async_test) endif() + # --aux-cpus: the CPU-set derivation (pure) and the placement of live threads; header-only, no GPU + add_executable(aux_cpus_test tests/platform/aux_cpus_test.cpp) + target_include_directories(aux_cpus_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include) + target_link_libraries(aux_cpus_test PRIVATE Threads::Threads) + add_test(NAME aux_cpus_test COMMAND aux_cpus_test) endif() if(STRATA_BUILD_TESTS) diff --git a/docs/DETAILS.md b/docs/DETAILS.md index d5a0c1fd..130e8f09 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -1454,6 +1454,37 @@ the pairs in which the switched arm won). They are here so you can try them on y - **`STRATA_ADAPT_LAG=2`: the adaptive tier's copies are waited for one window later** (#764). Decode, 6 pairs: Tesla P100 (PCIe 3.0 x16) +3.5% (6/6 pairs faster), RTX 5070 +0.2% (4/6), RTX 3060 -1.3% (0/6), so it stays opt-in. +## Thread placement: `--aux-cpus` (Linux, off by default) + +The CPU pool pins its workers (one logical CPU per physical core) and the host thread pins itself to the pool's reserved +core. A thread the engine starts after that inherits the host's one CPU: the adaptive tier's job thread, the prefill +helpers, the router look-ahead. The threads the CUDA driver starts are free to run on any CPU, the workers' included. +`--aux-cpus` puts every thread that is neither a pool worker nor the host thread on spare CPUs. It moves threads only and +never changes a result. + +- **Which CPUs.** `--aux-cpus auto` (or `STRATA_AUX_CPUS=auto`): the SMT siblings of the host's core first, then the CPUs of + physical cores that have no pool worker. A CPU that shares a core with a worker is never taken; when no CPU is spare + the feature does nothing and the start-up line says so. A list (`--aux-cpus 24,26` or `24-27`) is used as given, minus + the host's CPU and the workers' CPUs, and only CPUs the process may run on. `--aux-cpus off` is the default. +- **How.** Threads the engine starts pin themselves first thing: the adaptive tier's job thread and its per-round + threads, the prefill copy threads and helpers, the router look-ahead, the PLE reader, the file readers, the stdin reader + and the watchdog. The threads someone else started (the CUDA driver's) are moved by a sweep over `/proc/self/task` + once the pool exists and again at the start of every request. The pool's workers and the host thread are never moved, + and neither is a thread somebody pinned to one CPU. An explicit `STRATA_ADAPT_JOB_CPU` still wins for the adaptive tier's + job thread. `STRATA_AUX_STAGER=0` leaves the prefill copy threads where they were started: with a one-CPU spare set up + to 32 of them (`STRATA_STAGER_THREADS`) would share that CPU, which can slow the read of a long prompt. +- **Per request.** `"strata_tune": {"aux_cpus": 1}` (`serve/server.py` forwards `1`, `0`, `true` and `false`) moves the + threads to the set; `0` puts every moved thread back to the placement it had. A request without the key goes back to the + start-up setting. With `--batch` the most recently admitted request's value holds, as for the other `strata_tune` keys. + An engine started without `--aux-cpus` plans the set anyway, so `1` takes `auto`. +- **What it prints.** At start: `strata aux cpus: threads that are neither pool workers nor the host go to CPUs 24 (on; + N threads placed so far)`, or `(off at start; a request's aux_cpus=1 turns it on)`. A request that changes the state + prints `strata serve: aux cpus ON/off for this request`. +- **Not covered.** Other processes (the Python launcher, a container runtime) and the engine's host thread. +- **Measured.** TODO-EVIDENCE (PREvidence: the machine and CPU, `--aux-cpus` off against `auto` in interleaved pairs of + whole engine runs, the number of pairs and the A/A control, the host thread's involuntary context switches and + decode and prompt tok/s, cold rounds and warm rounds separately). + --- ## Experimental speed projection (EXPERIMENTAL, off by default) diff --git a/include/strata/platform/aux_cpus.hpp b/include/strata/platform/aux_cpus.hpp new file mode 100644 index 00000000..3a560316 --- /dev/null +++ b/include/strata/platform/aux_cpus.hpp @@ -0,0 +1,361 @@ +// strata/platform/aux_cpus.hpp - where the engine's OTHER threads run. +// +// The pool pins its workers (one logical CPU per physical core) and the host thread pins itself to the pool's reserved +// core. Every thread the host creates afterwards inherits the host's single CPU (the adaptive tier's job thread, the +// prefill helpers, the router lookahead ...), and the threads the CUDA driver creates float over every CPU, the pool +// workers' included. Measured on a 16-worker box: while the adaptive tier was busy the host thread was preempted 5x +// as often and the per-layer wait for the host's flag was 60-155 us instead of 8. +// +// `--aux-cpus LIST|auto|off` (STRATA_AUX_CPUS) puts every thread that is neither a pool worker nor the host thread on +// a small set of CPUs no worker uses: +// * threads the engine creates call `pin_current_thread()` first thing (a no-op while the feature is off); +// * threads somebody else created (the CUDA driver's) are caught by `sweep()` over /proc/self/task, run after the +// start-up and at every request. +// `auto` takes the SMT siblings of the host's core, then every CPU of a physical core no worker is pinned to. It +// never takes a CPU that shares a core with a worker (that would steal the worker's cycles): with nothing spare the +// feature does nothing. A list (`--aux-cpus 24,26`) is taken as given, minus the host's CPU and the workers' CPUs. +// +// Linux only (the other systems get empty functions). Header-only on purpose: the callers sit in four libraries that +// do not link each other. No output of the engine depends on where a thread runs. +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(__linux__) +#include +#include +#include +#include +#endif + +namespace strata::aux_cpus { + +/// One logical CPU the process may use and the physical core it belongs to (-1: unknown). +struct LogicalCpu { + int cpu = -1; + long pkg = -1; + long core = -1; +}; + +/// "24,26,30-31" -> {24, 26, 30, 31} (sorted, no duplicates). False for anything else (empty items, letters, +/// reversed ranges, negative numbers); `out` is then empty. +inline bool parse_cpu_list(const std::string& text, std::vector& out) { + out.clear(); + if (text.empty()) return false; + size_t i = 0; + auto number = [&](long& v) { + if (i >= text.size() || text[i] < '0' || text[i] > '9') return false; + v = 0; + while (i < text.size() && text[i] >= '0' && text[i] <= '9') { + v = v * 10 + (text[i] - '0'); + if (v > 100000) return false; + ++i; + } + return true; + }; + for (;;) { + long lo = 0, hi = 0; + if (!number(lo)) { out.clear(); return false; } + hi = lo; + if (i < text.size() && text[i] == '-') { + ++i; + if (!number(hi) || hi < lo) { out.clear(); return false; } + } + for (long c = lo; c <= hi; ++c) out.push_back((int) c); + if (i == text.size()) break; + if (text[i] != ',') { out.clear(); return false; } + ++i; + } + std::sort(out.begin(), out.end()); + out.erase(std::unique(out.begin(), out.end()), out.end()); + return true; +} + +/// The CPUs `auto` gives to the aux threads, in order: the SMT siblings of the host's physical core first, then every +/// CPU of a physical core that has no worker and is not the host's. A CPU that shares a core with a worker is never +/// returned, and neither is one whose core is unknown (no sysfs): it might be a worker's sibling. +inline std::vector derive(const std::vector& allowed, int host_cpu, const std::vector& worker_cpus) { + using Key = std::pair; + auto key_of = [&](int cpu, Key& k) { + for (const LogicalCpu& c : allowed) + if (c.cpu == cpu) { k = {c.pkg, c.core}; return c.pkg >= 0 && c.core >= 0; } + return false; + }; + std::vector worker_keys; + for (int w : worker_cpus) { + Key k; + if (key_of(w, k)) worker_keys.push_back(k); + } + Key host_key; + const bool host_known = host_cpu >= 0 && key_of(host_cpu, host_key); + std::vector siblings, free_cores; + for (const LogicalCpu& c : allowed) { + if (c.cpu == host_cpu || c.pkg < 0 || c.core < 0) continue; + if (std::find(worker_cpus.begin(), worker_cpus.end(), c.cpu) != worker_cpus.end()) continue; + const Key k{c.pkg, c.core}; + if (host_known && k == host_key) { + siblings.push_back(c.cpu); + } else if (std::find(worker_keys.begin(), worker_keys.end(), k) == worker_keys.end()) { + free_cores.push_back(c.cpu); + } + } + std::sort(siblings.begin(), siblings.end()); + std::sort(free_cores.begin(), free_cores.end()); + siblings.insert(siblings.end(), free_cores.begin(), free_cores.end()); + return siblings; +} + +/// An explicit list, restricted to CPUs the process may use, without the host's CPU and the workers' CPUs. +inline std::vector restrict_list(const std::vector& list, const std::vector& allowed, int host_cpu, + const std::vector& worker_cpus) { + std::vector out; + for (int c : list) { + if (c == host_cpu || std::find(worker_cpus.begin(), worker_cpus.end(), c) != worker_cpus.end()) continue; + const bool ok = std::any_of(allowed.begin(), allowed.end(), [&](const LogicalCpu& a) { return a.cpu == c; }); + if (ok) out.push_back(c); + } + return out; +} + +/// What `--aux-cpus` / STRATA_AUX_CPUS said. `on`: placed from the start-up; `use_list`: the list, not `auto`. +struct Config { + bool on = false; + bool use_list = false; + std::vector list; +}; + +/// "" and "off": off at start (a request can still turn it on with `auto`); "auto"; or a CPU list. +inline bool parse_spec(const std::string& spec, Config& cfg, std::string& err) { + cfg = Config{}; + if (spec.empty() || spec == "off") return true; + if (spec == "auto") { cfg.on = true; return true; } + if (!parse_cpu_list(spec, cfg.list)) { + err = "--aux-cpus takes off, auto or a CPU list such as 24,26 or 24-27 (got '" + spec + "')"; + return false; + } + cfg.on = true; + cfg.use_list = true; + return true; +} + +#if defined(__linux__) + +namespace detail { + +struct State { + std::mutex mu; + Config cfg; + std::atomic enabled{false}; + std::atomic have_plan{false}; + std::vector allowed; ///< the process's CPUs, snapshotted before any thread is pinned + std::vector plan; ///< the aux CPUs (empty: nothing to do) + std::vector workers; ///< the pool's CPUs: their threads are never touched + cpu_set_t target; + std::set owned; ///< tids of pool workers and host threads + std::map original; ///< tid -> the mask it had before this module moved it + State() { CPU_ZERO(&target); } +}; + +inline State& state() { + static State s; + return s; +} + +inline int self_tid() { return (int) syscall(SYS_gettid); } + +inline bool same_mask(const cpu_set_t& a, const cpu_set_t& b) { return CPU_EQUAL(&a, &b) != 0; } + +/// Moves `tid` to the aux set. Caller holds `mu`. Returns true if the thread's mask changed. +inline bool move_locked(State& s, int tid) { + cpu_set_t now; + CPU_ZERO(&now); + if (sched_getaffinity(tid, sizeof now, &now) != 0) return false; + if (same_mask(now, s.target)) return false; + if (CPU_COUNT(&now) == 1) { // pinned to one CPU of a worker by somebody: not ours + for (int w : s.workers) + if (CPU_ISSET(w, &now)) return false; + } + if (sched_setaffinity(tid, sizeof s.target, &s.target) != 0) return false; + s.original.emplace(tid, now); // the first mask only: a second move keeps the real original + return true; +} + +inline bool alive(int tid) { + char path[48]; + std::snprintf(path, sizeof path, "/proc/self/task/%d", tid); + return access(path, F_OK) == 0; +} + +inline std::vector task_ids() { + std::vector ids; + if (DIR* d = opendir("/proc/self/task")) { + while (const dirent* e = readdir(d)) + if (e->d_name[0] >= '0' && e->d_name[0] <= '9') ids.push_back(std::atoi(e->d_name)); + closedir(d); + } + return ids; +} + +/// Forgets the threads that have ended (their tids may come back for another thread). Caller holds `mu`. +inline void purge_locked(State& s) { + for (auto it = s.original.begin(); it != s.original.end();) it = alive(it->first) ? std::next(it) : s.original.erase(it); + for (auto it = s.owned.begin(); it != s.owned.end();) it = alive(*it) ? std::next(it) : s.owned.erase(it); +} + +} // namespace detail + +/// Reads the CPUs the calling thread may use and the spec. Call once, early, on the thread that has not been pinned +/// yet (the engine's main thread, before the pool exists). The main thread counts as the host. +inline bool configure(const std::string& spec, std::string& err) { + detail::State& s = detail::state(); + Config cfg; + if (!parse_spec(spec, cfg, err)) return false; + std::lock_guard lk(s.mu); + s.cfg = cfg; + s.allowed.clear(); + cpu_set_t now; + CPU_ZERO(&now); + if (sched_getaffinity(0, sizeof now, &now) == 0) + for (int c = 0; c < CPU_SETSIZE; ++c) + if (CPU_ISSET(c, &now)) s.allowed.push_back(c); + s.owned.insert(detail::self_tid()); + return true; +} + +/// The calling thread belongs to the pool or is the host: the sweep leaves it alone. +inline void note_owned_thread() { + detail::State& s = detail::state(); + std::lock_guard lk(s.mu); + s.owned.insert(detail::self_tid()); +} + +/// Moves every thread of the process that is not owned to the aux set (or, with the feature off, does nothing). +/// Returns the number of threads whose placement changed. +inline int sweep() { + detail::State& s = detail::state(); + if (!s.enabled.load(std::memory_order_acquire)) return 0; + std::lock_guard lk(s.mu); + detail::purge_locked(s); + int n = 0; + for (int tid : detail::task_ids()) + if (s.owned.find(tid) == s.owned.end() && detail::move_locked(s, tid)) ++n; + return n; +} + +/// First thing a thread the engine creates does: it goes to the aux set while the feature is on. Cheap when off. +inline void pin_current_thread() { + detail::State& s = detail::state(); + if (!s.enabled.load(std::memory_order_acquire)) return; + std::lock_guard lk(s.mu); + const int tid = detail::self_tid(); + if (s.owned.find(tid) == s.owned.end()) detail::move_locked(s, tid); +} + +/// Puts back the placement every moved thread had. Returns how many were restored. +inline int restore() { + detail::State& s = detail::state(); + std::lock_guard lk(s.mu); + int n = 0; + for (const auto& [tid, mask] : s.original) + if (detail::alive(tid) && sched_setaffinity(tid, sizeof mask, &mask) == 0) ++n; + s.original.clear(); + return n; +} + +/// Turns the placement on (sweeping at once) or off (restoring the moved threads). A no-op without a plan. +inline void set_enabled(bool on) { + detail::State& s = detail::state(); + if (on) { + if (!s.have_plan.load(std::memory_order_acquire)) return; + s.enabled.store(true, std::memory_order_release); + (void) sweep(); + } else { + s.enabled.store(false, std::memory_order_release); + (void) restore(); + } +} + +inline bool enabled() { return detail::state().enabled.load(std::memory_order_acquire); } + +/// The aux CPUs of the plan ({} when there is none). +inline std::vector plan() { + detail::State& s = detail::state(); + std::lock_guard lk(s.mu); + return s.plan; +} + +/// Reads sysfs for the cores of the process's CPUs. `cpus` empty: every CPU `configure` saw. +inline std::vector read_topology(const std::vector& cpus) { + auto read_id = [](int cpu, const char* what) -> long { + char path[96]; + std::snprintf(path, sizeof path, "/sys/devices/system/cpu/cpu%d/topology/%s", cpu, what); + long v = -1; + if (std::FILE* f = std::fopen(path, "r")) { + if (std::fscanf(f, "%ld", &v) != 1) v = -1; + std::fclose(f); + } + return v; + }; + std::vector out; + for (int c : cpus) out.push_back({c, read_id(c, "physical_package_id"), read_id(c, "core_id")}); + return out; +} + +/// Works the plan out once the pool exists: `host_cpu` is the CPU the host thread is pinned to (-1: unknown) and +/// `worker_cpus` the CPUs of the pool's workers. With the start-up setting on, the placement starts now. Returns one +/// line for the log. +inline std::string set_topology(int host_cpu, const std::vector& worker_cpus) { + detail::State& s = detail::state(); + std::vector plan; + std::string note; + { + std::lock_guard lk(s.mu); + const std::vector allowed = read_topology(s.allowed); + plan = s.cfg.use_list ? restrict_list(s.cfg.list, allowed, host_cpu, worker_cpus) + : derive(allowed, host_cpu, worker_cpus); + s.plan = plan; + s.workers = worker_cpus; + CPU_ZERO(&s.target); + for (int c : plan) CPU_SET(c, &s.target); + s.have_plan.store(!plan.empty(), std::memory_order_release); + for (size_t i = 0; i < plan.size(); ++i) note += (i ? "," : "") + std::to_string(plan[i]); + } + if (plan.empty()) note = "none spare (every CPU is the host's, a worker's or shares a core with a worker or has no known core)"; + if (s.cfg.on && !plan.empty()) set_enabled(true); + long moved; + { + std::lock_guard lk(s.mu); + moved = (long) s.original.size(); + } + return "strata aux cpus: threads that are neither pool workers nor the host go to CPUs " + note + + (!s.cfg.on ? " (off at start; a request's aux_cpus=1 turns it on)" + : plan.empty() ? " (nothing to do)" : " (on; " + std::to_string(moved) + " threads placed so far)"); +} + +#else // not Linux: the same names, doing nothing + +inline bool configure(const std::string& spec, std::string& err) { + Config cfg; + return parse_spec(spec, cfg, err); +} +inline void note_owned_thread() {} +inline int sweep() { return 0; } +inline void pin_current_thread() {} +inline int restore() { return 0; } +inline void set_enabled(bool) {} +inline bool enabled() { return false; } +inline std::vector plan() { return {}; } +inline std::string set_topology(int, const std::vector&) { return "strata aux cpus: not available on this system"; } + +#endif + +} // namespace strata::aux_cpus diff --git a/serve/server.py b/serve/server.py index 553f440c..2e7a5888 100644 --- a/serve/server.py +++ b/serve/server.py @@ -966,6 +966,12 @@ class StrataEngine: v = tune.get(k) if isinstance(v, (int, float)) and not isinstance(v, bool) and 0.0 <= float(v) <= 1.0: keys += f" {k}={float(v)!r}" + # --aux-cpus for this request: 1 puts the engine's threads that are neither pool workers nor the host on the + # spare CPUs, 0 leaves them where they were created (true/false or 1/0; the engine started without a spare CPU + # ignores a 1). Anything else is not sent. + ac = tune.get("aux_cpus") + if isinstance(ac, bool) or (isinstance(ac, (int, float)) and ac in (0, 1)): + keys += f" aux_cpus={int(ac)}" # "strata_checkpoint": false - a one-shot call (a classification, a probe) whose turn no later request # extends: no conversation checkpoint for it (#830). It still reuses a cached prefix. Absent = as before. if sampling.get("strata_checkpoint") is False: diff --git a/serve/test_server.py b/serve/test_server.py index 60e909e8..ec05503c 100644 --- a/serve/test_server.py +++ b/serve/test_server.py @@ -1522,6 +1522,14 @@ class SamplingKeys(unittest.TestCase): bad = self.keys(strata_tune={"pcie_frac": 3, "spec_min_p": True, "pool_workers": 2}) self.assertFalse([x for x in bad if x.split("=")[0] in ("pcie_frac", "spec_min_p", "pool_workers")]) + def test_tune_aux_cpus(self): + for val, want in ((True, "aux_cpus=1"), (1, "aux_cpus=1"), (False, "aux_cpus=0"), (0, "aux_cpus=0"), + (1.0, "aux_cpus=1"), (0.0, "aux_cpus=0")): + self.assertIn(want, self.keys(strata_tune={"aux_cpus": val}), val) + for bad in (2, -1, 0.5, "1", None, "auto"): + self.assertFalse([x for x in self.keys(strata_tune={"aux_cpus": bad}) if x.startswith("aux_cpus=")], bad) + self.assertFalse([x for x in self.keys(temperature=0) if x.startswith("aux_cpus=")]) + def test_checkpoint_key(self): self.assertIn("ckpt=0", self.keys(temperature=0, strata_checkpoint=False)) for absent in ({}, {"strata_checkpoint": True}, {"strata_checkpoint": 0}, {"cache_prompt": False}): diff --git a/src/core/expert_source.cpp b/src/core/expert_source.cpp index f92994fd..064381f4 100644 --- a/src/core/expert_source.cpp +++ b/src/core/expert_source.cpp @@ -2,6 +2,7 @@ #include "strata/core/expert_source.hpp" #include "strata/core/foresight_swap.hpp" #include "strata/core/on_device.hpp" +#include "strata/platform/aux_cpus.hpp" #include "strata/core/remote_experts.hpp" #include "strata/core/peer_experts.hpp" #include "strata/kernels/cpu/expert_layout.hpp" @@ -1949,7 +1950,10 @@ bool RouterLookahead::start(std::vector> routers, int64_t k_ = k < 1 ? 1 : k > (int) n_expert ? (int) n_expert : k; src_ = src; x_.assign((size_t) (8 * n_embd), 0.f); - thread_ = std::thread([this] { run(); }); + thread_ = std::thread([this] { + strata::aux_cpus::pin_current_thread(); + run(); + }); return true; } diff --git a/src/core/session.cpp b/src/core/session.cpp index d87452d0..8d1fad91 100644 --- a/src/core/session.cpp +++ b/src/core/session.cpp @@ -8,6 +8,7 @@ #include "strata/kernels/quantize_act.hpp" #include "strata/kernels/s2_expert_grouped.hpp" #include "strata/kernels/cpu/pool.hpp" +#include "strata/platform/aux_cpus.hpp" #include "strata/kernels/ngram.hpp" #include @@ -556,6 +557,7 @@ bool SessionLoopScratch::init(size_t parts_bytes_in, std::string& err) { pinned = pinned_core.valid; } } + strata::aux_cpus::note_owned_thread(); // the host: --aux-cpus leaves it where it is return true; } diff --git a/src/kernels/cpu/pool.cpp b/src/kernels/cpu/pool.cpp index 16e3fb2d..af1eb5a5 100644 --- a/src/kernels/cpu/pool.cpp +++ b/src/kernels/cpu/pool.cpp @@ -1,6 +1,7 @@ // src/kernels/cpu/pool.cpp - P2.S3: the CPU expert pool. Read pool.hpp first; it explains the protocol. #include "strata/kernels/cpu/pool.hpp" #include "strata/core/progress.hpp" +#include "strata/platform/aux_cpus.hpp" #include "strata/kernels/cpu/expert_layout.hpp" #include @@ -458,6 +459,7 @@ ExpertPool::ExpertPool(int n_workers, bool pin, bool host_works, PoolAffinity af for (int i = 0; i < n_; ++i) { const int core = pin ? (i < (int) topo_.worker_cores.size() ? topo_.worker_cores[(size_t) i] : -1) : -1; threads_.emplace_back([this, i, core] { + strata::aux_cpus::note_owned_thread(); // --aux-cpus never moves a worker pin_this_thread(core, i); worker(i); }); diff --git a/src/ngram/ple_reader.cpp b/src/ngram/ple_reader.cpp index a03e4c04..9d2a0505 100644 --- a/src/ngram/ple_reader.cpp +++ b/src/ngram/ple_reader.cpp @@ -1,5 +1,6 @@ // src/ngram/ple_reader.cpp - see include/strata/ngram/ple_reader.hpp. #include "strata/ngram/ple_reader.hpp" +#include "strata/platform/aux_cpus.hpp" #include #include @@ -363,7 +364,7 @@ bool PleReader::open(const std::string& path, uint64_t table_offset, uint64_t n_ impl_->threaded = io_thread; if (io_thread) { try { - impl_->worker = std::thread([this] { impl_->worker_loop(); }); + impl_->worker = std::thread([this] { strata::aux_cpus::pin_current_thread(); impl_->worker_loop(); }); } catch (const std::exception& e) { err = std::string("PleReader: cannot create I/O worker: ") + e.what(); close(); diff --git a/src/platform/direct_file.cpp b/src/platform/direct_file.cpp index cd4f6a71..5f8d9962 100644 --- a/src/platform/direct_file.cpp +++ b/src/platform/direct_file.cpp @@ -1,5 +1,6 @@ // src/platform/direct_file.cpp - see include/strata/platform/direct_file.hpp. #include "strata/platform/direct_file.hpp" +#include "strata/platform/aux_cpus.hpp" #include #include @@ -184,7 +185,7 @@ bool DirectFile::open(const std::string& path, std::string& err) { // Completions of reads that finish synchronously are still queued to the port, so every issued read // produces exactly one packet; `wait` is the only completion path. const int n = io_threads(4); - for (int i = 0; i < n; ++i) impl_->pool.emplace_back([this] { impl_->worker(); }); + for (int i = 0; i < n; ++i) impl_->pool.emplace_back([this] { strata::aux_cpus::pin_current_thread(); impl_->worker(); }); return true; } @@ -311,7 +312,7 @@ bool DirectFile::open(const std::string& path, std::string& err) { if (fstat(impl_->fd, &st) != 0) { err = "DirectFile: cannot size " + path; close(); return false; } impl_->size = (uint64_t) st.st_size; const int n = io_threads(16); - for (int i = 0; i < n; ++i) impl_->pool.emplace_back([this] { impl_->worker(); }); + for (int i = 0; i < n; ++i) impl_->pool.emplace_back([this] { strata::aux_cpus::pin_current_thread(); impl_->worker(); }); return true; } diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index 4e03dc8b..11cebaf2 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -5,6 +5,7 @@ #include "strata/core/mtp.hpp" #include "strata/core/progress.hpp" #include "strata/core/on_device.hpp" +#include "strata/platform/aux_cpus.hpp" #include "strata/core/layout.hpp" #include "strata/kernels/cpu/expert.hpp" @@ -442,7 +443,15 @@ struct Stager { : cudaEventDisableTiming) != cudaSuccess) return false; } cudaGetDevice(&device); - for (int t = 0; t < nthreads; ++t) threads.emplace_back([this] { work(); }); + for (int t = 0; t < nthreads; ++t) + threads.emplace_back([this] { + // --aux-cpus: the copy threads go to the spare CPUs with the other helpers; STRATA_AUX_STAGER=0 leaves them where + // they were created (a small spare set would then hold all of them: it limits the copy rate of a long read) + static const bool keep = [] { const char* v = std::getenv("STRATA_AUX_STAGER"); return v != nullptr && std::atoi(v) == 0; }(); + if (keep) strata::aux_cpus::note_owned_thread(); + else strata::aux_cpus::pin_current_thread(); + work(); + }); return true; } ~Stager() { @@ -2122,6 +2131,7 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri // layer 1 on, and gathering them here first left the GPU idle for the whole read (~0.4 s of a 32K prompt) if (ple_on && !ple_next.valid()) ple_next = std::async(std::launch::async, [&ple_gather, &ple_next_err, c0, b = ple_buf] { + strata::aux_cpus::pin_current_thread(); return ple_gather(c0, b, ple_next_err); }); bool ple_pending = ple_on; @@ -2147,6 +2157,7 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri return false; } ple_next = std::async(std::launch::async, [&ple_gather, &ple_next_err, c1 = c0 + m.T, b = ple_buf ^ 1] { + strata::aux_cpus::pin_current_thread(); return ple_gather(c1, b, ple_next_err); }); } @@ -2330,6 +2341,7 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri const bool threaded_issue = stream_all && issuer_on; if (threaded_issue) { issuer = std::thread([&] { + strata::aux_cpus::pin_current_thread(); const core::OnDevice od(m.device); for (size_t idx = 0; idx < seq.size(); ++idx) { while (idx >= a_consumed.load(std::memory_order_acquire) + (size_t) m.ring) { @@ -3908,6 +3920,7 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri next_->hand_in_ = h; next_->single_chunk_ = single_chunk; next_run_ = std::async(std::launch::async, [this, tokens, c0, T, p0] { + strata::aux_cpus::pin_current_thread(); return next_->run_impl(tokens + c0, T, p0, next_err_); }); hand_buf_ ^= 1; diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 3e143f53..351b8091 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -36,6 +36,7 @@ #include "strata/core/weights.hpp" #include "strata/kernels/cpu/expert.hpp" #include "strata/kernels/cpu/pool.hpp" +#include "strata/platform/aux_cpus.hpp" #include "strata/kernels/cpu/expert_layout.hpp" #include "strata/kernels/ngram.hpp" #include "strata/kernels/iq_kernels.hpp" @@ -415,6 +416,8 @@ struct Options { strata::kernels::cpu::PoolAffinity pool_affinity = strata::kernels::cpu::PoolAffinity::All; /// --host-core first|last (STRATA_HOST_CORE): the host thread's core (see HostCore in pool.hpp) std::string host_core; + /// --aux-cpus off|auto|LIST (STRATA_AUX_CPUS): where the non-pool, non-host threads run (strata/platform/aux_cpus.hpp) + std::string aux_cpus; /// R2.2's first half, as an A/B arm. **ON by default**, because the measurement that justifies it is the /// pool's own drain: 33.7 GB/s against 5/6 x 44.14 = 36.8 for five workers, on a machine whose sixth core /// is reserved for a host thread that has nothing to do while the drain runs. @@ -852,6 +855,13 @@ void usage() { " interrupts to one logical processor, usually the first, and every copy that lands\n" " raises one: a spinning host there waits for them. Moves threads only, never a\n" " result. Not on hybrid CPUs (STRATA_HOST_CORE sets it too).\n" + " --aux-cpus SET Where the threads that are neither pool workers nor the host thread run (the\n" + " adaptive tier's job thread, the prefill helpers, the CUDA driver's threads, ...):\n" + " off (the default: wherever they were created), auto (the SMT siblings of the host's\n" + " core, then physical cores with no worker; never a CPU that shares a core with a\n" + " worker; nothing is done when none is spare) or a CPU list such as 24,26 (Linux; the\n" + " host's and the workers' CPUs are dropped from it). Moves threads only, never a\n" + " result. STRATA_AUX_CPUS sets it too; a request's strata_tune aux_cpus=0|1 beats it.\n" " --pool-affinity MODE Worker CPU affinity: all (default: one worker per physical core, as\n" " always), auto (hybrid CPUs: P-cores first, then their SMT siblings,\n" " then E-cores) or p-cores (P-cores and their siblings only).\n" @@ -1320,10 +1330,13 @@ private: } void loop() { // the job's memcpys stay off the host's core and the pool's: by default the spare SMT sibling of the last - // two-thread core (Windows); STRATA_ADAPT_JOB_CPU=, or -1 for no pinning + // two-thread core (Windows); STRATA_ADAPT_JOB_CPU=, or -1 for no pinning. Without either, --aux-cpus + // (off by default) puts the thread on the spare CPUs; an explicit STRATA_ADAPT_JOB_CPU is the user's word over it. const char* c = std::getenv("STRATA_ADAPT_JOB_CPU"); const int cpu = c != nullptr ? std::atoi(c) : smt_spare_cpu(); if (cpu >= 0) (void) strata::kernels::cpu::pin_current_thread(cpu); + if (c != nullptr) strata::aux_cpus::note_owned_thread(); + else if (cpu < 0) strata::aux_cpus::pin_current_thread(); for (;;) { std::function f; { @@ -1733,6 +1746,15 @@ int main(int argc, char** argv) { return 2; } } + else if (a == "--aux-cpus") { + o.aux_cpus = next("--aux-cpus"); + std::string aerr; + strata::aux_cpus::Config acfg; + if (!strata::aux_cpus::parse_spec(o.aux_cpus, acfg, aerr)) { + std::fprintf(stderr, "strata generate: %s\n", aerr.c_str()); + return 2; + } + } else if (a == "--pool-affinity") { const std::string v = next("--pool-affinity"); if (v == "auto") o.pool_affinity = strata::kernels::cpu::PoolAffinity::Auto; @@ -1965,6 +1987,17 @@ int main(int argc, char** argv) { if (const char* e = std::getenv("STRATA_HOST_CORE")) hc = e; if (hc == "last") strata::kernels::cpu::set_host_core(strata::kernels::cpu::HostCore::Last); } + { // --aux-cpus / STRATA_AUX_CPUS: read the CPUs this process may use now, before any thread is pinned; the plan + // follows once the pool exists (it needs the workers' CPUs) + std::string ac = o.aux_cpus; + if (ac.empty()) + if (const char* e = std::getenv("STRATA_AUX_CPUS")) ac = e; + std::string aerr; + if (!strata::aux_cpus::configure(ac, aerr)) { + std::fprintf(stderr, "strata generate: STRATA_AUX_CPUS: %s\n", aerr.c_str()); + return 2; + } + } strata::core::set_peer_portable(o.peer_device >= 1); // multi-GPU: the Portable flag on mapped host buffers only with a peer device (before any allocation) if (o.serve && o.conversation_cache_mib > 0 && (o.prompt_cache == 0 || o.conversation_cache_slots == 0)) std::fprintf(stderr, "strata serve: warning: conversation caching is disabled by %s\n", @@ -4273,6 +4306,12 @@ int main(int argc, char** argv) { "(--host-core %s)\n", pool.workers(), on.c_str(), ht.host_core, pool.host_works() ? " (draining too)" : "", strata::kernels::cpu::host_core_setting() == strata::kernels::cpu::HostCore::Last ? "last" : "first"); + // --aux-cpus: the plan, now the workers' CPUs are known; the threads that exist already (the CUDA driver's) move + // now when it is on, the ones created later pin themselves (strata/platform/aux_cpus.hpp) + const size_t nw = std::min((size_t) pool.workers(), ht.worker_cores.size()); + std::fprintf(stderr, "%s\n", + strata::aux_cpus::set_topology(ht.host_core, std::vector(ht.worker_cores.begin(), + ht.worker_cores.begin() + (long) nw)).c_str()); } if (o.no_ple_prefetch) strata::kernels::ple_prefetch_enable(false); // ---- R4's slot storage. Allocated AFTER the weights and the session, so `cudaMemGetInfo` inside `open` @@ -4669,7 +4708,7 @@ int main(int argc, char** argv) { if (!per_layer && srcp == &src && src.unbuffered() && i % 64 == 0) { if (ahead.valid()) ahead.get(); else read_batch(i); - if (i + 64 < want) ahead = std::async(std::launch::async, read_batch, i + 64); + if (i + 64 < want) ahead = std::async(std::launch::async, [&read_batch](int64_t b) { strata::aux_cpus::pin_current_thread(); read_batch(b); }, i + 64); } if (fill_ahead > 0 && i + fill_ahead < want) (void) src.advise_pairs(profile.data() + i + fill_ahead, 1); const int32_t slot = xcache.admit(profile[(size_t) i].first, profile[(size_t) i].second); @@ -8007,6 +8046,7 @@ int main(int argc, char** argv) { std::deque in_lines; bool in_eof = false; std::thread([&] { + strata::aux_cpus::pin_current_thread(); // read(2) on the descriptor, not std::cin: glibc's exit() flushes every stdio stream and waits for // stdin's lock, which getline holds while it waits for input - an engine ending on an error (every // std::exit) would hang in exit() on Linux, and the server would wait for it forever @@ -8152,6 +8192,7 @@ int main(int argc, char** argv) { const int io_limit = wio ? std::atoi(wio) : limit * 10; if (limit > 0) std::thread([limit, io_limit] { + strata::aux_cpus::pin_current_thread(); strata::core::Progress& p = strata::core::progress(); uint64_t last = p.beats.load(), ticks_at = p.ticks.load(); auto since = std::chrono::steady_clock::now(); @@ -9016,6 +9057,7 @@ int main(int argc, char** argv) { // tuning keys (setup's calibration measures settings without restarting the engine): the PCIe share of // the missed experts and the draft-probability floor, for this request only double req_pcie_frac = o.pcie_frac, req_spec_min_p = o.spec_min_p; + int req_aux_cpus = -1; // aux_cpus=0|1: --aux-cpus for this request (-1 = the start-up value) if (endp != nullptr) { // GENI takes the same keys (#75: image requests were always greedy); its // embedding file path is the first token without an = for (;;) { @@ -9042,6 +9084,7 @@ int main(int argc, char** argv) { else if (key == "seed") req_seed = std::strtoull(tok.c_str() + eq + 1, nullptr, 10); else if (key == "pcie_frac") req_pcie_frac = std::clamp((double) fv, 0.0, 1.0); else if (key == "spec_min_p") req_spec_min_p = std::clamp((double) fv, 0.0, 1.0); + else if (key == "aux_cpus") req_aux_cpus = std::atoi(tok.c_str() + eq + 1) != 0 ? 1 : 0; // unknown keys are skipped: the ids start at the first token without '=' } } @@ -9878,6 +9921,16 @@ int main(int argc, char** argv) { ver.set_sampling(req_sp); if (pipe) ver_b.set_sampling(req_sp); // (reaches the later stage's odd verifier) if (use_mtp) mtp.set_draft_sampling(req_sp); // STRATA_SPEC_COUPLED=1: sampled drafts (a no-op otherwise) + { // aux_cpus=0|1: where the non-pool, non-host threads run for this request (-1 = the start-up --aux-cpus); moves + // threads only. An enabled placement is swept at every request: it catches threads created since. + static const bool aux_start = strata::aux_cpus::enabled(); + const bool was_on = strata::aux_cpus::enabled(); + const bool want = req_aux_cpus < 0 ? aux_start : req_aux_cpus != 0; + strata::aux_cpus::set_enabled(want); + if (want != was_on) + std::fprintf(stderr, "strata serve: aux cpus %s for this request%s\n", strata::aux_cpus::enabled() ? "ON" : "off", + want && !strata::aux_cpus::enabled() ? " (asked for, but no CPU is spare: see the start-up line)" : ""); + } drive.d.pcie_num = std::max(0, std::min(256, (int) (req_pcie_frac * 256.0 + 0.5))); // a layer split: CUDA0's share as asked; a later GPU keeps its own (its link) unless the request sets one for (int st = 0; st < split_drive.n; ++st) @@ -10297,7 +10350,7 @@ int main(int argc, char** argv) { if (!drive.d.usage.empty() && o.adapt_every > 0 && (rounds % o.adapt_every) == 0 && pending.empty() && !exch_wait) { pl_adapt_done = false; - pl_adapt_thr = std::thread([&] { pl_adapt_ok = adapt(); pl_adapt_done = true; }); + pl_adapt_thr = std::thread([&] { strata::aux_cpus::pin_current_thread(); pl_adapt_ok = adapt(); pl_adapt_done = true; }); } return true; }; @@ -10794,7 +10847,7 @@ int main(int argc, char** argv) { bool adapt_ok = true; // (--adapt-async 1: the asynchronous tier above instead, ticked before the window) if (!drive.d.usage.empty() && !ajob && ((rounds + 1) % o.adapt_every) == 0) - adapt_thr = std::thread([&] { adapt_ok = adapt(); }); + adapt_thr = std::thread([&] { strata::aux_cpus::pin_current_thread(); adapt_ok = adapt(); }); if (!ver.commit(a + 1, err)) { if (adapt_thr.joinable()) adapt_thr.join(); std::printf("ERR %s\n", err.c_str()); @@ -11907,7 +11960,7 @@ int main(int argc, char** argv) { std::thread adapt_thr; bool adapt_ok = true; if (!drive.d.usage.empty() && ((rounds + 1) % o.adapt_every) == 0) - adapt_thr = std::thread([&] { adapt_ok = adapt(); }); + adapt_thr = std::thread([&] { strata::aux_cpus::pin_current_thread(); adapt_ok = adapt(); }); if (!ver.commit(a + 1, err)) { if (adapt_thr.joinable()) adapt_thr.join(); std::fprintf(stderr, "strata generate: %s\n", err.c_str()); diff --git a/tests/platform/aux_cpus_test.cpp b/tests/platform/aux_cpus_test.cpp new file mode 100644 index 00000000..665ab99c --- /dev/null +++ b/tests/platform/aux_cpus_test.cpp @@ -0,0 +1,217 @@ +// aux_cpus_test: the CPU-set derivation of --aux-cpus (pure functions, no GPU) and, on Linux, the placement of live +// threads (a thread of the process moved to the aux set by the sweep, one that pins itself at creation, the owned ones +// left alone, and the original placement put back). +#include "strata/platform/aux_cpus.hpp" + +#include +#include +#include +#include +#include + +using namespace strata::aux_cpus; + +namespace { +int failures = 0; +#define CHECK(c) \ + do { \ + if (!(c)) { \ + std::fprintf(stderr, "FAILED %s:%d: %s\n", __FILE__, __LINE__, #c); \ + ++failures; \ + } \ + } while (0) + +using V = std::vector; + +std::vector cpus(std::initializer_list> rows) { + std::vector out; + for (const auto& r : rows) out.push_back({(int) r[0], r[1], r[2]}); + return out; +} + +// SMT machine: CPU i and i + n are the two threads of core i +std::vector smt(int n_cores, int n_threads_total) { + std::vector out; + for (int c = 0; c < n_threads_total; ++c) out.push_back({c, 0, c % n_cores}); + return out; +} + +void test_parse() { + V v; + CHECK(parse_cpu_list("24", v) && v == V{24}); + CHECK(parse_cpu_list("26,24", v) && v == (V{24, 26})); + CHECK(parse_cpu_list("24-27,30,25", v) && v == (V{24, 25, 26, 27, 30})); + CHECK(parse_cpu_list("0", v) && v == V{0}); + for (const char* bad : {"", ",", "1,", ",1", "a", "1-", "-1", "3-1", "1,,2", "1 2", "1;2", "99999999"}) { + CHECK(!parse_cpu_list(bad, v)); + CHECK(v.empty()); + } + Config c; + std::string err; + CHECK(parse_spec("", c, err) && !c.on); + CHECK(parse_spec("off", c, err) && !c.on); + CHECK(parse_spec("auto", c, err) && c.on && !c.use_list); + CHECK(parse_spec("24,26", c, err) && c.on && c.use_list && c.list == (V{24, 26})); + CHECK(!parse_spec("fast", c, err) && !err.empty()); +} + +void test_derive() { + // the production box's shape: 16 workers on 16 physical cores, the host on core 2, 24 allowed CPUs - CPUs 0-15 + // are cores 0-15 and 22-29 the second threads of cores 0-7: the host's sibling (CPU 24) is the only spare one + { + std::vector a; + for (int c = 0; c < 16; ++c) a.push_back({c, 0, c}); + for (int c = 22; c < 30; ++c) a.push_back({c, 0, c - 22}); + V workers; + for (int c = 0; c < 16; ++c) + if (c != 2) workers.push_back(c); + CHECK(derive(a, 2, workers) == V{24}); + // an explicit list is taken as given, minus the host's CPU and the workers' CPUs + CHECK(restrict_list({24, 26, 2, 5, 99}, a, 2, workers) == (V{24, 26})); + } + // 12 cores x 2 threads, host on CPU 0, workers on CPUs 1-7: the host's sibling first (12), then both threads of + // the four worker-free cores 8-11; the siblings of the workers (13-19) are never offered + { + const auto a = smt(12, 24); + CHECK(derive(a, 0, V{1, 2, 3, 4, 5, 6, 7}) == (V{12, 8, 9, 10, 11, 20, 21, 22, 23})); + } + // no SMT, every other core a worker: nothing spare + { + const auto a = cpus({{0, 0, 0}, {1, 0, 1}, {2, 0, 2}, {3, 0, 3}}); + CHECK(derive(a, 0, V{1, 2, 3}).empty()); + } + // no SMT, a core without a worker: that core + { + const auto a = cpus({{0, 0, 0}, {1, 0, 1}, {2, 0, 2}, {3, 0, 3}}); + CHECK(derive(a, 0, V{1, 2}) == V{3}); + } + // every CPU is a worker or the host's: nothing, with SMT too + { + const auto a = smt(4, 8); + CHECK(derive(a, 0, V{1, 2, 3}) == V{4}); // only the host's sibling + CHECK(derive(a, 0, V{1, 2, 3, 4}).empty()); // CPU 4 is a worker: the host core's sibling is taken + } + // two packages: core 1 of package 1 is not core 1 of package 0 + { + const auto a = cpus({{0, 0, 0}, {1, 0, 1}, {2, 1, 0}, {3, 1, 1}}); + CHECK(derive(a, 0, V{1, 2}) == V{3}); + } + // unknown cores (no sysfs): a CPU of unknown core could be a worker's sibling - none offered + { + const auto a = cpus({{0, -1, -1}, {1, -1, -1}, {2, -1, -1}, {3, -1, -1}}); + CHECK(derive(a, 0, V{1}).empty()); + } + // the host's CPU unknown: the free cores only + { + const auto a = smt(4, 8); + CHECK(derive(a, -1, V{0, 1}) == (V{2, 3, 6, 7})); + } + // CPUs the process may not use are not offered (a taskset): 5 and 6 are outside `a` + { + const auto a = cpus({{0, 0, 0}, {1, 0, 1}, {4, 0, 0}}); + CHECK(derive(a, 0, V{1}) == V{4}); + } + CHECK(derive(std::vector{}, 0, V{1}).empty()); +} + +#if defined(__linux__) +int tid_of_self() { return (int) syscall(SYS_gettid); } + +std::vector mask_of(int tid) { + cpu_set_t m; + CPU_ZERO(&m); + std::vector out; + if (sched_getaffinity(tid, sizeof m, &m) != 0) return out; + for (int c = 0; c < CPU_SETSIZE; ++c) + if (CPU_ISSET(c, &m)) out.push_back(c); + return out; +} + +void test_live() { + const std::vector allowed = mask_of(0); + if (allowed.size() < 4) { + std::printf("aux_cpus_test: live placement skipped (needs 4 allowed CPUs, have %zu)\n", allowed.size()); + return; + } + const int host = allowed[0], worker = allowed[1], aux_a = allowed[2], aux_b = allowed[3]; + std::string err; + CHECK(configure(std::to_string(aux_a) + "," + std::to_string(aux_b), err)); + // before the plan exists nothing is moved + CHECK(sweep() == 0); + const std::string line = set_topology(host, V{worker}); + std::printf("%s\n", line.c_str()); + CHECK(plan() == (V{aux_a, aux_b})); + CHECK(enabled()); + + // threads that stay alive until told: `floater` is created before the sweep (a CUDA driver thread's case), `owned` + // is a pool worker (registered), `late` pins itself at creation + std::atomic tid_floater{0}, tid_owned{0}, tid_late{0}; + std::atomic stop{false}; + auto body = [&](std::atomic& tid, bool owned, bool pin) { + if (owned) note_owned_thread(); + if (pin) pin_current_thread(); + tid = tid_of_self(); + while (!stop.load()) std::this_thread::sleep_for(std::chrono::milliseconds(2)); + }; + set_enabled(false); // earlier threads are born unmoved + CHECK(!enabled()); + std::thread floater([&] { body(tid_floater, false, false); }); + std::thread owned([&] { body(tid_owned, true, false); }); + for (int i = 0; i < 500 && (!tid_floater || !tid_owned); ++i) std::this_thread::sleep_for(std::chrono::milliseconds(2)); + CHECK(mask_of(tid_floater) == allowed); + + set_enabled(true); // the sweep + const V aux{aux_a, aux_b}; + CHECK(mask_of(tid_floater) == aux); + CHECK(mask_of(tid_owned) == allowed); // owned threads are left alone + CHECK(mask_of(tid_of_self()) == allowed); // so is the main thread (configure registered it) + + std::thread late([&] { body(tid_late, false, true); }); + for (int i = 0; i < 500 && !tid_late; ++i) std::this_thread::sleep_for(std::chrono::milliseconds(2)); + CHECK(mask_of(tid_late) == aux); // pinned at creation + + set_enabled(false); // back to the placements they had + CHECK(mask_of(tid_floater) == allowed); + CHECK(mask_of(tid_late) == allowed); + CHECK(mask_of(tid_owned) == allowed); + CHECK(sweep() == 0); // off: nothing moves + + // a thread pinned to ONE worker CPU by someone else is not ours even when unregistered + std::atomic tid_pinned{0}; + std::thread pinned([&] { + cpu_set_t m; + CPU_ZERO(&m); + CPU_SET(worker, &m); + sched_setaffinity(0, sizeof m, &m); + tid_pinned = tid_of_self(); + while (!stop.load()) std::this_thread::sleep_for(std::chrono::milliseconds(2)); + }); + for (int i = 0; i < 500 && !tid_pinned; ++i) std::this_thread::sleep_for(std::chrono::milliseconds(2)); + set_enabled(true); + CHECK(mask_of(tid_pinned) == V{worker}); + CHECK(mask_of(tid_floater) == aux); + set_enabled(false); + + stop = true; + floater.join(); + owned.join(); + late.join(); + pinned.join(); +} +#else +void test_live() { std::printf("aux_cpus_test: live placement is Linux only\n"); } +#endif + +} // namespace + +int main() { + test_parse(); + test_derive(); + test_live(); + if (failures) { + std::fprintf(stderr, "aux_cpus_test: %d check(s) failed\n", failures); + return 1; + } + std::printf("aux_cpus_test: ok\n"); + return 0; +}