Merge f-022-numa: NUMA-split CPU pool on multi-node machines (#3201)
This commit is contained in:
commit
4bd5912695
14 files changed
+1472
-50
No files matched your search
@@ -2112,6 +2112,11 @@ if(STRATA_BUILD_TESTS)
|
||||
add_executable(pool_plan_test src/kernels/cpu/pool_plan_test.cpp)
|
||||
target_include_directories(pool_plan_test PRIVATE include)
|
||||
add_test(NAME pool_plan_test COMMAND pool_plan_test)
|
||||
# 0.2.2: when the pool splits per NUMA node by itself (a fake sysfs node folder, mock cores; STRATA_NUMA_POOL=0, one node = unchanged)
|
||||
add_executable(numa_pool_test src/kernels/cpu/numa_pool_test.cpp)
|
||||
target_include_directories(numa_pool_test PRIVATE include)
|
||||
target_compile_features(numa_pool_test PRIVATE cxx_std_17)
|
||||
add_test(NAME numa_pool_test COMMAND numa_pool_test)
|
||||
# #3204: when the HIP start-up warm-up of hipBLAS may run (pure policy, no GPU)
|
||||
add_executable(warm_policy_test src/prefill/warm_policy_test.cpp)
|
||||
target_include_directories(warm_policy_test PRIVATE include)
|
||||
|
||||
+24
-1
@@ -649,7 +649,7 @@ when the sockets wait for each other's counters. Prompt speed did not change in
|
||||
with it translating every DMA (`cat /sys/kernel/iommu_groups/*/type | sort | uniq -c` shows `DMA-FQ`), pinned host-to-device copies ran at
|
||||
7.7 to 9.2 GB/s on PCIe 3.0 x16 and at 12.3 GB/s with `iommu=pt` on the kernel command line, which moved prompt speed by about 30% there.
|
||||
A NUMA-aware pool (one slice of workers per socket, each reading its own socket's copy of the CPU experts) gave +10 to +14% on
|
||||
the first box in a contributor's branch; it is not in this build. Do not wrap the server in `numactl --cpunodebind` when you test
|
||||
the first box in a contributor's branch; 0.2.2 has it (on by itself with 2 or more NUMA nodes, `STRATA_NUMA_POOL=0` turns it off: see "NUMA-split CPU expert pool" below). Do not wrap the server in `numactl --cpunodebind` when you test
|
||||
workers across sockets: it pins them to one node.
|
||||
|
||||
### Running it at startup (Task Scheduler)
|
||||
@@ -2110,6 +2110,29 @@ never changes a result.
|
||||
stalls above 100 us, in 7 and 8 of 12 requests off against 0 or 1 with `auto`. That preemption of the host causes the
|
||||
loss is an inference; the counters do not prove it. The warm-up requests of each run were discarded.
|
||||
|
||||
**NUMA-split CPU expert pool (0.2.2: on by itself when the machine has 2 or more NUMA nodes; off with `STRATA_NUMA_POOL=0`):** on a 2-socket Linux box it splits the CPU expert pool into
|
||||
one slice per NUMA node, each with its own task counter and barrier, and at load it places each node's half of every
|
||||
CPU-side expert's rows in that node's memory (first touch by threads pinned to that node; the model file's page cache is
|
||||
released first), so a slice reads its own socket's memory. Under the split the default worker count is the physical cores
|
||||
of both sockets minus the host core, minus one more kept free from 16 workers on, capped at 32 (22 on 2x12 cores); an explicit `--pool-workers N` is spread alternately across the
|
||||
sockets. Measured on a dual Xeon Gold 6226 (2x12 cores, 64 GB, 4 of 6 memory channels per socket populated), RTX 3090,
|
||||
PCIe 3.0 with the kernel's IOMMU in passthrough (`iommu=pt`), `orcarouter-qwen3.8-flash-next-uncensored-iq4_xs` (the
|
||||
IQ4_XS pack) at 262K context, server decode median over 12 samples: 59.3 tok/s with the split against 54.05 for the 0.2.0
|
||||
default (11 workers, one socket), +9.7% (+14% and +11.5% in two earlier sessions with the IOMMU translating DMA). Without
|
||||
the split, 22 workers gave 43.25 tok/s, and the split at 12 workers gave 51.45; prompt speed is unchanged. It needs Linux, exactly 2
|
||||
NUMA nodes and enough free memory on each node for its half: otherwise the log warns `NUMA placement at risk`, and after
|
||||
the load it judges the placement from move_pages samples and prints FAILED when a node holds under 95% of its slice. Only
|
||||
native expert layers are split (`ArenaExpertSource` and the `cudaHostAlloc` path are not, and the engine says so at start-up
|
||||
for the arena path). The pool refuses the split with `STRATA_EXCHANGE_ROTATE=1` and when the two sockets' worker counts are
|
||||
lopsided, logs the reason (`NUMA split off: ...`) and runs as usual. `STRATA_NUMA_SPLIT=test` builds the same slices by
|
||||
alternating the threads between two slices on any machine, with no node lookup, no pinning requirement and no memory
|
||||
placement; it is for testing the per-slice scheduling, not for speed.
|
||||
|
||||
*0.2.2: when it runs.* The split was a contributor's opt-in (`STRATA_NUMA_SPLIT=1`, issue #3201, measured on one dual Xeon Gold 6226 box). From 0.2.2 the pool counts the NUMA nodes that have CPUs (Linux: `/sys/devices/system/node/node*/cpulist`; Windows: `GetNumaHighestNodeNumber`) and, with 2 or more and neither `STRATA_NUMA_POOL` nor `STRATA_NUMA_SPLIT` set, tries the split by itself. **One node is exactly the pool as before: nothing is read, nothing is logged, no worker count changes.** On 2 or more nodes the split runs only when it can (Linux, exactly 2 nodes holding the pool's threads, balanced slices, pinned threads, no `STRATA_EXCHANGE_ROTATE=1`); otherwise the pool keeps its old worker count and cores and logs why: `strata cpu pool: NUMA pool off: <reason> (N NUMA nodes found), the pool runs as before` (a 4-node machine, a container that sees one node's CPUs, Windows). When it runs the log says `strata cpu pool: NUMA pool on: N NUMA nodes found, one slice of the pool per node (STRATA_NUMA_POOL=0 turns it off)`, then the `NUMA split on: slice 0 = node ...` line. **Off switch: `STRATA_NUMA_POOL=0`** (also `off`, `false`, `no`); it wins over `STRATA_NUMA_SPLIT=1`, and on a 2-node machine logs `NUMA pool off (STRATA_NUMA_POOL=0)`. `STRATA_NUMA_SPLIT=1` still asks for the split on any machine (and keeps the contributor's worker counts when it cannot run), `STRATA_NUMA_SPLIT=0` is off. On Windows the node count is read but the split itself is Linux-only for now: a Windows machine with 2 nodes logs the reason and runs as before. The 0.2.2 default was built from the report and tested on one-node machines only (identity gate and speed A/B unchanged there; the node logic runs in `numa_pool_test` on made-up topologies); it has not been run on a two-socket machine by us. Log: `strata cpu pool: NUMA split on: slice 0 = node 0 (N threads), slice 1 =
|
||||
node 1 (M threads)` at start, then `FileExpertSource: NUMA placement: node 0 <GiB> (xx.x % of its slices), node 1
|
||||
<GiB> (xx.x % of its slices); free before: ...; after the drop: ...; pages taken and page-locked in N s since the
|
||||
placement started`.
|
||||
|
||||
---
|
||||
|
||||
## Experimental speed projection (EXPERIMENTAL, off by default)
|
||||
|
||||
@@ -3,3 +3,4 @@
|
||||
## What is new
|
||||
|
||||
- **An engine package for the RX 6000 series (built, not tested on a real RX 6000 card).** Linux has `rx6000` and Windows has `rdna2`, each with GPU code for gfx1030 and gfx1031 (RX 6800, 6900 and 6950 series, RX 6700 XT). They are offered to a PC whose card reports one of those two and to no other: the RX 7000, RX 9000 and Strix Halo packages are unchanged, and a PC with an RX 7000 or 9000 card next to an RX 6000 card keeps the package it had. The engine runs plain kernels on these cards (RDNA2 has no matrix cores, so none of the RX 7000 / RX 9000 or Radeon 780M prompt paths apply) and plain hipBLAS (hipBLASLt ships no kernels for gfx1030, so there is no tuning table). Setup and the app say once that this package was built and not tested on a real RX 6000 card. What was checked: the Linux package builds, every program in it has code for exactly gfx1030 and gfx1031, the rocBLAS kernel files for both are in it, every library it imports is in the package or belongs to the system, and the whole engine (all targets, tests included) compiles for gfx1030 and gfx1031. What was not: a model on an RX 6000 card, on either system, and the Windows package itself (the Windows build scripts take the new architecture list, but no Windows `rdna2` package has been built). Earlier reports on these cards came from people who built the engine from source ([docs/AMD_HIP.md](AMD_HIP.md#rdna2-gfx1030)). If something goes wrong, open an issue with the end of `strata-<model>.log`.
|
||||
- **The CPU expert pool splits per NUMA node on a machine with two or more NUMA nodes (built from the report in #3201, not tested on a two-socket machine).** Until now the pool kept its workers on the host thread's socket, because workers on the other socket read the experts across the link and were slower. The split gives each socket its own slice of the pool with its own task counter, and places each socket's half of every CPU-side expert in that socket's memory, so a slice reads local memory only. The reporter measured +10 to +14 % decode on a dual Xeon Gold 6226 (59.3 against 54.05 tok/s with the IOMMU in passthrough); a second reporter's dual Xeon E5-2670 v2 preferred more workers across both sockets, which the split also uses. It starts by itself when the machine has two or more NUMA nodes with CPUs and runs only when it can (Linux, two nodes, pinned threads, enough free memory per node); otherwise the pool is exactly what it was and the log says why. **A machine with one NUMA node runs the same code path as 0.2.1:** the identity gate (10 prompts, exact_pp 4K and 20K) is byte-identical and the single-request speed A/B is not slower on the one-node test boxes (numbers in the notes of the branch). `STRATA_NUMA_POOL=0` turns the split off; `STRATA_NUMA_SPLIT=1` still asks for it on any machine. The start-up log says what it did: `NUMA pool on: 2 NUMA nodes found ...` or `NUMA pool off: <reason>`. On Windows the node count is read but the split itself is Linux-only for now, so a two-node Windows PC logs the reason and runs as before. The logic runs in unit tests on made-up two-, three- and four-node machines; we have no two-socket machine, so the placement and the speed on real ones are the reporters' numbers, not ours. Do not wrap the server in `numactl --cpunodebind` or `--membind`: it pulls both halves onto one node. Thanks to baptisterajaut for the branch this is built on, and to xrip and Tworks25 for their numbers. Please send the start-up lines and a decode run with and without `STRATA_NUMA_POOL=0` from a two-socket machine.
|
||||
@@ -28,6 +28,7 @@
|
||||
#include "strata/kernels/cpu/pool.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cmath>
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
@@ -115,6 +116,15 @@ uint64_t meminfo_bytes(const std::string& meminfo_text, const std::string& key);
|
||||
/// SMALLEST node's free), i.e. what an even spread would find. Only lowers the figure, so the pages are then taken in
|
||||
/// steps (which reclaim cache as they fault) instead of in one driver call; it never refuses and never caps.
|
||||
uint64_t numa_pin_free(uint64_t global_free, const std::vector<uint64_t>& node_free);
|
||||
/// Byte ranges [first, second) of slice `slice` of 2 inside one complement slot at arena offset `slot_off`, whose roles
|
||||
/// (gate, up, down) are `role_bytes[0..2]` long and back to back. Role r's slice-0 bytes are [start_r, start_r + role_r/2),
|
||||
/// its slice-1 bytes the rest. Page rule (absolute arena offsets): any page holding a slice-0 byte belongs to slice 0,
|
||||
/// so slice-0 ranges round OUTWARDS (start down, end up) and slice-1 ranges round INWARDS (start up, end down) - this
|
||||
/// also settles pages shared across role and slot boundaries. Returns three ranges in arena offsets, possibly empty
|
||||
/// (first == second). Adjacent roles smaller than a page may give overlapping slice-0 ranges: harmless (same node, the
|
||||
/// caller coalesces them).
|
||||
std::array<std::pair<uint64_t, uint64_t>, 3> numa_slice_ranges(uint64_t slot_off, const uint64_t role_bytes[3],
|
||||
int slice, uint64_t page = 4096);
|
||||
/// The sentence appended to a "not enough RAM" start failure: how much of the RAM is file cache (Cached + Buffers of
|
||||
/// `meminfo_text`, mapped pages included) and what to do about it; "" when under 1 GiB of cache (nothing to say).
|
||||
std::string page_cache_hint(const std::string& meminfo_text);
|
||||
@@ -706,6 +716,9 @@ public:
|
||||
bool open(const std::string& pack_dir, int64_t n_layers, int64_t n_expert, std::string& err);
|
||||
/// CS-T: the --native shard (native_experts.txt names the other files beside it); see `open`.
|
||||
void set_gguf(const std::string& native) { gguf_ = native; }
|
||||
/// STRATA_NUMA_SPLIT: files the engine read at start outside this source (the pack's dense.bin, the MTP head),
|
||||
/// whose cached pages the placement's drop gives back too. Set BEFORE `pin_cache_complement`.
|
||||
void set_extra_drop_files(std::vector<std::string> paths) { extra_drop_files_ = std::move(paths); }
|
||||
/// Whether the experts are read from the GGUF shards in place (no experts.bin).
|
||||
bool gguf_mode() const { return !role_ptr_.empty(); }
|
||||
/// Pin a compact host mirror of experts absent from a fully filled static GPU cache. The mmap remains open
|
||||
@@ -1052,6 +1065,7 @@ private:
|
||||
static constexpr uint64_t kNoComplement = detail::kNoCacheComplement;
|
||||
// ---- CS-T: the GGUF shards in place
|
||||
std::string gguf_;
|
||||
std::vector<std::string> extra_drop_files_; ///< set_extra_drop_files
|
||||
struct Map {
|
||||
const uint8_t* base = nullptr;
|
||||
uint64_t bytes = 0;
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
// include/strata/kernels/cpu/numa_pool.hpp - when the CPU expert pool splits per NUMA node (0.2.2).
|
||||
//
|
||||
// Pure decisions, no threads and no globals, so a test can feed them a made-up machine:
|
||||
// * numa_cpu_node_count_at(dir) how many NUMA nodes with CPUs a sysfs node folder lists (Linux: /sys/devices/system/node;
|
||||
// Windows reads GetNumaHighestNodeNumber in pool.cpp; every other system: 1)
|
||||
// * pick_numa_pool(...) whether the split is tried without STRATA_NUMA_SPLIT, and the line that says so
|
||||
// * decide_numa_split(...) the split's plan for a pool whose threads sit on given cores
|
||||
//
|
||||
// One node is exactly the code path before the split existed: pick_numa_pool answers `Unchanged` with no log line and the pool
|
||||
// never reads anything else from here. STRATA_NUMA_POOL=0 is the off switch of the default; STRATA_NUMA_SPLIT=1 / test keep
|
||||
// their meaning from the contributor's branch (#3201).
|
||||
#pragma once
|
||||
|
||||
#include "strata/kernels/cpu/pool_plan.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <functional>
|
||||
#include <string>
|
||||
#include <system_error>
|
||||
#include <vector>
|
||||
|
||||
namespace strata::kernels::cpu {
|
||||
|
||||
/// Whether text is "0", "off", "false" or "no" (any case): the spelling of every off switch of the pool.
|
||||
inline bool numa_switch_off(const char* v) {
|
||||
if (v == nullptr) return false;
|
||||
std::string s(v);
|
||||
std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) { return (char) std::tolower(c); });
|
||||
return s == "0" || s == "off" || s == "false" || s == "no";
|
||||
}
|
||||
|
||||
/// The NUMA nodes with CPUs under a sysfs node folder (`node0`, `node1`, ... each holding a `cpulist`). A node without CPUs
|
||||
/// (CXL or other memory-only nodes) is not counted: the pool splits threads, and a node with none has none to split.
|
||||
/// A folder that is missing or has no node entries counts 0 (the caller treats 0 and 1 alike: no split).
|
||||
inline int numa_cpu_node_count_at(const std::string& node_dir) {
|
||||
std::error_code ec;
|
||||
int nodes = 0;
|
||||
for (std::filesystem::directory_iterator it(node_dir, ec), end; !ec && it != end; it.increment(ec)) {
|
||||
const std::string name = it->path().filename().string();
|
||||
if (name.size() < 5 || name.compare(0, 4, "node") != 0) continue;
|
||||
if (!std::all_of(name.begin() + 4, name.end(), [](unsigned char c) { return std::isdigit(c) != 0; })) continue;
|
||||
std::ifstream f(it->path() / "cpulist");
|
||||
std::string list;
|
||||
std::getline(f, list);
|
||||
if (list.find_first_of("0123456789") != std::string::npos) ++nodes;
|
||||
}
|
||||
return nodes;
|
||||
}
|
||||
|
||||
enum class NumaPoolChoice {
|
||||
Unchanged, ///< nothing new: STRATA_NUMA_SPLIT (set or not) decides as it did before 0.2.2
|
||||
Off, ///< STRATA_NUMA_POOL=0 on a machine that matters: the split is off, whatever STRATA_NUMA_SPLIT says
|
||||
Auto, ///< two or more NUMA nodes and nothing set: try the split by itself; if it cannot run the pool stays as it was
|
||||
};
|
||||
struct NumaPoolPick {
|
||||
NumaPoolChoice choice = NumaPoolChoice::Unchanged;
|
||||
std::string log; ///< the line to print ("" = print nothing)
|
||||
};
|
||||
|
||||
/// `pool_env` is STRATA_NUMA_POOL, `split_env` STRATA_NUMA_SPLIT (nullptr or "" = unset), `nodes` the NUMA nodes with CPUs.
|
||||
/// one node, nothing set -> Unchanged, silent (today's code path to the instruction)
|
||||
/// STRATA_NUMA_POOL=0, two or more nodes -> Off, with a line that says so
|
||||
/// STRATA_NUMA_POOL=0, STRATA_NUMA_SPLIT set -> Off (the off switch wins), with a line
|
||||
/// STRATA_NUMA_SPLIT set (1, test, 0, ...) -> Unchanged: the contributor's variable keeps its old meaning
|
||||
/// two or more nodes, nothing set -> Auto
|
||||
inline NumaPoolPick pick_numa_pool(const char* pool_env, const char* split_env, int nodes) {
|
||||
const bool split_set = split_env != nullptr && *split_env != '\0';
|
||||
NumaPoolPick pick;
|
||||
if (numa_switch_off(pool_env) && (nodes >= 2 || split_set)) {
|
||||
pick.choice = NumaPoolChoice::Off;
|
||||
pick.log = "strata cpu pool: NUMA pool off (STRATA_NUMA_POOL=0): " +
|
||||
(nodes >= 2 ? std::to_string(nodes) + " NUMA nodes found" : std::string("one NUMA node")) +
|
||||
", the pool runs as before";
|
||||
return pick;
|
||||
}
|
||||
if (split_set || nodes < 2) return pick;
|
||||
pick.choice = NumaPoolChoice::Auto;
|
||||
return pick;
|
||||
}
|
||||
|
||||
struct NumaSplitDecision {
|
||||
bool on = false;
|
||||
std::string why; ///< the reason when off
|
||||
int nodes[2] = {-1, -1}; ///< the two node ids, ascending
|
||||
std::vector<int> slice; ///< each thread's slice (0 or 1)
|
||||
int per[2] = {0, 0}; ///< threads per slice
|
||||
};
|
||||
|
||||
/// The real-node split of a pool whose threads sit on `thread_core` (workers first, then the host when it drains; -1 = no core).
|
||||
/// `n_workers` tells a worker from the host in the messages; `pinned` is whether the pool pins its threads; `rotate` is
|
||||
/// STRATA_EXCHANGE_ROTATE=1 (experts move between slots, the split needs fixed ones); `node_of(core)` is the core's NUMA node or -1.
|
||||
inline NumaSplitDecision decide_numa_split(const std::vector<int>& thread_core, int n_workers, bool pinned, bool rotate,
|
||||
const std::function<int(int)>& node_of) {
|
||||
NumaSplitDecision d;
|
||||
const int threads = (int) thread_core.size();
|
||||
std::vector<int> node((size_t) threads, -1);
|
||||
if (threads < 2) {
|
||||
d.why = "the pool has " + std::to_string(threads) + " thread, the split needs 2 or more";
|
||||
return d;
|
||||
}
|
||||
if (rotate) {
|
||||
d.why = "STRATA_EXCHANGE_ROTATE=1 moves experts between slots, the split needs fixed slots";
|
||||
return d;
|
||||
}
|
||||
if (!pinned) {
|
||||
d.why = "the pool's threads are not pinned";
|
||||
return d;
|
||||
}
|
||||
for (int j = 0; j < threads; ++j) {
|
||||
const int c = thread_core[(size_t) j];
|
||||
if (c < 0) {
|
||||
d.why = j < n_workers ? "worker " + std::to_string(j) + " has no core to be pinned to" : "the host thread has no core";
|
||||
return d;
|
||||
}
|
||||
if ((node[(size_t) j] = node_of(c)) < 0) {
|
||||
d.why = "CPU " + std::to_string(c) + " has no known NUMA node";
|
||||
return d;
|
||||
}
|
||||
}
|
||||
std::vector<int> nodes = node;
|
||||
std::sort(nodes.begin(), nodes.end());
|
||||
nodes.erase(std::unique(nodes.begin(), nodes.end()), nodes.end());
|
||||
if (nodes.size() != 2) {
|
||||
d.why = "the pool's threads span " + std::to_string(nodes.size()) + " NUMA node(s), the NUMA split supports exactly 2";
|
||||
return d;
|
||||
}
|
||||
d.nodes[0] = nodes[0];
|
||||
d.nodes[1] = nodes[1];
|
||||
d.slice.assign((size_t) threads, 0);
|
||||
for (int j = 0; j < threads; ++j) {
|
||||
d.slice[(size_t) j] = node[(size_t) j] == nodes[1] ? 1 : 0;
|
||||
++d.per[d.slice[(size_t) j]];
|
||||
}
|
||||
if (!numa_slices_balanced(d.per[0], d.per[1])) {
|
||||
d.why = "slices too unbalanced (node " + std::to_string(nodes[0]) + ": " + std::to_string(d.per[0]) + " thread" +
|
||||
(d.per[0] == 1 ? "" : "s") + ", node " + std::to_string(nodes[1]) + ": " + std::to_string(d.per[1]) + " thread" +
|
||||
(d.per[1] == 1 ? "" : "s") + ")";
|
||||
d.nodes[0] = d.nodes[1] = -1;
|
||||
d.slice.clear();
|
||||
d.per[0] = d.per[1] = 0;
|
||||
return d;
|
||||
}
|
||||
d.on = true;
|
||||
return d;
|
||||
}
|
||||
|
||||
} // namespace strata::kernels::cpu
|
||||
@@ -38,6 +38,7 @@
|
||||
#include <condition_variable>
|
||||
#include <cstdint>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
@@ -153,6 +154,20 @@ struct ThreadAffinity {
|
||||
ThreadAffinity pin_current_thread(int core);
|
||||
void restore_thread_affinity(const ThreadAffinity& previous);
|
||||
|
||||
/// STRATA_NUMA_SPLIT's decision for a pool (see `ExpertPool`'s NodeSync). `1` splits on the real NUMA nodes of
|
||||
/// the pinned threads (Linux, exactly 2 nodes); `test` splits by thread index (thread j -> slice j % 2) with no real
|
||||
/// node, for the parity test.
|
||||
struct NumaSplitPlan {
|
||||
bool on = false; ///< split enabled
|
||||
bool test = false; ///< STRATA_NUMA_SPLIT=test: no real nodes, never places memory
|
||||
int nodes[2] = {-1, -1}; ///< real node id of slice 0 and 1 (ascending); -1 in test mode
|
||||
std::vector<int> cores[2]; ///< the cores the pool pinned for each slice (workers + host)
|
||||
std::string why; ///< reason when off ("" when on, or when the env var is unset)
|
||||
};
|
||||
/// The live pool's decision (set by the ExpertPool constructor, reset by its destructor); `on == false` when no
|
||||
/// pool exists or the split is off.
|
||||
const NumaSplitPlan& active_numa_split();
|
||||
|
||||
class ExpertPool {
|
||||
public:
|
||||
/// `n_workers <= 0` means "every physical core except the first". Workers are pinned to physical cores
|
||||
@@ -185,11 +200,17 @@ public:
|
||||
const char* plan_limit() const { return plan_limit_; }
|
||||
int plan_cores() const { return plan_cores_; }
|
||||
int plan_logical() const { return plan_logical_; }
|
||||
/// STRATA_NUMA_SPLIT: 2 when the native row phases are split per NUMA node, 0 when off.
|
||||
int numa_slices() const { return numa_n_; }
|
||||
/// Accumulated drain time of slice `s` over the mode-5/6 phases, ms: publish to the slice's last `done`.
|
||||
double numa_slice_ms(int s) const { return s >= 0 && s < numa_n_ ? slice_ms_[s] : 0.0; }
|
||||
/// Whether the host thread also drains. Reported at startup, because "the engine adapts to the machine it
|
||||
/// is on" is only true if the engine says which adaptation it took.
|
||||
bool host_works() const { return host_works_; }
|
||||
|
||||
bool is_hybrid() const { return topo_.is_hybrid; }
|
||||
/// The CPUs worker i is pinned to, in worker order (STRATA_NUMA_SPLIT reorders them: interleave_packages).
|
||||
const std::vector<int>& worker_cores() const { return topo_.worker_cores; }
|
||||
int p_cores() const { return topo_.p_cores; }
|
||||
int p_threads() const { return topo_.p_threads; }
|
||||
int e_cores() const { return topo_.e_cores; }
|
||||
@@ -326,6 +347,48 @@ private:
|
||||
};
|
||||
const NativeFmt* nfmt_ = nullptr;
|
||||
std::vector<SplitBufMulti> split_multi_;
|
||||
// STRATA_NUMA_SPLIT=1 (opt-in, Linux, exactly 2 nodes): in the native row phases (modes 5/6) every expert's rows
|
||||
// are cut into one slice per NUMA node (slice k = rows [per*k/2, per*(k+1)/2) of the gate/up or down matrix, the
|
||||
// part the resident complement places on node k in step B), and each node's threads claim and count on their own
|
||||
// slice's counters; in every mode they park on their own `parked`. Off (`numa_n_ == 0`, the decision is final in
|
||||
// the constructor): none of this is touched and the pool is as before.
|
||||
//
|
||||
// THE CLAIM PROTOCOL IS issue #29's, ONCE PER SLICE. Each slice head packs `epoch | njobs | index` and is claimed
|
||||
// with the same CAS as `head_`. A mode-5/6 batch stores every slice head with its epoch and leaves `head_` alone;
|
||||
// any other batch stores `head_` and leaves the slice heads alone. So for batch `e` exactly one family of heads
|
||||
// carries `e`, and a stale head is always exhausted (`wait_done` saw every task of it done). A worker therefore
|
||||
// never reads `mode_` to pick a counter: it tries its slice head, then `head_`, and the epoch tag makes the wrong
|
||||
// one fail - as it makes a late worker's claim fail.
|
||||
struct NodeSync {
|
||||
alignas(64) std::atomic<uint64_t> head{0}; // as `head_`, for this slice of the phase
|
||||
alignas(64) std::atomic<uint32_t> done{0}; // as `done_`
|
||||
alignas(64) std::atomic<uint32_t> parked{0}; // as `parked_`, this slice's workers only
|
||||
alignas(64) std::atomic<int64_t> drained_ns{0}; // steady_clock ns when `done` reached `tasks` (0: not yet)
|
||||
// the batch's description, written by the host before the head's release store, read after a claim
|
||||
alignas(64) int base = 0; // the slice's first task index in the phase (task ids are global for `diag`)
|
||||
int tasks = 0; // T: the slice's task count
|
||||
int h = 0; // rows of each expert in the slice
|
||||
int row0 = 0; // the slice's first matrix row (per*k/2)
|
||||
int64_t rows = 0; // R = experts * h
|
||||
};
|
||||
// CBA: the NodeSync blocks live wherever `new` puts them (the host's node); per-node pages if the remote home
|
||||
// of a line ever shows up in the counters.
|
||||
std::unique_ptr<NodeSync[]> nsync_;
|
||||
int numa_n_ = 0; // slices (2 when on), 0 = off
|
||||
std::vector<int> wslice_; // each worker's slice
|
||||
int hslice_ = 0; // the host's slice (when it drains)
|
||||
std::vector<int> slice_threads_; // threads draining each slice (the host counted in its own)
|
||||
int64_t pub_ns_ = 0; // the current mode-5/6 phase's publish time (host only)
|
||||
double slice_ms_[2] = {0.0, 0.0}; // accumulated per-slice drain time (host only)
|
||||
bool numa_phase() const { return numa_n_ > 0 && mode_ >= 5; }
|
||||
/// The claim of `claim()` on slice `slice`'s head: `base + i`, or -1.
|
||||
int claim_slice(uint32_t epoch, int slice);
|
||||
std::atomic<uint32_t>& parked_of(int id) { return numa_n_ > 0 ? nsync_[(size_t) wslice_[(size_t) id]].parked : parked_; }
|
||||
uint32_t parked_count() const;
|
||||
/// Fill the slices' descriptions for a mode-5/6 phase of `nb` experts of `per` rows; returns the total tasks.
|
||||
int numa_plan_phase(int per, int nb);
|
||||
/// Per-slice counters for the stall messages and `diag` ("" when off).
|
||||
std::string numa_counters() const;
|
||||
PoolAffinity affinity_ = PoolAffinity::All;
|
||||
CpuTopology topo_;
|
||||
};
|
||||
|
||||
@@ -43,6 +43,10 @@ struct PoolPlanInput {
|
||||
/// +12.6% over the 19 of one-per-core, 24 workers -44%: notes-152-users.md).
|
||||
int p_cores = 0;
|
||||
int e_cores = 0;
|
||||
/// STRATA_NUMA_SPLIT (opt-in): the split needs workers on both NUMA nodes, so the default may use the cores of
|
||||
/// every package instead of the host's only, and a configured count above the host's socket is not warned about.
|
||||
/// The other bounds (reserve, hybrid, quota, cap) stay. False: the plan above, unchanged.
|
||||
bool span_packages = false;
|
||||
};
|
||||
|
||||
/// #3262: is a CPU an efficiency-class core? `pmu_core` / `pmu_atom` / `pmu_lowpower` are Intel's hybrid PMU lists
|
||||
@@ -83,11 +87,14 @@ inline PoolPlan plan_pool_workers(const PoolPlanInput& in) {
|
||||
local = cores;
|
||||
p.packages = 1;
|
||||
}
|
||||
const bool span = in.span_packages && p.topology_known && p.packages > 1;
|
||||
if (span) local = cores; // STRATA_NUMA_SPLIT: every socket counts as local
|
||||
p.cores = cores;
|
||||
p.cores_local = local;
|
||||
p.limit = "every physical core but the host's";
|
||||
int n = std::max(1, local - 1); // the host thread has the first core
|
||||
if (!p.topology_known) p.limit = "half the logical processors (the OS gave no core layout)";
|
||||
else if (span) p.limit = "every CPU socket (STRATA_NUMA_SPLIT)";
|
||||
else if (p.packages > 1) p.limit = "the host's CPU socket";
|
||||
if (n >= kPoolReserveFrom) { // a big CPU keeps a core for the engine's other threads
|
||||
n -= kPoolReserve;
|
||||
@@ -127,7 +134,7 @@ inline std::string pool_workers_warning(int requested, const PoolPlanInput& in,
|
||||
if (plan.topology_known && requested + 1 > plan.cores)
|
||||
return asked + ", but this CPU has " + std::to_string(plan.cores) +
|
||||
" physical cores. Two workers on one core share its memory bandwidth and slow each other down. " + rec;
|
||||
if (plan.packages > 1 && requested + 1 > plan.cores_local)
|
||||
if (plan.packages > 1 && !in.span_packages && requested + 1 > plan.cores_local)
|
||||
return asked + ", more than the " + std::to_string(plan.cores_local) +
|
||||
" cores of the CPU socket the engine's main thread runs on. Workers on the other socket read the experts " +
|
||||
"across the link and were measured slower than fewer local ones. " + rec;
|
||||
@@ -138,4 +145,27 @@ inline std::string pool_workers_warning(int requested, const PoolPlanInput& in,
|
||||
std::to_string(plan.workers) + " workers and the end of each layer waits for every one). " + rec;
|
||||
}
|
||||
|
||||
/// STRATA_NUMA_SPLIT: whether two slices of `a` and `b` threads may split the rows 50/50 - a slice with under half
|
||||
/// the other's threads would be the straggler of every batch, so the pool refuses that split.
|
||||
inline bool numa_slices_balanced(int a, int b) { return std::min(a, b) * 2 >= std::max(a, b); }
|
||||
|
||||
/// STRATA_NUMA_SPLIT: the order to take worker cores in so that a count below the core count (the default or a
|
||||
/// configured one) still spans the packages evenly - round-robin over the packages in their first-seen order (the
|
||||
/// host's first), stable inside each.
|
||||
/// `package[i]` is worker core i's package (-1: unknown, a package of its own); returns indices into it.
|
||||
inline std::vector<size_t> interleave_packages(const std::vector<int>& package) {
|
||||
std::vector<int> ids; // packages in first-seen order
|
||||
std::vector<std::vector<size_t>> of; // each package's worker indices, in order
|
||||
for (size_t i = 0; i < package.size(); ++i) {
|
||||
const size_t k = (size_t) (std::find(ids.begin(), ids.end(), package[i]) - ids.begin());
|
||||
if (k == ids.size()) { ids.push_back(package[i]); of.emplace_back(); }
|
||||
of[k].push_back(i);
|
||||
}
|
||||
std::vector<size_t> order;
|
||||
for (size_t r = 0; order.size() < package.size(); ++r)
|
||||
for (const auto& v : of)
|
||||
if (r < v.size()) order.push_back(v[r]);
|
||||
return order;
|
||||
}
|
||||
|
||||
} // namespace strata::kernels::cpu
|
||||
+288
-3
@@ -15,11 +15,13 @@
|
||||
#include "strata/kernels/s2_expert_grouped.hpp"
|
||||
#include "strata/kernels/cpu/kq_avx1.hpp"
|
||||
#include "strata/kernels/cpu/kq_avx2.hpp"
|
||||
#include "strata/kernels/cpu/pool.hpp"
|
||||
|
||||
#include <cuda_runtime.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <cassert>
|
||||
#include <cerrno>
|
||||
#include <chrono>
|
||||
#include <cstdio>
|
||||
@@ -55,6 +57,7 @@
|
||||
#if defined(__linux__)
|
||||
#include <cerrno>
|
||||
#include <linux/aio_abi.h> // the kernel's own asynchronous reads (io_submit): no library, allowed by Docker's seccomp
|
||||
#include <sched.h>
|
||||
#include <sys/syscall.h>
|
||||
#endif
|
||||
|
||||
@@ -126,6 +129,24 @@ uint64_t numa_pin_free(uint64_t global_free, const std::vector<uint64_t>& node_f
|
||||
return std::min<uint64_t>(global_free, smallest * (uint64_t) node_free.size());
|
||||
}
|
||||
|
||||
std::array<std::pair<uint64_t, uint64_t>, 3> numa_slice_ranges(uint64_t slot_off, const uint64_t role_bytes[3],
|
||||
int slice, uint64_t page) {
|
||||
assert(slice == 0 || slice == 1);
|
||||
std::array<std::pair<uint64_t, uint64_t>, 3> out{};
|
||||
uint64_t start = slot_off;
|
||||
for (int r = 0; r < 3; ++r) {
|
||||
const uint64_t mid = start + role_bytes[r] / 2, end = start + role_bytes[r];
|
||||
if (slice == 0) {
|
||||
out[r] = {start / page * page, (mid + page - 1) / page * page};
|
||||
} else {
|
||||
const uint64_t lo = (mid + page - 1) / page * page, hi = end / page * page;
|
||||
out[r] = hi > lo ? std::make_pair(lo, hi) : std::make_pair(lo, lo);
|
||||
}
|
||||
start = end;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
std::string page_cache_hint(const std::string& meminfo_text) {
|
||||
const uint64_t cache = meminfo_bytes(meminfo_text, "Cached") + meminfo_bytes(meminfo_text, "Buffers");
|
||||
if (cache < (1ull << 30)) return "";
|
||||
@@ -502,6 +523,218 @@ void log_complement_memory(const char* stage, uint64_t requested) {
|
||||
#endif
|
||||
}
|
||||
|
||||
#if defined(__linux__)
|
||||
/// STRATA_NUMA_SPLIT step B: each NUMA slice of every complement slot (numa_slice_ranges) is first-touched by a helper
|
||||
/// thread pinned to one core of that slice's node, so the default local policy puts its pages there (no mbind: ~113k
|
||||
/// ranges would split the arena into more VMAs than vm.max_map_count allows). Inactive (`place` false) unless the
|
||||
/// live pool split on real nodes; then the paced fault loop hands it each step to touch.
|
||||
struct NumaComplementPlacement {
|
||||
bool place = false;
|
||||
int nodes[2] = {-1, -1};
|
||||
int core[2] = {-1, -1};
|
||||
std::vector<std::pair<uint64_t, uint64_t>> ranges[2]; ///< page-aligned, sorted, coalesced, arena offsets
|
||||
uint64_t slice_bytes[2] = {0, 0};
|
||||
std::vector<uint64_t> free_before; ///< MemFree per node before the allocation
|
||||
std::vector<uint64_t> free_after; ///< the same after the model files' pages are released
|
||||
std::atomic<bool> pin_failed{false};
|
||||
std::chrono::steady_clock::time_point t0;
|
||||
|
||||
static std::vector<uint64_t> node_free() {
|
||||
// CBA: stops at the first missing node directory (as free_memory_bytes does), sparse node ids give a false
|
||||
// "at risk 0.00" line only; list the node directory if a sparse-id host ever shows it
|
||||
std::vector<uint64_t> out;
|
||||
for (int n = 0; n < 64; ++n) {
|
||||
std::ifstream node("/sys/devices/system/node/node" + std::to_string(n) + "/meminfo");
|
||||
if (!node) break;
|
||||
std::string line;
|
||||
uint64_t kb = 0;
|
||||
while (std::getline(node, line)) {
|
||||
std::istringstream f(line);
|
||||
std::string a, id, key;
|
||||
if (f >> a >> id >> key >> kb && key == "MemFree:") break;
|
||||
kb = 0;
|
||||
}
|
||||
out.push_back(kb * 1024);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
static std::string free_text(const std::vector<uint64_t>& free) {
|
||||
std::string s;
|
||||
char buf[64];
|
||||
for (size_t n = 0; n < free.size(); ++n) {
|
||||
std::snprintf(buf, sizeof buf, "%snode %zu %.2f GiB", n ? ", " : "", n, (double) free[n] / 1073741824.0);
|
||||
s += buf;
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
/// Decides from the live pool's plan; false with a logged reason when the split is on but placement cannot run.
|
||||
void init(const std::vector<uint64_t>& offsets, int64_t n_expert, const std::vector<uint64_t>& blob_bytes,
|
||||
const std::vector<uint64_t>& role_bytes) {
|
||||
// relies on the pool being built first (generate.cpp: the ExpertPool at ~5632, the complement at ~7690)
|
||||
const auto& plan = strata::kernels::cpu::active_numa_split();
|
||||
if (!plan.on || plan.test) return;
|
||||
free_before = node_free();
|
||||
const char* why = nullptr;
|
||||
if (role_bytes.size() != 3 * blob_bytes.size()) why = "this pack has no per-role byte sizes (not a GGUF-mapped native pack)";
|
||||
for (size_t l = 0; why == nullptr && l < blob_bytes.size(); ++l)
|
||||
if (role_bytes[3 * l] + role_bytes[3 * l + 1] + role_bytes[3 * l + 2] != blob_bytes[l])
|
||||
why = "the role sizes do not add up to the expert blob";
|
||||
for (int k = 0; why == nullptr && k < 2; ++k)
|
||||
if (plan.cores[k].empty()) why = "a slice has no core";
|
||||
else if (plan.nodes[k] < 0 || plan.nodes[k] >= 64) why = "a node id is out of range";
|
||||
if (why != nullptr) {
|
||||
std::fprintf(stderr, "FileExpertSource: WARNING: NUMA placement FAILED: %s; the complement is placed by "
|
||||
"first touch as usual (the split runs with remote reads)\n", why);
|
||||
return;
|
||||
}
|
||||
for (int k = 0; k < 2; ++k) {
|
||||
nodes[k] = plan.nodes[k];
|
||||
core[k] = plan.cores[k].front(); // workers come before the host core in the plan
|
||||
std::vector<std::pair<uint64_t, uint64_t>> all;
|
||||
for (size_t i = 0; i < offsets.size(); ++i) {
|
||||
if (offsets[i] == detail::kNoCacheComplement) continue;
|
||||
const size_t l = i / (size_t) n_expert;
|
||||
for (const auto& r : detail::numa_slice_ranges(offsets[i], &role_bytes[3 * l], k))
|
||||
if (r.second > r.first) all.push_back(r);
|
||||
}
|
||||
std::sort(all.begin(), all.end());
|
||||
for (const auto& r : all) { // coalesce: ends become monotonic, so a step finds its first range by bisection
|
||||
if (!ranges[k].empty() && r.first <= ranges[k].back().second)
|
||||
ranges[k].back().second = std::max(ranges[k].back().second, r.second);
|
||||
else ranges[k].push_back(r);
|
||||
}
|
||||
for (const auto& r : ranges[k]) slice_bytes[k] += r.second - r.first;
|
||||
}
|
||||
place = true;
|
||||
t0 = std::chrono::steady_clock::now();
|
||||
std::fprintf(stderr, "FileExpertSource: NUMA placement of the complement: slice 0 -> node %d (%.2f GiB, toucher "
|
||||
"CPU %d), slice 1 -> node %d (%.2f GiB, toucher CPU %d), 4 KiB pages; free before: %s\n",
|
||||
nodes[0], (double) slice_bytes[0] / 1073741824.0, core[0], nodes[1],
|
||||
(double) slice_bytes[1] / 1073741824.0, core[1], free_text(free_before).c_str());
|
||||
}
|
||||
|
||||
/// Touches one byte per page of each slice's ranges clipped to [lo, hi), one pinned thread per slice; then the
|
||||
/// calling thread touches the step's other pages (outside every slice: slot tails, the arena end). The caller
|
||||
/// must not re-touch slice pages: with automatic NUMA balancing on, its access faults would migrate them to its node.
|
||||
void touch_step(uint8_t* arena, uint64_t lo, uint64_t hi) {
|
||||
// CBA: two threads spawned per 1 GiB step (~50 spawns per start); long-lived touchers if the spawn ever shows
|
||||
auto touch = [&](int k) {
|
||||
cpu_set_t set;
|
||||
CPU_ZERO(&set);
|
||||
CPU_SET(core[k], &set);
|
||||
if (sched_setaffinity(0, sizeof set, &set) != 0) pin_failed = true;
|
||||
const auto& rs = ranges[k];
|
||||
auto it = std::partition_point(rs.begin(), rs.end(), [&](const auto& r) { return r.second <= lo; });
|
||||
for (; it != rs.end() && it->first < hi; ++it)
|
||||
for (uint64_t at = std::max(it->first, lo); at < std::min(it->second, hi); at += 4096)
|
||||
((volatile uint8_t*) arena)[at] = 0;
|
||||
};
|
||||
// CBA: a failed spawn terminates; fall back to an unpinned touch if it ever happens
|
||||
std::thread a(touch, 0), b(touch, 1);
|
||||
a.join();
|
||||
b.join();
|
||||
size_t c[2] = {0, 0}; // the pages no slice holds, as the default loop touches them
|
||||
for (uint64_t at = lo; at < hi; at += 4096) {
|
||||
bool covered = false;
|
||||
for (int k = 0; k < 2; ++k) {
|
||||
while (c[k] < ranges[k].size() && ranges[k][c[k]].second <= at) ++c[k];
|
||||
covered = covered || (c[k] < ranges[k].size() && ranges[k][c[k]].first <= at);
|
||||
}
|
||||
if (!covered) ((volatile uint8_t*) arena)[at] = 0;
|
||||
}
|
||||
}
|
||||
|
||||
/// After the drop: a node whose free memory cannot take its slice plus `reserve_share` will spill to the other node
|
||||
/// (no local reclaim); named up front, the 95 % check stays the verdict.
|
||||
void check_room(uint64_t reserve_share) const {
|
||||
for (int k = 0; k < 2; ++k) {
|
||||
const uint64_t room = (size_t) nodes[k] < free_after.size() ? free_after[(size_t) nodes[k]] : 0;
|
||||
if (room < slice_bytes[k] + reserve_share)
|
||||
std::fprintf(stderr, "FileExpertSource: WARNING: NUMA placement at risk: node %d has %.2f GiB free for its "
|
||||
"%.2f GiB slice plus %.2f GiB of reserve\n",
|
||||
nodes[k], (double) room / 1073741824.0, (double) slice_bytes[k] / 1073741824.0,
|
||||
(double) reserve_share / 1073741824.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// Samples one page in 64 of each slice with move_pages (null node list: returns each page's node) and logs the
|
||||
/// share on the intended node, once the arena is registered (its final state); `got < bytes` means the paced loop
|
||||
/// stopped early, `registered < bytes` that the driver did not page-lock all of it: the placement then fails.
|
||||
void report(const uint8_t* arena, uint64_t got, uint64_t registered, uint64_t bytes, const char* stop) const {
|
||||
const double secs = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
|
||||
uint64_t on_node[2] = {0, 0}, sampled[2] = {0, 0}, per_node[2][64] = {}, absent[2] = {0, 0};
|
||||
constexpr int kNotSampled = -100000; // outside any per-page status (a node id, or -errno)
|
||||
int sys_errno[2] = {0, 0}; // first errno of a failed move_pages batch, per slice
|
||||
size_t batches[2] = {0, 0}, failed[2] = {0, 0};
|
||||
std::vector<void*> pages;
|
||||
std::vector<int> status;
|
||||
for (int k = 0; k < 2; ++k) {
|
||||
uint64_t n = 0;
|
||||
pages.clear();
|
||||
for (const auto& r : ranges[k])
|
||||
for (uint64_t at = r.first; at < r.second; at += 4096, ++n)
|
||||
if (n % 64 == 0) pages.push_back((void*) (arena + at));
|
||||
status.assign(pages.size(), -1);
|
||||
for (size_t b = 0; b < pages.size(); b += 4096) {
|
||||
const size_t cnt = std::min<size_t>(4096, pages.size() - b);
|
||||
++batches[k];
|
||||
if (syscall(SYS_move_pages, 0, (unsigned long) cnt, pages.data() + b, nullptr, status.data() + b, 0) != 0) {
|
||||
if (sys_errno[k] == 0) sys_errno[k] = errno;
|
||||
++failed[k];
|
||||
for (size_t i = b; i < b + cnt; ++i) status[i] = kNotSampled; // the syscall failed: no sample, unlike a page's own -errno
|
||||
}
|
||||
}
|
||||
for (int s : status) {
|
||||
if (s == kNotSampled) continue;
|
||||
++sampled[k];
|
||||
if (s >= 0 && s < 64) ++per_node[k][s];
|
||||
else ++absent[k];
|
||||
}
|
||||
on_node[k] = nodes[k] >= 0 && nodes[k] < 64 ? per_node[k][nodes[k]] : 0;
|
||||
}
|
||||
double share[2];
|
||||
for (int k = 0; k < 2; ++k) share[k] = sampled[k] > 0 ? 100.0 * (double) on_node[k] / (double) sampled[k] : 0.0;
|
||||
char what[2][96]; // a slice whose move_pages batches all failed has no share to print
|
||||
for (int k = 0; k < 2; ++k) {
|
||||
if (batches[k] > 0 && failed[k] == batches[k]) std::snprintf(what[k], sizeof what[k], "not verified");
|
||||
else std::snprintf(what[k], sizeof what[k], "%.2f GiB (%.1f %% of its slices)",
|
||||
share[k] / 100.0 * (double) slice_bytes[k] / 1073741824.0, share[k]);
|
||||
}
|
||||
std::fprintf(stderr, "FileExpertSource: NUMA placement: node %d %s, node %d %s; free before: %s; after the drop: %s; "
|
||||
"pages taken and page-locked in %.1f s since the placement started\n",
|
||||
nodes[0], what[0], nodes[1], what[1], free_text(free_before).c_str(), free_text(free_after).c_str(), secs);
|
||||
if (got < bytes)
|
||||
std::fprintf(stderr, "FileExpertSource: WARNING: NUMA placement FAILED: the paced loop stopped at %.2f of %.2f "
|
||||
"GiB (%s); the rest is first-touched by unpinned copy threads (memory not placed on its node: the split runs with remote reads)\n",
|
||||
(double) got / 1073741824.0, (double) bytes / 1073741824.0, stop != nullptr ? stop : "?");
|
||||
else if (registered < bytes)
|
||||
std::fprintf(stderr, "FileExpertSource: WARNING: NUMA placement FAILED: only %.2f of %.2f GiB page-locked (%s); "
|
||||
"the unregistered pages can be migrated by NUMA balancing (memory not placed on its node: the split runs with remote reads)\n",
|
||||
(double) registered / 1073741824.0, (double) bytes / 1073741824.0, stop != nullptr ? stop : "?");
|
||||
if (pin_failed)
|
||||
std::fprintf(stderr, "FileExpertSource: WARNING: NUMA placement: a toucher could not be pinned to its core\n");
|
||||
for (int k = 0; k < 2; ++k) {
|
||||
if (batches[k] > 0 && failed[k] == batches[k]) {
|
||||
std::fprintf(stderr, "FileExpertSource: WARNING: NUMA placement could not be verified: move_pages failed "
|
||||
"(errno %d: %s) for slice %d (node %d)\n", sys_errno[k], std::strerror(sys_errno[k]), k, nodes[k]);
|
||||
continue;
|
||||
}
|
||||
if (failed[k] > 0)
|
||||
std::fprintf(stderr, "FileExpertSource: WARNING: NUMA placement: move_pages failed (errno %d: %s) for %zu of %zu "
|
||||
"batches of slice %d; judged on the other samples\n", sys_errno[k],
|
||||
std::strerror(sys_errno[k]), failed[k], batches[k], k);
|
||||
if (share[k] < 95.0)
|
||||
std::fprintf(stderr, "FileExpertSource: WARNING: NUMA placement FAILED: slice %d has %.1f %% of its pages "
|
||||
"on node %d (< 95 %%; of %llu sampled: node %d %llu, node %d %llu, not present %llu)\n",
|
||||
k, share[k], nodes[k], (unsigned long long) sampled[k], nodes[0],
|
||||
(unsigned long long) per_node[k][nodes[0]], nodes[1], (unsigned long long) per_node[k][nodes[1]],
|
||||
(unsigned long long) absent[k]);
|
||||
}
|
||||
}
|
||||
};
|
||||
#endif
|
||||
|
||||
/// #286: an unbuffered file handle - a HANDLE on Windows, an O_DIRECT descriptor (as a pointer-sized integer) on Linux.
|
||||
void close_direct(void* h) {
|
||||
#if defined(_WIN32)
|
||||
@@ -3449,6 +3682,9 @@ bool FileExpertSource::pin_cache_complement(
|
||||
uint64_t partial_pin = 0; ///< CS-T: a registered prefix of a locked arena
|
||||
uint64_t lock_off = 0; ///< where the working-set lock starts (after the registered prefix)
|
||||
std::string note;
|
||||
#if defined(__linux__)
|
||||
NumaComplementPlacement numa; ///< STRATA_NUMA_SPLIT step B; inert unless the live pool split on real nodes
|
||||
#endif
|
||||
auto release = [&]() {
|
||||
if (arena == nullptr) return;
|
||||
if (pinned_ok) (void) cudaFreeHost(arena);
|
||||
@@ -3468,6 +3704,17 @@ bool FileExpertSource::pin_cache_complement(
|
||||
};
|
||||
if (maps_.empty()) drop(base_, mapped_bytes_, fd_);
|
||||
else for (const Map& m : maps_) drop(m.closed ? nullptr : m.base, m.bytes, m.fd);
|
||||
// the files read at start outside this source (set_extra_drop_files): their pages are already copied to VRAM
|
||||
// or RAM, and they sat on whichever node read them (~2.2 GiB on node 0 measured on the 3090 box)
|
||||
// CBA: whole files by path; a file read at start but not listed stays cached (the per-node free line shows
|
||||
// it), a registry of the files the loaders open if that ever bites
|
||||
for (const std::string& p : extra_drop_files_) {
|
||||
const int fd = ::open(p.c_str(), O_RDONLY | O_CLOEXEC);
|
||||
if (fd >= 0) {
|
||||
(void) posix_fadvise(fd, 0, 0, POSIX_FADV_DONTNEED);
|
||||
::close(fd);
|
||||
}
|
||||
}
|
||||
};
|
||||
#endif
|
||||
if (bytes > 0) {
|
||||
@@ -3481,6 +3728,7 @@ bool FileExpertSource::pin_cache_complement(
|
||||
// does not cover the complement, register it in steps, each only while the RAM left stays above the reserve.
|
||||
// STRATA_PIN_GUARD=0 pages-locks in one go as before, =2 always registers in steps (a test); STRATA_PIN_RESERVE_GIB
|
||||
// is the RAM that must stay above every step (default: the resident headroom, at least 2 GiB)
|
||||
// STRATA_NUMA_SPLIT placement forces the drop and the paced path whatever the guard (STRATA_PIN_GUARD=0 included)
|
||||
const uint64_t pace_reserve = [&] {
|
||||
const char* v = std::getenv("STRATA_PIN_RESERVE_GIB");
|
||||
return v != nullptr && std::atof(v) > 0 ? (uint64_t) (std::atof(v) * 1073741824.0)
|
||||
@@ -3493,9 +3741,26 @@ bool FileExpertSource::pin_cache_complement(
|
||||
return v == nullptr ? 1 : std::atoi(v);
|
||||
}();
|
||||
uint64_t free_now = 0;
|
||||
if (guard == 2) {
|
||||
numa.init(offsets, n_expert_, layer_blob_bytes_, role_bytes_); // STRATA_NUMA_SPLIT: placed by the paced loop
|
||||
if (numa.place) {
|
||||
// the engine's own mapped model pages sit on whichever node read them, and a toucher on a full node
|
||||
// gets its pages from the other one (no local reclaim): give them back first, as the guard=1 path does
|
||||
drop_file_cache();
|
||||
numa.free_after = NumaComplementPlacement::node_free();
|
||||
std::fprintf(stderr, "FileExpertSource: NUMA placement: the model files' cached pages were released; "
|
||||
"free after the drop: %s\n",
|
||||
NumaComplementPlacement::free_text(numa.free_after).c_str());
|
||||
// CBA: half the pace reserve as each node's share of the headroom; a per-node reserve if one node
|
||||
// carries the host's other allocations
|
||||
numa.check_room(pace_reserve / 2);
|
||||
if (guard == 0)
|
||||
std::fprintf(stderr, "FileExpertSource: STRATA_PIN_GUARD=0 overridden: NUMA placement needs the "
|
||||
"paced path\n");
|
||||
}
|
||||
if (guard == 2 || numa.place) {
|
||||
paced = true;
|
||||
std::fprintf(stderr, "FileExpertSource: STRATA_PIN_GUARD=2: page-locking the complement in steps\n");
|
||||
std::fprintf(stderr, "FileExpertSource: %s: page-locking the complement in steps\n",
|
||||
guard == 2 ? "STRATA_PIN_GUARD=2" : "STRATA_NUMA_SPLIT");
|
||||
} else if (guard != 0 && free_memory_bytes(free_now) &&
|
||||
detail::pin_depends_on_reclaim(free_now, bytes, pace_reserve)) {
|
||||
drop_file_cache();
|
||||
@@ -3510,6 +3775,9 @@ bool FileExpertSource::pin_cache_complement(
|
||||
std::fprintf(stderr, "FileExpertSource: the rest comes from reclaimed cache of other files: "
|
||||
"page-locking it in steps, as far as the RAM allows (#1250)\n");
|
||||
}
|
||||
} else if (strata::kernels::cpu::active_numa_split().on && !strata::kernels::cpu::active_numa_split().test) {
|
||||
std::fprintf(stderr, "FileExpertSource: WARNING: NUMA placement FAILED: the complement is not page-locked, "
|
||||
"nothing placed\n");
|
||||
}
|
||||
#endif
|
||||
if (pin && !paced) {
|
||||
@@ -3548,6 +3816,15 @@ bool FileExpertSource::pin_cache_complement(
|
||||
void* aligned = nullptr;
|
||||
const uint64_t page = 4096;
|
||||
if (posix_memalign(&aligned, (size_t) page, (size_t) ((bytes + page - 1) / page * page)) == 0) arena = aligned;
|
||||
#endif
|
||||
#if defined(__linux__)
|
||||
// STRATA_NUMA_SPLIT: a 2 MiB huge page would put several slices on its toucher's node, so the arena
|
||||
// takes 4 KiB pages (one call, no VMA split)
|
||||
if (arena != nullptr && numa.place) {
|
||||
if (madvise(arena, (size_t) ((bytes + page - 1) / page * page), MADV_NOHUGEPAGE) != 0)
|
||||
std::fprintf(stderr, "FileExpertSource: WARNING: madvise(MADV_NOHUGEPAGE) on the complement "
|
||||
"failed (errno %d)\n", errno);
|
||||
}
|
||||
#endif
|
||||
} else {
|
||||
arena = std::malloc((size_t) bytes);
|
||||
@@ -3596,7 +3873,11 @@ bool FileExpertSource::pin_cache_complement(
|
||||
stop = "the RAM left would fall under the reserve";
|
||||
break;
|
||||
}
|
||||
for (uint64_t at = got; at < got + step; at += kPage) ((volatile uint8_t*) arena)[at] = 0;
|
||||
#if defined(__linux__)
|
||||
if (numa.place) numa.touch_step((uint8_t*) arena, got, got + step); // slices on their nodes
|
||||
else
|
||||
#endif
|
||||
for (uint64_t at = got; at < got + step; at += kPage) ((volatile uint8_t*) arena)[at] = 0;
|
||||
got += step;
|
||||
}
|
||||
// cut at an expert boundary: a blob that runs past the registered range would be refused by a
|
||||
@@ -3635,6 +3916,10 @@ bool FileExpertSource::pin_cache_complement(
|
||||
(double) partial_pin / 1073741824.0);
|
||||
note += std::string(note.empty() ? "" : "; ") + msg;
|
||||
if (stop != nullptr) std::fprintf(stderr, "FileExpertSource: %s\n", msg);
|
||||
#if defined(__linux__)
|
||||
// judged on the final state: registered pages no longer move; before the copy fills them
|
||||
if (numa.place) numa.report((const uint8_t*) arena, got, partial_pin, bytes, stop);
|
||||
#endif
|
||||
} else if (budget_bytes > 0 && partial_on) {
|
||||
const uint64_t step = 2ull << 30;
|
||||
for (uint64_t want = std::min(bytes, pin_cap); want >= step; want = want > step ? want - step : 0) {
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
// numa_pool_test: when the CPU expert pool splits per NUMA node (include/strata/kernels/cpu/numa_pool.hpp), on mock machines.
|
||||
// No threads, no OS topology: a fake sysfs node folder in a temp directory and a made-up core -> node map. It runs anywhere.
|
||||
#include "strata/kernels/cpu/numa_pool.hpp"
|
||||
|
||||
#include <cstdio>
|
||||
#include <ctime>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace cpu = strata::kernels::cpu;
|
||||
namespace fs = std::filesystem;
|
||||
|
||||
static int g_fail = 0;
|
||||
|
||||
static void expect(bool ok, const std::string& what) {
|
||||
if (!ok) {
|
||||
++g_fail;
|
||||
std::fprintf(stderr, "FAIL: %s\n", what.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
// /sys/devices/system/node with `node<i>/cpulist` files; an empty string is a memory-only node
|
||||
static fs::path make_nodes(const fs::path& root, const std::vector<std::string>& cpulists, bool noise = true) {
|
||||
fs::remove_all(root);
|
||||
fs::create_directories(root);
|
||||
for (size_t i = 0; i < cpulists.size(); ++i) {
|
||||
fs::create_directories(root / ("node" + std::to_string(i)));
|
||||
std::ofstream(root / ("node" + std::to_string(i)) / "cpulist") << cpulists[i] << "\n";
|
||||
}
|
||||
if (noise) { // files and folders in that directory that are not nodes
|
||||
std::ofstream(root / "online") << "0-1\n";
|
||||
std::ofstream(root / "possible") << "0-1\n";
|
||||
fs::create_directories(root / "nodes");
|
||||
fs::create_directories(root / "node");
|
||||
fs::create_directories(root / "nodeX");
|
||||
}
|
||||
return root;
|
||||
}
|
||||
|
||||
int main() {
|
||||
const fs::path tmp = fs::temp_directory_path() / ("strata_numa_pool_test_" + std::to_string((long long) std::time(nullptr)));
|
||||
|
||||
// ---- the node count of a sysfs node folder
|
||||
expect(cpu::numa_cpu_node_count_at((tmp / "missing").string()) == 0, "no folder: 0 nodes");
|
||||
expect(cpu::numa_cpu_node_count_at(make_nodes(tmp, {"0-23"}).string()) == 1, "one node");
|
||||
expect(cpu::numa_cpu_node_count_at(make_nodes(tmp, {"0-11,24-35", "12-23,36-47"}).string()) == 2, "two sockets: 2 nodes");
|
||||
expect(cpu::numa_cpu_node_count_at(make_nodes(tmp, {"0-7", "8-15", "16-23", "24-31"}).string()) == 4, "four nodes");
|
||||
expect(cpu::numa_cpu_node_count_at(make_nodes(tmp, {"0-23", ""}).string()) == 1, "a memory-only node (CXL) is not a node of CPUs");
|
||||
expect(cpu::numa_cpu_node_count_at(make_nodes(tmp, {"0-11", "12-23", ""}).string()) == 2, "two nodes of CPUs and a memory-only one");
|
||||
|
||||
// ---- pick_numa_pool: one node is today's path
|
||||
using C = cpu::NumaPoolChoice;
|
||||
auto pick = [](const char* pool, const char* split, int nodes) { return cpu::pick_numa_pool(pool, split, nodes); };
|
||||
for (int nodes : {0, 1}) {
|
||||
for (const char* pool : {(const char*) nullptr, "", "1", "garbage"}) {
|
||||
for (const char* split : {(const char*) nullptr, ""}) {
|
||||
const auto p = pick(pool, split, nodes);
|
||||
expect(p.choice == C::Unchanged && p.log.empty(), "one node, nothing set: Unchanged and silent");
|
||||
}
|
||||
}
|
||||
const auto zero = pick("0", nullptr, nodes);
|
||||
expect(zero.choice == C::Unchanged && zero.log.empty(), "one node, STRATA_NUMA_POOL=0: Unchanged and silent");
|
||||
expect(pick(nullptr, "1", nodes).choice == C::Unchanged, "one node, STRATA_NUMA_SPLIT=1: the old variable decides");
|
||||
expect(pick(nullptr, "test", nodes).choice == C::Unchanged, "one node, STRATA_NUMA_SPLIT=test: the old variable decides");
|
||||
}
|
||||
{
|
||||
const auto p = pick(nullptr, nullptr, 2);
|
||||
expect(p.choice == C::Auto && p.log.empty(), "two nodes, nothing set: Auto");
|
||||
expect(pick("1", nullptr, 2).choice == C::Auto, "two nodes, STRATA_NUMA_POOL=1: Auto");
|
||||
expect(pick("", "", 2).choice == C::Auto, "two nodes, empty variables: Auto");
|
||||
expect(pick(nullptr, nullptr, 4).choice == C::Auto, "four nodes: Auto (the decision refuses it, with a line)");
|
||||
for (const char* off : {"0", "off", "OFF", "false", "No"}) {
|
||||
const auto o = pick(off, nullptr, 2);
|
||||
expect(o.choice == C::Off, std::string("two nodes, STRATA_NUMA_POOL=") + off + ": Off");
|
||||
expect(o.log.find("STRATA_NUMA_POOL=0") != std::string::npos && o.log.find("2 NUMA nodes") != std::string::npos,
|
||||
"the off line names the switch and the node count");
|
||||
}
|
||||
expect(pick("0", "1", 2).choice == C::Off, "STRATA_NUMA_POOL=0 beats STRATA_NUMA_SPLIT=1");
|
||||
expect(pick("0", "test", 1).choice == C::Off, "STRATA_NUMA_POOL=0 beats STRATA_NUMA_SPLIT=test, even on one node");
|
||||
expect(pick(nullptr, "1", 2).choice == C::Unchanged, "two nodes, STRATA_NUMA_SPLIT=1: the old variable decides");
|
||||
expect(pick(nullptr, "0", 2).choice == C::Unchanged, "two nodes, STRATA_NUMA_SPLIT=0: the old variable decides (off)");
|
||||
}
|
||||
|
||||
// ---- decide_numa_split on a made-up 2 x 12-core box (host core 0; cores 0-11 node 0, 12-23 node 1)
|
||||
auto node_of = [](int core) { return core < 0 ? -1 : core < 12 ? 0 : 1; };
|
||||
auto cores = [](std::initializer_list<int> v) { return std::vector<int>(v); };
|
||||
{ // 22 workers interleaved over the nodes + the host
|
||||
std::vector<int> c;
|
||||
for (int i = 0; i < 11; ++i) { c.push_back(1 + i); c.push_back(12 + i); }
|
||||
c.push_back(0); // the host
|
||||
const auto d = cpu::decide_numa_split(c, 22, true, false, node_of);
|
||||
expect(d.on, "22 workers + host on 2 nodes: on");
|
||||
expect(d.nodes[0] == 0 && d.nodes[1] == 1, "the nodes are 0 and 1");
|
||||
expect(d.per[0] == 12 && d.per[1] == 11, "12 threads on node 0 (the host counted), 11 on node 1");
|
||||
expect(d.slice.size() == c.size() && d.slice.back() == 0, "the host drains in slice 0");
|
||||
expect(d.slice[0] == 0 && d.slice[1] == 1, "workers alternate between the slices");
|
||||
}
|
||||
{ // all workers on one node: refused
|
||||
const auto d = cpu::decide_numa_split(cores({1, 2, 3, 4, 0}), 4, true, false, node_of);
|
||||
expect(!d.on && d.why.find("span 1 NUMA node(s)") != std::string::npos, "one node's threads only: refused with the count");
|
||||
}
|
||||
{ // a node with under half of the other's threads: unbalanced
|
||||
std::vector<int> c = {1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 0};
|
||||
const auto d = cpu::decide_numa_split(c, 10, true, false, node_of);
|
||||
expect(!d.on && d.why.find("unbalanced") != std::string::npos, "10 + 1 threads: refused as unbalanced");
|
||||
expect(d.nodes[0] == -1 && d.slice.empty() && d.per[0] == 0, "a refused split leaves no plan behind");
|
||||
}
|
||||
{ // three nodes
|
||||
auto three = [](int core) { return core < 8 ? 0 : core < 16 ? 1 : 2; };
|
||||
const auto d = cpu::decide_numa_split(cores({1, 9, 17, 2, 10, 18, 0}), 6, true, false, three);
|
||||
expect(!d.on && d.why.find("span 3 NUMA node(s)") != std::string::npos && d.why.find("exactly 2") != std::string::npos,
|
||||
"three nodes: refused, exactly 2 are supported");
|
||||
}
|
||||
{
|
||||
const auto base = cores({1, 12, 2, 13, 0});
|
||||
expect(cpu::decide_numa_split(base, 4, true, false, node_of).on, "4 workers + host, balanced: on");
|
||||
const auto rot = cpu::decide_numa_split(base, 4, true, true, node_of);
|
||||
expect(!rot.on && rot.why.find("STRATA_EXCHANGE_ROTATE=1") != std::string::npos, "rotating slots: refused");
|
||||
const auto nopin = cpu::decide_numa_split(base, 4, false, false, node_of);
|
||||
expect(!nopin.on && nopin.why.find("not pinned") != std::string::npos, "unpinned threads: refused");
|
||||
const auto nocore = cpu::decide_numa_split(cores({1, -1, 2, 13}), 4, true, false, node_of);
|
||||
expect(!nocore.on && nocore.why.find("worker 1 has no core") != std::string::npos, "a worker without a core: refused");
|
||||
const auto nohost = cpu::decide_numa_split(cores({1, 12, -1}), 2, true, false, node_of);
|
||||
expect(!nohost.on && nohost.why.find("host thread has no core") != std::string::npos, "a host without a core: refused");
|
||||
auto unknown = [](int core) { return core == 12 ? -1 : 0; };
|
||||
const auto un = cpu::decide_numa_split(base, 4, true, false, unknown);
|
||||
expect(!un.on && un.why.find("CPU 12 has no known NUMA node") != std::string::npos, "a core with no node: refused");
|
||||
const auto one = cpu::decide_numa_split(cores({1}), 1, true, false, node_of);
|
||||
expect(!one.on && one.why.find("needs 2 or more") != std::string::npos, "one thread: refused");
|
||||
}
|
||||
{ // a single-node machine fed to the decision (STRATA_NUMA_SPLIT=1 on one node): refused, never half-on
|
||||
auto flat = [](int core) { return core < 0 ? -1 : 0; };
|
||||
const auto d = cpu::decide_numa_split(cores({1, 2, 3, 4, 0}), 4, true, false, flat);
|
||||
expect(!d.on, "every core on node 0: off");
|
||||
}
|
||||
|
||||
fs::remove_all(tmp);
|
||||
if (g_fail) {
|
||||
std::fprintf(stderr, "numa_pool_test: %d failure(s)\n", g_fail);
|
||||
return 1;
|
||||
}
|
||||
std::printf("numa_pool_test: OK\n");
|
||||
return 0;
|
||||
}
|
||||
+341
-37
@@ -3,6 +3,7 @@
|
||||
#include "strata/core/progress.hpp"
|
||||
#include "strata/platform/aux_cpus.hpp"
|
||||
#include "strata/kernels/cpu/expert_layout.hpp"
|
||||
#include "strata/kernels/cpu/numa_pool.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
@@ -27,6 +28,7 @@
|
||||
#else
|
||||
#include <pthread.h>
|
||||
#include <sched.h>
|
||||
#include <unistd.h>
|
||||
#include "pool_affinity_linux.hpp"
|
||||
#endif
|
||||
|
||||
@@ -530,6 +532,55 @@ bool pin_this_thread(int core, [[maybe_unused]] int worker = -1) {
|
||||
#endif
|
||||
}
|
||||
|
||||
#if defined(__linux__)
|
||||
// Where the NUMA topology is read from: /sys. STRATA_TEST_SYSFS_ROOT=<dir> reads <dir>/devices/system/{node,cpu} instead,
|
||||
// so a test can give the pool a made-up two-node machine (pool_tasks_test); nobody sets it for real.
|
||||
std::string sysfs_root() {
|
||||
const char* e = std::getenv("STRATA_TEST_SYSFS_ROOT");
|
||||
return e != nullptr && *e != '\0' ? std::string(e) : std::string("/sys");
|
||||
}
|
||||
|
||||
// The NUMA node of a logical CPU (sysfs), or -1.
|
||||
int cpu_numa_node(int cpu) {
|
||||
if (cpu < 0) return -1;
|
||||
const std::string root = sysfs_root();
|
||||
char path[512];
|
||||
for (int node = 0; node < 64; ++node) {
|
||||
std::snprintf(path, sizeof path, "%s/devices/system/cpu/cpu%d/node%d", root.c_str(), cpu, node);
|
||||
if (access(path, F_OK) == 0) return node;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
#endif
|
||||
|
||||
// The NUMA nodes with CPUs this machine has (0.2.2: the split is tried by itself from 2 on). Linux: the sysfs node folder
|
||||
// (numa_pool.hpp); Windows: GetNumaHighestNodeNumber; any other system, or a sandbox that hides the folder: 1.
|
||||
int numa_node_count() {
|
||||
#if defined(__linux__)
|
||||
return (std::max)(1, numa_cpu_node_count_at(sysfs_root() + "/devices/system/node"));
|
||||
#elif defined(_WIN32)
|
||||
ULONG highest = 0;
|
||||
return GetNumaHighestNodeNumber(&highest) ? (int) highest + 1 : 1;
|
||||
#else
|
||||
return 1;
|
||||
#endif
|
||||
}
|
||||
|
||||
// The real-node split for threads on `thread_core` (numa_pool.hpp). Linux only: the placement of the experts' memory
|
||||
// (first touch by threads pinned to a node, move_pages to check) has no Windows or macOS version.
|
||||
NumaSplitDecision decide_real_numa_split([[maybe_unused]] const std::vector<int>& thread_core, [[maybe_unused]] int n_workers,
|
||||
[[maybe_unused]] bool pinned) {
|
||||
#if defined(__linux__)
|
||||
// the expert source's own reading of it (expert_source.cpp): exactly "1"
|
||||
const char* rotate = std::getenv("STRATA_EXCHANGE_ROTATE");
|
||||
return decide_numa_split(thread_core, n_workers, pinned, rotate != nullptr && std::strcmp(rotate, "1") == 0, cpu_numa_node);
|
||||
#else
|
||||
NumaSplitDecision d;
|
||||
d.why = "the split needs Linux";
|
||||
return d;
|
||||
#endif
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
ThreadAffinity pin_current_thread(int core) {
|
||||
@@ -583,13 +634,38 @@ int64_t now_ms() {
|
||||
return std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now().time_since_epoch())
|
||||
.count();
|
||||
}
|
||||
int64_t now_ns() {
|
||||
return std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::steady_clock::now().time_since_epoch())
|
||||
.count();
|
||||
}
|
||||
// CBA: one plain global, written by the constructor and destructor of the pool that owns it; fine while pools are
|
||||
// built and destroyed on one thread (generate's measure pools, then the main one), an atomic owner if that changes.
|
||||
NumaSplitPlan g_numa_plan;
|
||||
const ExpertPool* g_numa_owner = nullptr;
|
||||
} // namespace
|
||||
|
||||
const NumaSplitPlan& active_numa_split() { return g_numa_plan; }
|
||||
|
||||
void ExpertPool::diag(std::FILE* f) const {
|
||||
const uint64_t h = head_.load();
|
||||
uint32_t batch = (uint32_t) (h >> 32), claimed = (uint32_t) h & 0xffffu, total = (uint32_t) (h >> 16) & 0xffffu,
|
||||
done = done_.load();
|
||||
// CBA: this summed-slices branch is never run by a test (it needs a diag call mid-phase), it is a trivial sum, a mid-phase
|
||||
// diag test if it ever misreports
|
||||
if (numa_n_ > 0 && mode_ >= 5) { // a split native batch never writes head_/done_: the slices' sums instead
|
||||
claimed = total = done = 0;
|
||||
for (int k = 0; k < numa_n_; ++k) {
|
||||
const uint64_t sh = nsync_[(size_t) k].head.load();
|
||||
batch = (uint32_t) (sh >> 32); // every slice head carries the batch's epoch
|
||||
claimed += (uint32_t) sh & 0xffffu;
|
||||
total += (uint32_t) (sh >> 16) & 0xffffu;
|
||||
done += nsync_[(size_t) k].done.load();
|
||||
}
|
||||
}
|
||||
std::fprintf(f, " expert pool: epoch %u, batch epoch %u: %u of %u jobs claimed, %u done; %u of %d workers parked, "
|
||||
"%u sleeping; mode %d\n", epoch_.load(), (uint32_t) (h >> 32), (uint32_t) h & 0xffffu,
|
||||
(uint32_t) (h >> 16) & 0xffffu, done_.load(), parked_.load(), n_, sleepers_.load(), mode_);
|
||||
"%u sleeping; mode %d\n", epoch_.load(), batch, claimed, total, done, parked_count(), n_,
|
||||
sleepers_.load(), mode_);
|
||||
if (numa_n_ > 0) std::fprintf(f, " expert pool NUMA slices:%s\n", numa_counters().c_str());
|
||||
std::fprintf(f, " expert pool threads:");
|
||||
for (int i = 0; i < n_; ++i) {
|
||||
const int32_t s = wstate_[(size_t) i].load();
|
||||
@@ -611,21 +687,79 @@ ExpertPool::ExpertPool(int n_workers, bool pin, bool host_works, PoolAffinity af
|
||||
if (tasks < 0 || tasks > kMaxTasks) throw std::invalid_argument("expert pool tasks must be in 0..4096");
|
||||
if (const char* e = std::getenv("STRATA_POOL_SPIN_US")) // a test knob; see kSpinBeforeSleep
|
||||
spin_before_sleep_ = std::chrono::microseconds((std::max)(0, std::atoi(e)));
|
||||
// STRATA_NUMA_SPLIT, read here for the worker count (the split itself is decided below, once the count is known).
|
||||
// 0.2.2: with 2 or more NUMA nodes and neither variable set the split is tried by itself, and STRATA_NUMA_POOL=0 turns that
|
||||
// off (numa_pool.hpp). One node: pick_numa_pool says Unchanged and nothing below differs from the pool before the split.
|
||||
const char* env = std::getenv("STRATA_NUMA_SPLIT");
|
||||
const int numa_nodes = numa_node_count();
|
||||
const NumaPoolPick pool_pick = pick_numa_pool(std::getenv("STRATA_NUMA_POOL"), env, numa_nodes);
|
||||
if (!pool_pick.log.empty()) std::fprintf(stderr, "%s\n", pool_pick.log.c_str());
|
||||
if (pool_pick.choice == NumaPoolChoice::Off) env = nullptr;
|
||||
bool auto_pool = pool_pick.choice == NumaPoolChoice::Auto; // the split without STRATA_NUMA_SPLIT: only if it can run
|
||||
bool env_off = !auto_pool && (env == nullptr || *env == '\0' || std::strcmp(env, "0") == 0);
|
||||
bool env_known = auto_pool || (!env_off && (std::strcmp(env, "1") == 0 || std::strcmp(env, "test") == 0));
|
||||
const PoolPlanInput plan_in = pool_plan_input(topo_);
|
||||
const PoolPlan plan = plan_pool_workers(plan_in);
|
||||
if (n_workers > 0) {
|
||||
n_ = n_workers;
|
||||
// recommend, never force: a count above what this CPU uses well runs as configured, with a plain warning
|
||||
static std::atomic<bool> warned{false};
|
||||
const std::string why = pool_workers_warning(n_workers, plan_in, plan);
|
||||
if (!why.empty() && !warned.exchange(true)) std::fprintf(stderr, "strata cpu pool: warning: %s\n", why.c_str());
|
||||
} else if (topo_.is_hybrid && affinity_ != PoolAffinity::All) {
|
||||
n_ = (std::max)(1, topo_.p_cores - 1);
|
||||
} else {
|
||||
n_ = (std::min)(plan.workers, (std::max)(1, (int) topo_.worker_cores.size()));
|
||||
plan_limit_ = plan.limit;
|
||||
const PoolPlan wplan = plan_pool_workers(plan_in);
|
||||
// the split needs workers on both nodes: its cores are taken round-robin over the nodes (the packages when a core's node
|
||||
// is unknown), so any count under the core count (the default or a configured one) spans them evenly (one node: the order
|
||||
// is kept)
|
||||
auto interleave_cores = [&] {
|
||||
if (topo_.worker_package.size() != topo_.worker_cores.size()) return;
|
||||
std::vector<int> key = topo_.worker_package;
|
||||
#if defined(__linux__)
|
||||
std::vector<int> by_node;
|
||||
for (int c : topo_.worker_cores) by_node.push_back(cpu_numa_node(c));
|
||||
if (std::none_of(by_node.begin(), by_node.end(), [](int n) { return n < 0; })) key = by_node;
|
||||
#endif
|
||||
std::vector<int> cores, pkgs;
|
||||
for (size_t i : interleave_packages(key)) {
|
||||
cores.push_back(topo_.worker_cores[i]);
|
||||
pkgs.push_back(topo_.worker_package[i]);
|
||||
}
|
||||
topo_.worker_cores = std::move(cores);
|
||||
topo_.worker_package = std::move(pkgs);
|
||||
};
|
||||
// the worker count: configured, else the hybrid P cores, else the plan (`span`: every socket counts, the split's default)
|
||||
auto pick_workers = [&](bool span, const char** limit) -> int {
|
||||
if (n_workers > 0) return n_workers;
|
||||
if (topo_.is_hybrid && affinity_ != PoolAffinity::All) return (std::max)(1, topo_.p_cores - 1);
|
||||
if (span) {
|
||||
PoolPlanInput span_in = plan_in;
|
||||
span_in.span_packages = true;
|
||||
const PoolPlan sp = plan_pool_workers(span_in);
|
||||
*limit = sp.limit;
|
||||
return (std::min)(sp.workers, (std::max)(1, (int) topo_.worker_cores.size()));
|
||||
}
|
||||
*limit = wplan.limit;
|
||||
return (std::min)(wplan.workers, (std::max)(1, (int) topo_.worker_cores.size()));
|
||||
};
|
||||
if (auto_pool) {
|
||||
// try the split on a copy: when it cannot run the cores, the count and the plan stay exactly what they were
|
||||
const CpuTopology plain_topo = topo_;
|
||||
interleave_cores();
|
||||
const char* try_limit = nullptr;
|
||||
const int try_n = pick_workers(true, &try_limit);
|
||||
std::vector<int> thread_core;
|
||||
for (int j = 0; j < try_n; ++j)
|
||||
thread_core.push_back(pin && j < (int) topo_.worker_cores.size() ? topo_.worker_cores[(size_t) j] : -1);
|
||||
if (host_works_) thread_core.push_back(topo_.host_core);
|
||||
const NumaSplitDecision tried = decide_real_numa_split(thread_core, try_n, pin);
|
||||
if (!tried.on) {
|
||||
topo_ = plain_topo;
|
||||
auto_pool = env_known = false;
|
||||
env_off = true;
|
||||
std::fprintf(stderr, "strata cpu pool: NUMA pool off: %s (%d NUMA nodes found), the pool runs as before\n",
|
||||
tried.why.c_str(), numa_nodes);
|
||||
}
|
||||
} else if (env_known) {
|
||||
interleave_cores();
|
||||
}
|
||||
plan_cores_ = plan.cores;
|
||||
{
|
||||
const char* limit = nullptr;
|
||||
n_ = pick_workers(env_known, &limit);
|
||||
if (limit != nullptr) plan_limit_ = limit;
|
||||
}
|
||||
plan_cores_ = wplan.cores;
|
||||
plan_logical_ = plan_in.logical;
|
||||
if (n_ < 1) n_ = 1;
|
||||
scratch_.resize((size_t) n_);
|
||||
@@ -636,12 +770,82 @@ ExpertPool::ExpertPool(int n_workers, bool pin, bool host_works, PoolAffinity af
|
||||
strata::core::diag_pool_fn().store(&diag_active_pool);
|
||||
split_.resize((size_t) kMaxSplit);
|
||||
split_multi_.resize((size_t) kMaxSplitMulti);
|
||||
// STRATA_NUMA_SPLIT: decided here, before any worker starts (a worker counts into its slice's `parked` from its
|
||||
// first instruction), and never revised. Unset: the plan stays empty and nothing below runs.
|
||||
NumaSplitPlan plan;
|
||||
if (!env_off && !env_known) {
|
||||
plan.why = std::string("unknown STRATA_NUMA_SPLIT value '") + env + "' (use 1 or test)";
|
||||
std::fprintf(stderr, "strata cpu pool: NUMA split off: %s\n", plan.why.c_str());
|
||||
} else if (env_known) {
|
||||
plan.test = !auto_pool && std::strcmp(env, "test") == 0;
|
||||
const int threads = n_ + (host_works_ ? 1 : 0); // thread j < n_: worker j; j == n_: the host
|
||||
std::vector<int> slice((size_t) threads, 0);
|
||||
std::string why;
|
||||
if (threads < 2) {
|
||||
why = "the pool has " + std::to_string(threads) + " thread, the split needs 2 or more";
|
||||
} else if (plan.test) {
|
||||
for (int j = 0; j < threads; ++j) slice[(size_t) j] = j % 2;
|
||||
} else {
|
||||
std::vector<int> thread_core;
|
||||
for (int j = 0; j < threads; ++j)
|
||||
thread_core.push_back(j == n_ ? topo_.host_core
|
||||
: pin && j < (int) topo_.worker_cores.size() ? topo_.worker_cores[(size_t) j] : -1);
|
||||
const NumaSplitDecision d = decide_real_numa_split(thread_core, n_, pin);
|
||||
why = d.why;
|
||||
if (d.on) {
|
||||
slice = d.slice;
|
||||
plan.nodes[0] = d.nodes[0];
|
||||
plan.nodes[1] = d.nodes[1];
|
||||
for (int j = 0; j < threads; ++j) plan.cores[slice[(size_t) j]].push_back(thread_core[(size_t) j]);
|
||||
}
|
||||
}
|
||||
plan.why = why;
|
||||
plan.on = plan.why.empty();
|
||||
if (!plan.on) { // a refusal after the slices were planned (unbalanced) leaves no half-filled plan behind
|
||||
plan.nodes[0] = plan.nodes[1] = -1;
|
||||
plan.cores[0].clear();
|
||||
plan.cores[1].clear();
|
||||
}
|
||||
if (plan.on) {
|
||||
numa_n_ = 2;
|
||||
nsync_.reset(new NodeSync[2]);
|
||||
wslice_.assign(slice.begin(), slice.begin() + n_);
|
||||
hslice_ = host_works_ ? slice[(size_t) n_] : 0;
|
||||
slice_threads_.assign(2, 0);
|
||||
for (int k : slice) ++slice_threads_[(size_t) k];
|
||||
if (auto_pool)
|
||||
std::fprintf(stderr, "strata cpu pool: NUMA pool on: %d NUMA nodes found, one slice of the pool per node "
|
||||
"(STRATA_NUMA_POOL=0 turns it off)\n", numa_nodes);
|
||||
if (plan.test)
|
||||
std::fprintf(stderr, "strata cpu pool: NUMA split on (test, no real nodes): slice 0 = %d threads, "
|
||||
"slice 1 = %d threads\n", slice_threads_[0], slice_threads_[1]);
|
||||
else
|
||||
std::fprintf(stderr, "strata cpu pool: NUMA split on: slice 0 = node %d (%d threads), slice 1 = node %d "
|
||||
"(%d threads)\n", plan.nodes[0], slice_threads_[0], plan.nodes[1], slice_threads_[1]);
|
||||
} else {
|
||||
std::fprintf(stderr, "strata cpu pool: NUMA split off: %s\n", plan.why.c_str());
|
||||
}
|
||||
}
|
||||
if (n_workers > 0) {
|
||||
// recommend, never force: a count above what this CPU uses well runs as configured, with a plain warning
|
||||
// (STRATA_NUMA_SPLIT on: workers on the other socket are the point, that case is not warned about)
|
||||
PoolPlanInput warn_in = plan_in;
|
||||
warn_in.span_packages = plan.on;
|
||||
static std::atomic<bool> warned{false};
|
||||
const std::string why = pool_workers_warning(n_workers, warn_in, plan_pool_workers(warn_in));
|
||||
if (!why.empty() && !warned.exchange(true)) std::fprintf(stderr, "strata cpu pool: warning: %s\n", why.c_str());
|
||||
}
|
||||
g_numa_plan = std::move(plan);
|
||||
g_numa_owner = this;
|
||||
threads_.reserve((size_t) n_);
|
||||
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);
|
||||
// a failed pin only costs locality under the split: the worker keeps the slice it was given
|
||||
if (!pin_this_thread(core, i) && core >= 0 && numa_n_ > 0)
|
||||
std::fprintf(stderr, "strata cpu pool: NUMA split: worker %d not pinned to CPU %d, its slice's rows may "
|
||||
"be read remotely\n", i, core);
|
||||
worker(i);
|
||||
});
|
||||
}
|
||||
@@ -650,6 +854,10 @@ ExpertPool::ExpertPool(int n_workers, bool pin, bool host_works, PoolAffinity af
|
||||
ExpertPool::~ExpertPool() {
|
||||
const ExpertPool* self = this;
|
||||
g_diag_pool.compare_exchange_strong(self, nullptr);
|
||||
if (g_numa_owner == this) {
|
||||
g_numa_plan = NumaSplitPlan{};
|
||||
g_numa_owner = nullptr;
|
||||
}
|
||||
stop_.store(true, std::memory_order_release);
|
||||
// Bump the epoch so a PARKED worker notices the stop flag rather than sleeping through it.
|
||||
publish();
|
||||
@@ -675,7 +883,7 @@ void ExpertPool::worker(int id) {
|
||||
// on the RETURN from a drain leaves `parked_` at 0 until each worker has finished one batch, and the first
|
||||
// `run()` - which waits for `parked_ == n_` before publishing - then deadlocks. It deadlocks on the very
|
||||
// first call, which is the good case; a version that deadlocked on the second would be far worse.
|
||||
parked_.fetch_add(1, std::memory_order_acq_rel);
|
||||
parked_of(id).fetch_add(1, std::memory_order_acq_rel);
|
||||
for (;;) {
|
||||
// Park: wait for work. `_mm_pause` rather than a bare spin because it yields the pipeline to the
|
||||
// sibling hyperthread; `epoch_` is bumped once per LAYER, not once per expert, so most of these
|
||||
@@ -724,7 +932,7 @@ void ExpertPool::worker(int id) {
|
||||
if (stop_.load(std::memory_order_acquire)) return;
|
||||
// acquire: the batch this epoch published (`head`, and the description before it) is visible from here
|
||||
seen = epoch_.load(std::memory_order_acquire);
|
||||
parked_.fetch_sub(1, std::memory_order_acq_rel); // leaving the park
|
||||
parked_of(id).fetch_sub(1, std::memory_order_acq_rel); // leaving the park
|
||||
|
||||
// Drain: one claim per iteration, so a slow worker takes fewer experts and a fast one takes more.
|
||||
// Every job is the same size (all experts are 1,382,400 bytes), so there is nothing to schedule. Only
|
||||
@@ -732,7 +940,7 @@ void ExpertPool::worker(int id) {
|
||||
wstate_[(size_t) id].store(kBetween, std::memory_order_relaxed);
|
||||
drain(id, scratch_[(size_t) id], seen);
|
||||
wstate_[(size_t) id].store(kParked, std::memory_order_relaxed);
|
||||
parked_.fetch_add(1, std::memory_order_acq_rel); // back at the park
|
||||
parked_of(id).fetch_add(1, std::memory_order_acq_rel); // back at the park
|
||||
}
|
||||
}
|
||||
|
||||
@@ -747,6 +955,56 @@ int ExpertPool::claim(uint32_t epoch) {
|
||||
}
|
||||
}
|
||||
|
||||
int ExpertPool::claim_slice(uint32_t epoch, int slice) {
|
||||
NodeSync& ns = nsync_[(size_t) slice];
|
||||
uint64_t h = ns.head.load(std::memory_order_acquire);
|
||||
for (;;) {
|
||||
if ((uint32_t) (h >> 32) != epoch) return -1; // not this batch, or not a mode-5/6 batch
|
||||
const uint32_t n = (uint32_t) (h >> 16) & 0xffffu, i = (uint32_t) h & 0xffffu;
|
||||
if (i >= n) return -1; // the slice is exhausted
|
||||
if (ns.head.compare_exchange_weak(h, h + 1, std::memory_order_acq_rel, std::memory_order_acquire))
|
||||
return ns.base + (int) i; // the description is stable from here
|
||||
}
|
||||
}
|
||||
|
||||
uint32_t ExpertPool::parked_count() const {
|
||||
if (numa_n_ == 0) return parked_.load(std::memory_order_acquire);
|
||||
uint32_t p = 0; // each slice's counter is bounded by its own workers, so the sum is n_ only when each is full
|
||||
for (int k = 0; k < numa_n_; ++k) p += nsync_[(size_t) k].parked.load(std::memory_order_acquire);
|
||||
return p;
|
||||
}
|
||||
|
||||
std::string ExpertPool::numa_counters() const {
|
||||
std::string s;
|
||||
for (int k = 0; k < numa_n_; ++k) {
|
||||
const NodeSync& ns = nsync_[(size_t) k];
|
||||
const uint64_t h = ns.head.load();
|
||||
char buf[200];
|
||||
std::snprintf(buf, sizeof buf, "%s slice %d: batch epoch %u, %u of %u claimed, %u done, %u parked, %d threads",
|
||||
k == 0 ? " [" : ";", k, (uint32_t) (h >> 32), (uint32_t) h & 0xffffu, (uint32_t) (h >> 16) & 0xffffu,
|
||||
ns.done.load(), ns.parked.load(), slice_threads_[(size_t) k]);
|
||||
s += buf;
|
||||
}
|
||||
if (numa_n_ > 0) s += "]";
|
||||
return s;
|
||||
}
|
||||
|
||||
int ExpertPool::numa_plan_phase(int per, int nb) {
|
||||
int base = 0;
|
||||
for (int k = 0; k < numa_n_; ++k) {
|
||||
NodeSync& ns = nsync_[(size_t) k];
|
||||
ns.row0 = per * k / numa_n_;
|
||||
ns.h = per * (k + 1) / numa_n_ - ns.row0;
|
||||
ns.rows = (int64_t) nb * ns.h;
|
||||
// about three tasks per thread of the slice's node; an explicit --pool-tasks is shared between the slices
|
||||
const int64_t want = tasks_ == 0 ? 3 * (int64_t) slice_threads_[(size_t) k] : (int64_t) (std::max)(1, tasks_ / 2);
|
||||
ns.tasks = (int) (std::min)(want, ns.rows);
|
||||
ns.base = base;
|
||||
base += ns.tasks;
|
||||
}
|
||||
return base;
|
||||
}
|
||||
|
||||
uint32_t ExpertPool::begin_batch(int n) {
|
||||
if (n < 0 || n > 0xffff) {
|
||||
std::fprintf(stderr, "strata: expert pool batch of %d jobs is out of range\n", n);
|
||||
@@ -754,9 +1012,21 @@ uint32_t ExpertPool::begin_batch(int n) {
|
||||
}
|
||||
// Every job of the previous batch has completed (`wait_done`), and a claim of it can no longer succeed, so
|
||||
// nothing adds to `done` until this batch's first claim - which the release below orders after the reset.
|
||||
done_.store(0, std::memory_order_relaxed);
|
||||
const uint32_t e = epoch_.load(std::memory_order_relaxed) + 1; // only the host bumps the epoch
|
||||
head_.store(pack_head(e, (uint32_t) n, 0), std::memory_order_release);
|
||||
if (numa_phase()) {
|
||||
// every slice's head, even a slice with no task, and never `head_`: for this epoch only the slice heads
|
||||
// carry `e`, so a claim on `head_` fails, and every head left from an earlier batch is exhausted (pool.hpp)
|
||||
for (int k = 0; k < numa_n_; ++k) {
|
||||
NodeSync& ns = nsync_[(size_t) k];
|
||||
ns.done.store(0, std::memory_order_relaxed);
|
||||
ns.drained_ns.store(0, std::memory_order_relaxed);
|
||||
ns.head.store(pack_head(e, (uint32_t) ns.tasks, 0), std::memory_order_release);
|
||||
}
|
||||
pub_ns_ = now_ns();
|
||||
} else {
|
||||
done_.store(0, std::memory_order_relaxed);
|
||||
head_.store(pack_head(e, (uint32_t) n, 0), std::memory_order_release);
|
||||
}
|
||||
publish();
|
||||
return e;
|
||||
}
|
||||
@@ -766,15 +1036,15 @@ void ExpertPool::wait_parked(const char* what) {
|
||||
hstate_ms_.store(now_ms(), std::memory_order_relaxed);
|
||||
uint32_t spins = 0;
|
||||
std::chrono::steady_clock::time_point t0{};
|
||||
while (parked_.load(std::memory_order_acquire) != (uint32_t) n_) {
|
||||
while (parked_count() != (uint32_t) n_) {
|
||||
_mm_pause();
|
||||
if ((++spins & 1023u) != 0) continue;
|
||||
const auto now = std::chrono::steady_clock::now();
|
||||
if (spins == 1024u) t0 = now;
|
||||
else if (now - t0 > kStall) {
|
||||
std::fprintf(stderr, "strata: the CPU expert pool stalled %s (%u of %d workers parked) - stopping the engine "
|
||||
std::fprintf(stderr, "strata: the CPU expert pool stalled %s (%u of %d workers parked)%s - stopping the engine "
|
||||
"so the server can start it again (issue #29)\n",
|
||||
what, parked_.load(), n_);
|
||||
what, parked_count(), n_, numa_counters().c_str());
|
||||
strata::core::release_gpu_waits(stderr); // #267: the GPU may be spinning on this layer's flag
|
||||
std::fflush(stderr);
|
||||
std::abort();
|
||||
@@ -788,16 +1058,20 @@ void ExpertPool::wait_done(int n) {
|
||||
uint32_t spins = 0, seen = 0;
|
||||
std::chrono::steady_clock::time_point t0{};
|
||||
for (;;) {
|
||||
const uint32_t d = done_.load(std::memory_order_acquire);
|
||||
uint32_t d = 0;
|
||||
if (numa_phase()) // the slices' counts, each bounded by its tasks: the sum is n only when every slice is done
|
||||
for (int k = 0; k < numa_n_; ++k) d += nsync_[(size_t) k].done.load(std::memory_order_acquire);
|
||||
else
|
||||
d = done_.load(std::memory_order_acquire);
|
||||
if (d >= (uint32_t) n) return; // `>=`: never a wait that an overshoot outlives
|
||||
_mm_pause();
|
||||
if ((++spins & 1023u) != 0) continue;
|
||||
const auto now = std::chrono::steady_clock::now();
|
||||
if (spins == 1024u || d != seen) { t0 = now; seen = d; } // progress restarts the clock
|
||||
else if (now - t0 > kStall) {
|
||||
std::fprintf(stderr, "strata: the CPU expert pool stalled: %u of %d jobs done, %u of %d workers parked - "
|
||||
std::fprintf(stderr, "strata: the CPU expert pool stalled: %u of %d jobs done, %u of %d workers parked%s - "
|
||||
"stopping the engine so the server can start it again (issue #29)\n",
|
||||
d, n, parked_.load(), n_);
|
||||
d, n, parked_count(), n_, numa_counters().c_str());
|
||||
strata::core::release_gpu_waits(stderr); // #267
|
||||
std::fflush(stderr);
|
||||
std::abort();
|
||||
@@ -806,9 +1080,13 @@ void ExpertPool::wait_done(int n) {
|
||||
}
|
||||
|
||||
void ExpertPool::drain(int id, ExpertScratch& scratch, uint32_t epoch) {
|
||||
(void) id;
|
||||
const int s = numa_n_ == 0 ? 0 : id >= 0 ? wslice_[(size_t) id] : hslice_;
|
||||
for (;;) {
|
||||
const int ci = claim(epoch);
|
||||
// STRATA_NUMA_SPLIT: a mode-5/6 batch lives on the slice heads, any other on `head_`; the epoch tag makes the
|
||||
// other family's claim fail, so `mode_` is never read before a claim has succeeded (pool.hpp)
|
||||
int ci = numa_n_ > 0 ? claim_slice(epoch, s) : -1;
|
||||
const bool sliced = ci >= 0;
|
||||
if (!sliced) ci = claim(epoch);
|
||||
if (ci < 0) break;
|
||||
const uint32_t i = (uint32_t) ci;
|
||||
if (id >= 0) wstate_[(size_t) id].store(ci, std::memory_order_relaxed);
|
||||
@@ -827,11 +1105,21 @@ void ExpertPool::drain(int id, ExpertScratch& scratch, uint32_t epoch) {
|
||||
} else if (mode_ >= 5) {
|
||||
// plan v0.3 P6: native layers, 5 = gate/up rows, 6 = down rows (the layer's own n_ff / n_embd: Flash-Next's
|
||||
// FF / H, or another family's smaller expert)
|
||||
// Task j of T over R rows of `h` per expert from matrix row `row0`: the whole phase (R = mrows_, h = per,
|
||||
// row0 = 0) or, under the NUMA split, this thread's slice (slice-local row g -> expert g / h, matrix row
|
||||
// row0 + g % h)
|
||||
const int per = mode_ == 5 ? (int) nfmt_->n_ff : (int) nfmt_->n_embd;
|
||||
const int64_t g0 = mrows_ * (int64_t) i / mtasks_, g1 = mrows_ * (int64_t) (i + 1) / mtasks_;
|
||||
for (int64_t r = g0; r < g1;) {
|
||||
const int e = (int) (r / per), r0 = (int) (r % per);
|
||||
const int r1 = (int) std::min<int64_t>(per, r0 + (g1 - r));
|
||||
int64_t R = mrows_, T = mtasks_, j = i;
|
||||
int h = per, row0 = 0;
|
||||
if (sliced) {
|
||||
const NodeSync& ns = nsync_[(size_t) s];
|
||||
R = ns.rows; T = ns.tasks; h = ns.h; row0 = ns.row0; j = ci - ns.base;
|
||||
}
|
||||
const int64_t g0 = R * j / T, g1 = R * (j + 1) / T;
|
||||
for (int64_t g = g0; g < g1;) {
|
||||
const int e = (int) (g / h), l0 = (int) (g % h);
|
||||
const int l1 = (int) std::min<int64_t>(h, l0 + (g1 - g));
|
||||
const int r0 = row0 + l0, r1 = row0 + l1;
|
||||
SplitBufMulti& sb = split_multi_[(size_t) e];
|
||||
const NativeFmt* const nfmt = mjobs_[e].fmt != nullptr ? mjobs_[e].fmt : nfmt_; // 149-cold: same types and rows
|
||||
if (mode_ == 5 && q2_native_kernels(nfmt->gu_type)) {
|
||||
@@ -861,7 +1149,7 @@ void ExpertPool::drain(int id, ExpertScratch& scratch, uint32_t epoch) {
|
||||
for (int t = 0; t < mjobs_[e].nt; ++t) hq[t] = sb.hq[t];
|
||||
native_down_rows(*nfmt, mjobs_[e].blob, hq, mjobs_[e].nt, mjobs_[e].out, r0, r1);
|
||||
}
|
||||
r += r1 - r0;
|
||||
g += l1 - l0;
|
||||
}
|
||||
} else {
|
||||
// plan v0.3 P6: an equal range of the phase's rows across ALL its experts (a range may span two)
|
||||
@@ -883,7 +1171,15 @@ void ExpertPool::drain(int id, ExpertScratch& scratch, uint32_t epoch) {
|
||||
r += r1 - r0;
|
||||
}
|
||||
}
|
||||
done_.fetch_add(1, std::memory_order_release);
|
||||
if (sliced) {
|
||||
NodeSync& ns = nsync_[(size_t) s];
|
||||
const uint32_t t = (uint32_t) ns.tasks;
|
||||
// the slice's last task stamps its drain time; read by the host once this thread has parked again
|
||||
if (ns.done.fetch_add(1, std::memory_order_release) + 1 == t)
|
||||
ns.drained_ns.store(now_ns(), std::memory_order_relaxed);
|
||||
} else {
|
||||
done_.fetch_add(1, std::memory_order_release);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -895,6 +1191,14 @@ void ExpertPool::run_phase(int mode, int n_tasks) {
|
||||
if (host_works_) drain(-1, host_scratch_, e);
|
||||
wait_done(n_tasks);
|
||||
wait_parked("after a phase");
|
||||
// Each slice's stamp is stored after its last `done` increment, so `wait_done` can return before it lands; the
|
||||
// thread that stored it has parked again since (it left the park to claim), and that re-park is what the wait
|
||||
// above acquired. So the stamps are read here, not in `wait_done`.
|
||||
if (numa_phase())
|
||||
for (int k = 0; k < numa_n_; ++k) {
|
||||
const int64_t t = nsync_[(size_t) k].drained_ns.load(std::memory_order_acquire);
|
||||
if (t != 0) slice_ms_[k] += (double) (t - pub_ns_) / 1e6;
|
||||
}
|
||||
hstate_.store(kIdle, std::memory_order_relaxed);
|
||||
hstate_ms_.store(now_ms(), std::memory_order_relaxed);
|
||||
}
|
||||
@@ -967,7 +1271,7 @@ void ExpertPool::run_split_multi_native(const NativeFmt& f, ExpertJobMulti* jobs
|
||||
mjobs_ = jobs + b0;
|
||||
nfmt_ = &f;
|
||||
mrows_ = (int64_t) nb * f.n_ff;
|
||||
mtasks_ = phase_tasks(mrows_);
|
||||
mtasks_ = numa_n_ > 0 ? numa_plan_phase((int) f.n_ff, nb) : phase_tasks(mrows_);
|
||||
const auto a = std::chrono::steady_clock::now();
|
||||
run_phase(5, mtasks_);
|
||||
const auto b = std::chrono::steady_clock::now();
|
||||
@@ -977,7 +1281,7 @@ void ExpertPool::run_split_multi_native(const NativeFmt& f, ExpertJobMulti* jobs
|
||||
else native_quant_h(f, split_multi_[(size_t) e].ff[t], split_multi_[(size_t) e].hq[t]);
|
||||
const auto c = std::chrono::steady_clock::now();
|
||||
mrows_ = (int64_t) nb * f.n_embd;
|
||||
mtasks_ = phase_tasks(mrows_);
|
||||
mtasks_ = numa_n_ > 0 ? numa_plan_phase((int) f.n_embd, nb) : phase_tasks(mrows_);
|
||||
run_phase(6, mtasks_);
|
||||
const auto d = std::chrono::steady_clock::now();
|
||||
ms_multi_gu += std::chrono::duration<double, std::milli>(b - a).count();
|
||||
|
||||
@@ -150,6 +150,60 @@ int main() {
|
||||
expect(cpu::pool_workers_warning(8, q, cpu::plan_pool_workers(q)).find("container") != std::string::npos,
|
||||
"8 workers under a 4-CPU quota: names the container limit");
|
||||
|
||||
// STRATA_NUMA_SPLIT (span_packages): the default spans every socket, the other bounds stay; off = the plan above
|
||||
{
|
||||
auto x = xeon; // 2 x 20 cores: 39 but the host's, one kept free -> 38, then the cap
|
||||
x.span_packages = true;
|
||||
line("2-socket 40c/80t, NUMA split", x);
|
||||
const cpu::PoolPlan px = cpu::plan_pool_workers(x);
|
||||
expect(px.workers == cpu::kPoolWorkersCap, "2x20c split: both sockets, then the cap");
|
||||
expect(px.cores_local == 40, "2x20c split: every socket counts as local");
|
||||
auto b = cpu_of(48, {12, 12}); // the 2 x Xeon Gold 6226 box: 23 but the host's, one kept free
|
||||
expect(cpu::plan_pool_workers(b).workers == 11, "2x12c no split: the host socket's 11 (unchanged)");
|
||||
b.span_packages = true;
|
||||
expect(cpu::plan_pool_workers(b).workers == 22, "2x12c split: 22 workers across both sockets");
|
||||
auto one = cpu_of(16, {8});
|
||||
one.span_packages = true;
|
||||
expect(cpu::plan_pool_workers(one).workers == 7, "one socket: the split changes nothing");
|
||||
// the socket warning is silenced while the split is on; the others stay
|
||||
expect(cpu::pool_workers_warning(30, x, px).empty(), "30 workers on 2x20c under the split: no socket warning");
|
||||
auto bx = cpu_of(80, {20, 20});
|
||||
bx.span_packages = true;
|
||||
const std::string w = cpu::pool_workers_warning(36, bx, cpu::plan_pool_workers(bx));
|
||||
expect(!w.empty() && w.find("socket") == std::string::npos, "36 on 2x20c under the split: the cap warning, not the socket one");
|
||||
expect(cpu::pool_workers_warning(60, bx, cpu::plan_pool_workers(bx)).find("physical cores") != std::string::npos,
|
||||
"60 on 2x20c under the split: still more than the physical cores");
|
||||
}
|
||||
// interleave_packages: round-robin over the packages (host's first), stable inside each
|
||||
{
|
||||
const std::vector<size_t> o = cpu::interleave_packages({0, 0, 0, 1, 1, 1, 1});
|
||||
const std::vector<size_t> want = {0, 3, 1, 4, 2, 5, 6};
|
||||
expect(o == want, "interleave 3+4: 0 3 1 4 2 5 6");
|
||||
expect(cpu::interleave_packages({}).empty(), "interleave of nothing");
|
||||
const std::vector<size_t> same = cpu::interleave_packages({1, 1, 1});
|
||||
expect(same == std::vector<size_t>({0, 1, 2}), "one package: the order is kept");
|
||||
}
|
||||
// a configured count under the split, on the 2 x 12-core box: the worker cores as fill_plan_fields orders them
|
||||
// (the host's socket first: its 11 cores but the host's, then the other socket's 12), taken in interleave order;
|
||||
// the host thread drains on socket 0
|
||||
{
|
||||
std::vector<int> pkg(11, 0);
|
||||
pkg.insert(pkg.end(), 12, 1);
|
||||
const std::vector<size_t> o = cpu::interleave_packages(pkg);
|
||||
auto per = [&](int n, bool interleaved, int s) {
|
||||
int c = 0;
|
||||
for (int i = 0; i < n; ++i) c += pkg[interleaved ? o[(size_t) i] : (size_t) i] == s;
|
||||
return c;
|
||||
};
|
||||
expect(per(12, true, 0) == 6 && per(12, true, 1) == 6, "--pool-workers 12 under the split: 6 + 6 workers");
|
||||
expect(cpu::numa_slices_balanced(per(12, true, 0) + 1, per(12, true, 1)), "12: 7 / 6 threads, balanced");
|
||||
expect(per(13, true, 0) == 7 && per(13, true, 1) == 6, "--pool-workers 13 under the split: 7 + 6 workers");
|
||||
expect(cpu::numa_slices_balanced(per(13, true, 0) + 1, per(13, true, 1)), "13: 8 / 6 threads, balanced");
|
||||
expect(!cpu::numa_slices_balanced(per(12, false, 0) + 1, per(12, false, 1)),
|
||||
"12 in the host-first order would be 12 / 1 threads: refused (what the interleave avoids)");
|
||||
expect(per(22, true, 0) == 11 && per(22, true, 1) == 11, "22 (the split default here): 11 + 11 workers");
|
||||
}
|
||||
|
||||
if (g_fail) {
|
||||
std::fprintf(stderr, "pool_plan_test: %d failure(s)\n", g_fail);
|
||||
return 1;
|
||||
|
||||
@@ -8,12 +8,42 @@
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <ctime>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <limits>
|
||||
#include <random>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace cpu = strata::kernels::cpu;
|
||||
|
||||
static void put_env(const char* k, const char* v) {
|
||||
#if defined(_WIN32)
|
||||
_putenv_s(k, v);
|
||||
#else
|
||||
setenv(k, v, 1);
|
||||
#endif
|
||||
}
|
||||
// a synthetic Strata-form (s2) expert: random codes, fp16 scales ~0.004-0.016 (as expert_multi_test's)
|
||||
static void make_s2_blob(uint8_t* b, std::mt19937& rng) {
|
||||
for (size_t i = 0; i < cpu::O_GU_SCALES; ++i) b[i] = (uint8_t) rng();
|
||||
for (size_t i = cpu::O_GU_SCALES; i < cpu::BLOB; i += 2) {
|
||||
const uint16_t h = (uint16_t) (0x1C00 + rng() % 0x0800);
|
||||
std::memcpy(b + i, &h, 2);
|
||||
}
|
||||
}
|
||||
static bool same_h(const float* a, const float* b) { return std::memcmp(a, b, (size_t) cpu::H * sizeof(float)) == 0; }
|
||||
static void nan_h(float* a) { std::fill(a, a + cpu::H, std::numeric_limits<float>::quiet_NaN()); }
|
||||
static void unset_env(const char* k) {
|
||||
#if defined(_WIN32)
|
||||
_putenv_s(k, "");
|
||||
#else
|
||||
unsetenv(k);
|
||||
#endif
|
||||
}
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
if (argc != 1 && argc != 4) return 2;
|
||||
// its activation quantiser is the AVX one at least (act_quant_any): a CPU without AVX (Westmere) would stop on an illegal instruction
|
||||
@@ -51,7 +81,7 @@ int main(int argc, char** argv) {
|
||||
cpu::native_quant_act(f, x.data(), act[t].data());
|
||||
cpu::act_quant_any(x.data(), cpu::H, qact[t]);
|
||||
}
|
||||
int checks = 0;
|
||||
int checks = 0, split_checks = 0, mixed_checks = 0;
|
||||
for (int n : {1, 7, cpu::ExpertPool::kMaxSplitMulti + 1}) {
|
||||
std::vector<cpu::ExpertJobMulti> jobs(n);
|
||||
std::vector<float> out((size_t) n * cpu::MAXT * cpu::H);
|
||||
@@ -86,7 +116,258 @@ int main(int argc, char** argv) {
|
||||
++checks;
|
||||
}
|
||||
}
|
||||
// STRATA_NUMA_SPLIT=test: two slices without a real second node (thread j -> slice j % 2), every worker
|
||||
// sleeping between batches (spin 0) so the late-wake path of issue #29 runs constantly
|
||||
put_env("STRATA_NUMA_SPLIT", "test");
|
||||
put_env("STRATA_POOL_SPIN_US", "0");
|
||||
for (bool host : {false, true}) for (int workers : {1, 2, 3, 5})
|
||||
for (int tasks : {0, 1, 41, cpu::ExpertPool::kMaxTasks}) {
|
||||
cpu::ExpertPool pool(workers, false, host, cpu::PoolAffinity::All, tasks);
|
||||
const int slices = workers + (host ? 1 : 0) >= 2 ? 2 : 0;
|
||||
if (pool.numa_slices() != slices || cpu::active_numa_split().on != (slices == 2) ||
|
||||
(slices == 2 && !cpu::active_numa_split().test)) {
|
||||
std::fprintf(stderr, "numa-split slices %d, expected %d (workers=%d host=%d)\n",
|
||||
pool.numa_slices(), slices, workers, host);
|
||||
return 1;
|
||||
}
|
||||
for (int repeat = 0; repeat < 2; ++repeat) {
|
||||
for (const auto& job : jobs) for (int t = 0; t < job.nt; ++t)
|
||||
std::fill(job.out[t], job.out[t] + cpu::H, std::numeric_limits<float>::quiet_NaN());
|
||||
pool.run_split_multi_native(f, jobs.data(), n);
|
||||
if (std::memcmp(ref.data(), out.data(), out.size() * sizeof(float)) != 0) {
|
||||
std::fprintf(stderr, "numa-split mismatch n=%d workers=%d host=%d tasks=%d repeat=%d\n",
|
||||
n, workers, host, tasks, repeat);
|
||||
return 1;
|
||||
}
|
||||
++split_checks;
|
||||
}
|
||||
pool.diag(stderr);
|
||||
}
|
||||
// The split with modes 0-4 between the native batches, on one pool: a mode-0..4 batch lives on `head_`, a
|
||||
// native one on the slice heads, so this alternates the two families of heads (a stale claim must fail on
|
||||
// the other family) and runs the per-slice `parked` through the non-native modes. The Strata-form kernels
|
||||
// need AVX-512 VBMI, the oracle contract included (a Xeon Gold 6226 stops on vpmultishiftqb inside
|
||||
// s2_expert_vnni_q with the oracle on), so a CPU without it skips this part.
|
||||
// CBA: no coverage on a VBMI-free CPU (the 6226 box); a test-only kernel seam in the pool if it must have it.
|
||||
const cpu::CpuFeatures feat = cpu::cpu_features();
|
||||
if (n == 7 && feat.usable()) {
|
||||
std::mt19937 rng(7);
|
||||
std::vector<std::vector<uint8_t>> s2(3, std::vector<uint8_t>(cpu::BLOB));
|
||||
for (auto& b : s2) make_s2_blob(b.data(), rng);
|
||||
const int NJ = 5; // single-token jobs: run() and run_split()
|
||||
std::vector<cpu::ExpertJob> sj(NJ);
|
||||
std::vector<float> sout((size_t) NJ * cpu::H), sref(sout.size());
|
||||
std::vector<cpu::ExpertJobMulti> mj(3); // multi-token jobs: run_split_multi(), 1, 2 and 3 tokens
|
||||
std::vector<float> mout((size_t) 3 * cpu::MAXT * cpu::H), mref(mout.size());
|
||||
{ // the serial reference: run_split and run_split_multi are bitwise run's, token for token (pool.hpp)
|
||||
cpu::ExpertScratch ws;
|
||||
for (int j = 0; j < NJ; ++j) {
|
||||
sj[j].blob = s2[(size_t) j % 3].data();
|
||||
sj[j].act = &qact[(size_t) j % cpu::MAXT];
|
||||
sj[j].out = sout.data() + (size_t) j * cpu::H;
|
||||
sj[j].slot = j;
|
||||
cpu::s2_expert_vnni_q(sj[j].blob, *sj[j].act, sref.data() + (size_t) j * cpu::H, ws);
|
||||
}
|
||||
for (int e = 0; e < 3; ++e) {
|
||||
mj[e].blob = s2[(size_t) e].data();
|
||||
mj[e].nt = e + 1;
|
||||
for (int t = 0; t < mj[e].nt; ++t) {
|
||||
mj[e].act[t] = &qact[(size_t) t];
|
||||
mj[e].out[t] = mout.data() + ((size_t) e * cpu::MAXT + t) * cpu::H;
|
||||
cpu::s2_expert_vnni_q(mj[e].blob, qact[(size_t) t], mref.data() + ((size_t) e * cpu::MAXT + t) * cpu::H, ws);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (float v : sref) if (!std::isfinite(v)) { std::fprintf(stderr, "s2 reference not finite\n"); return 1; }
|
||||
for (bool host : {false, true}) for (int workers : {1, 2, 3, 5})
|
||||
for (int tasks : {0, 41}) {
|
||||
cpu::ExpertPool pool(workers, false, host, cpu::PoolAffinity::All, tasks);
|
||||
for (int repeat = 0; repeat < 3; ++repeat)
|
||||
for (int step = 0; step < 6; ++step) {
|
||||
bool ok = true;
|
||||
if (step % 2 == 1) { // the native batch between each pair
|
||||
for (const auto& job : jobs) for (int t = 0; t < job.nt; ++t) nan_h(job.out[t]);
|
||||
pool.run_split_multi_native(f, jobs.data(), n);
|
||||
ok = std::memcmp(ref.data(), out.data(), out.size() * sizeof(float)) == 0;
|
||||
} else if (step < 4) { // 0: run (mode 0), 2: run_split (modes 1/2)
|
||||
for (int j = 0; j < NJ; ++j) nan_h(sj[j].out);
|
||||
if (step == 0) pool.run(sj.data(), NJ);
|
||||
else pool.run_split(sj.data(), NJ);
|
||||
for (int j = 0; j < NJ; ++j) ok = ok && same_h(sj[j].out, sref.data() + (size_t) j * cpu::H);
|
||||
} else { // 4: run_split_multi (modes 3/4)
|
||||
for (const auto& job : mj) for (int t = 0; t < job.nt; ++t) nan_h(job.out[t]);
|
||||
pool.run_split_multi(mj.data(), 3);
|
||||
for (int e = 0; e < 3; ++e) for (int t = 0; t < mj[e].nt; ++t)
|
||||
ok = ok && same_h(mj[e].out[t], mref.data() + ((size_t) e * cpu::MAXT + t) * cpu::H);
|
||||
}
|
||||
if (!ok) {
|
||||
std::fprintf(stderr, "numa-split mixed-mode mismatch step=%d workers=%d host=%d tasks=%d "
|
||||
"repeat=%d\n", step, workers, host, tasks, repeat);
|
||||
return 1;
|
||||
}
|
||||
++mixed_checks;
|
||||
}
|
||||
pool.diag(stderr);
|
||||
}
|
||||
} else if (n == 7) {
|
||||
std::printf("pool tasks: modes 0-4 interleaved under the split SKIPPED (%s)\n", feat.reason());
|
||||
}
|
||||
unset_env("STRATA_NUMA_SPLIT");
|
||||
unset_env("STRATA_POOL_SPIN_US");
|
||||
if (cpu::active_numa_split().on) { std::fprintf(stderr, "numa-split plan outlived its pool\n"); return 1; }
|
||||
}
|
||||
std::printf("pool tasks: %d bitwise comparisons passed\n", checks);
|
||||
#if defined(__linux__)
|
||||
{ // the real split refuses STRATA_EXCHANGE_ROTATE=1 (experts move between slots, the slices need fixed ones)
|
||||
put_env("STRATA_NUMA_SPLIT", "1");
|
||||
put_env("STRATA_EXCHANGE_ROTATE", "1");
|
||||
bool refused = false;
|
||||
{
|
||||
cpu::ExpertPool pool(2, true, true);
|
||||
refused = !cpu::active_numa_split().on &&
|
||||
cpu::active_numa_split().why.find("STRATA_EXCHANGE_ROTATE") != std::string::npos;
|
||||
}
|
||||
unset_env("STRATA_EXCHANGE_ROTATE");
|
||||
unset_env("STRATA_NUMA_SPLIT");
|
||||
if (!refused) { std::fprintf(stderr, "numa-split did not refuse STRATA_EXCHANGE_ROTATE=1\n"); return 1; }
|
||||
}
|
||||
{ // the real split on any host: on means two distinct nodes and cores on both slices, off always says why
|
||||
put_env("STRATA_NUMA_SPLIT", "1");
|
||||
bool ok = false;
|
||||
{
|
||||
cpu::ExpertPool pool(4, true, true);
|
||||
const auto& plan = cpu::active_numa_split();
|
||||
ok = plan.on ? plan.nodes[0] != plan.nodes[1] && !plan.cores[0].empty() && !plan.cores[1].empty()
|
||||
: !plan.why.empty() && plan.nodes[0] == -1 && plan.nodes[1] == -1 && plan.cores[0].empty() &&
|
||||
plan.cores[1].empty();
|
||||
std::printf("pool tasks: real split %s%s\n", plan.on ? "on" : "off: ", plan.why.c_str());
|
||||
}
|
||||
unset_env("STRATA_NUMA_SPLIT");
|
||||
if (!ok) { std::fprintf(stderr, "numa-split real-mode plan invariant broken\n"); return 1; }
|
||||
// the DEFAULT worker count under the split spans every socket (pool_plan.hpp span_packages): on a 2-socket
|
||||
// host the split must then be on, where 0.2.0's host-socket default alone would leave every thread on one node
|
||||
put_env("STRATA_NUMA_SPLIT", "1");
|
||||
{
|
||||
const int packages = (int) cpu::pool_plan_input(cpu::detect_cpu_topology(true, cpu::PoolAffinity::All))
|
||||
.cores_per_package.size();
|
||||
cpu::ExpertPool pool(0, true, true);
|
||||
const auto& plan = cpu::active_numa_split();
|
||||
std::printf("pool tasks: default pool under the split: %d workers on %d socket(s), split %s%s (%s)\n",
|
||||
pool.workers(), packages, plan.on ? "on" : "off: ", plan.why.c_str(), pool.plan_limit());
|
||||
ok = packages != 2 || (plan.on && plan.cores[0].size() > 0 && plan.cores[1].size() > 0);
|
||||
}
|
||||
unset_env("STRATA_NUMA_SPLIT");
|
||||
if (!ok) { std::fprintf(stderr, "numa-split: the default pool on a 2-socket host did not span both nodes\n"); return 1; }
|
||||
// a value other than 1 / test is off, with the value in the reason; "0" and "" are off silently
|
||||
for (const char* v : {"off", "yes"}) {
|
||||
put_env("STRATA_NUMA_SPLIT", v);
|
||||
bool bad = false;
|
||||
{
|
||||
cpu::ExpertPool pool(2, true, true);
|
||||
bad = cpu::active_numa_split().on || cpu::active_numa_split().why.find(std::string("'") + v + "'") == std::string::npos;
|
||||
}
|
||||
unset_env("STRATA_NUMA_SPLIT");
|
||||
if (bad) { std::fprintf(stderr, "numa-split did not refuse STRATA_NUMA_SPLIT=%s\n", v); return 1; }
|
||||
}
|
||||
}
|
||||
{ // 0.2.2: STRATA_NUMA_POOL=0 is the off switch of the split, STRATA_NUMA_SPLIT=1 or test included; and with neither set the
|
||||
// plan is empty on a host with one NUMA node (the code path of the pool before the split) and, on two or more, on only
|
||||
// when it says why or says the nodes (the pool then runs as before)
|
||||
for (const char* v : {"1", "test"}) {
|
||||
put_env("STRATA_NUMA_POOL", "0");
|
||||
put_env("STRATA_NUMA_SPLIT", v);
|
||||
bool off = false;
|
||||
{
|
||||
cpu::ExpertPool pool(4, true, true);
|
||||
off = !cpu::active_numa_split().on && cpu::active_numa_split().why.empty() && pool.numa_slices() == 0;
|
||||
}
|
||||
unset_env("STRATA_NUMA_POOL");
|
||||
unset_env("STRATA_NUMA_SPLIT");
|
||||
if (!off) { std::fprintf(stderr, "STRATA_NUMA_POOL=0 did not switch the split off (STRATA_NUMA_SPLIT=%s)\n", v); return 1; }
|
||||
}
|
||||
unset_env("STRATA_NUMA_SPLIT");
|
||||
cpu::ExpertPool pool(4, true, true);
|
||||
const auto& plan = cpu::active_numa_split();
|
||||
std::printf("pool tasks: nothing set: split %s%s\n", plan.on ? "on" : "off", plan.why.empty() ? "" : (": " + plan.why).c_str());
|
||||
if (!plan.on && !plan.why.empty()) { std::fprintf(stderr, "an automatic split that did not run left a refusal reason\n"); return 1; }
|
||||
}
|
||||
{ // 0.2.2: a made-up two-node machine (STRATA_TEST_SYSFS_ROOT): the pool's own node lookup, the automatic split, its log lines
|
||||
const std::vector<int> cores = cpu::detect_cpu_topology(true, cpu::PoolAffinity::All).worker_cores;
|
||||
const int host = cpu::detect_cpu_topology(true, cpu::PoolAffinity::All).host_core;
|
||||
if (cores.size() < 4 || host < 0) {
|
||||
std::printf("pool tasks: fake two-node machine SKIPPED (needs 4 worker cores and a host core)\n");
|
||||
} else {
|
||||
namespace fs = std::filesystem;
|
||||
const fs::path root = fs::temp_directory_path() / ("strata_pool_fake_sysfs_" + std::to_string((long long) std::time(nullptr)));
|
||||
// node k of worker core i: the workers alternate between the nodes, the host core is on node 0
|
||||
auto build = [&](int n_nodes) {
|
||||
fs::remove_all(root);
|
||||
fs::create_directories(root / "devices/system/node");
|
||||
std::vector<std::string> list((size_t) n_nodes);
|
||||
auto put = [&](int cpu, int node) {
|
||||
fs::create_directories(root / "devices/system/cpu" / ("cpu" + std::to_string(cpu)) / ("node" + std::to_string(node)));
|
||||
list[(size_t) node] += (list[(size_t) node].empty() ? "" : ",") + std::to_string(cpu);
|
||||
};
|
||||
put(host, 0);
|
||||
for (size_t i = 0; i < cores.size(); ++i) put(cores[i], (int) (i % (size_t) n_nodes));
|
||||
for (int k = 0; k < n_nodes; ++k) {
|
||||
fs::create_directories(root / "devices/system/node" / ("node" + std::to_string(k)));
|
||||
std::ofstream(root / "devices/system/node" / ("node" + std::to_string(k)) / "cpulist") << list[(size_t) k] << "\n";
|
||||
}
|
||||
};
|
||||
put_env("STRATA_TEST_SYSFS_ROOT", root.string().c_str());
|
||||
unset_env("STRATA_NUMA_SPLIT");
|
||||
unset_env("STRATA_NUMA_POOL");
|
||||
const int workers = (int) std::min<size_t>(cores.size(), 8) & ~1; // even: the nodes get the same count
|
||||
|
||||
build(2); // two nodes, nothing set: the split runs by itself
|
||||
{
|
||||
cpu::ExpertPool pool(workers, true, true);
|
||||
const auto& plan = cpu::active_numa_split();
|
||||
const bool ok = plan.on && !plan.test && plan.nodes[0] == 0 && plan.nodes[1] == 1 && pool.numa_slices() == 2 &&
|
||||
!plan.cores[0].empty() && !plan.cores[1].empty();
|
||||
std::printf("pool tasks: fake two nodes, nothing set: split %s (%zu + %zu cores)\n", plan.on ? "on" : "off",
|
||||
plan.cores[0].size(), plan.cores[1].size());
|
||||
if (!ok) { std::fprintf(stderr, "the automatic split did not run on a two-node machine\n"); return 1; }
|
||||
}
|
||||
put_env("STRATA_NUMA_POOL", "0"); // the off switch
|
||||
{
|
||||
cpu::ExpertPool pool(workers, true, true);
|
||||
if (cpu::active_numa_split().on || pool.numa_slices() != 0) { std::fprintf(stderr, "STRATA_NUMA_POOL=0 did not switch the automatic split off\n"); return 1; }
|
||||
}
|
||||
unset_env("STRATA_NUMA_POOL");
|
||||
put_env("STRATA_EXCHANGE_ROTATE", "1"); // the split cannot run: the pool stays as it was, with no half-made plan
|
||||
{
|
||||
cpu::ExpertPool pool(workers, true, true);
|
||||
if (cpu::active_numa_split().on || pool.numa_slices() != 0 || !cpu::active_numa_split().why.empty()) {
|
||||
std::fprintf(stderr, "an automatic split that cannot run left a plan or a reason behind\n");
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
unset_env("STRATA_EXCHANGE_ROTATE");
|
||||
for (int nodes : {1, 3}) { // one node: the pool before the split; three: not supported, the pool as it was
|
||||
build(nodes);
|
||||
cpu::ExpertPool pool(workers, true, true);
|
||||
if (cpu::active_numa_split().on || pool.numa_slices() != 0) { std::fprintf(stderr, "split on a %d-node machine\n", nodes); return 1; }
|
||||
}
|
||||
{ // the default worker count and cores of a one-node machine do not depend on the split code at all
|
||||
build(1);
|
||||
cpu::ExpertPool a(0, true, true);
|
||||
const std::vector<int> a_cores = a.worker_cores();
|
||||
const int a_workers = a.workers();
|
||||
unset_env("STRATA_TEST_SYSFS_ROOT");
|
||||
cpu::ExpertPool b(0, true, true);
|
||||
if (a_workers != b.workers() || a_cores != b.worker_cores()) {
|
||||
std::fprintf(stderr, "a one-node fake machine changed the pool's workers or cores\n");
|
||||
return 1;
|
||||
}
|
||||
std::printf("pool tasks: one node: %d workers and the same cores as with no topology override\n", a_workers);
|
||||
}
|
||||
unset_env("STRATA_TEST_SYSFS_ROOT");
|
||||
fs::remove_all(root);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
std::printf("pool tasks: %d bitwise comparisons passed, %d of them in NUMA-split mode (%d with modes 0-4 "
|
||||
"interleaved)\n", checks + split_checks + mixed_checks, split_checks + mixed_checks, mixed_checks);
|
||||
return 0;
|
||||
}
|
||||
@@ -5824,6 +5824,9 @@ int main(int argc, char** argv) {
|
||||
if (pool.plan_limit()[0] != '\0') // the default count: what it was bounded by (a configured count is never changed)
|
||||
std::fprintf(stderr, "strata generate: CPU pool: %d workers by default (%d physical cores, %d logical processors; bounded by %s)\n",
|
||||
pool.workers(), pool.plan_cores(), pool.plan_logical(), pool.plan_limit());
|
||||
if (srcp == &arena_src && strata::kernels::cpu::active_numa_split().on && !strata::kernels::cpu::active_numa_split().test)
|
||||
std::fprintf(stderr, "strata generate: NUMA split on, but this model's experts come from the arena path: memory is "
|
||||
"not placed per node (known limitation)\n");
|
||||
if (pool.is_hybrid() && pool.affinity() != strata::kernels::cpu::PoolAffinity::All) {
|
||||
const char* aff_str = pool.affinity() == strata::kernels::cpu::PoolAffinity::PCores ? "p-cores" :
|
||||
pool.affinity() == strata::kernels::cpu::PoolAffinity::All ? "all" : "auto";
|
||||
@@ -5832,9 +5835,11 @@ int main(int argc, char** argv) {
|
||||
}
|
||||
{ // where the threads run (--host-core)
|
||||
const strata::kernels::cpu::CpuTopology ht = strata::kernels::cpu::detect_cpu_topology(true, o.pool_affinity);
|
||||
// the pool's own order, not a fresh detection's: STRATA_NUMA_SPLIT interleaves the sockets
|
||||
const std::vector<int>& wc = pool.worker_cores();
|
||||
std::string on;
|
||||
for (int i = 0; i < pool.workers() && i < (int) ht.worker_cores.size(); ++i)
|
||||
on += (i > 0 ? "," : "") + std::to_string(ht.worker_cores[(size_t) i]);
|
||||
for (int i = 0; i < pool.workers() && i < (int) wc.size(); ++i)
|
||||
on += (i > 0 ? "," : "") + std::to_string(wc[(size_t) i]);
|
||||
std::fprintf(stderr, "strata generate: %d pool workers on logical processors %s, the host thread on %d%s "
|
||||
"(--host-core %s)\n", pool.workers(), on.c_str(), ht.host_core,
|
||||
pool.host_works() ? " (draining too)" : "",
|
||||
@@ -5843,10 +5848,9 @@ int main(int argc, char** argv) {
|
||||
: "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>((size_t) pool.workers(), ht.worker_cores.size());
|
||||
const size_t nw = std::min<size_t>((size_t) pool.workers(), wc.size());
|
||||
std::fprintf(stderr, "%s\n",
|
||||
strata::aux_cpus::set_topology(ht.host_core, std::vector<int>(ht.worker_cores.begin(),
|
||||
ht.worker_cores.begin() + (long) nw)).c_str());
|
||||
strata::aux_cpus::set_topology(ht.host_core, std::vector<int>(wc.begin(), wc.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`
|
||||
@@ -7986,6 +7990,17 @@ int main(int argc, char** argv) {
|
||||
}
|
||||
src.stage_lend_regions(std::move(stage_lends));
|
||||
}
|
||||
{ // the pack's and the MTP head's files: read at start, their cache is given back by the complement's drop
|
||||
std::vector<std::string> drop;
|
||||
for (const std::string& d : {o.pack, o.mtp}) {
|
||||
std::error_code ec;
|
||||
if (d.empty()) continue;
|
||||
if (std::filesystem::is_regular_file(d, ec)) { drop.push_back(d); continue; }
|
||||
for (const auto& f : std::filesystem::directory_iterator(d, ec))
|
||||
if (f.is_regular_file(ec)) drop.push_back(f.path().string());
|
||||
}
|
||||
src.set_extra_drop_files(std::move(drop));
|
||||
}
|
||||
const std::vector<std::pair<int32_t, int32_t>>& rank_all = profile_all.empty() ? profile : profile_all;
|
||||
bool resident_ok = src.pin_cache_complement(xcache, err, o.resident_pin, stage_pairs, lend_from,
|
||||
o.resident_headroom, o.resident_budget, &rank_all);
|
||||
@@ -16304,10 +16319,13 @@ int main(int argc, char** argv) {
|
||||
(double) (drive.d.multi_entries - entries0) / (double) (rounds * g.n_layers));
|
||||
if (rounds > 0)
|
||||
std::printf("%-24s gate/up %.3f quantize %.3f down %.3f ms/round; %.1f GB/s over the rows phases; "
|
||||
"CPU pool call %.3f ms/round\n", "pool multi", pool.ms_multi_gu / rounds,
|
||||
"CPU pool call %.3f ms/round", "pool multi", pool.ms_multi_gu / rounds,
|
||||
pool.ms_multi_q / rounds, pool.ms_multi_down / rounds,
|
||||
(double) pool.multi_bytes / 1e6 / std::max(1e-9, pool.ms_multi_gu + pool.ms_multi_down),
|
||||
(drive.cpu_ms - pool_ms0) / rounds);
|
||||
if (rounds > 0 && pool.numa_slices() == 2) // STRATA_NUMA_SPLIT: each slice's drain, publish to its last task
|
||||
std::printf("; numa slices: s0 %.3f ms s1 %.3f ms", pool.numa_slice_ms(0) / rounds, pool.numa_slice_ms(1) / rounds);
|
||||
if (rounds > 0) std::printf("\n");
|
||||
if (rounds > 0)
|
||||
std::printf("%-24s plan %.3f activation quantize %.3f jobs %.3f run %.3f ms/round\n", "dispatch",
|
||||
drive.d.ms_plan / rounds, drive.d.ms_actq / rounds, drive.d.ms_jobs / rounds,
|
||||
|
||||
@@ -399,6 +399,51 @@ void test_pin_pacing() {
|
||||
require(page_cache_hint("MemFree: 100 kB\nCached: 1000 kB\n").empty(), "a small cache was reported");
|
||||
}
|
||||
|
||||
// NUMA split: per-slice byte ranges of one complement slot (page rule: a page holding a slice-0 byte is slice 0's)
|
||||
void test_numa_slice_ranges() {
|
||||
using strata::core::detail::numa_slice_ranges;
|
||||
constexpr uint64_t P = 4096;
|
||||
const uint64_t roles[3] = {870400, 870400, 921600};
|
||||
const uint64_t slot_bytes = roles[0] + roles[1] + roles[2];
|
||||
const uint64_t offs[3] = {0, 2662400ull * 7, P * 3 + 100};
|
||||
for (uint64_t off : offs) {
|
||||
const auto r0 = numa_slice_ranges(off, roles, 0), r1 = numa_slice_ranges(off, roles, 1);
|
||||
for (int r = 0; r < 3; ++r) {
|
||||
require(r0[r].first % P == 0 && r0[r].second % P == 0 && r1[r].first % P == 0 && r1[r].second % P == 0,
|
||||
"a slice range boundary was not page aligned");
|
||||
require(r0[r].first <= r0[r].second && r1[r].first <= r1[r].second, "a slice range was inverted");
|
||||
}
|
||||
// every page fully inside the slot is in exactly one of the six ranges (and none is in two)
|
||||
for (uint64_t pg = (off + P - 1) / P * P; pg + P <= off + slot_bytes; pg += P) {
|
||||
int hits = 0;
|
||||
for (int r = 0; r < 3; ++r) {
|
||||
hits += (pg >= r0[r].first && pg + P <= r0[r].second);
|
||||
hits += (pg >= r1[r].first && pg + P <= r1[r].second);
|
||||
}
|
||||
require(hits == 1, "a page was in " + std::to_string(hits) + " slice ranges, not exactly one");
|
||||
}
|
||||
}
|
||||
// (b) no slice-1 range intersects a slice-0 range, within a slot and across two consecutive slots
|
||||
const auto meet = [](const std::pair<uint64_t, uint64_t>& x, const std::pair<uint64_t, uint64_t>& y) {
|
||||
return x.first < y.second && y.first < x.second;
|
||||
};
|
||||
for (uint64_t off : offs) {
|
||||
const auto s0 = numa_slice_ranges(off, roles, 0), s1 = numa_slice_ranges(off, roles, 1);
|
||||
const auto n0 = numa_slice_ranges(off + slot_bytes, roles, 0), n1 = numa_slice_ranges(off + slot_bytes, roles, 1);
|
||||
for (int i = 0; i < 3; ++i)
|
||||
for (int j = 0; j < 3; ++j) {
|
||||
require(!meet(s0[i], s1[j]), "a slice-1 range intersects a slice-0 range of the same slot");
|
||||
require(!meet(s1[i], n0[j]) && !meet(n1[i], s0[j]),
|
||||
"a slice-1 range intersects a slice-0 range of the neighbouring slot");
|
||||
}
|
||||
}
|
||||
const auto a = numa_slice_ranges(0, roles, 0), b = numa_slice_ranges(0, roles, 1);
|
||||
require(a[0].first <= 435199 && 435199 < a[0].second, "last slice-0 gate byte not in slice 0's gate range");
|
||||
require(b[0].first <= 435200 + P && 435200 + P < b[0].second, "a slice-1 gate byte not in slice 1's gate range");
|
||||
require(a[1].first <= 870400 && 870400 < a[1].second, "the gate/up boundary page was not slice 0's up range");
|
||||
require(!(b[0].first <= 870400 && 870400 < b[0].second), "the gate/up boundary page was in slice 1's gate range");
|
||||
}
|
||||
|
||||
void test_resident_memory_budget() {
|
||||
using strata::core::detail::clamp_resident_budget;
|
||||
constexpr uint64_t GiB = 1ull << 30, margin = 256ull << 20, headroom = 4 * GiB;
|
||||
@@ -947,6 +992,7 @@ int main(int argc, char** argv) {
|
||||
test_resident_exchange();
|
||||
test_resident_memory_budget();
|
||||
test_pin_pacing();
|
||||
test_numa_slice_ranges();
|
||||
test_cgroup_memory_budget();
|
||||
test_host_memory();
|
||||
test_canonical_layout();
|
||||
|
||||
Reference in new issue
Block a user