okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

waveringanaedge0-strata: add the engine for Edge0 145B and Edge0 120Bfd19246dc

main
80.0 KiB1630 linesraw
1// src/kernels/cpu/pool.cpp - P2.S3: the CPU expert pool.  Read pool.hpp first; it explains the protocol.
2#include "strata/kernels/cpu/pool.hpp"
3#include "strata/core/progress.hpp"
4#include "strata/platform/aux_cpus.hpp"
5#include "strata/kernels/cpu/expert_layout.hpp"
6#include "strata/kernels/f16_bits.hpp"
7#include "strata/kernels/cpu/kq_avx2.hpp"
8namespace strata { namespace kernels {
9static float lat_q8_0_q8_1_row(const uint8_t* row, const uint8_t* xq, int ncols) {
10    const int nb = ncols / 32;
11    float acc = 0.0f;
12    for (int b = 0; b < nb; ++b) {
13        const uint8_t* wb = row + (size_t) b * 34;
14        const uint8_t* xb = xq + (size_t) b * 36;
15        const float dw = strata::kernels::f32_from_f16((uint16_t)(wb[0] | (wb[1] << 8)));
16        const float dx = strata::kernels::f32_from_f16((uint16_t)(xb[0] | (xb[1] << 8)));
17        const int8_t* ws = (const int8_t*)(wb + 2);
18        const int8_t* xs = (const int8_t*)(xb + 4);
19        int s = 0;
20        for (int j = 0; j < 32; ++j) s += (int)xs[j] * (int)ws[j];
21        acc += dw * dx * (float) s;
22    }
23    return acc;
24}
25// Q4DU: the Q4_0 form of the same row - {f16 d; uint8 nib[16]} blocks, element j in byte j's low
26// nibble, j+16 in its high one, value (code - 8) * d; the reference for the AVX2 path's numbers.
27static float lat_q4_0_q8_1_row(const uint8_t* row, const uint8_t* xq, int ncols) {
28    const int nb = ncols / 32;
29    float acc = 0.0f;
30    for (int b = 0; b < nb; ++b) {
31        const uint8_t* wb = row + (size_t) b * 18;
32        const uint8_t* xb = xq + (size_t) b * 36;
33        const float dw = strata::kernels::f32_from_f16((uint16_t)(wb[0] | (wb[1] << 8)));
34        const float dx = strata::kernels::f32_from_f16((uint16_t)(xb[0] | (xb[1] << 8)));
35        const int8_t* xs = (const int8_t*)(xb + 4);
36        int s = 0;
37        for (int j = 0; j < 16; ++j) {
38            const int byte_ = wb[2 + j];
39            s += (int)xs[j] * ((int)(byte_ & 0xF) - 8);
40            s += (int)xs[j + 16] * ((int)(byte_ >> 4) - 8);
41        }
42        acc += dw * dx * (float) s;
43    }
44    return acc;
45}
46} }
47#include "strata/kernels/cpu/numa_pool.hpp"
48#include "strata/kernels/cpu/cgroup_cpu.hpp"
49
50#include <algorithm>
51#include <atomic>
52#include <cmath>
53#include <chrono>
54#include "strata/platform/cpu_relax.hpp"
55#if defined(_MSC_VER)
56#include <intrin.h>   // __cpuidex, __rdtsc (STRATA_POOL_UMWAIT)
57#endif
58
59#include <cstdio>
60#include <cstdlib>
61#include <cstring>
62#include <stdexcept>
63#include <string>
64#include <thread>
65
66#if defined(_WIN32)
67#define WIN32_LEAN_AND_MEAN
68#include <windows.h>
69#include "pool_affinity_win.hpp"
70#else
71#include <pthread.h>
72#include <sched.h>
73#include <unistd.h>
74#include "pool_affinity_linux.hpp"
75#endif
76
77namespace strata::kernels::cpu {
78
79namespace {
80// STRATA_POOL_UMWAIT=<TSC cycles> (experimental, x86 WAITPKG only): a parked worker waits with UMONITOR/UMWAIT on the
81// epoch's cache line instead of spinning on _mm_pause.  It wakes when the host publishes (a write to that line) or
82// after the cycles, in the light C0.1 state; on a laptop the CPU then gives back the power the spin took, which the
83// GPU's share of the budget gets.  0 or unset (or no WAITPKG): the spin, unchanged.  STRATA_POOL_UMWAIT_C02=1: the
84// deeper C0.2 state (slower wake).  MSVC x64 only for now (the intrinsics need no target flag there); other builds spin.
85uint64_t umwait_cycles() {
86    static const uint64_t c = [] {
87        const char* e = std::getenv("STRATA_POOL_UMWAIT");
88        if (e == nullptr || std::atoll(e) <= 0) return (uint64_t) 0;
89#if defined(_MSC_VER) && defined(_M_X64) && !defined(__clang__)   // MSVC proper: clang-cl (the Windows HIP build) has no WAITPKG intrinsics by default
90        int r[4] = {0, 0, 0, 0};
91        __cpuidex(r, 7, 0);
92        if (((r[2] >> 5) & 1) == 0) {
93            std::fprintf(stderr, "strata: STRATA_POOL_UMWAIT: this CPU has no WAITPKG, the workers spin\n");
94            return (uint64_t) 0;
95        }
96        std::fprintf(stderr, "strata: STRATA_POOL_UMWAIT: parked workers wait with UMWAIT (%lld cycles)\n", std::atoll(e));
97        return (uint64_t) std::atoll(e);
98#else
99        return (uint64_t) 0;
100#endif
101    }();
102    return c;
103}
104unsigned umwait_state() {
105    static const unsigned s = [] { const char* e = std::getenv("STRATA_POOL_UMWAIT_C02"); return e && *e == '1' ? 0u : 1u; }();
106    return s;   // 1 = C0.1 (light), 0 = C0.2
107}
108// STRATA_POOL_UMWAIT_ESC=<TSC cycles> (experimental): an escalating wait - C0.1 for the first cycles of a park, C0.2 after
109// (a wait that has lasted that long is a GPU phase, a draft or a prompt read, where a slower wake costs little).
110uint64_t umwait_escalate() {
111    static const uint64_t c = [] { const char* e = std::getenv("STRATA_POOL_UMWAIT_ESC"); return e ? (uint64_t) (std::max)(0LL, std::atoll(e)) : (uint64_t) 0; }();
112    return c;
113}
114
115constexpr uint64_t pack_head(uint32_t epoch, uint32_t n, uint32_t i) {
116    return ((uint64_t) epoch << 32) | ((uint64_t) n << 16) | (uint64_t) i;
117}
118}  // namespace
119
120namespace {
121std::atomic<int> g_host_core{(int) HostCore::First};
122}  // namespace
123
124void set_host_core(HostCore where) { g_host_core.store((int) where); }
125HostCore host_core_setting() { return (HostCore) g_host_core.load(); }
126
127namespace {
128std::vector<int> g_pool_cores;   // --pool-cores: set once at start-up, before the pool exists
129}  // namespace
130void set_pool_cores(const std::vector<int>& cpus) { g_pool_cores = cpus; }
131const std::vector<int>& pool_cores_setting() { return g_pool_cores; }
132
133std::vector<LogicalCpuInfo> logical_cpu_layout() {
134    std::vector<LogicalCpuInfo> out;
135#if defined(_WIN32)
136    DWORD len = 0;
137    GetLogicalProcessorInformationEx(RelationProcessorCore, nullptr, &len);
138    if (len == 0) return out;
139    std::vector<char> buf(len);
140    if (!GetLogicalProcessorInformationEx(RelationProcessorCore, (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX) buf.data(), &len))
141        return out;
142    // a `start /affinity` or a job limit on a PC with one processor group: only those processors are the process's
143    DWORD_PTR proc_mask = 0, sys_mask = 0;
144    const bool limited = GetActiveProcessorGroupCount() == 1 && GetProcessAffinityMask(GetCurrentProcess(), &proc_mask, &sys_mask);
145    long core = 0;
146    for (const char* p = buf.data(); p < buf.data() + len; p += ((const SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX*) p)->Size) {
147        const auto* e = (const SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX*) p;
148        if (e->Relationship != RelationProcessorCore) continue;
149        for (WORD group = 0; group < e->Processor.GroupCount; ++group) {
150            const GROUP_AFFINITY& g = e->Processor.GroupMask[group];
151            for (int bit = 0; bit < 64; ++bit)
152                if ((g.Mask & (KAFFINITY(1) << bit)) && (!limited || (proc_mask & (DWORD_PTR(1) << bit))))
153                    out.push_back({(int) (g.Group * 64 + bit), core});
154        }
155        ++core;
156    }
157#elif defined(__linux__)
158    std::vector<unsigned long> mask;
159    std::vector<int> allowed;
160    if (detail::get_thread_affinity(mask, &allowed) != 0) return out;
161    auto read = [](int cpu, const char* what) -> long {
162        char path[96];
163        std::snprintf(path, sizeof path, "/sys/devices/system/cpu/cpu%d/topology/%s", cpu, what);
164        long v = -1;
165        if (std::FILE* f = std::fopen(path, "r")) {
166            if (std::fscanf(f, "%ld", &v) != 1) v = -1;
167            std::fclose(f);
168        }
169        return v;
170    };
171    for (int cpu : allowed) {
172        const long pkg = read(cpu, "physical_package_id"), core = read(cpu, "core_id");
173        out.push_back({cpu, pkg >= 0 && core >= 0 ? pkg * 1000000 + core : -1});
174    }
175#else
176    for (unsigned i = 0; i < std::thread::hardware_concurrency(); ++i) out.push_back({(int) i, -1});
177#endif
178    return out;
179}
180
181static CpuTopology detect_cpu_topology_impl(bool skip_first, PoolAffinity affinity);
182
183// The fields the default worker count needs (pool_plan.hpp): the logical processors the process may use, the CPU
184// package of the host core and of every worker core, whether the OS told physical cores from SMT siblings, the
185// container CPU quota.  On a multi-socket CPU (not hybrid) the host package comes first in `worker_cores`.
186static void fill_plan_fields(CpuTopology& topo, bool skip_first) {
187    topo.cpu_quota = container_cpu_quota();
188    topo.worker_package.assign(topo.worker_cores.size(), -1);
189#if defined(_WIN32)
190    (void) skip_first;
191    topo.logical = (int) GetActiveProcessorCount(ALL_PROCESSOR_GROUPS);
192    return;   // (the sockets of a Windows box are not told apart: one package)
193#elif defined(__APPLE__)
194    (void) skip_first;
195    topo.logical = (int) std::thread::hardware_concurrency();
196    return;   // no SMT on Apple silicon and no sysfs: the cores are the processors
197#else
198    std::vector<unsigned long> mask;
199    std::vector<int> allowed;
200    topo.logical = detail::get_thread_affinity(mask, &allowed) == 0 ? (int) allowed.size()
201                                                                     : (int) std::thread::hardware_concurrency();
202    auto read = [](int cpu, const char* what) -> long {
203        char path[96];
204        std::snprintf(path, sizeof path, "/sys/devices/system/cpu/cpu%d/topology/%s", cpu, what);
205        long v = -1;
206        if (std::FILE* f = std::fopen(path, "r")) {
207            if (std::fscanf(f, "%ld", &v) != 1) v = -1;
208            std::fclose(f);
209        }
210        return v;
211    };
212    bool known = !topo.worker_cores.empty() || topo.host_core >= 0;
213    auto pkg_of = [&](int cpu) {
214        const long pkg = read(cpu, "physical_package_id"), core = read(cpu, "core_id");
215        if (pkg < 0 || core < 0) known = false;
216        return (int) pkg;
217    };
218    if (topo.host_core >= 0) topo.host_package = pkg_of(topo.host_core);
219    for (size_t i = 0; i < topo.worker_cores.size(); ++i) topo.worker_package[i] = pkg_of(topo.worker_cores[i]);
220    topo.layout_known = known;
221    if (!known) return;
222    if (skip_first && !topo.is_hybrid && topo.host_core >= 0 && topo.host_package >= 0) {
223        // the host socket first (stable inside each socket): the default workers are the local ones
224        std::vector<size_t> order(topo.worker_cores.size());
225        for (size_t i = 0; i < order.size(); ++i) order[i] = i;
226        std::stable_partition(order.begin(), order.end(),
227                              [&](size_t i) { return topo.worker_package[i] == topo.host_package; });
228        std::vector<int> cores, pkgs;
229        for (size_t i : order) { cores.push_back(topo.worker_cores[i]); pkgs.push_back(topo.worker_package[i]); }
230        topo.worker_cores = std::move(cores);
231        topo.worker_package = std::move(pkgs);
232    }
233#endif
234}
235
236CpuTopology detect_cpu_topology(bool skip_first, PoolAffinity affinity) {
237    CpuTopology topo = detect_cpu_topology_impl(skip_first, affinity);
238    // --host-core last: the host takes the last core, the workers the others (the first included)
239    if (skip_first && host_core_setting() == HostCore::Last && !topo.is_hybrid && topo.host_core >= 0 &&
240        !topo.worker_cores.empty()) {
241        const int last = topo.worker_cores.back();
242        topo.worker_cores.pop_back();
243        topo.worker_cores.insert(topo.worker_cores.begin(), topo.host_core);
244        topo.host_core = last;
245    }
246    // --host-core sibling: the host on its core's other hardware thread; the first logical processor stays to the
247    // interrupts and to nothing else (a worker on it would share the host's core)
248    if (skip_first && host_core_setting() == HostCore::Sibling && topo.host_sibling >= 0) {
249        topo.worker_cores.erase(std::remove(topo.worker_cores.begin(), topo.worker_cores.end(), topo.host_sibling),
250                                topo.worker_cores.end());
251        topo.host_core = topo.host_sibling;
252    }
253    fill_plan_fields(topo, skip_first);
254    return topo;
255}
256
257double container_cpu_quota() {
258#if defined(__linux__)
259    // the smallest cgroup CPU quota from this process's group up to the mount's root (cgroup v2 cpu.max, v1 cfs quota); see cgroup_cpu.hpp
260    std::string self;
261    if (std::FILE* f = std::fopen("/proc/self/cgroup", "r")) {
262        char buf[512];
263        size_t n;
264        while ((n = std::fread(buf, 1, sizeof buf, f)) > 0) self.append(buf, n);
265        std::fclose(f);
266    }
267    return cgroup_cpu_quota_at("/sys/fs/cgroup", self);
268#else
269    return 0.0;
270#endif
271}
272
273PoolPlanInput pool_plan_input(const CpuTopology& topo) {
274    PoolPlanInput in;
275    in.logical = topo.logical > 0 ? topo.logical : (int) std::thread::hardware_concurrency();
276    in.cpu_quota = topo.cpu_quota;
277    if (topo.is_hybrid) { in.p_cores = topo.p_cores; in.e_cores = topo.e_cores; }
278    if (!topo.layout_known) return in;   // cores_per_package stays empty
279    // the cores per package, the host package first; the host core counts in its package
280    std::vector<std::pair<int, int>> counts;   // (package, cores)
281    auto add = [&](int pkg) {
282        for (auto& c : counts)
283            if (c.first == pkg) { ++c.second; return; }
284        counts.emplace_back(pkg, 1);
285    };
286    if (topo.host_core >= 0) add(topo.host_package);
287    for (size_t i = 0; i < topo.worker_cores.size(); ++i)
288        add(i < topo.worker_package.size() ? topo.worker_package[i] : -1);
289    if (topo.host_core >= 0) {   // (the host package first even when it has no worker core listed)
290        auto it = std::find_if(counts.begin(), counts.end(), [&](const auto& c) { return c.first == topo.host_package; });
291        if (it != counts.begin()) std::iter_swap(counts.begin(), it);
292    }
293    for (const auto& c : counts) in.cores_per_package.push_back(c.second);
294    return in;
295}
296
297int planned_host_core(PoolAffinity affinity) { return detect_cpu_topology(true, affinity).host_core; }
298
299static CpuTopology detect_cpu_topology_impl(bool skip_first, PoolAffinity affinity) {
300    CpuTopology topo;
301#if defined(_WIN32)
302    // Ask the OS rather than assuming a layout.  `hardware_concurrency()` returns LOGICAL processors, and on
303    // every SMT machine half of them are siblings - pinning one worker to each of the first N would put two
304    // workers on each physical core and halve the bandwidth the expert kernel is bound by.
305    DWORD len = 0;
306    GetLogicalProcessorInformationEx(RelationProcessorCore, nullptr, &len);
307    if (len == 0) {
308        // Preserve group identity even when detailed core topology is unavailable.
309        const WORD groups = GetActiveProcessorGroupCount();
310        for (WORD group = 0; group < groups; ++group) {
311            const DWORD count = GetActiveProcessorCount(group);
312            if (count == 0 || count == (DWORD) -1 || count > 64) continue;
313            for (DWORD i = 0; i < count; ++i) topo.worker_cores.push_back((int) group * 64 + (int) i);
314        }
315        if (skip_first && !topo.worker_cores.empty()) {
316            topo.host_core = topo.worker_cores.front();
317            topo.worker_cores.erase(topo.worker_cores.begin());
318        }
319        // The OS did not say which logical processors share a core, and every one is listed as a core above: the default
320        // worker count must not count them as cores (30 workers on a 16c/32t PC would sit two to a core).  With the layout
321        // unknown the plan takes half the logical processors (pool_plan.hpp), as on Linux without sysfs.
322        topo.layout_known = false;
323        return topo;
324    }
325    std::vector<char> buf(len);
326    if (GetLogicalProcessorInformationEx(RelationProcessorCore,
327                                         (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX) buf.data(), &len)) {
328        const char* p = buf.data();
329        const char* end = p + len;
330        struct CoreDesc {
331            uint8_t efficiency = 0;
332            bool has_smt = false;
333            std::vector<int> lps;
334        };
335        std::vector<CoreDesc> descs;
336        while (p < end) {
337            const auto* e = (const SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX*) p;
338            if (e->Relationship == RelationProcessorCore) {
339                CoreDesc cd;
340                cd.efficiency = e->Processor.EfficiencyClass;
341                cd.has_smt = (e->Processor.Flags & LTP_PC_SMT) != 0;
342                for (WORD group = 0; group < e->Processor.GroupCount; ++group) {
343                    const GROUP_AFFINITY& g = e->Processor.GroupMask[group];
344                    for (int bit = 0; bit < 64; ++bit) {
345                        if (g.Mask & (KAFFINITY(1) << bit)) {
346                            cd.lps.push_back((int) (g.Group * 64 + bit));
347                        }
348                    }
349                }
350                if (!cd.lps.empty()) {
351                    descs.push_back(std::move(cd));
352                }
353            }
354            p += e->Size;
355        }
356
357        uint8_t min_eff = 255, max_eff = 0;
358        for (const auto& c : descs) {
359            min_eff = (std::min)(min_eff, c.efficiency);
360            max_eff = (std::max)(max_eff, c.efficiency);
361        }
362
363        topo.is_hybrid = (max_eff > min_eff);
364        if (topo.is_hybrid) {
365            for (const auto& c : descs) {
366                if (c.efficiency == max_eff) {
367                    topo.p_cores++;
368                    topo.p_threads += (int) c.lps.size();
369                } else {
370                    topo.e_cores++;
371                }
372            }
373        } else {
374            topo.p_cores = (int) descs.size();
375            for (const auto& c : descs) topo.p_threads += (int) c.lps.size();
376        }
377
378        if (affinity == PoolAffinity::All || !topo.is_hybrid) {
379            // #642 (from Hardin22's fork): on a hybrid CPU the P-cores first (the host takes the first of them), so a
380            // pool smaller than the core count (setup's --pool-workers for a hybrid CPU) runs on the P-cores and the
381            // first E-cores rather than on whatever the OS numbered first.  All cores alike: the order is unchanged.
382            if (topo.is_hybrid)
383                std::stable_sort(descs.begin(), descs.end(),
384                                 [](const CoreDesc& x, const CoreDesc& y) { return x.efficiency > y.efficiency; });
385            for (const auto& c : descs) topo.worker_cores.push_back(c.lps[0]);
386            if (skip_first && !topo.worker_cores.empty()) {
387                topo.host_core = topo.worker_cores.front();
388                topo.worker_cores.erase(topo.worker_cores.begin());
389                if (descs.front().lps.size() > 1) topo.host_sibling = descs.front().lps[1];
390            }
391            return topo;
392        }
393
394        // Hybrid CPU with Auto or PCores affinity:
395        // Prioritize Performance cores:
396        // 1. Primary logical processor of each P-core (avoids SMT resource contention)
397        // 2. SMT sibling logical processors of P-cores
398        // 3. E-cores (only as overflow in Auto mode)
399        std::vector<int> p_primaries;
400        std::vector<int> p_siblings;
401        std::vector<int> e_cores;
402
403        for (const auto& c : descs) {
404            if (c.efficiency == max_eff) {
405                p_primaries.push_back(c.lps[0]);
406                for (size_t s = 1; s < c.lps.size(); ++s) {
407                    p_siblings.push_back(c.lps[s]);
408                }
409            } else {
410                for (int lp : c.lps) e_cores.push_back(lp);
411            }
412        }
413
414        if (skip_first && !p_primaries.empty()) {
415            topo.host_core = p_primaries.front();
416            p_primaries.erase(p_primaries.begin());
417            for (const auto& c : descs)
418                if (c.lps[0] == topo.host_core) {
419                    if (c.lps.size() > 1) topo.host_sibling = c.lps[1];
420                    break;
421                }
422        }
423
424        for (int cpu : p_primaries) topo.worker_cores.push_back(cpu);
425        for (int cpu : p_siblings) topo.worker_cores.push_back(cpu);
426        if (affinity != PoolAffinity::PCores) {
427            for (int cpu : e_cores) topo.worker_cores.push_back(cpu);
428        }
429        return topo;
430    }
431#else
432    // The logical CPUs this process may run on, ONE PER PHYSICAL CORE (issue #40): SMT siblings share a core's
433    // load/store bandwidth, so a worker on each would put two workers on one core, as the Windows branch above
434    // explains.  sysfs names each CPU's (package, core); the first allowed CPU of each pair is kept, so a taskset
435    // that leaves out the first sibling still gets its core.  Without sysfs every allowed CPU counts, as before.
436    auto topo_read = [](int cpu, const char* what) -> long {
437        char path[96];
438        std::snprintf(path, sizeof path, "/sys/devices/system/cpu/cpu%d/topology/%s", cpu, what);
439        long v = -1;
440        if (std::FILE* f = std::fopen(path, "r")) {
441            if (std::fscanf(f, "%ld", &v) != 1) v = -1;
442            std::fclose(f);
443        }
444        return v;
445    };
446    auto cap_read = [](int cpu) -> long {
447        char path[96];
448        std::snprintf(path, sizeof path, "/sys/devices/system/cpu/cpu%d/cpu_capacity", cpu);
449        long v = -1;
450        if (std::FILE* f = std::fopen(path, "r")) {
451            if (std::fscanf(f, "%ld", &v) != 1) v = -1;
452            std::fclose(f);
453        }
454        return v;
455    };
456
457    // #798: a cpulist ("0-7,16") of one of the hybrid PMU's CPU sets: /sys/devices/cpu_core/cpus and cpu_atom/cpus
458    auto cpulist_read = [](const char* path, std::vector<int>& out) -> bool {
459        std::FILE* f = std::fopen(path, "r");
460        if (!f) return false;
461        char text[1024] = {0};
462        const size_t n = std::fread(text, 1, sizeof text - 1, f);
463        std::fclose(f);
464        text[n] = '\0';
465        for (const char* p = text; *p;) {
466            char* end = nullptr;
467            const long lo = std::strtol(p, &end, 10);
468            if (end == p) break;
469            long hi = lo;
470            if (*end == '-') {
471                p = end + 1;
472                hi = std::strtol(p, &end, 10);
473            }
474            for (long c = lo; c <= hi && c < 4096; ++c) out.push_back((int) c);
475            p = end;
476            while (*p == ',' || *p == ' ' || *p == '\n')  ++p;
477        }
478        return !out.empty();
479    };
480
481    std::vector<int> allowed;
482    std::vector<unsigned long> allowed_mask;
483    if (detail::get_thread_affinity(allowed_mask, &allowed) != 0) {
484        for (unsigned i = 0; i < std::thread::hardware_concurrency(); ++i) allowed.push_back((int) i);
485    }
486
487    struct CoreLinux {
488        int cpu = -1;
489        long pkg = -1;
490        long core = -1;
491        long cap = -1;
492        bool is_sibling = false;
493    };
494    std::vector<CoreLinux> all_cpus;
495    std::vector<std::pair<long, long>> seen_phys;
496    long max_cap = 0, min_cap = 1000000;
497
498    for (int cpu : allowed) {
499        CoreLinux cl;
500        cl.cpu = cpu;
501        cl.pkg = topo_read(cpu, "physical_package_id");
502        cl.core = topo_read(cpu, "core_id");
503        cl.cap = cap_read(cpu);
504        if (cl.cap > 0) {
505            max_cap = (std::max)(max_cap, cl.cap);
506            min_cap = (std::min)(min_cap, cl.cap);
507        }
508        if (cl.pkg >= 0 && cl.core >= 0) {
509            const std::pair<long, long> key{cl.pkg, cl.core};
510            if (std::find(seen_phys.begin(), seen_phys.end(), key) != seen_phys.end()) {
511                cl.is_sibling = true;
512            } else {
513                seen_phys.push_back(key);
514            }
515        }
516        all_cpus.push_back(cl);
517    }
518
519    // #798: which CPUs are E-cores.  Intel's hybrid PMU lists them (cpu_atom/cpus beside cpu_core/cpus); without it a
520    // CPU is an E-core when its capacity is under 90% of the largest.  Turbo Boost Max 3.0 gives the "favored"
521    // P-cores a slightly higher capacity (1024 against 1012 on a Core Ultra 7 270K Plus): "capacity == the maximum"
522    // counted 2 of its 8 P-cores and started 1 pool worker.
523    // #3262: Meteor Lake and Arrow Lake-H list their LP-E cores (SoC tile, no L3, ~2.5 GHz) in a third set,
524    // /sys/devices/cpu_lowpower/cpus, that is in neither of the other two; they are E-cores too (and sort last).
525    std::vector<int> pmu_core, pmu_atom, pmu_lowpower;
526    const bool pmu = cpulist_read("/sys/devices/cpu_core/cpus", pmu_core) &&
527                     cpulist_read("/sys/devices/cpu_atom/cpus", pmu_atom);
528    cpulist_read("/sys/devices/cpu_lowpower/cpus", pmu_lowpower);
529    auto is_e = [&](const CoreLinux& cl) {
530        return hybrid_cpu_is_efficiency(cl.cpu, cl.cap, max_cap, pmu, pmu_core, pmu_atom, pmu_lowpower);
531    };
532    bool any_e = false, any_p = false;
533    for (const auto& cl : all_cpus) (is_e(cl) ? any_e : any_p) = true;
534    topo.is_hybrid = any_e && any_p;
535    if (topo.is_hybrid) {
536        for (const auto& cl : all_cpus) {
537            if (!is_e(cl)) {
538                if (!cl.is_sibling) topo.p_cores++;
539                topo.p_threads++;
540            } else {
541                if (!cl.is_sibling) topo.e_cores++;
542            }
543        }
544    } else {
545        topo.p_cores = (int) seen_phys.size();
546        topo.p_threads = (int) all_cpus.size();
547    }
548
549    // the host core's SMT sibling, an allowed CPU of the same (package, core) (--host-core sibling)
550    auto sibling_of = [&](int cpu) {
551        for (const auto& h : all_cpus)
552            if (h.cpu == cpu && h.pkg >= 0 && h.core >= 0)
553                for (const auto& cl : all_cpus)
554                    if (cl.cpu != cpu && cl.pkg == h.pkg && cl.core == h.core) return cl.cpu;
555        return -1;
556    };
557
558    if (affinity == PoolAffinity::All || !topo.is_hybrid) {
559        if (topo.is_hybrid)   // #642: the P-cores first (see the Windows branch)
560            std::stable_sort(all_cpus.begin(), all_cpus.end(),
561                             [&](const CoreLinux& x, const CoreLinux& y) {
562                                 return is_e(x) != is_e(y) ? !is_e(x) : x.cap > y.cap;
563                             });
564        for (const auto& cl : all_cpus) {
565            if (!cl.is_sibling) topo.worker_cores.push_back(cl.cpu);
566        }
567        if (skip_first && !topo.worker_cores.empty()) {
568            topo.host_core = topo.worker_cores.front();
569            topo.worker_cores.erase(topo.worker_cores.begin());
570            topo.host_sibling = sibling_of(topo.host_core);
571        }
572        return topo;
573    }
574
575    // Hybrid CPU on Linux:
576    std::vector<int> p_primaries;
577    std::vector<int> p_siblings;
578    std::vector<int> e_cores;
579
580    for (const auto& cl : all_cpus) {
581        if (!is_e(cl)) {
582            if (!cl.is_sibling) p_primaries.push_back(cl.cpu);
583            else p_siblings.push_back(cl.cpu);
584        } else {
585            e_cores.push_back(cl.cpu);
586        }
587    }
588
589    if (skip_first && !p_primaries.empty()) {
590        topo.host_core = p_primaries.front();
591        p_primaries.erase(p_primaries.begin());
592        topo.host_sibling = sibling_of(topo.host_core);
593    }
594
595    for (int cpu : p_primaries) topo.worker_cores.push_back(cpu);
596    for (int cpu : p_siblings) topo.worker_cores.push_back(cpu);
597    if (affinity != PoolAffinity::PCores) {
598        for (int cpu : e_cores) topo.worker_cores.push_back(cpu);
599    }
600    return topo;
601#endif
602    return topo;
603}
604
605std::vector<int> physical_cores(bool skip_first, PoolAffinity affinity) {
606    return detect_cpu_topology(skip_first, affinity).worker_cores;
607}
608
609namespace {
610
611bool pin_this_thread(int core, [[maybe_unused]] int worker = -1) {
612    if (core < 0) return false;
613#if defined(_WIN32)
614    return detail::set_thread_group_affinity(core, worker);
615#else
616    const int error = detail::pin_thread_to_cpu(core);
617    if (error != 0)
618        std::fprintf(stderr, "strata cpu pool: affinity for worker %d (CPU %d) failed: %d; previous affinity kept\n",
619                     worker, core, error);
620    return error == 0;
621#endif
622}
623
624#if defined(__linux__)
625// Where the NUMA topology is read from: /sys. STRATA_TEST_SYSFS_ROOT=<dir> reads <dir>/devices/system/{node,cpu} instead,
626// so a test can give the pool a made-up two-node machine (pool_tasks_test); nobody sets it for real.
627std::string sysfs_root() {
628    const char* e = std::getenv("STRATA_TEST_SYSFS_ROOT");
629    return e != nullptr && *e != '\0' ? std::string(e) : std::string("/sys");
630}
631
632// The NUMA node of a logical CPU (sysfs), or -1.
633int cpu_numa_node(int cpu) {
634    if (cpu < 0) return -1;
635    const std::string root = sysfs_root();
636    char path[512];
637    for (int node = 0; node < 64; ++node) {
638        std::snprintf(path, sizeof path, "%s/devices/system/cpu/cpu%d/node%d", root.c_str(), cpu, node);
639        if (access(path, F_OK) == 0) return node;
640    }
641    return -1;
642}
643#endif
644
645// 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
646// (numa_pool.hpp); Windows: GetNumaHighestNodeNumber; any other system, or a sandbox that hides the folder: 1.
647int numa_node_count() {
648#if defined(__linux__)
649    return (std::max)(1, numa_cpu_node_count_at(sysfs_root() + "/devices/system/node"));
650#elif defined(_WIN32)
651    ULONG highest = 0;
652    return GetNumaHighestNodeNumber(&highest) ? (int) highest + 1 : 1;
653#else
654    return 1;
655#endif
656}
657
658// The real-node split for threads on `thread_core` (numa_pool.hpp).  Linux only: the placement of the experts' memory
659// (first touch by threads pinned to a node, move_pages to check) has no Windows or macOS version.
660NumaSplitDecision decide_real_numa_split([[maybe_unused]] const std::vector<int>& thread_core, [[maybe_unused]] int n_workers,
661                                         [[maybe_unused]] bool pinned) {
662#if defined(__linux__)
663    // the expert source's own reading of it (expert_source.cpp): exactly "1"
664    const char* rotate = std::getenv("STRATA_EXCHANGE_ROTATE");
665    return decide_numa_split(thread_core, n_workers, pinned, rotate != nullptr && std::strcmp(rotate, "1") == 0, cpu_numa_node);
666#else
667    NumaSplitDecision d;
668    d.why = "the split needs Linux";
669    return d;
670#endif
671}
672
673}  // namespace
674
675ThreadAffinity pin_current_thread(int core) {
676    if (core < 0) return {};
677#if defined(_WIN32)
678    ThreadAffinity previous;
679    ULONG target = 0;
680    if (!detail::get_thread_cpu_sets(previous.cpu_sets) || !detail::cpu_set_for_core(core, target) ||
681        !SetThreadSelectedCpuSets(GetCurrentThread(), &target, 1)) {
682        std::fprintf(stderr, "strata cpu pool: host CPU Set selection for processor %d failed: %lu; previous placement kept\n",
683                     core, (unsigned long) GetLastError());
684        return {};
685    }
686    previous.valid = true;
687    return previous;
688#else
689    ThreadAffinity previous;
690    int error = detail::get_thread_affinity(previous.mask);
691    if (error == 0) error = detail::pin_thread_to_cpu(core);
692    if (error != 0) {
693        std::fprintf(stderr, "strata cpu pool: host affinity for CPU %d failed: %d; previous affinity kept\n", core, error);
694        return {};
695    }
696    previous.valid = true;
697    return previous;
698#endif
699}
700
701void restore_thread_affinity(const ThreadAffinity& previous) {
702    if (!previous.valid) return;
703#if defined(_WIN32)
704    // Clearing an originally empty selection restores process-default/all-group eligibility without
705    // turning the caller's implicit Windows 11 affinity into an explicit single-group hard mask.
706    if (!SetThreadSelectedCpuSets(GetCurrentThread(), previous.cpu_sets.empty() ? nullptr : previous.cpu_sets.data(),
707                                 (ULONG) previous.cpu_sets.size()))
708        std::fprintf(stderr, "strata cpu pool: host CPU Set restoration failed: %lu\n",
709                     (unsigned long) GetLastError());
710#else
711    const int error = detail::set_thread_affinity(previous.mask);
712    if (error != 0)
713        std::fprintf(stderr, "strata cpu pool: host affinity restoration failed: %d\n", error);
714#endif
715}
716
717namespace {
718std::atomic<const ExpertPool*> g_diag_pool{nullptr};
719void diag_active_pool(std::FILE* f) {
720    if (const ExpertPool* p = g_diag_pool.load()) p->diag(f);
721}
722int64_t now_ms() {
723    return std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now().time_since_epoch())
724        .count();
725}
726int64_t now_ns() {
727    return std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::steady_clock::now().time_since_epoch())
728        .count();
729}
730// CBA: one plain global, written by the constructor and destructor of the pool that owns it; fine while pools are
731// built and destroyed on one thread (generate's measure pools, then the main one), an atomic owner if that changes.
732NumaSplitPlan g_numa_plan;
733const ExpertPool* g_numa_owner = nullptr;
734}  // namespace
735
736const NumaSplitPlan& active_numa_split() { return g_numa_plan; }
737
738void ExpertPool::diag(std::FILE* f) const {
739    const uint64_t h = head_.load();
740    uint32_t batch = (uint32_t) (h >> 32), claimed = (uint32_t) h & 0xffffu, total = (uint32_t) (h >> 16) & 0xffffu,
741             done = done_.load();
742    // 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
743    // diag test if it ever misreports
744    if (numa_n_ > 0 && mode_ >= 5) {   // a split native batch never writes head_/done_: the slices' sums instead
745        claimed = total = done = 0;
746        for (int k = 0; k < numa_n_; ++k) {
747            const uint64_t sh = nsync_[(size_t) k].head.load();
748            batch = (uint32_t) (sh >> 32);   // every slice head carries the batch's epoch
749            claimed += (uint32_t) sh & 0xffffu;
750            total += (uint32_t) (sh >> 16) & 0xffffu;
751            done += nsync_[(size_t) k].done.load();
752        }
753    }
754    std::fprintf(f, "  expert pool: epoch %u, batch epoch %u: %u of %u jobs claimed, %u done; %u of %d workers parked, "
755                    "%u sleeping; mode %d\n", epoch_.load(), batch, claimed, total, done, parked_count(), n_,
756                 sleepers_.load(), mode_);
757    if (numa_n_ > 0) std::fprintf(f, "  expert pool NUMA slices:%s\n", numa_counters().c_str());
758    std::fprintf(f, "  expert pool threads:");
759    for (int i = 0; i < n_; ++i) {
760        const int32_t s = wstate_[(size_t) i].load();
761        if (s == kParked) std::fprintf(f, " w%d=parked", i);
762        else if (s == kSleeping) std::fprintf(f, " w%d=sleeping", i);
763        else if (s == kBetween) std::fprintf(f, " w%d=draining", i);
764        else std::fprintf(f, " w%d=job%d", i, s);
765    }
766    const int32_t hs = hstate_.load();
767    const char* hn = hs == kIdle ? "idle" : hs == kWaitParked ? "waiting for the workers to park"
768                   : hs == kWaitDone ? "waiting for the jobs to finish" : "running a job";
769    std::fprintf(f, "; host %s", hn);
770    if (hs >= 0) std::fprintf(f, " %d", hs);
771    std::fprintf(f, " for %lld ms\n", (long long) (now_ms() - hstate_ms_.load()));
772}
773
774ExpertPool::ExpertPool(int n_workers, bool pin, bool host_works, PoolAffinity affinity, int tasks)
775    : tasks_(tasks), host_works_(host_works), affinity_(affinity), topo_(detect_cpu_topology(true, affinity)) {
776    if (tasks < 0 || tasks > kMaxTasks) throw std::invalid_argument("expert pool tasks must be in 0..4096");
777    pinned_ = pin;
778    layout_ = logical_cpu_layout();   // now, before anything pins the caller (Linux reads the calling thread's allowed CPUs)
779    if (const char* e = std::getenv("STRATA_POOL_SPIN_US"))   // a test knob; see kSpinBeforeSleep
780        spin_before_sleep_ = std::chrono::microseconds((std::max)(0, std::atoi(e)));
781    // STRATA_NUMA_SPLIT, read here for the worker count (the split itself is decided below, once the count is known).
782    // 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
783    // off (numa_pool.hpp).  One node: pick_numa_pool says Unchanged and nothing below differs from the pool before the split.
784    const char* env = std::getenv("STRATA_NUMA_SPLIT");
785    const int numa_nodes = numa_node_count();
786    const NumaPoolPick pool_pick = pick_numa_pool(std::getenv("STRATA_NUMA_POOL"), env, numa_nodes);
787    if (!pool_pick.log.empty()) std::fprintf(stderr, "%s\n", pool_pick.log.c_str());
788    if (pool_pick.choice == NumaPoolChoice::Off) env = nullptr;
789    bool auto_pool = pool_pick.choice == NumaPoolChoice::Auto;   // the split without STRATA_NUMA_SPLIT: only if it can run
790    bool env_off = !auto_pool && (env == nullptr || *env == '\0' || std::strcmp(env, "0") == 0);
791    bool env_known = auto_pool || (!env_off && (std::strcmp(env, "1") == 0 || std::strcmp(env, "test") == 0));
792    const PoolPlanInput plan_in = pool_plan_input(topo_);
793    const PoolPlan wplan = plan_pool_workers(plan_in);
794    // --pool-cores (experimental, off by default): the person's own list of logical processors for the workers.  The plan above
795    // was made from the real topology; only the cores the workers are pinned to (and, by default, their count) come from the list.
796    if (!pool_cores_setting().empty()) {
797        const PoolCoresCheck chk = check_pool_cores(pool_cores_setting(), layout_, topo_.host_core);
798        static std::atomic<bool> told{false};   // (a throw-away pool of --pool-affinity measure builds the same list again)
799        const bool say = !told.exchange(true);
800        if (say)
801            for (const std::string& w : chk.warnings) std::fprintf(stderr, "strata cpu pool: --pool-cores: %s\n", w.c_str());
802        if (chk.cpus.empty()) {
803            if (say)
804                std::fprintf(stderr, "strata cpu pool: --pool-cores: no usable logical processor in the list; the pool uses its "
805                                     "default placement\n");
806        } else {
807            topo_.worker_cores = chk.cpus;
808            topo_.worker_package.assign(chk.cpus.size(), -1);
809            explicit_cores_ = true;
810        }
811    }
812    // the split needs workers on both nodes: its cores are taken round-robin over the nodes (the packages when a core's node
813    // is unknown), so any count under the core count (the default or a configured one) spans them evenly (one node: the order
814    // is kept)
815    auto interleave_cores = [&] {
816        if (explicit_cores_) return;   // --pool-cores: the person's order stays
817        if (topo_.worker_package.size() != topo_.worker_cores.size()) return;
818        std::vector<int> key = topo_.worker_package;
819#if defined(__linux__)
820        std::vector<int> by_node;
821        for (int c : topo_.worker_cores) by_node.push_back(cpu_numa_node(c));
822        if (std::none_of(by_node.begin(), by_node.end(), [](int n) { return n < 0; })) key = by_node;
823#endif
824        std::vector<int> cores, pkgs;
825        for (size_t i : interleave_packages(key)) {
826            cores.push_back(topo_.worker_cores[i]);
827            pkgs.push_back(topo_.worker_package[i]);
828        }
829        topo_.worker_cores = std::move(cores);
830        topo_.worker_package = std::move(pkgs);
831    };
832    // the worker count: configured, else the hybrid P cores, else the plan (`span`: every socket counts, the split's default)
833    auto pick_workers = [&](bool span, const char** limit) -> int {
834        if (n_workers > 0) return n_workers;
835        if (explicit_cores_) {
836            *limit = "your --pool-cores list";
837            return (int) topo_.worker_cores.size();
838        }
839        if (topo_.is_hybrid && affinity_ != PoolAffinity::All) return (std::max)(1, topo_.p_cores - 1);
840        if (span) {
841            PoolPlanInput span_in = plan_in;
842            span_in.span_packages = true;
843            const PoolPlan sp = plan_pool_workers(span_in);
844            *limit = sp.limit;
845            return (std::min)(sp.workers, (std::max)(1, (int) topo_.worker_cores.size()));
846        }
847        *limit = wplan.limit;
848        return (std::min)(wplan.workers, (std::max)(1, (int) topo_.worker_cores.size()));
849    };
850    if (auto_pool) {
851        // try the split on a copy: when it cannot run the cores, the count and the plan stay exactly what they were
852        const CpuTopology plain_topo = topo_;
853        interleave_cores();
854        const char* try_limit = nullptr;
855        const int try_n = pick_workers(true, &try_limit);
856        std::vector<int> thread_core;
857        for (int j = 0; j < try_n; ++j)
858            thread_core.push_back(pin && j < (int) topo_.worker_cores.size() ? topo_.worker_cores[(size_t) j] : -1);
859        if (host_works_) thread_core.push_back(topo_.host_core);
860        const NumaSplitDecision tried = decide_real_numa_split(thread_core, try_n, pin);
861        if (!tried.on) {
862            topo_ = plain_topo;
863            auto_pool = env_known = false;
864            env_off = true;
865            std::fprintf(stderr, "strata cpu pool: NUMA pool off: %s (%d NUMA nodes found), the pool runs as before\n",
866                         tried.why.c_str(), numa_nodes);
867        }
868    } else if (env_known) {
869        interleave_cores();
870    }
871    {
872        const char* limit = nullptr;
873        n_ = pick_workers(env_known, &limit);
874        if (limit != nullptr) plan_limit_ = limit;
875    }
876    plan_cores_ = wplan.cores;
877    plan_logical_ = plan_in.logical;
878    if (n_ < 1) n_ = 1;
879    scratch_.resize((size_t) n_);
880    wstate_.reset(new std::atomic<int32_t>[(size_t) n_]);
881    for (int i = 0; i < n_; ++i) wstate_[(size_t) i].store(kParked);
882    hstate_ms_.store(now_ms());
883    g_diag_pool.store(this);
884    strata::core::diag_pool_fn().store(&diag_active_pool);
885    split_.resize((size_t) kMaxSplit);
886    split_multi_.resize((size_t) kMaxSplitMulti);
887    // STRATA_NUMA_SPLIT: decided here, before any worker starts (a worker counts into its slice's `parked` from its
888    // first instruction), and never revised.  Unset: the plan stays empty and nothing below runs.
889    NumaSplitPlan plan;
890    if (!env_off && !env_known) {
891        plan.why = std::string("unknown STRATA_NUMA_SPLIT value '") + env + "' (use 1 or test)";
892        std::fprintf(stderr, "strata cpu pool: NUMA split off: %s\n", plan.why.c_str());
893    } else if (env_known) {
894        plan.test = !auto_pool && std::strcmp(env, "test") == 0;
895        const int threads = n_ + (host_works_ ? 1 : 0);   // thread j < n_: worker j; j == n_: the host
896        std::vector<int> slice((size_t) threads, 0);
897        std::string why;
898        if (threads < 2) {
899            why = "the pool has " + std::to_string(threads) + " thread, the split needs 2 or more";
900        } else if (plan.test) {
901            for (int j = 0; j < threads; ++j) slice[(size_t) j] = j % 2;
902        } else {
903            std::vector<int> thread_core;
904            for (int j = 0; j < threads; ++j)
905                thread_core.push_back(j == n_ ? topo_.host_core
906                                              : pin && j < (int) topo_.worker_cores.size() ? topo_.worker_cores[(size_t) j] : -1);
907            const NumaSplitDecision d = decide_real_numa_split(thread_core, n_, pin);
908            why = d.why;
909            if (d.on) {
910                slice = d.slice;
911                plan.nodes[0] = d.nodes[0];
912                plan.nodes[1] = d.nodes[1];
913                for (int j = 0; j < threads; ++j) plan.cores[slice[(size_t) j]].push_back(thread_core[(size_t) j]);
914            }
915        }
916        plan.why = why;
917        plan.on = plan.why.empty();
918        if (!plan.on) {   // a refusal after the slices were planned (unbalanced) leaves no half-filled plan behind
919            plan.nodes[0] = plan.nodes[1] = -1;
920            plan.cores[0].clear();
921            plan.cores[1].clear();
922        }
923        if (plan.on) {
924            numa_n_ = 2;
925            nsync_.reset(new NodeSync[2]);
926            wslice_.assign(slice.begin(), slice.begin() + n_);
927            hslice_ = host_works_ ? slice[(size_t) n_] : 0;
928            slice_threads_.assign(2, 0);
929            for (int k : slice) ++slice_threads_[(size_t) k];
930            if (auto_pool)
931                std::fprintf(stderr, "strata cpu pool: NUMA pool on: %d NUMA nodes found, one slice of the pool per node "
932                                     "(STRATA_NUMA_POOL=0 turns it off)\n", numa_nodes);
933            if (plan.test)
934                std::fprintf(stderr, "strata cpu pool: NUMA split on (test, no real nodes): slice 0 = %d threads, "
935                                     "slice 1 = %d threads\n", slice_threads_[0], slice_threads_[1]);
936            else
937                std::fprintf(stderr, "strata cpu pool: NUMA split on: slice 0 = node %d (%d threads), slice 1 = node %d "
938                                     "(%d threads)\n", plan.nodes[0], slice_threads_[0], plan.nodes[1], slice_threads_[1]);
939        } else {
940            std::fprintf(stderr, "strata cpu pool: NUMA split off: %s\n", plan.why.c_str());
941        }
942    }
943    if (n_workers > 0) {
944        // recommend, never force: a count above what this CPU uses well runs as configured, with a plain warning
945        // (STRATA_NUMA_SPLIT on: workers on the other socket are the point, that case is not warned about)
946        PoolPlanInput warn_in = plan_in;
947        warn_in.span_packages = plan.on;
948        static std::atomic<bool> warned{false};
949        const std::string why = pool_workers_warning(n_workers, warn_in, plan_pool_workers(warn_in));
950        if (!why.empty() && !warned.exchange(true)) std::fprintf(stderr, "strata cpu pool: warning: %s\n", why.c_str());
951    }
952    g_numa_plan = std::move(plan);
953    g_numa_owner = this;
954    threads_.reserve((size_t) n_);
955    for (int i = 0; i < n_; ++i) {
956        const int core = pin ? (i < (int) topo_.worker_cores.size() ? topo_.worker_cores[(size_t) i] : -1) : -1;
957        threads_.emplace_back([this, i, core] {
958            strata::platform::name_this_thread("strata-pool", i);
959            strata::aux_cpus::note_owned_thread();   // --aux-cpus never moves a worker
960            // a failed pin only costs locality under the split: the worker keeps the slice it was given
961            if (!pin_this_thread(core, i) && core >= 0 && numa_n_ > 0)
962                std::fprintf(stderr, "strata cpu pool: NUMA split: worker %d not pinned to CPU %d, its slice's rows may "
963                                     "be read remotely\n", i, core);
964            worker(i);
965        });
966    }
967}
968
969std::string ExpertPool::placement_line() const {
970    if (n_ <= 0) return "";
971    if (!pinned_) return "CPU workers: " + std::to_string(n_) + " workers, not pinned to logical processors (the OS places them)";
972    // a worker beyond the cores listed runs unpinned (more --pool-workers than --pool-cores entries)
973    std::vector<int> on(topo_.worker_cores.begin(), topo_.worker_cores.begin() + (std::min)((size_t) n_, topo_.worker_cores.size()));
974    std::string s = describe_worker_placement(on, topo_.host_core, layout_, explicit_cores_);
975    if ((int) on.size() < n_) s += " (" + std::to_string(n_ - (int) on.size()) + " more workers run unpinned)";
976    return s;
977}
978
979ExpertPool::~ExpertPool() {
980    const ExpertPool* self = this;
981    g_diag_pool.compare_exchange_strong(self, nullptr);
982    if (g_numa_owner == this) {
983        g_numa_plan = NumaSplitPlan{};
984        g_numa_owner = nullptr;
985    }
986    stop_.store(true, std::memory_order_release);
987    // Bump the epoch so a PARKED worker notices the stop flag rather than sleeping through it.
988    publish();
989    for (auto& t : threads_) t.join();
990}
991
992void ExpertPool::publish() {
993    // Both sides are seq_cst, and that is the whole lost-wakeup argument: a worker going to sleep does
994    // `sleepers_++` and then reads `epoch_`, the host does `epoch_++` and then reads `sleepers_`.  In one total
995    // order at least one of them sees the other's write - the worker sees the new epoch and does not sleep, or
996    // the host sees the sleeper and notifies under the mutex the worker holds until it is inside `wait`.
997    // On x86 the fetch_add is a locked xadd either way, so this costs the token path nothing.
998    epoch_.fetch_add(1, std::memory_order_seq_cst);
999    if (sleepers_.load(std::memory_order_seq_cst) != 0) {
1000        std::lock_guard<std::mutex> lk(sleep_mu_);
1001        sleep_cv_.notify_all();
1002    }
1003}
1004
1005void ExpertPool::worker(int id) {
1006    uint32_t seen = 0;
1007    // ARRIVE at the park before the first wait, so `parked_ == n_` is true from construction.  Counting only
1008    // on the RETURN from a drain leaves `parked_` at 0 until each worker has finished one batch, and the first
1009    // `run()` - which waits for `parked_ == n_` before publishing - then deadlocks.  It deadlocks on the very
1010    // first call, which is the good case; a version that deadlocked on the second would be far worse.
1011    parked_of(id).fetch_add(1, std::memory_order_acq_rel);
1012    for (;;) {
1013        // Park: wait for work.  `_mm_pause` rather than a bare spin because it yields the pipeline to the
1014        // sibling hyperthread; `epoch_` is bumped once per LAYER, not once per expert, so most of these
1015        // iterations are spent here with nothing to do.
1016        //
1017        // **AND NOTHING ELSE HAPPENS IN HERE.**  This loop used to do `pauses_.fetch_add(1)` on every iteration
1018        // - a locked read-modify-write, five workers against one cache line - so the workers spent their wait
1019        // invalidating each other's caches and the very line the host writes to publish work.  The counter was
1020        // diagnostic and nothing branched on it.  See the note on the atomics in pool.hpp.
1021        //
1022        // After `kSpinBeforeSleep` with no work the worker sleeps instead (issue #4).  The clock is read once
1023        // every 1024 pauses, so the spin itself is unchanged.
1024        const auto parked_at = std::chrono::steady_clock::now();
1025        uint32_t spins = 0;
1026        const uint64_t um = umwait_cycles();
1027#if defined(_MSC_VER) && defined(_M_X64) && !defined(__clang__)   // MSVC proper: clang-cl (the Windows HIP build) has no WAITPKG intrinsics by default
1028        const uint64_t um_esc = umwait_escalate();
1029        const uint64_t um_t0 = um != 0 && um_esc != 0 ? __rdtsc() : 0;
1030#endif
1031        while (epoch_.load(std::memory_order_acquire) == seen) {
1032            if (stop_.load(std::memory_order_relaxed)) return;
1033#if defined(_MSC_VER) && defined(_M_X64) && !defined(__clang__)   // MSVC proper: clang-cl (the Windows HIP build) has no WAITPKG intrinsics by default
1034            if (um != 0) {   // STRATA_POOL_UMWAIT: wake on the publish's write to epoch_, or after `um` cycles
1035                _umonitor((void*) &epoch_);
1036                if (epoch_.load(std::memory_order_acquire) != seen) break;
1037                const uint64_t now = __rdtsc();
1038                const unsigned st = um_esc != 0 ? (now - um_t0 < um_esc ? 1u : 0u) : umwait_state();
1039                _umwait(st, now + um);
1040                if ((++spins & 15u) != 0) continue;   // each wait is ~um cycles: look at the clock more often
1041            } else
1042#endif
1043            {
1044                strata_cpu_pause();
1045                if ((++spins & 1023u) != 0) continue;
1046            }
1047            if (std::chrono::steady_clock::now() - parked_at < spin_before_sleep_) continue;
1048            std::unique_lock<std::mutex> lk(sleep_mu_);
1049            wstate_[(size_t) id].store(kSleeping, std::memory_order_relaxed);
1050            sleepers_.fetch_add(1, std::memory_order_seq_cst);
1051            sleep_cv_.wait(lk, [&] {
1052                return epoch_.load(std::memory_order_seq_cst) != seen || stop_.load(std::memory_order_relaxed);
1053            });
1054            sleepers_.fetch_sub(1, std::memory_order_relaxed);
1055            wstate_[(size_t) id].store(kParked, std::memory_order_relaxed);
1056        }
1057        if (stop_.load(std::memory_order_acquire)) return;
1058        // acquire: the batch this epoch published (`head`, and the description before it) is visible from here
1059        seen = epoch_.load(std::memory_order_acquire);
1060        parked_of(id).fetch_sub(1, std::memory_order_acq_rel);   // leaving the park
1061
1062        // Drain: one claim per iteration, so a slow worker takes fewer experts and a fast one takes more.
1063        // Every job is the same size (all experts are 1,382,400 bytes), so there is nothing to schedule.  Only
1064        // this epoch's jobs: if the host has already moved on, the claims fail and the worker parks again.
1065        wstate_[(size_t) id].store(kBetween, std::memory_order_relaxed);
1066        drain(id, scratch_[(size_t) id], seen);
1067        wstate_[(size_t) id].store(kParked, std::memory_order_relaxed);
1068        parked_of(id).fetch_add(1, std::memory_order_acq_rel);   // back at the park
1069    }
1070}
1071
1072int ExpertPool::claim(uint32_t epoch) {
1073    uint64_t h = head_.load(std::memory_order_acquire);
1074    for (;;) {
1075        if ((uint32_t) (h >> 32) != epoch) return -1;               // not the batch this thread woke for
1076        const uint32_t n = (uint32_t) (h >> 16) & 0xffffu, i = (uint32_t) h & 0xffffu;
1077        if (i >= n) return -1;                                       // exhausted
1078        if (head_.compare_exchange_weak(h, h + 1, std::memory_order_acq_rel, std::memory_order_acquire))
1079            return (int) i;
1080    }
1081}
1082
1083int ExpertPool::claim_slice(uint32_t epoch, int slice) {
1084    NodeSync& ns = nsync_[(size_t) slice];
1085    uint64_t h = ns.head.load(std::memory_order_acquire);
1086    for (;;) {
1087        if ((uint32_t) (h >> 32) != epoch) return -1;               // not this batch, or not a mode-5/6 batch
1088        const uint32_t n = (uint32_t) (h >> 16) & 0xffffu, i = (uint32_t) h & 0xffffu;
1089        if (i >= n) return -1;                                       // the slice is exhausted
1090        if (ns.head.compare_exchange_weak(h, h + 1, std::memory_order_acq_rel, std::memory_order_acquire))
1091            return ns.base + (int) i;                                // the description is stable from here
1092    }
1093}
1094
1095uint32_t ExpertPool::parked_count() const {
1096    if (numa_n_ == 0) return parked_.load(std::memory_order_acquire);
1097    uint32_t p = 0;   // each slice's counter is bounded by its own workers, so the sum is n_ only when each is full
1098    for (int k = 0; k < numa_n_; ++k) p += nsync_[(size_t) k].parked.load(std::memory_order_acquire);
1099    return p;
1100}
1101
1102std::string ExpertPool::numa_counters() const {
1103    std::string s;
1104    for (int k = 0; k < numa_n_; ++k) {
1105        const NodeSync& ns = nsync_[(size_t) k];
1106        const uint64_t h = ns.head.load();
1107        char buf[200];
1108        std::snprintf(buf, sizeof buf, "%s slice %d: batch epoch %u, %u of %u claimed, %u done, %u parked, %d threads",
1109                      k == 0 ? " [" : ";", k, (uint32_t) (h >> 32), (uint32_t) h & 0xffffu, (uint32_t) (h >> 16) & 0xffffu,
1110                      ns.done.load(), ns.parked.load(), slice_threads_[(size_t) k]);
1111        s += buf;
1112    }
1113    if (numa_n_ > 0) s += "]";
1114    return s;
1115}
1116
1117int ExpertPool::numa_plan_phase(int per, int nb) {
1118    int base = 0;
1119    for (int k = 0; k < numa_n_; ++k) {
1120        NodeSync& ns = nsync_[(size_t) k];
1121        ns.row0 = per * k / numa_n_;
1122        ns.h = per * (k + 1) / numa_n_ - ns.row0;
1123        ns.rows = (int64_t) nb * ns.h;
1124        // about three tasks per thread of the slice's node; an explicit --pool-tasks is shared between the slices
1125        const int64_t want = tasks_ == 0 ? 3 * (int64_t) slice_threads_[(size_t) k] : (int64_t) (std::max)(1, tasks_ / 2);
1126        ns.tasks = (int) (std::min)(want, ns.rows);
1127        ns.base = base;
1128        base += ns.tasks;
1129    }
1130    return base;
1131}
1132
1133uint32_t ExpertPool::begin_batch(int n) {
1134    if (n < 0 || n > 0xffff) {
1135        std::fprintf(stderr, "strata: expert pool batch of %d jobs is out of range\n", n);
1136        std::abort();
1137    }
1138    // Every job of the previous batch has completed (`wait_done`), and a claim of it can no longer succeed, so
1139    // nothing adds to `done` until this batch's first claim - which the release below orders after the reset.
1140    const uint32_t e = epoch_.load(std::memory_order_relaxed) + 1;   // only the host bumps the epoch
1141    if (numa_phase()) {
1142        // every slice's head, even a slice with no task, and never `head_`: for this epoch only the slice heads
1143        // carry `e`, so a claim on `head_` fails, and every head left from an earlier batch is exhausted (pool.hpp)
1144        for (int k = 0; k < numa_n_; ++k) {
1145            NodeSync& ns = nsync_[(size_t) k];
1146            ns.done.store(0, std::memory_order_relaxed);
1147            ns.drained_ns.store(0, std::memory_order_relaxed);
1148            ns.head.store(pack_head(e, (uint32_t) ns.tasks, 0), std::memory_order_release);
1149        }
1150        pub_ns_ = now_ns();
1151    } else {
1152        done_.store(0, std::memory_order_relaxed);
1153        head_.store(pack_head(e, (uint32_t) n, 0), std::memory_order_release);
1154    }
1155    publish();
1156    return e;
1157}
1158
1159void ExpertPool::wait_parked(const char* what) {
1160    hstate_.store(kWaitParked, std::memory_order_relaxed);
1161    hstate_ms_.store(now_ms(), std::memory_order_relaxed);
1162    uint32_t spins = 0;
1163    std::chrono::steady_clock::time_point t0{};
1164    while (parked_count() != (uint32_t) n_) {
1165        strata_cpu_pause();
1166        if ((++spins & 1023u) != 0) continue;
1167        const auto now = std::chrono::steady_clock::now();
1168        if (spins == 1024u) t0 = now;
1169        else if (now - t0 > kStall) {
1170            std::fprintf(stderr, "strata: the CPU expert pool stalled %s (%u of %d workers parked)%s - stopping the engine "
1171                                 "so the server can start it again (issue #29)\n",
1172                         what, parked_count(), n_, numa_counters().c_str());
1173            strata::core::release_gpu_waits(stderr);   // #267: the GPU may be spinning on this layer's flag
1174            std::fflush(stderr);
1175            std::abort();
1176        }
1177    }
1178}
1179
1180void ExpertPool::wait_done(int n) {
1181    hstate_.store(kWaitDone, std::memory_order_relaxed);
1182    hstate_ms_.store(now_ms(), std::memory_order_relaxed);
1183    uint32_t spins = 0, seen = 0;
1184    std::chrono::steady_clock::time_point t0{};
1185    for (;;) {
1186        uint32_t d = 0;
1187        if (numa_phase())   // the slices' counts, each bounded by its tasks: the sum is n only when every slice is done
1188            for (int k = 0; k < numa_n_; ++k) d += nsync_[(size_t) k].done.load(std::memory_order_acquire);
1189        else
1190            d = done_.load(std::memory_order_acquire);
1191        if (d >= (uint32_t) n) {
1192            static std::atomic<int64_t> s_tw{0};
1193            const int64_t tw = s_tw.fetch_add(1, std::memory_order_relaxed);
1194            if (std::getenv("STRATA_DIAG_A") != nullptr && tw % 48 == 0) {
1195                double lo = 1e18, hi = -1e18; int lo_id = -1, hi_id = -1, cnt = 0;
1196                for (int k = 0; k < n_ && k < 64; ++k) {
1197                    if (tail_fin_[k] <= 0) continue;
1198                    if (tail_fin_[k] < lo) { lo = tail_fin_[k]; lo_id = k; }
1199                    if (tail_fin_[k] > hi) { hi = tail_fin_[k]; hi_id = k; }
1200                    ++cnt;
1201                }
1202                if (cnt > 1)
1203                    std::fprintf(stderr, "PROBETAIL mode=%d n=%d last=w%d spread=%.1f us (first w%d of %d)\n",
1204                                 mode_, n, hi_id, (hi - lo) / 1000.0, lo_id, cnt);
1205            }
1206            return;
1207        }                                // `>=`: never a wait that an overshoot outlives
1208        strata_cpu_pause();
1209        if ((++spins & 1023u) != 0) continue;
1210        const auto now = std::chrono::steady_clock::now();
1211        if (spins == 1024u || d != seen) { t0 = now; seen = d; }     // progress restarts the clock
1212        else if (now - t0 > kStall) {
1213            std::fprintf(stderr, "strata: the CPU expert pool stalled: %u of %d jobs done, %u of %d workers parked%s - "
1214                                 "stopping the engine so the server can start it again (issue #29)\n",
1215                         d, n, parked_count(), n_, numa_counters().c_str());
1216            strata::core::release_gpu_waits(stderr);   // #267
1217            std::fflush(stderr);
1218            std::abort();
1219        }
1220    }
1221}
1222
1223void ExpertPool::drain(int id, ExpertScratch& scratch, uint32_t epoch) {
1224    const int s = numa_n_ == 0 ? 0 : id >= 0 ? wslice_[(size_t) id] : hslice_;
1225    for (;;) {
1226        // STRATA_NUMA_SPLIT: a mode-5/6 batch lives on the slice heads, any other on `head_`; the epoch tag makes the
1227        // other family's claim fail, so `mode_` is never read before a claim has succeeded (pool.hpp)
1228        int ci = numa_n_ > 0 ? claim_slice(epoch, s) : -1;
1229        const bool sliced = ci >= 0;
1230        if (!sliced) ci = claim(epoch);
1231        if (ci < 0) {
1232            if (id >= 0 && id < 64) {   // PROBE-TAIL: this worker's last task of the phase
1233                if (tail_ep_[id] != (uint64_t) epoch) {
1234                    tail_ep_[id] = (uint64_t) epoch;
1235                    tail_fin_[id] = (double) now_ns();
1236                }
1237            }
1238            break;
1239        }
1240        const uint32_t i = (uint32_t) ci;
1241        if (id >= 0) wstate_[(size_t) id].store(ci, std::memory_order_relaxed);
1242        else { hstate_.store(ci, std::memory_order_relaxed); hstate_ms_.store(now_ms(), std::memory_order_relaxed); }
1243        if (mode_ == 0) {
1244            const ExpertJob& j = jobs_[i];
1245            s2_expert_vnni_q(j.blob, *j.act, j.out, scratch);
1246        } else if (mode_ == 1) {
1247            const int e = (int) i / parts_a_, part = (int) i % parts_a_;
1248            const int r0 = FF * part / parts_a_, r1 = FF * (part + 1) / parts_a_;
1249            s2_expert_gu_rows(jobs_[e].blob, *jobs_[e].act, split_[(size_t) e].ff, r0, r1);
1250        } else if (mode_ == 2) {
1251            const int e = (int) i / parts_b_, part = (int) i % parts_b_;
1252            const int r0 = H * part / parts_b_, r1 = H * (part + 1) / parts_b_;
1253            s2_expert_down_rows(jobs_[e].blob, split_[(size_t) e].a2, jobs_[e].out, r0, r1);
1254        } else if (mode_ == 7) {
1255            // latent MoE (edge0): a row range of one of the D/U matvecs (Q8_0 weights x Q8_1 acts).
1256            // AVX-2 when the host has it (one loaded weight row serves all the tokens; the scalar
1257            // lat_q8_0_q8_1_row below is the fallback and the reference for the numbers).
1258            const int64_t R = mrows_, T = mtasks_;
1259            const int64_t g0 = R * (int64_t) i / T, g1 = R * (int64_t) (i + 1) / T;
1260            int64_t base = 0;
1261            for (int m = 0; m < lmv_n_ && base < g1; ++m) {
1262                const LatentMatvec& mv = lmv_[m];
1263                if (base + mv.nrows > g0) {
1264                    const int r0 = (int) std::max<int64_t>(g0 - base, 0);
1265                    const int r1 = (int) std::min<int64_t>(g1 - base, mv.nrows);
1266                    // Q4DU: the matvec's row bytes decide the format (18 vs 34 per 32-value
1267                    // block - set by the caller from LatentDense::row_b()); no other plumbing.
1268                    const bool lat_q4 = mv.row_bytes == (size_t) (mv.ncols / 32) * 18;
1269                    if (lat_q4) {
1270                        if (strata::kernels::cpu::cpu_avx2_ok())
1271                            strata::kernels::cpu::lat_q4_0_q8_1_rows(mv.w, mv.row_bytes, mv.ncols, mv.act, mv.nt,
1272                                                                     mv.out, r0, r1);
1273                        else
1274                            for (int r = r0; r < r1; ++r) {
1275                                const uint8_t* row = mv.w + (size_t) r * mv.row_bytes;
1276                                for (int t = 0; t < mv.nt; ++t)
1277                                    mv.out[t][r] = lat_q4_0_q8_1_row(row, (const uint8_t*) mv.act[t], mv.ncols);
1278                            }
1279                    } else
1280                    if (strata::kernels::cpu::cpu_avx2_ok())
1281                        strata::kernels::cpu::lat_q8_0_q8_1_rows(mv.w, mv.row_bytes, mv.ncols, mv.act, mv.nt,
1282                                                                 mv.out, r0, r1);
1283                    else
1284                        for (int r = r0; r < r1; ++r) {
1285                            const uint8_t* row = mv.w + (size_t) r * mv.row_bytes;
1286                            for (int t = 0; t < mv.nt; ++t)
1287                                mv.out[t][r] = lat_q8_0_q8_1_row(row, (const uint8_t*) mv.act[t], mv.ncols);
1288                        }
1289                }
1290                base += mv.nrows;
1291            }
1292        } else if (mode_ >= 5) {
1293            // plan v0.3 P6: native layers, 5 = gate/up rows, 6 = down rows (the layer's own n_ff / n_embd: Flash-Next's
1294            // FF / H, or another family's smaller expert)
1295            // Task j of T over R rows of `h` per expert from matrix row `row0`: the whole phase (R = mrows_, h = per,
1296            // row0 = 0) or, under the NUMA split, this thread's slice (slice-local row g -> expert g / h, matrix row
1297            // row0 + g % h)
1298            const int per = mode_ == 5 ? (int) nfmt_->n_ff : (int) nfmt_->n_embd;
1299            int64_t R = mrows_, T = mtasks_, j = i;
1300            int h = per, row0 = 0;
1301            if (sliced) {
1302                const NodeSync& ns = nsync_[(size_t) s];
1303                R = ns.rows; T = ns.tasks; h = ns.h; row0 = ns.row0; j = ci - ns.base;
1304            }
1305            const int64_t g0 = R * j / T, g1 = R * (j + 1) / T;
1306            for (int64_t g = g0; g < g1;) {
1307                const int e = (int) (g / h), l0 = (int) (g % h);
1308                const int l1 = (int) std::min<int64_t>(h, l0 + (g1 - g));
1309                const int r0 = row0 + l0, r1 = row0 + l1;
1310                SplitBufMulti& sb = split_multi_[(size_t) e];
1311                const NativeFmt* const nfmt = mjobs_[e].fmt != nullptr ? mjobs_[e].fmt : nfmt_;   // 149-cold: same types and rows
1312                if (mode_ == 5 && q2_native_kernels(nfmt->gu_type)) {
1313                    // a native Q2_0 pack: gate and up rows on the Q2_0 kernels, then SwiGLU
1314                    thread_local float gbuf[MAXT][FF], ubuf[MAXT][FF];
1315                    float* gp[MAXT];
1316                    float* up[MAXT];
1317                    for (int t = 0; t < mjobs_[e].nt; ++t) { gp[t] = gbuf[t]; up[t] = ubuf[t]; }
1318                    const int nbk = (int) (nfmt->n_embd / 64);
1319                    q2_rows_any(mjobs_[e].blob, nfmt->gu_row, nbk, mjobs_[e].act, mjobs_[e].nt, gp, r0, r1);
1320                    q2_rows_any(mjobs_[e].blob + nfmt->up_off, nfmt->gu_row, nbk, mjobs_[e].act, mjobs_[e].nt, up, r0, r1);
1321                    for (int t = 0; t < mjobs_[e].nt; ++t)
1322                        for (int r = r0; r < r1; ++r)
1323                            sb.ff[t][r] = (gbuf[t][r] / (1.f + std::exp(-gbuf[t][r]))) * ubuf[t][r];
1324                } else if (mode_ == 5) {
1325                    float* ff[MAXT];
1326                    for (int t = 0; t < mjobs_[e].nt; ++t) ff[t] = sb.ff[t];
1327                    if (narithmetic_ == NativeArithmetic::WindowInvariant)
1328                        native_gu_rows_invariant(*nfmt, mjobs_[e].blob, mjobs_[e].nact, mjobs_[e].nt, ff, r0, r1);
1329                    else
1330                        native_gu_rows(*nfmt, mjobs_[e].blob, mjobs_[e].nact, mjobs_[e].nt, ff, r0, r1);
1331                } else if (q2_native_kernels(nfmt->d_type)) {
1332                    // Q2_0 down (most IQ layers): the AVX-512 kernel, ggml-cpu has only a scalar one on x86
1333                    const ActQ* a2[MAXT];
1334                    for (int t = 0; t < mjobs_[e].nt; ++t) a2[t] = &sb.a2[t];
1335                    q2_rows_any(mjobs_[e].blob + nfmt->down_off, nfmt->d_row, (int) (nfmt->n_ff / 64), a2,
1336                                mjobs_[e].nt, mjobs_[e].out, r0, r1);
1337                } else {
1338                    const void* hq[MAXT];
1339                    for (int t = 0; t < mjobs_[e].nt; ++t) hq[t] = sb.hq[t];
1340                    if (narithmetic_ == NativeArithmetic::WindowInvariant)
1341                        native_down_rows_invariant(*nfmt, mjobs_[e].blob, hq, mjobs_[e].nt, mjobs_[e].out, r0, r1);
1342                    else
1343                        native_down_rows(*nfmt, mjobs_[e].blob, hq, mjobs_[e].nt, mjobs_[e].out, r0, r1);
1344                }
1345                g += l1 - l0;
1346            }
1347        } else {
1348            // plan v0.3 P6: an equal range of the phase's rows across ALL its experts (a range may span two)
1349            const int per = mode_ == 3 ? FF : H;
1350            const int64_t g0 = mrows_ * (int64_t) i / mtasks_, g1 = mrows_ * (int64_t) (i + 1) / mtasks_;
1351            for (int64_t r = g0; r < g1;) {
1352                const int e = (int) (r / per), r0 = (int) (r % per);
1353                const int r1 = (int) std::min<int64_t>(per, r0 + (g1 - r));
1354                SplitBufMulti& sb = split_multi_[(size_t) e];
1355                if (mode_ == 3) {
1356                    float* ff[MAXT];
1357                    for (int t = 0; t < mjobs_[e].nt; ++t) ff[t] = sb.ff[t];
1358                    s2_expert_gu_rows_multi(mjobs_[e].blob, mjobs_[e].act, mjobs_[e].nt, ff, r0, r1);
1359                } else {
1360                    const ActQ* a2[MAXT];
1361                    for (int t = 0; t < mjobs_[e].nt; ++t) a2[t] = &sb.a2[t];
1362                    s2_expert_down_rows_multi(mjobs_[e].blob, a2, mjobs_[e].nt, mjobs_[e].out, r0, r1);
1363                }
1364                r += r1 - r0;
1365            }
1366        }
1367        if (sliced) {
1368            NodeSync& ns = nsync_[(size_t) s];
1369            const uint32_t t = (uint32_t) ns.tasks;
1370            // the slice's last task stamps its drain time; read by the host once this thread has parked again
1371            if (ns.done.fetch_add(1, std::memory_order_release) + 1 == t)
1372                ns.drained_ns.store(now_ns(), std::memory_order_relaxed);
1373        } else {
1374            done_.fetch_add(1, std::memory_order_release);
1375        }
1376    }
1377}
1378
1379void ExpertPool::run_phase(int mode, int n_tasks) {
1380    // PROBE-PHASE: the five walls of one phase dispatch, per mode (5=gu 6=down 7=latent-U), DIAGP-style
1381    static std::atomic<double> s_pb[8]{}, s_bb[8]{}, s_hd[8]{}, s_wd[8]{}, s_pa[8]{};
1382    static std::atomic<int64_t> s_pn[8]{};
1383    const auto _p0 = std::chrono::steady_clock::now();
1384    wait_parked("before a phase");
1385    const auto _p1 = std::chrono::steady_clock::now();
1386    mode_ = mode;
1387    njobs_ = n_tasks;
1388    const uint32_t e = begin_batch(n_tasks);
1389    const auto _p2 = std::chrono::steady_clock::now();
1390    if (host_works_) drain(-1, host_scratch_, e);
1391    const auto _p3 = std::chrono::steady_clock::now();
1392    wait_done(n_tasks);
1393    const auto _p4 = std::chrono::steady_clock::now();
1394    wait_parked("after a phase");
1395    const auto _p5 = std::chrono::steady_clock::now();
1396    const int mi = mode;
1397    s_pb[mi].fetch_add(std::chrono::duration<double, std::milli>(_p1 - _p0).count(), std::memory_order_relaxed);
1398    s_bb[mi].fetch_add(std::chrono::duration<double, std::milli>(_p2 - _p1).count(), std::memory_order_relaxed);
1399    s_hd[mi].fetch_add(std::chrono::duration<double, std::milli>(_p3 - _p2).count(), std::memory_order_relaxed);
1400    s_wd[mi].fetch_add(std::chrono::duration<double, std::milli>(_p4 - _p3).count(), std::memory_order_relaxed);
1401    s_pa[mi].fetch_add(std::chrono::duration<double, std::milli>(_p5 - _p4).count(), std::memory_order_relaxed);
1402    s_pn[mi].fetch_add(1, std::memory_order_relaxed);
1403    static std::atomic<int64_t> s_total{0};
1404    const int64_t tot = s_total.fetch_add(1, std::memory_order_relaxed);
1405    if (std::getenv("STRATA_DIAG_A") != nullptr && tot % 288 == 0) {
1406        std::fprintf(stderr, "PROBEPH per-mode ms/phase (parkB begin hostDrain waitDone parkA):\n");
1407        for (int m = 0; m < 8; ++m) {
1408            const int64_t c = s_pn[m].load();
1409            if (c == 0) continue;
1410            std::fprintf(stderr, "  mode %d: parkB %.3f begin %.3f hostDrain %.3f waitDone %.3f parkA %.3f (n %lld)\n",
1411                         m, s_pb[m].load() / (double) c, s_bb[m].load() / (double) c, s_hd[m].load() / (double) c,
1412                         s_wd[m].load() / (double) c, s_pa[m].load() / (double) c, (long long) c);
1413        }
1414    }
1415    // Each slice's stamp is stored after its last `done` increment, so `wait_done` can return before it lands; the
1416    // thread that stored it has parked again since (it left the park to claim), and that re-park is what the wait
1417    // above acquired.  So the stamps are read here, not in `wait_done`.
1418    if (numa_phase())
1419        for (int k = 0; k < numa_n_; ++k) {
1420            const int64_t t = nsync_[(size_t) k].drained_ns.load(std::memory_order_acquire);
1421            if (t != 0) slice_ms_[k] += (double) (t - pub_ns_) / 1e6;
1422        }
1423    hstate_.store(kIdle, std::memory_order_relaxed);
1424    hstate_ms_.store(now_ms(), std::memory_order_relaxed);
1425}
1426
1427void ExpertPool::run_split(ExpertJob* jobs, int n) {
1428    if (n <= 0) return;
1429    if (n > kMaxSplit || n_ == 1 || expert_oracle_q8_0_enabled()) { run(jobs, n); return; }
1430    const auto t0 = std::chrono::steady_clock::now();
1431    jobs_ = jobs;
1432    const int threads = n_ + (host_works_ ? 1 : 0);
1433    // about three tasks per thread in each phase, so the tail is short
1434    parts_a_ = (std::max)(1, (3 * threads + n - 1) / n);
1435    parts_b_ = parts_a_;
1436    run_phase(1, n * parts_a_);
1437    for (int e = 0; e < n; ++e) act_quant_q8_1(split_[(size_t) e].ff, FF, split_[(size_t) e].a2);
1438    run_phase(2, n * parts_b_);
1439    mode_ = 0;
1440    ms_drain_ += std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count();
1441}
1442
1443int ExpertPool::phase_tasks(int64_t rows) const {
1444    return tasks_ == 0 ? 3 * (n_ + (host_works_ ? 1 : 0)) : (int) (std::min)(rows, (int64_t) tasks_);
1445}
1446
1447void ExpertPool::run_split_multi(ExpertJobMulti* jobs, int n) {
1448    if (n <= 0) return;
1449    if (n > kMaxSplitMulti || expert_oracle_q8_0_enabled()) {
1450        // one token at a time through the single-token path (the oracle contract has no multi kernel)
1451        std::vector<ExpertJob> single;
1452        for (int e = 0; e < n; ++e)
1453            for (int t = 0; t < jobs[e].nt; ++t) {
1454                ExpertJob j;
1455                j.blob = jobs[e].blob;
1456                j.act = jobs[e].act[t];
1457                j.out = jobs[e].out[t];
1458                single.push_back(j);
1459            }
1460        for (size_t i = 0; i < single.size(); i += kMaxSplit)
1461            run_split(single.data() + i, (int) (std::min)((size_t) kMaxSplit, single.size() - i));
1462        return;
1463    }
1464    const auto t0 = std::chrono::steady_clock::now();
1465    mjobs_ = jobs;
1466    mrows_ = (int64_t) n * FF;
1467    mtasks_ = phase_tasks(mrows_);
1468    run_phase(3, mtasks_);
1469    const auto t1 = std::chrono::steady_clock::now();
1470    for (int e = 0; e < n; ++e)
1471        for (int t = 0; t < jobs[e].nt; ++t)
1472            act_quant_q8_1(split_multi_[(size_t) e].ff[t], FF, split_multi_[(size_t) e].a2[t]);
1473    const auto t2 = std::chrono::steady_clock::now();
1474    mrows_ = (int64_t) n * H;
1475    mtasks_ = phase_tasks(mrows_);
1476    run_phase(4, mtasks_);
1477    const auto t3 = std::chrono::steady_clock::now();
1478    ms_multi_gu += std::chrono::duration<double, std::milli>(t1 - t0).count();
1479    ms_multi_q += std::chrono::duration<double, std::milli>(t2 - t1).count();
1480    ms_multi_down += std::chrono::duration<double, std::milli>(t3 - t2).count();
1481    multi_bytes += (int64_t) n * (int64_t) BLOB;
1482    mode_ = 0;
1483    ms_drain_ += std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count();
1484}
1485
1486void ExpertPool::run_split_multi_native(const NativeFmt& f, ExpertJobMulti* jobs, int n, NativeArithmetic arithmetic) {
1487    if (n <= 0) return;
1488    const auto t0 = std::chrono::steady_clock::now();
1489    const bool diag_a = std::getenv("STRATA_DIAG_A") != nullptr;
1490    // more distinct experts than buffers: run them in batches
1491    for (int b0 = 0; b0 < n; b0 += kMaxSplitMulti) {
1492        const int nb = (std::min)(kMaxSplitMulti, n - b0);
1493        mjobs_ = jobs + b0;
1494        nfmt_ = &f;
1495        narithmetic_ = arithmetic;
1496        mrows_ = (int64_t) nb * f.n_ff;
1497        mtasks_ = numa_n_ > 0 ? numa_plan_phase((int) f.n_ff, nb) : phase_tasks(mrows_);
1498        const int diag_rows = (int) mrows_, diag_tasks = mtasks_;   // DIAGA: the split before run
1499        const auto a = std::chrono::steady_clock::now();
1500        run_phase(5, mtasks_);
1501        const auto b = std::chrono::steady_clock::now();
1502        if (diag_a)
1503            std::fprintf(stderr, "DIAGA phase5: jobs=%d n_ff=%lld rows=%d tasks=%d wall=%.3f ms\n",
1504                         nb, (long long) f.n_ff, diag_rows, diag_tasks,
1505                         std::chrono::duration<double, std::milli>(b - a).count());
1506        for (int e = 0; e < nb; ++e)
1507            for (int t = 0; t < mjobs_[e].nt; ++t)
1508                if (q2_native_kernels(f.d_type)) act_quant_any(split_multi_[(size_t) e].ff[t], FF, split_multi_[(size_t) e].a2[t]);
1509                else native_quant_h(f, split_multi_[(size_t) e].ff[t], split_multi_[(size_t) e].hq[t]);
1510        const auto c = std::chrono::steady_clock::now();
1511        if (diag_a)
1512            std::fprintf(stderr, "DIAGA quant: jobs=%d entries=%d wall=%.3f ms\n",
1513                         nb, (int) [&]{ int n = 0; for (int e = 0; e < nb; ++e) n += mjobs_[e].nt; return n; }(),
1514                         std::chrono::duration<double, std::milli>(c - b).count());
1515        mrows_ = (int64_t) nb * f.n_embd;
1516        mtasks_ = numa_n_ > 0 ? numa_plan_phase((int) f.n_embd, nb) : phase_tasks(mrows_);
1517        run_phase(6, mtasks_);
1518        const auto d = std::chrono::steady_clock::now();
1519        if (diag_a)
1520            std::fprintf(stderr, "DIAGA phase6: jobs=%d n_embd=%lld rows=%d tasks=%d wall=%.3f ms\n",
1521                         nb, (long long) f.n_embd, (int) mrows_, (int) mtasks_,
1522                         std::chrono::duration<double, std::milli>(d - c).count());
1523        ms_multi_gu += std::chrono::duration<double, std::milli>(b - a).count();
1524        ms_multi_q += std::chrono::duration<double, std::milli>(c - b).count();
1525        ms_multi_down += std::chrono::duration<double, std::milli>(d - c).count();
1526    }
1527    multi_bytes += (int64_t) n * (int64_t) f.bytes;
1528    mode_ = 0;
1529    ms_drain_ += std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count();
1530}
1531
1532void ExpertPool::run_latent_rows(LatentMatvec* mv, int n) {
1533    if (n <= 0) return;
1534    const auto t0 = std::chrono::steady_clock::now();
1535    const bool diag_a = std::getenv("STRATA_DIAG_A") != nullptr;
1536    int64_t rows = 0, bytes = 0;
1537    for (int m = 0; m < n; ++m) { rows += mv[m].nrows; bytes += (int64_t) mv[m].row_bytes * mv[m].nrows; }
1538    lmv_ = mv;
1539    lmv_n_ = n;
1540    mrows_ = rows;
1541    mtasks_ = phase_tasks(rows);
1542    run_phase(7, mtasks_);
1543    mode_ = 0;
1544    const double wall = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count();
1545    if (diag_a)
1546        std::fprintf(stderr, "DIAGU groups=%d rows=%lld tasks=%d bytes=%lld wall=%.3f ms = %.1f GB/s\n",
1547                     n, (long long) rows, mtasks_, (long long) bytes, wall, (double) bytes / wall / 1e6);
1548    ms_drain_ += wall;
1549}
1550
1551void ExpertPool::run(ExpertJob* jobs, int n) {
1552    if (n <= 0) return;
1553    if (n_ == 1) {   // no workers: run inline, so a single-core machine still produces a token
1554        for (int i = 0; i < n; ++i) s2_expert_vnni_q(jobs[i].blob, *jobs[i].act, jobs[i].out, scratch_[0]);
1555        return;
1556    }
1557    // Wait for every worker to be parked BEFORE touching the batch, so the publish below is the only thing
1558    // that can move a worker into the drain loop.
1559    //
1560    // THE THREE PHASES ARE TIMED SEPARATELY.  They were one number, which cannot distinguish a pool that is
1561    // slow at the WORK from one that is slow at the SYNCHRONISATION - and those need opposite fixes.
1562    const auto t_a = std::chrono::steady_clock::now();
1563    wait_parked("before a batch");
1564    const auto t_b = std::chrono::steady_clock::now();
1565    jobs_ = jobs;
1566    njobs_ = n;
1567    mode_ = 0;
1568    const uint32_t e = begin_batch(n);   // done, then head (release), then the epoch: the batch is described first
1569
1570    // ---- **THE HOST DRAINS TOO (R2.2), INSTEAD OF SPINNING ON `done_`.**
1571    //
1572    // The loop below used to be `while (done_ != n) strata_cpu_pause();`.  The host is pinned to core 0 - the core
1573    // `physical_cores(true)` deliberately keeps the five workers off - so for the whole drain that core was
1574    // idle while five cores did six cores' worth of work.  Measured before the change: 33.7 GB/s against
1575    // 5/6 x 44.14 = 36.8 for five workers and 44.14 for six.
1576    //
1577    // The host claims through the SAME `head_` counter, so this is not a second scheduler and nothing about
1578    // the ordering changes: `head_` is a single `fetch_add`, every job is the same size, and a thread that
1579    // arrives late simply claims nothing.  `done_` is still the completion signal and the host still waits for
1580    // it - what changed is only that the host arrives at that wait having done a share of the work.
1581    //
1582    // The host's `done_.fetch_add` is a release for the same reason a worker's is: `j.out` is read by the
1583    // device after `run()` returns, so the write must be published, not merely performed.
1584    if (host_works_) {
1585        for (;;) {
1586            const int ci = claim(e);
1587            if (ci < 0) break;
1588            hstate_.store(ci, std::memory_order_relaxed);
1589            hstate_ms_.store(now_ms(), std::memory_order_relaxed);
1590            const ExpertJob& j = jobs_[ci];
1591            s2_expert_vnni_q(j.blob, *j.act, j.out, host_scratch_);
1592            done_.fetch_add(1, std::memory_order_release);
1593        }
1594    }
1595
1596    wait_done(n);
1597    // And park again, so the next `run` starts from a known state.  See the header for why `done` alone is
1598    // not enough.
1599    const auto t_c = std::chrono::steady_clock::now();
1600    wait_parked("after a batch");
1601    hstate_.store(kIdle, std::memory_order_relaxed);
1602    hstate_ms_.store(now_ms(), std::memory_order_relaxed);
1603    const auto t_d = std::chrono::steady_clock::now();
1604
1605    ms_wait_park_ += std::chrono::duration<double, std::milli>(t_b - t_a).count();
1606    ms_drain_ += std::chrono::duration<double, std::milli>(t_c - t_b).count();
1607    ms_repark_ += std::chrono::duration<double, std::milli>(t_d - t_c).count();
1608}
1609
1610}  // namespace strata::kernels::cpu
1611
1612#if defined(_WIN32)
1613// strata/platform/thread_name.hpp: the Windows half lives here, where <windows.h> is already included.  SetThreadDescription
1614// (Windows 10 1607 and later) is looked up, not linked: older SDKs and toolchains lack the import.
1615namespace strata::platform {
1616void name_this_thread(const char* base, int index) {
1617    char name[64];
1618    if (index >= 0) std::snprintf(name, sizeof name, "%s-%d", base, index);
1619    else std::snprintf(name, sizeof name, "%s", base);
1620    using SetDesc = HRESULT(WINAPI*)(HANDLE, PCWSTR);
1621    static const SetDesc fn = (SetDesc) GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "SetThreadDescription");
1622    if (fn == nullptr) return;
1623    wchar_t wide[64];
1624    int i = 0;
1625    for (; name[i] != '\0' && i < 63; ++i) wide[i] = (wchar_t) (unsigned char) name[i];
1626    wide[i] = L'\0';
1627    (void) fn(GetCurrentThread(), wide);
1628}
1629}  // namespace strata::platform
1630#endif