okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
fd19246dc
main
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 ) { 10const int nb = ncols /32 ; 11float acc = 0.0f ; 12for (int b = 0 ;b < nb ;++ b ) { 13const uint8_t * wb = row + (size_t )b * 34 ; 14const uint8_t * xb = xq + (size_t )b * 36 ; 15const float dw = strata::kernels::f32_from_f16 ((uint16_t )(wb [0 ] | (wb [1 ] <<8 ))); 16const float dx = strata::kernels::f32_from_f16 ((uint16_t )(xb [0 ] | (xb [1 ] <<8 ))); 17const int8_t * ws = (const int8_t * )(wb + 2 ); 18const int8_t * xs = (const int8_t * )(xb + 4 ); 19int s = 0 ; 20for (int j = 0 ;j < 32 ;++ j )s += (int )xs [j ]* (int )ws [j ]; 21acc += dw * dx * (float )s ; 22 } 23return 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 ) { 28const int nb = ncols /32 ; 29float acc = 0.0f ; 30for (int b = 0 ;b < nb ;++ b ) { 31const uint8_t * wb = row + (size_t )b * 18 ; 32const uint8_t * xb = xq + (size_t )b * 36 ; 33const float dw = strata::kernels::f32_from_f16 ((uint16_t )(wb [0 ] | (wb [1 ] <<8 ))); 34const float dx = strata::kernels::f32_from_f16 ((uint16_t )(xb [0 ] | (xb [1 ] <<8 ))); 35const int8_t * xs = (const int8_t * )(xb + 4 ); 36int s = 0 ; 37for (int j = 0 ;j < 16 ;++ j ) { 38const int byte_ = wb [2 + j ]; 39s += (int )xs [j ]* ((int )(byte_ & 0xF )- 8 ); 40s += (int )xs [j + 16 ]* ((int )(byte_ >>4 )- 8 ); 41 } 42acc += dw * dx * (float )s ; 43 } 44return 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 () { 86static const uint64_t c = [] { 87const char * e = std::getenv ("STRATA_POOL_UMWAIT" ); 88if (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 90int r [4 ]= {0 ,0 ,0 ,0 }; 91__cpuidex (r ,7 ,0 ); 92if (((r [2 ] >>5 )& 1 )== 0 ) { 93 std::fprintf (stderr ,"strata: STRATA_POOL_UMWAIT: this CPU has no WAITPKG, the workers spin\n" ); 94return (uint64_t )0 ; 95 } 96 std::fprintf (stderr ,"strata: STRATA_POOL_UMWAIT: parked workers wait with UMWAIT (%lld cycles)\n" , std::atoll (e )); 97return (uint64_t ) std::atoll (e ); 98#else 99return (uint64_t )0 ; 100#endif 101 }(); 102return c ; 103} 104unsigned umwait_state () { 105static const unsigned s = [] {const char * e = std::getenv ("STRATA_POOL_UMWAIT_C02" );return e && * e == '1' ?0u :1u ; }(); 106return 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 () { 111static 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 ; }(); 112return c ; 113} 114 115constexpr uint64_t pack_head (uint32_t epoch ,uint32_t n ,uint32_t i ) { 116return ((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 ) 136DWORD len = 0 ; 137GetLogicalProcessorInformationEx (RelationProcessorCore ,nullptr ,& len ); 138if (len == 0 )return out ; 139 std::vector < char > buf (len ); 140if (!GetLogicalProcessorInformationEx (RelationProcessorCore , (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX )buf .data (),& len )) 141return out ; 142// a `start /affinity` or a job limit on a PC with one processor group: only those processors are the process's 143DWORD_PTR proc_mask = 0 ,sys_mask = 0 ; 144const bool limited = GetActiveProcessorGroupCount ()== 1 && GetProcessAffinityMask (GetCurrentProcess (),& proc_mask ,& sys_mask ); 145long core = 0 ; 146for (const char * p = buf .data ();p < buf .data ()+ len ;p += ((const SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX * )p )-> Size ) { 147const auto * e = (const SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX * )p ; 148if (e -> Relationship != RelationProcessorCore )continue ; 149for (WORD group = 0 ;group < e -> Processor .GroupCount ;++ group ) { 150const GROUP_AFFINITY & g = e -> Processor .GroupMask [group ]; 151for (int bit = 0 ;bit < 64 ;++ bit ) 152if ((g .Mask & (KAFFINITY (1 ) <<bit ))&& (!limited || (proc_mask & (DWORD_PTR (1 ) <<bit )))) 153out .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 ; 160if (detail::get_thread_affinity (mask ,& allowed )!= 0 )return out ; 161auto read = [](int cpu ,const char * what )-> long { 162char path [96 ]; 163 std::snprintf (path ,sizeof path ,"/sys/devices/system/cpu/cpu%d/topology/%s" ,cpu ,what ); 164long v = -1 ; 165if (std::FILE * f = std::fopen (path ,"r" )) { 166if (std::fscanf (f ,"%ld" ,& v )!= 1 )v = -1 ; 167 std::fclose (f ); 168 } 169return v ; 170 }; 171for (int cpu :allowed ) { 172const long pkg = read (cpu ,"physical_package_id" ),core = read (cpu ,"core_id" ); 173out .push_back ({cpu ,pkg >=0 && core >=0 ?pkg * 1000000 + core :-1 }); 174 } 175#else 176for (unsigned i = 0 ;i < std::thread::hardware_concurrency ();++ i )out .push_back ({(int )i ,-1 }); 177#endif 178return 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 ) { 187topo .cpu_quota = container_cpu_quota (); 188topo .worker_package .assign (topo .worker_cores .size (),-1 ); 189#if defined(_WIN32 ) 190 (void )skip_first ; 191topo .logical = (int )GetActiveProcessorCount (ALL_PROCESSOR_GROUPS ); 192return ;// (the sockets of a Windows box are not told apart: one package) 193#elif defined(__APPLE__ ) 194 (void )skip_first ; 195topo .logical = (int ) std::thread::hardware_concurrency (); 196return ;// 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 ; 200topo .logical = detail::get_thread_affinity (mask ,& allowed )== 0 ? (int )allowed .size () 201 : (int ) std::thread::hardware_concurrency (); 202auto read = [](int cpu ,const char * what )-> long { 203char path [96 ]; 204 std::snprintf (path ,sizeof path ,"/sys/devices/system/cpu/cpu%d/topology/%s" ,cpu ,what ); 205long v = -1 ; 206if (std::FILE * f = std::fopen (path ,"r" )) { 207if (std::fscanf (f ,"%ld" ,& v )!= 1 )v = -1 ; 208 std::fclose (f ); 209 } 210return v ; 211 }; 212bool known = !topo .worker_cores .empty ()|| topo .host_core >=0 ; 213auto pkg_of = [& ](int cpu ) { 214const long pkg = read (cpu ,"physical_package_id" ),core = read (cpu ,"core_id" ); 215if (pkg < 0 || core < 0 )known = false; 216return (int )pkg ; 217 }; 218if (topo .host_core >=0 )topo .host_package = pkg_of (topo .host_core ); 219for (size_t i = 0 ;i < topo .worker_cores .size ();++ i )topo .worker_package [i ]= pkg_of (topo .worker_cores [i ]); 220topo .layout_known = known ; 221if (!known )return ; 222if (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 ()); 225for (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 ; 229for (size_t i :order ) {cores .push_back (topo .worker_cores [i ]);pkgs .push_back (topo .worker_package [i ]); } 230topo .worker_cores = std::move (cores ); 231topo .worker_package = std::move (pkgs ); 232 } 233#endif 234} 235 236CpuTopology detect_cpu_topology (bool skip_first ,PoolAffinity affinity ) { 237CpuTopology 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) 239if (skip_first && host_core_setting ()== HostCore ::Last && !topo .is_hybrid && topo .host_core >=0 && 240 !topo .worker_cores .empty ()) { 241const int last = topo .worker_cores .back (); 242topo .worker_cores .pop_back (); 243topo .worker_cores .insert (topo .worker_cores .begin (),topo .host_core ); 244topo .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) 248if (skip_first && host_core_setting ()== HostCore ::Sibling && topo .host_sibling >=0 ) { 249topo .worker_cores .erase (std::remove (topo .worker_cores .begin (),topo .worker_cores .end (),topo .host_sibling ), 250topo .worker_cores .end ()); 251topo .host_core = topo .host_sibling ; 252 } 253fill_plan_fields (topo ,skip_first ); 254return 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 ; 261if (std::FILE * f = std::fopen ("/proc/self/cgroup" ,"r" )) { 262char buf [512 ]; 263size_t n ; 264while ((n = std::fread (buf ,1 ,sizeof buf ,f ))> 0 )self .append (buf ,n ); 265 std::fclose (f ); 266 } 267return cgroup_cpu_quota_at ("/sys/fs/cgroup" ,self ); 268#else 269return 0.0 ; 270#endif 271} 272 273PoolPlanInput pool_plan_input (const CpuTopology & topo ) { 274PoolPlanInput in ; 275in .logical = topo .logical > 0 ?topo .logical : (int ) std::thread::hardware_concurrency (); 276in .cpu_quota = topo .cpu_quota ; 277if (topo .is_hybrid ) {in .p_cores = topo .p_cores ;in .e_cores = topo .e_cores ; } 278if (!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) 281auto add = [& ](int pkg ) { 282for (auto & c :counts ) 283if (c .first == pkg ) {++ c .second ;return ; } 284counts .emplace_back (pkg ,1 ); 285 }; 286if (topo .host_core >=0 )add (topo .host_package ); 287for (size_t i = 0 ;i < topo .worker_cores .size ();++ i ) 288add (i < topo .worker_package .size () ?topo .worker_package [i ] :-1 ); 289if (topo .host_core >=0 ) {// (the host package first even when it has no worker core listed) 290auto it = std::find_if (counts .begin (),counts .end (), [& ](const auto & c ) {return c .first == topo .host_package ; }); 291if (it != counts .begin ()) std::iter_swap (counts .begin (),it ); 292 } 293for (const auto & c :counts )in .cores_per_package .push_back (c .second ); 294return 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 ) { 300CpuTopology 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. 305DWORD len = 0 ; 306GetLogicalProcessorInformationEx (RelationProcessorCore ,nullptr ,& len ); 307if (len == 0 ) { 308// Preserve group identity even when detailed core topology is unavailable. 309const WORD groups = GetActiveProcessorGroupCount (); 310for (WORD group = 0 ;group < groups ;++ group ) { 311const DWORD count = GetActiveProcessorCount (group ); 312if (count == 0 || count == (DWORD )- 1 || count > 64 )continue ; 313for (DWORD i = 0 ;i < count ;++ i )topo .worker_cores .push_back ((int )group * 64 + (int )i ); 314 } 315if (skip_first && !topo .worker_cores .empty ()) { 316topo .host_core = topo .worker_cores .front (); 317topo .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. 322topo .layout_known = false; 323return topo ; 324 } 325 std::vector < char > buf (len ); 326if (GetLogicalProcessorInformationEx (RelationProcessorCore , 327 (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX )buf .data (),& len )) { 328const char * p = buf .data (); 329const char * end = p + len ; 330struct CoreDesc { 331uint8_t efficiency = 0 ; 332bool has_smt = false; 333 std::vector < int > lps ; 334 }; 335 std::vector < CoreDesc > descs ; 336while (p < end ) { 337const auto * e = (const SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX * )p ; 338if (e -> Relationship == RelationProcessorCore ) { 339CoreDesc cd ; 340cd .efficiency = e -> Processor .EfficiencyClass ; 341cd .has_smt = (e -> Processor .Flags & LTP_PC_SMT )!= 0 ; 342for (WORD group = 0 ;group < e -> Processor .GroupCount ;++ group ) { 343const GROUP_AFFINITY & g = e -> Processor .GroupMask [group ]; 344for (int bit = 0 ;bit < 64 ;++ bit ) { 345if (g .Mask & (KAFFINITY (1 ) <<bit )) { 346cd .lps .push_back ((int ) (g .Group * 64 + bit )); 347 } 348 } 349 } 350if (!cd .lps .empty ()) { 351descs .push_back (std::move (cd )); 352 } 353 } 354p += e -> Size ; 355 } 356 357uint8_t min_eff = 255 ,max_eff = 0 ; 358for (const auto & c :descs ) { 359min_eff = (std::min )(min_eff ,c .efficiency ); 360max_eff = (std::max )(max_eff ,c .efficiency ); 361 } 362 363topo .is_hybrid = (max_eff > min_eff ); 364if (topo .is_hybrid ) { 365for (const auto & c :descs ) { 366if (c .efficiency == max_eff ) { 367topo .p_cores ++ ; 368topo .p_threads += (int )c .lps .size (); 369 }else { 370topo .e_cores ++ ; 371 } 372 } 373 }else { 374topo .p_cores = (int )descs .size (); 375for (const auto & c :descs )topo .p_threads += (int )c .lps .size (); 376 } 377 378if (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. 382if (topo .is_hybrid ) 383 std::stable_sort (descs .begin (),descs .end (), 384 [](const CoreDesc & x ,const CoreDesc & y ) {return x .efficiency > y .efficiency ; }); 385for (const auto & c :descs )topo .worker_cores .push_back (c .lps [0 ]); 386if (skip_first && !topo .worker_cores .empty ()) { 387topo .host_core = topo .worker_cores .front (); 388topo .worker_cores .erase (topo .worker_cores .begin ()); 389if (descs .front ().lps .size ()> 1 )topo .host_sibling = descs .front ().lps [1 ]; 390 } 391return 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 403for (const auto & c :descs ) { 404if (c .efficiency == max_eff ) { 405p_primaries .push_back (c .lps [0 ]); 406for (size_t s = 1 ;s < c .lps .size ();++ s ) { 407p_siblings .push_back (c .lps [s ]); 408 } 409 }else { 410for (int lp :c .lps )e_cores .push_back (lp ); 411 } 412 } 413 414if (skip_first && !p_primaries .empty ()) { 415topo .host_core = p_primaries .front (); 416p_primaries .erase (p_primaries .begin ()); 417for (const auto & c :descs ) 418if (c .lps [0 ]== topo .host_core ) { 419if (c .lps .size ()> 1 )topo .host_sibling = c .lps [1 ]; 420break ; 421 } 422 } 423 424for (int cpu :p_primaries )topo .worker_cores .push_back (cpu ); 425for (int cpu :p_siblings )topo .worker_cores .push_back (cpu ); 426if (affinity != PoolAffinity ::PCores ) { 427for (int cpu :e_cores )topo .worker_cores .push_back (cpu ); 428 } 429return 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. 436auto topo_read = [](int cpu ,const char * what )-> long { 437char path [96 ]; 438 std::snprintf (path ,sizeof path ,"/sys/devices/system/cpu/cpu%d/topology/%s" ,cpu ,what ); 439long v = -1 ; 440if (std::FILE * f = std::fopen (path ,"r" )) { 441if (std::fscanf (f ,"%ld" ,& v )!= 1 )v = -1 ; 442 std::fclose (f ); 443 } 444return v ; 445 }; 446auto cap_read = [](int cpu )-> long { 447char path [96 ]; 448 std::snprintf (path ,sizeof path ,"/sys/devices/system/cpu/cpu%d/cpu_capacity" ,cpu ); 449long v = -1 ; 450if (std::FILE * f = std::fopen (path ,"r" )) { 451if (std::fscanf (f ,"%ld" ,& v )!= 1 )v = -1 ; 452 std::fclose (f ); 453 } 454return 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 458auto cpulist_read = [](const char * path , std::vector < int >& out )-> bool { 459 std::FILE * f = std::fopen (path ,"r" ); 460if (!f )return false; 461char text [1024 ]= {0 }; 462const size_t n = std::fread (text ,1 ,sizeof text - 1 ,f ); 463 std::fclose (f ); 464text [n ]= '\0' ; 465for (const char * p = text ;* p ;) { 466char * end = nullptr ; 467const long lo = std::strtol (p ,& end ,10 ); 468if (end == p )break ; 469long hi = lo ; 470if (* end == '-' ) { 471p = end + 1 ; 472hi = std::strtol (p ,& end ,10 ); 473 } 474for (long c = lo ;c <=hi && c < 4096 ;++ c )out .push_back ((int )c ); 475p = end ; 476while (* p == ',' || * p == ' ' || * p == '\n' )++ p ; 477 } 478return !out .empty (); 479 }; 480 481 std::vector < int > allowed ; 482 std::vector < unsigned long > allowed_mask ; 483if (detail::get_thread_affinity (allowed_mask ,& allowed )!= 0 ) { 484for (unsigned i = 0 ;i < std::thread::hardware_concurrency ();++ i )allowed .push_back ((int )i ); 485 } 486 487struct CoreLinux { 488int cpu = -1 ; 489long pkg = -1 ; 490long core = -1 ; 491long cap = -1 ; 492bool is_sibling = false; 493 }; 494 std::vector < CoreLinux > all_cpus ; 495 std::vector < std::pair < long ,long >> seen_phys ; 496long max_cap = 0 ,min_cap = 1000000 ; 497 498for (int cpu :allowed ) { 499CoreLinux cl ; 500cl .cpu = cpu ; 501cl .pkg = topo_read (cpu ,"physical_package_id" ); 502cl .core = topo_read (cpu ,"core_id" ); 503cl .cap = cap_read (cpu ); 504if (cl .cap > 0 ) { 505max_cap = (std::max )(max_cap ,cl .cap ); 506min_cap = (std::min )(min_cap ,cl .cap ); 507 } 508if (cl .pkg >=0 && cl .core >=0 ) { 509const std::pair < long ,long > key {cl .pkg ,cl .core }; 510if (std::find (seen_phys .begin (),seen_phys .end (),key )!= seen_phys .end ()) { 511cl .is_sibling = true; 512 }else { 513seen_phys .push_back (key ); 514 } 515 } 516all_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 ; 526const bool pmu = cpulist_read ("/sys/devices/cpu_core/cpus" ,pmu_core )&& 527cpulist_read ("/sys/devices/cpu_atom/cpus" ,pmu_atom ); 528cpulist_read ("/sys/devices/cpu_lowpower/cpus" ,pmu_lowpower ); 529auto is_e = [& ](const CoreLinux & cl ) { 530return hybrid_cpu_is_efficiency (cl .cpu ,cl .cap ,max_cap ,pmu ,pmu_core ,pmu_atom ,pmu_lowpower ); 531 }; 532bool any_e = false,any_p = false; 533for (const auto & cl :all_cpus ) (is_e (cl ) ?any_e :any_p )= true; 534topo .is_hybrid = any_e && any_p ; 535if (topo .is_hybrid ) { 536for (const auto & cl :all_cpus ) { 537if (!is_e (cl )) { 538if (!cl .is_sibling )topo .p_cores ++ ; 539topo .p_threads ++ ; 540 }else { 541if (!cl .is_sibling )topo .e_cores ++ ; 542 } 543 } 544 }else { 545topo .p_cores = (int )seen_phys .size (); 546topo .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) 550auto sibling_of = [& ](int cpu ) { 551for (const auto & h :all_cpus ) 552if (h .cpu == cpu && h .pkg >=0 && h .core >=0 ) 553for (const auto & cl :all_cpus ) 554if (cl .cpu != cpu && cl .pkg == h .pkg && cl .core == h .core )return cl .cpu ; 555return -1 ; 556 }; 557 558if (affinity == PoolAffinity ::All || !topo .is_hybrid ) { 559if (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 ) { 562return is_e (x )!= is_e (y ) ? !is_e (x ) :x .cap > y .cap ; 563 }); 564for (const auto & cl :all_cpus ) { 565if (!cl .is_sibling )topo .worker_cores .push_back (cl .cpu ); 566 } 567if (skip_first && !topo .worker_cores .empty ()) { 568topo .host_core = topo .worker_cores .front (); 569topo .worker_cores .erase (topo .worker_cores .begin ()); 570topo .host_sibling = sibling_of (topo .host_core ); 571 } 572return 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 580for (const auto & cl :all_cpus ) { 581if (!is_e (cl )) { 582if (!cl .is_sibling )p_primaries .push_back (cl .cpu ); 583else p_siblings .push_back (cl .cpu ); 584 }else { 585e_cores .push_back (cl .cpu ); 586 } 587 } 588 589if (skip_first && !p_primaries .empty ()) { 590topo .host_core = p_primaries .front (); 591p_primaries .erase (p_primaries .begin ()); 592topo .host_sibling = sibling_of (topo .host_core ); 593 } 594 595for (int cpu :p_primaries )topo .worker_cores .push_back (cpu ); 596for (int cpu :p_siblings )topo .worker_cores .push_back (cpu ); 597if (affinity != PoolAffinity ::PCores ) { 598for (int cpu :e_cores )topo .worker_cores .push_back (cpu ); 599 } 600return topo ; 601#endif 602return topo ; 603} 604 605std::vector < int > physical_cores (bool skip_first ,PoolAffinity affinity ) { 606return detect_cpu_topology (skip_first ,affinity ).worker_cores ; 607} 608 609namespace { 610 611bool pin_this_thread (int core , [[maybe_unused ]]int worker = -1 ) { 612if (core < 0 )return false; 613#if defined(_WIN32 ) 614return detail::set_thread_group_affinity (core ,worker ); 615#else 616const int error = detail::pin_thread_to_cpu (core ); 617if (error != 0 ) 618 std::fprintf (stderr ,"strata cpu pool: affinity for worker %d (CPU %d) failed: %d; previous affinity kept\n" , 619worker ,core ,error ); 620return 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 () { 628const char * e = std::getenv ("STRATA_TEST_SYSFS_ROOT" ); 629return 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 ) { 634if (cpu < 0 )return -1 ; 635const std::string root = sysfs_root (); 636char path [512 ]; 637for (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 ); 639if (access (path ,F_OK )== 0 )return node ; 640 } 641return -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__ ) 649return (std::max )(1 ,numa_cpu_node_count_at (sysfs_root ()+ "/devices/system/node" )); 650#elif defined(_WIN32 ) 651ULONG highest = 0 ; 652return GetNumaHighestNodeNumber (& highest ) ? (int )highest + 1 :1 ; 653#else 654return 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" 664const char * rotate = std::getenv ("STRATA_EXCHANGE_ROTATE" ); 665return decide_numa_split (thread_core ,n_workers ,pinned ,rotate != nullptr && std::strcmp (rotate ,"1" )== 0 ,cpu_numa_node ); 666#else 667NumaSplitDecision d ; 668d .why = "the split needs Linux" ; 669return d ; 670#endif 671} 672 673}// namespace 674 675ThreadAffinity pin_current_thread (int core ) { 676if (core < 0 )return {}; 677#if defined(_WIN32 ) 678ThreadAffinity previous ; 679ULONG target = 0 ; 680if (!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" , 683core , (unsigned long )GetLastError ()); 684return {}; 685 } 686previous .valid = true; 687return previous ; 688#else 689ThreadAffinity previous ; 690int error = detail::get_thread_affinity (previous .mask ); 691if (error == 0 )error = detail::pin_thread_to_cpu (core ); 692if (error != 0 ) { 693 std::fprintf (stderr ,"strata cpu pool: host affinity for CPU %d failed: %d; previous affinity kept\n" ,core ,error ); 694return {}; 695 } 696previous .valid = true; 697return previous ; 698#endif 699} 700 701void restore_thread_affinity (const ThreadAffinity & previous ) { 702if (!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. 706if (!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 711const int error = detail::set_thread_affinity (previous .mask ); 712if (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 ) { 720if (const ExpertPool * p = g_diag_pool .load ())p -> diag (f ); 721} 722int64_t now_ms () { 723return std::chrono::duration_cast < std::chrono::milliseconds > (std::chrono::steady_clock::now ().time_since_epoch ()) 724 .count (); 725} 726int64_t now_ns () { 727return 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 { 739const uint64_t h = head_ .load (); 740uint32_t batch = (uint32_t ) (h >>32 ),claimed = (uint32_t )h & 0xffffu ,total = (uint32_t ) (h >>16 )& 0xffffu , 741done = 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 744if (numa_n_ > 0 && mode_ >=5 ) {// a split native batch never writes head_/done_: the slices' sums instead 745claimed = total = done = 0 ; 746for (int k = 0 ;k < numa_n_ ;++ k ) { 747const uint64_t sh = nsync_ [(size_t )k ].head .load (); 748batch = (uint32_t ) (sh >>32 );// every slice head carries the batch's epoch 749claimed += (uint32_t )sh & 0xffffu ; 750total += (uint32_t ) (sh >>16 )& 0xffffu ; 751done += 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_ , 756sleepers_ .load (),mode_ ); 757if (numa_n_ > 0 ) std::fprintf (f ," expert pool NUMA slices:%s\n" ,numa_counters ().c_str ()); 758 std::fprintf (f ," expert pool threads:" ); 759for (int i = 0 ;i < n_ ;++ i ) { 760const int32_t s = wstate_ [(size_t )i ].load (); 761if (s == kParked ) std::fprintf (f ," w%d=parked" ,i ); 762else if (s == kSleeping ) std::fprintf (f ," w%d=sleeping" ,i ); 763else if (s == kBetween ) std::fprintf (f ," w%d=draining" ,i ); 764else std::fprintf (f ," w%d=job%d" ,i ,s ); 765 } 766const int32_t hs = hstate_ .load (); 767const 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 ); 770if (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 )) { 776if (tasks < 0 || tasks > kMaxTasks )throw std::invalid_argument ("expert pool tasks must be in 0..4096" ); 777pinned_ = pin ; 778layout_ = logical_cpu_layout ();// now, before anything pins the caller (Linux reads the calling thread's allowed CPUs) 779if (const char * e = std::getenv ("STRATA_POOL_SPIN_US" ))// a test knob; see kSpinBeforeSleep 780spin_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. 784const char * env = std::getenv ("STRATA_NUMA_SPLIT" ); 785const int numa_nodes = numa_node_count (); 786const NumaPoolPick pool_pick = pick_numa_pool (std::getenv ("STRATA_NUMA_POOL" ),env ,numa_nodes ); 787if (!pool_pick .log .empty ()) std::fprintf (stderr ,"%s\n" ,pool_pick .log .c_str ()); 788if (pool_pick .choice == NumaPoolChoice ::Off )env = nullptr ; 789bool auto_pool = pool_pick .choice == NumaPoolChoice ::Auto ;// the split without STRATA_NUMA_SPLIT: only if it can run 790bool env_off = !auto_pool && (env == nullptr || * env == '\0' || std::strcmp (env ,"0" )== 0 ); 791bool env_known = auto_pool || (!env_off && (std::strcmp (env ,"1" )== 0 || std::strcmp (env ,"test" )== 0 )); 792const PoolPlanInput plan_in = pool_plan_input (topo_ ); 793const 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. 796if (!pool_cores_setting ().empty ()) { 797const PoolCoresCheck chk = check_pool_cores (pool_cores_setting (),layout_ ,topo_ .host_core ); 798static std::atomic < bool > told {false};// (a throw-away pool of --pool-affinity measure builds the same list again) 799const bool say = !told .exchange (true); 800if (say ) 801for (const std::string & w :chk .warnings ) std::fprintf (stderr ,"strata cpu pool: --pool-cores: %s\n" ,w .c_str ()); 802if (chk .cpus .empty ()) { 803if (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 { 807topo_ .worker_cores = chk .cpus ; 808topo_ .worker_package .assign (chk .cpus .size (),-1 ); 809explicit_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) 815auto interleave_cores = [& ] { 816if (explicit_cores_ )return ;// --pool-cores: the person's order stays 817if (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 ; 821for (int c :topo_ .worker_cores )by_node .push_back (cpu_numa_node (c )); 822if (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 ; 825for (size_t i :interleave_packages (key )) { 826cores .push_back (topo_ .worker_cores [i ]); 827pkgs .push_back (topo_ .worker_package [i ]); 828 } 829topo_ .worker_cores = std::move (cores ); 830topo_ .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) 833auto pick_workers = [& ](bool span ,const char ** limit )-> int { 834if (n_workers > 0 )return n_workers ; 835if (explicit_cores_ ) { 836* limit = "your --pool-cores list" ; 837return (int )topo_ .worker_cores .size (); 838 } 839if (topo_ .is_hybrid && affinity_ != PoolAffinity ::All )return (std::max )(1 ,topo_ .p_cores - 1 ); 840if (span ) { 841PoolPlanInput span_in = plan_in ; 842span_in .span_packages = true; 843const PoolPlan sp = plan_pool_workers (span_in ); 844* limit = sp .limit ; 845return (std::min )(sp .workers , (std::max )(1 , (int )topo_ .worker_cores .size ())); 846 } 847* limit = wplan .limit ; 848return (std::min )(wplan .workers , (std::max )(1 , (int )topo_ .worker_cores .size ())); 849 }; 850if (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 852const CpuTopology plain_topo = topo_ ; 853interleave_cores (); 854const char * try_limit = nullptr ; 855const int try_n = pick_workers (true,& try_limit ); 856 std::vector < int > thread_core ; 857for (int j = 0 ;j < try_n ;++ j ) 858thread_core .push_back (pin && j < (int )topo_ .worker_cores .size () ?topo_ .worker_cores [(size_t )j ] :-1 ); 859if (host_works_ )thread_core .push_back (topo_ .host_core ); 860const NumaSplitDecision tried = decide_real_numa_split (thread_core ,try_n ,pin ); 861if (!tried .on ) { 862topo_ = plain_topo ; 863auto_pool = env_known = false; 864env_off = true; 865 std::fprintf (stderr ,"strata cpu pool: NUMA pool off: %s (%d NUMA nodes found), the pool runs as before\n" , 866tried .why .c_str (),numa_nodes ); 867 } 868 }else if (env_known ) { 869interleave_cores (); 870 } 871 { 872const char * limit = nullptr ; 873n_ = pick_workers (env_known ,& limit ); 874if (limit != nullptr )plan_limit_ = limit ; 875 } 876plan_cores_ = wplan .cores ; 877plan_logical_ = plan_in .logical ; 878if (n_ < 1 )n_ = 1 ; 879scratch_ .resize ((size_t )n_ ); 880wstate_ .reset (new std::atomic < int32_t > [(size_t )n_ ]); 881for (int i = 0 ;i < n_ ;++ i )wstate_ [(size_t )i ].store (kParked ); 882hstate_ms_ .store (now_ms ()); 883g_diag_pool .store (this ); 884 strata::core::diag_pool_fn ().store (& diag_active_pool ); 885split_ .resize ((size_t )kMaxSplit ); 886split_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. 889NumaSplitPlan plan ; 890if (!env_off && !env_known ) { 891plan .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 ) { 894plan .test = !auto_pool && std::strcmp (env ,"test" )== 0 ; 895const 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 ; 898if (threads < 2 ) { 899why = "the pool has " + std::to_string (threads )+ " thread, the split needs 2 or more" ; 900 }else if (plan .test ) { 901for (int j = 0 ;j < threads ;++ j )slice [(size_t )j ]= j %2 ; 902 }else { 903 std::vector < int > thread_core ; 904for (int j = 0 ;j < threads ;++ j ) 905thread_core .push_back (j == n_ ?topo_ .host_core 906 :pin && j < (int )topo_ .worker_cores .size () ?topo_ .worker_cores [(size_t )j ] :-1 ); 907const NumaSplitDecision d = decide_real_numa_split (thread_core ,n_ ,pin ); 908why = d .why ; 909if (d .on ) { 910slice = d .slice ; 911plan .nodes [0 ]= d .nodes [0 ]; 912plan .nodes [1 ]= d .nodes [1 ]; 913for (int j = 0 ;j < threads ;++ j )plan .cores [slice [(size_t )j ]].push_back (thread_core [(size_t )j ]); 914 } 915 } 916plan .why = why ; 917plan .on = plan .why .empty (); 918if (!plan .on ) {// a refusal after the slices were planned (unbalanced) leaves no half-filled plan behind 919plan .nodes [0 ]= plan .nodes [1 ]= -1 ; 920plan .cores [0 ].clear (); 921plan .cores [1 ].clear (); 922 } 923if (plan .on ) { 924numa_n_ = 2 ; 925nsync_ .reset (new NodeSync [2 ]); 926wslice_ .assign (slice .begin (),slice .begin ()+ n_ ); 927hslice_ = host_works_ ?slice [(size_t )n_ ] :0 ; 928slice_threads_ .assign (2 ,0 ); 929for (int k :slice )++ slice_threads_ [(size_t )k ]; 930if (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 ); 933if (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 ]); 936else 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 } 943if (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) 946PoolPlanInput warn_in = plan_in ; 947warn_in .span_packages = plan .on ; 948static std::atomic < bool > warned {false}; 949const std::string why = pool_workers_warning (n_workers ,warn_in ,plan_pool_workers (warn_in )); 950if (!why .empty ()&& !warned .exchange (true)) std::fprintf (stderr ,"strata cpu pool: warning: %s\n" ,why .c_str ()); 951 } 952g_numa_plan = std::move (plan ); 953g_numa_owner = this ; 954threads_ .reserve ((size_t )n_ ); 955for (int i = 0 ;i < n_ ;++ i ) { 956const int core = pin ? (i < (int )topo_ .worker_cores .size () ?topo_ .worker_cores [(size_t )i ] :-1 ) :-1 ; 957threads_ .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 961if (!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 ); 964worker (i ); 965 }); 966 } 967} 968 969std::string ExpertPool ::placement_line ()const { 970if (n_ <=0 )return "" ; 971if (!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_ ); 975if ((int )on .size ()< n_ )s += " (" + std::to_string (n_ - (int )on .size ())+ " more workers run unpinned)" ; 976return s ; 977} 978 979ExpertPool ::~ExpertPool () { 980const ExpertPool * self = this ; 981g_diag_pool .compare_exchange_strong (self ,nullptr ); 982if (g_numa_owner == this ) { 983g_numa_plan = NumaSplitPlan {}; 984g_numa_owner = nullptr ; 985 } 986stop_ .store (true, std::memory_order_release ); 987// Bump the epoch so a PARKED worker notices the stop flag rather than sleeping through it. 988publish (); 989for (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. 998epoch_ .fetch_add (1 , std::memory_order_seq_cst ); 999if (sleepers_ .load (std::memory_order_seq_cst )!= 0 ) { 1000 std::lock_guard < std::mutex > lk (sleep_mu_ ); 1001sleep_cv_ .notify_all (); 1002 } 1003} 1004 1005void ExpertPool ::worker (int id ) { 1006uint32_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. 1011parked_of (id ).fetch_add (1 , std::memory_order_acq_rel ); 1012for (;;) { 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. 1024const auto parked_at = std::chrono::steady_clock::now (); 1025uint32_t spins = 0 ; 1026const 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 1028const uint64_t um_esc = umwait_escalate (); 1029const uint64_t um_t0 = um != 0 && um_esc != 0 ?__rdtsc () :0 ; 1030#endif 1031while (epoch_ .load (std::memory_order_acquire )== seen ) { 1032if (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 1034if (um != 0 ) {// STRATA_POOL_UMWAIT: wake on the publish's write to epoch_, or after `um` cycles 1035_umonitor ((void * )& epoch_ ); 1036if (epoch_ .load (std::memory_order_acquire )!= seen )break ; 1037const uint64_t now = __rdtsc (); 1038const unsigned st = um_esc != 0 ? (now - um_t0 < um_esc ?1u :0u ) :umwait_state (); 1039_umwait (st ,now + um ); 1040if ((++ spins & 15u )!= 0 )continue ;// each wait is ~um cycles: look at the clock more often 1041 }else 1042#endif 1043 { 1044strata_cpu_pause (); 1045if ((++ spins & 1023u )!= 0 )continue ; 1046 } 1047if (std::chrono::steady_clock::now ()- parked_at < spin_before_sleep_ )continue ; 1048 std::unique_lock < std::mutex > lk (sleep_mu_ ); 1049wstate_ [(size_t )id ].store (kSleeping , std::memory_order_relaxed ); 1050sleepers_ .fetch_add (1 , std::memory_order_seq_cst ); 1051sleep_cv_ .wait (lk , [& ] { 1052return epoch_ .load (std::memory_order_seq_cst )!= seen || stop_ .load (std::memory_order_relaxed ); 1053 }); 1054sleepers_ .fetch_sub (1 , std::memory_order_relaxed ); 1055wstate_ [(size_t )id ].store (kParked , std::memory_order_relaxed ); 1056 } 1057if (stop_ .load (std::memory_order_acquire ))return ; 1058// acquire: the batch this epoch published (`head`, and the description before it) is visible from here 1059seen = epoch_ .load (std::memory_order_acquire ); 1060parked_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. 1065wstate_ [(size_t )id ].store (kBetween , std::memory_order_relaxed ); 1066drain (id ,scratch_ [(size_t )id ],seen ); 1067wstate_ [(size_t )id ].store (kParked , std::memory_order_relaxed ); 1068parked_of (id ).fetch_add (1 , std::memory_order_acq_rel );// back at the park 1069 } 1070} 1071 1072int ExpertPool ::claim (uint32_t epoch ) { 1073uint64_t h = head_ .load (std::memory_order_acquire ); 1074for (;;) { 1075if ((uint32_t ) (h >>32 )!= epoch )return -1 ;// not the batch this thread woke for 1076const uint32_t n = (uint32_t ) (h >>16 )& 0xffffu ,i = (uint32_t )h & 0xffffu ; 1077if (i >=n )return -1 ;// exhausted 1078if (head_ .compare_exchange_weak (h ,h + 1 , std::memory_order_acq_rel , std::memory_order_acquire )) 1079return (int )i ; 1080 } 1081} 1082 1083int ExpertPool ::claim_slice (uint32_t epoch ,int slice ) { 1084NodeSync & ns = nsync_ [(size_t )slice ]; 1085uint64_t h = ns .head .load (std::memory_order_acquire ); 1086for (;;) { 1087if ((uint32_t ) (h >>32 )!= epoch )return -1 ;// not this batch, or not a mode-5/6 batch 1088const uint32_t n = (uint32_t ) (h >>16 )& 0xffffu ,i = (uint32_t )h & 0xffffu ; 1089if (i >=n )return -1 ;// the slice is exhausted 1090if (ns .head .compare_exchange_weak (h ,h + 1 , std::memory_order_acq_rel , std::memory_order_acquire )) 1091return ns .base + (int )i ;// the description is stable from here 1092 } 1093} 1094 1095uint32_t ExpertPool ::parked_count ()const { 1096if (numa_n_ == 0 )return parked_ .load (std::memory_order_acquire ); 1097uint32_t p = 0 ;// each slice's counter is bounded by its own workers, so the sum is n_ only when each is full 1098for (int k = 0 ;k < numa_n_ ;++ k )p += nsync_ [(size_t )k ].parked .load (std::memory_order_acquire ); 1099return p ; 1100} 1101 1102std::string ExpertPool ::numa_counters ()const { 1103 std::string s ; 1104for (int k = 0 ;k < numa_n_ ;++ k ) { 1105const NodeSync & ns = nsync_ [(size_t )k ]; 1106const uint64_t h = ns .head .load (); 1107char buf [200 ]; 1108 std::snprintf (buf ,sizeof buf ,"%s slice %d: batch epoch %u, %u of %u claimed, %u done, %u parked, %d threads" , 1109k == 0 ?" [" :";" ,k , (uint32_t ) (h >>32 ), (uint32_t )h & 0xffffu , (uint32_t ) (h >>16 )& 0xffffu , 1110ns .done .load (),ns .parked .load (),slice_threads_ [(size_t )k ]); 1111s += buf ; 1112 } 1113if (numa_n_ > 0 )s += "]" ; 1114return s ; 1115} 1116 1117int ExpertPool ::numa_plan_phase (int per ,int nb ) { 1118int base = 0 ; 1119for (int k = 0 ;k < numa_n_ ;++ k ) { 1120NodeSync & ns = nsync_ [(size_t )k ]; 1121ns .row0 = per * k /numa_n_ ; 1122ns .h = per * (k + 1 ) /numa_n_ - ns .row0 ; 1123ns .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 1125const int64_t want = tasks_ == 0 ?3 * (int64_t )slice_threads_ [(size_t )k ] : (int64_t ) (std::max )(1 ,tasks_ /2 ); 1126ns .tasks = (int ) (std::min )(want ,ns .rows ); 1127ns .base = base ; 1128base += ns .tasks ; 1129 } 1130return base ; 1131} 1132 1133uint32_t ExpertPool ::begin_batch (int n ) { 1134if (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. 1140const uint32_t e = epoch_ .load (std::memory_order_relaxed )+ 1 ;// only the host bumps the epoch 1141if (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) 1144for (int k = 0 ;k < numa_n_ ;++ k ) { 1145NodeSync & ns = nsync_ [(size_t )k ]; 1146ns .done .store (0 , std::memory_order_relaxed ); 1147ns .drained_ns .store (0 , std::memory_order_relaxed ); 1148ns .head .store (pack_head (e , (uint32_t )ns .tasks ,0 ), std::memory_order_release ); 1149 } 1150pub_ns_ = now_ns (); 1151 }else { 1152done_ .store (0 , std::memory_order_relaxed ); 1153head_ .store (pack_head (e , (uint32_t )n ,0 ), std::memory_order_release ); 1154 } 1155publish (); 1156return e ; 1157} 1158 1159void ExpertPool ::wait_parked (const char * what ) { 1160hstate_ .store (kWaitParked , std::memory_order_relaxed ); 1161hstate_ms_ .store (now_ms (), std::memory_order_relaxed ); 1162uint32_t spins = 0 ; 1163 std::chrono::steady_clock::time_point t0 {}; 1164while (parked_count ()!= (uint32_t )n_ ) { 1165strata_cpu_pause (); 1166if ((++ spins & 1023u )!= 0 )continue ; 1167const auto now = std::chrono::steady_clock::now (); 1168if (spins == 1024u )t0 = now ; 1169else 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" , 1172what ,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 ) { 1181hstate_ .store (kWaitDone , std::memory_order_relaxed ); 1182hstate_ms_ .store (now_ms (), std::memory_order_relaxed ); 1183uint32_t spins = 0 ,seen = 0 ; 1184 std::chrono::steady_clock::time_point t0 {}; 1185for (;;) { 1186uint32_t d = 0 ; 1187if (numa_phase ())// the slices' counts, each bounded by its tasks: the sum is n only when every slice is done 1188for (int k = 0 ;k < numa_n_ ;++ k )d += nsync_ [(size_t )k ].done .load (std::memory_order_acquire ); 1189else 1190d = done_ .load (std::memory_order_acquire ); 1191if (d >= (uint32_t )n ) { 1192static std::atomic < int64_t > s_tw {0 }; 1193const int64_t tw = s_tw .fetch_add (1 , std::memory_order_relaxed ); 1194if (std::getenv ("STRATA_DIAG_A" )!= nullptr && tw %48 == 0 ) { 1195double lo = 1e18 ,hi = -1e18 ;int lo_id = -1 ,hi_id = -1 ,cnt = 0 ; 1196for (int k = 0 ;k < n_ && k < 64 ;++ k ) { 1197if (tail_fin_ [k ] <=0 )continue ; 1198if (tail_fin_ [k ]< lo ) {lo = tail_fin_ [k ];lo_id = k ; } 1199if (tail_fin_ [k ]> hi ) {hi = tail_fin_ [k ];hi_id = k ; } 1200++ cnt ; 1201 } 1202if (cnt > 1 ) 1203 std::fprintf (stderr ,"PROBETAIL mode=%d n=%d last=w%d spread=%.1f us (first w%d of %d)\n" , 1204mode_ ,n ,hi_id , (hi - lo ) /1000.0 ,lo_id ,cnt ); 1205 } 1206return ; 1207 }// `>=`: never a wait that an overshoot outlives 1208strata_cpu_pause (); 1209if ((++ spins & 1023u )!= 0 )continue ; 1210const auto now = std::chrono::steady_clock::now (); 1211if (spins == 1024u || d != seen ) {t0 = now ;seen = d ; }// progress restarts the clock 1212else 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" , 1215d ,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 ) { 1224const int s = numa_n_ == 0 ?0 :id >=0 ?wslice_ [(size_t )id ] :hslice_ ; 1225for (;;) { 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) 1228int ci = numa_n_ > 0 ?claim_slice (epoch ,s ) :-1 ; 1229const bool sliced = ci >=0 ; 1230if (!sliced )ci = claim (epoch ); 1231if (ci < 0 ) { 1232if (id >=0 && id < 64 ) {// PROBE-TAIL: this worker's last task of the phase 1233if (tail_ep_ [id ]!= (uint64_t )epoch ) { 1234tail_ep_ [id ]= (uint64_t )epoch ; 1235tail_fin_ [id ]= (double )now_ns (); 1236 } 1237 } 1238break ; 1239 } 1240const uint32_t i = (uint32_t )ci ; 1241if (id >=0 )wstate_ [(size_t )id ].store (ci , std::memory_order_relaxed ); 1242else {hstate_ .store (ci , std::memory_order_relaxed );hstate_ms_ .store (now_ms (), std::memory_order_relaxed ); } 1243if (mode_ == 0 ) { 1244const ExpertJob & j = jobs_ [i ]; 1245s2_expert_vnni_q (j .blob ,* j .act ,j .out ,scratch ); 1246 }else if (mode_ == 1 ) { 1247const int e = (int )i /parts_a_ ,part = (int )i %parts_a_ ; 1248const int r0 = FF * part /parts_a_ ,r1 = FF * (part + 1 ) /parts_a_ ; 1249s2_expert_gu_rows (jobs_ [e ].blob ,* jobs_ [e ].act ,split_ [(size_t )e ].ff ,r0 ,r1 ); 1250 }else if (mode_ == 2 ) { 1251const int e = (int )i /parts_b_ ,part = (int )i %parts_b_ ; 1252const int r0 = H * part /parts_b_ ,r1 = H * (part + 1 ) /parts_b_ ; 1253s2_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). 1258const int64_t R = mrows_ ,T = mtasks_ ; 1259const int64_t g0 = R * (int64_t )i /T ,g1 = R * (int64_t ) (i + 1 ) /T ; 1260int64_t base = 0 ; 1261for (int m = 0 ;m < lmv_n_ && base < g1 ;++ m ) { 1262const LatentMatvec & mv = lmv_ [m ]; 1263if (base + mv .nrows > g0 ) { 1264const int r0 = (int ) std::max < int64_t > (g0 - base ,0 ); 1265const 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. 1268const bool lat_q4 = mv .row_bytes == (size_t ) (mv .ncols /32 )* 18 ; 1269if (lat_q4 ) { 1270if (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 , 1272mv .out ,r0 ,r1 ); 1273else 1274for (int r = r0 ;r < r1 ;++ r ) { 1275const uint8_t * row = mv .w + (size_t )r * mv .row_bytes ; 1276for (int t = 0 ;t < mv .nt ;++ t ) 1277mv .out [t ][r ]= lat_q4_0_q8_1_row (row , (const uint8_t * )mv .act [t ],mv .ncols ); 1278 } 1279 }else 1280if (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 , 1282mv .out ,r0 ,r1 ); 1283else 1284for (int r = r0 ;r < r1 ;++ r ) { 1285const uint8_t * row = mv .w + (size_t )r * mv .row_bytes ; 1286for (int t = 0 ;t < mv .nt ;++ t ) 1287mv .out [t ][r ]= lat_q8_0_q8_1_row (row , (const uint8_t * )mv .act [t ],mv .ncols ); 1288 } 1289 } 1290base += 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) 1298const int per = mode_ == 5 ? (int )nfmt_ -> n_ff : (int )nfmt_ -> n_embd ; 1299int64_t R = mrows_ ,T = mtasks_ ,j = i ; 1300int h = per ,row0 = 0 ; 1301if (sliced ) { 1302const NodeSync & ns = nsync_ [(size_t )s ]; 1303R = ns .rows ;T = ns .tasks ;h = ns .h ;row0 = ns .row0 ;j = ci - ns .base ; 1304 } 1305const int64_t g0 = R * j /T ,g1 = R * (j + 1 ) /T ; 1306for (int64_t g = g0 ;g < g1 ;) { 1307const int e = (int ) (g /h ),l0 = (int ) (g %h ); 1308const int l1 = (int ) std::min < int64_t > (h ,l0 + (g1 - g )); 1309const int r0 = row0 + l0 ,r1 = row0 + l1 ; 1310SplitBufMulti & sb = split_multi_ [(size_t )e ]; 1311const NativeFmt * const nfmt = mjobs_ [e ].fmt != nullptr ?mjobs_ [e ].fmt :nfmt_ ;// 149-cold: same types and rows 1312if (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_localfloat gbuf [MAXT ][FF ],ubuf [MAXT ][FF ]; 1315float * gp [MAXT ]; 1316float * up [MAXT ]; 1317for (int t = 0 ;t < mjobs_ [e ].nt ;++ t ) {gp [t ]= gbuf [t ];up [t ]= ubuf [t ]; } 1318const int nbk = (int ) (nfmt -> n_embd /64 ); 1319q2_rows_any (mjobs_ [e ].blob ,nfmt -> gu_row ,nbk ,mjobs_ [e ].act ,mjobs_ [e ].nt ,gp ,r0 ,r1 ); 1320q2_rows_any (mjobs_ [e ].blob + nfmt -> up_off ,nfmt -> gu_row ,nbk ,mjobs_ [e ].act ,mjobs_ [e ].nt ,up ,r0 ,r1 ); 1321for (int t = 0 ;t < mjobs_ [e ].nt ;++ t ) 1322for (int r = r0 ;r < r1 ;++ r ) 1323sb .ff [t ][r ]= (gbuf [t ][r ] / (1.f + std::exp (- gbuf [t ][r ])))* ubuf [t ][r ]; 1324 }else if (mode_ == 5 ) { 1325float * ff [MAXT ]; 1326for (int t = 0 ;t < mjobs_ [e ].nt ;++ t )ff [t ]= sb .ff [t ]; 1327if (narithmetic_ == NativeArithmetic ::WindowInvariant ) 1328native_gu_rows_invariant (* nfmt ,mjobs_ [e ].blob ,mjobs_ [e ].nact ,mjobs_ [e ].nt ,ff ,r0 ,r1 ); 1329else 1330native_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 1333const ActQ * a2 [MAXT ]; 1334for (int t = 0 ;t < mjobs_ [e ].nt ;++ t )a2 [t ]= & sb .a2 [t ]; 1335q2_rows_any (mjobs_ [e ].blob + nfmt -> down_off ,nfmt -> d_row , (int ) (nfmt -> n_ff /64 ),a2 , 1336mjobs_ [e ].nt ,mjobs_ [e ].out ,r0 ,r1 ); 1337 }else { 1338const void * hq [MAXT ]; 1339for (int t = 0 ;t < mjobs_ [e ].nt ;++ t )hq [t ]= sb .hq [t ]; 1340if (narithmetic_ == NativeArithmetic ::WindowInvariant ) 1341native_down_rows_invariant (* nfmt ,mjobs_ [e ].blob ,hq ,mjobs_ [e ].nt ,mjobs_ [e ].out ,r0 ,r1 ); 1342else 1343native_down_rows (* nfmt ,mjobs_ [e ].blob ,hq ,mjobs_ [e ].nt ,mjobs_ [e ].out ,r0 ,r1 ); 1344 } 1345g += 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) 1349const int per = mode_ == 3 ?FF :H ; 1350const int64_t g0 = mrows_ * (int64_t )i /mtasks_ ,g1 = mrows_ * (int64_t ) (i + 1 ) /mtasks_ ; 1351for (int64_t r = g0 ;r < g1 ;) { 1352const int e = (int ) (r /per ),r0 = (int ) (r %per ); 1353const int r1 = (int ) std::min < int64_t > (per ,r0 + (g1 - r )); 1354SplitBufMulti & sb = split_multi_ [(size_t )e ]; 1355if (mode_ == 3 ) { 1356float * ff [MAXT ]; 1357for (int t = 0 ;t < mjobs_ [e ].nt ;++ t )ff [t ]= sb .ff [t ]; 1358s2_expert_gu_rows_multi (mjobs_ [e ].blob ,mjobs_ [e ].act ,mjobs_ [e ].nt ,ff ,r0 ,r1 ); 1359 }else { 1360const ActQ * a2 [MAXT ]; 1361for (int t = 0 ;t < mjobs_ [e ].nt ;++ t )a2 [t ]= & sb .a2 [t ]; 1362s2_expert_down_rows_multi (mjobs_ [e ].blob ,a2 ,mjobs_ [e ].nt ,mjobs_ [e ].out ,r0 ,r1 ); 1363 } 1364r += r1 - r0 ; 1365 } 1366 } 1367if (sliced ) { 1368NodeSync & ns = nsync_ [(size_t )s ]; 1369const 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 1371if (ns .done .fetch_add (1 , std::memory_order_release )+ 1 == t ) 1372ns .drained_ns .store (now_ns (), std::memory_order_relaxed ); 1373 }else { 1374done_ .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 1381static std::atomic < double > s_pb [8 ]{},s_bb [8 ]{},s_hd [8 ]{},s_wd [8 ]{},s_pa [8 ]{}; 1382static std::atomic < int64_t > s_pn [8 ]{}; 1383const auto _p0 = std::chrono::steady_clock::now (); 1384wait_parked ("before a phase" ); 1385const auto _p1 = std::chrono::steady_clock::now (); 1386mode_ = mode ; 1387njobs_ = n_tasks ; 1388const uint32_t e = begin_batch (n_tasks ); 1389const auto _p2 = std::chrono::steady_clock::now (); 1390if (host_works_ )drain (-1 ,host_scratch_ ,e ); 1391const auto _p3 = std::chrono::steady_clock::now (); 1392wait_done (n_tasks ); 1393const auto _p4 = std::chrono::steady_clock::now (); 1394wait_parked ("after a phase" ); 1395const auto _p5 = std::chrono::steady_clock::now (); 1396const int mi = mode ; 1397s_pb [mi ].fetch_add (std::chrono::duration < double , std::milli > (_p1 - _p0 ).count (), std::memory_order_relaxed ); 1398s_bb [mi ].fetch_add (std::chrono::duration < double , std::milli > (_p2 - _p1 ).count (), std::memory_order_relaxed ); 1399s_hd [mi ].fetch_add (std::chrono::duration < double , std::milli > (_p3 - _p2 ).count (), std::memory_order_relaxed ); 1400s_wd [mi ].fetch_add (std::chrono::duration < double , std::milli > (_p4 - _p3 ).count (), std::memory_order_relaxed ); 1401s_pa [mi ].fetch_add (std::chrono::duration < double , std::milli > (_p5 - _p4 ).count (), std::memory_order_relaxed ); 1402s_pn [mi ].fetch_add (1 , std::memory_order_relaxed ); 1403static std::atomic < int64_t > s_total {0 }; 1404const int64_t tot = s_total .fetch_add (1 , std::memory_order_relaxed ); 1405if (std::getenv ("STRATA_DIAG_A" )!= nullptr && tot %288 == 0 ) { 1406 std::fprintf (stderr ,"PROBEPH per-mode ms/phase (parkB begin hostDrain waitDone parkA):\n" ); 1407for (int m = 0 ;m < 8 ;++ m ) { 1408const int64_t c = s_pn [m ].load (); 1409if (c == 0 )continue ; 1410 std::fprintf (stderr ," mode %d: parkB %.3f begin %.3f hostDrain %.3f waitDone %.3f parkA %.3f (n %lld)\n" , 1411m ,s_pb [m ].load () / (double )c ,s_bb [m ].load () / (double )c ,s_hd [m ].load () / (double )c , 1412s_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`. 1418if (numa_phase ()) 1419for (int k = 0 ;k < numa_n_ ;++ k ) { 1420const int64_t t = nsync_ [(size_t )k ].drained_ns .load (std::memory_order_acquire ); 1421if (t != 0 )slice_ms_ [k ]+= (double ) (t - pub_ns_ ) /1e6 ; 1422 } 1423hstate_ .store (kIdle , std::memory_order_relaxed ); 1424hstate_ms_ .store (now_ms (), std::memory_order_relaxed ); 1425} 1426 1427void ExpertPool ::run_split (ExpertJob * jobs ,int n ) { 1428if (n <=0 )return ; 1429if (n > kMaxSplit || n_ == 1 || expert_oracle_q8_0_enabled ()) {run (jobs ,n );return ; } 1430const auto t0 = std::chrono::steady_clock::now (); 1431jobs_ = jobs ; 1432const int threads = n_ + (host_works_ ?1 :0 ); 1433// about three tasks per thread in each phase, so the tail is short 1434parts_a_ = (std::max )(1 , (3 * threads + n - 1 ) /n ); 1435parts_b_ = parts_a_ ; 1436run_phase (1 ,n * parts_a_ ); 1437for (int e = 0 ;e < n ;++ e )act_quant_q8_1 (split_ [(size_t )e ].ff ,FF ,split_ [(size_t )e ].a2 ); 1438run_phase (2 ,n * parts_b_ ); 1439mode_ = 0 ; 1440ms_drain_ += std::chrono::duration < double , std::milli > (std::chrono::steady_clock::now ()- t0 ).count (); 1441} 1442 1443int ExpertPool ::phase_tasks (int64_t rows )const { 1444return 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 ) { 1448if (n <=0 )return ; 1449if (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 ; 1452for (int e = 0 ;e < n ;++ e ) 1453for (int t = 0 ;t < jobs [e ].nt ;++ t ) { 1454ExpertJob j ; 1455j .blob = jobs [e ].blob ; 1456j .act = jobs [e ].act [t ]; 1457j .out = jobs [e ].out [t ]; 1458single .push_back (j ); 1459 } 1460for (size_t i = 0 ;i < single .size ();i += kMaxSplit ) 1461run_split (single .data ()+ i , (int ) (std::min )((size_t )kMaxSplit ,single .size ()- i )); 1462return ; 1463 } 1464const auto t0 = std::chrono::steady_clock::now (); 1465mjobs_ = jobs ; 1466mrows_ = (int64_t )n * FF ; 1467mtasks_ = phase_tasks (mrows_ ); 1468run_phase (3 ,mtasks_ ); 1469const auto t1 = std::chrono::steady_clock::now (); 1470for (int e = 0 ;e < n ;++ e ) 1471for (int t = 0 ;t < jobs [e ].nt ;++ t ) 1472act_quant_q8_1 (split_multi_ [(size_t )e ].ff [t ],FF ,split_multi_ [(size_t )e ].a2 [t ]); 1473const auto t2 = std::chrono::steady_clock::now (); 1474mrows_ = (int64_t )n * H ; 1475mtasks_ = phase_tasks (mrows_ ); 1476run_phase (4 ,mtasks_ ); 1477const auto t3 = std::chrono::steady_clock::now (); 1478ms_multi_gu += std::chrono::duration < double , std::milli > (t1 - t0 ).count (); 1479ms_multi_q += std::chrono::duration < double , std::milli > (t2 - t1 ).count (); 1480ms_multi_down += std::chrono::duration < double , std::milli > (t3 - t2 ).count (); 1481multi_bytes += (int64_t )n * (int64_t )BLOB ; 1482mode_ = 0 ; 1483ms_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 ) { 1487if (n <=0 )return ; 1488const auto t0 = std::chrono::steady_clock::now (); 1489const bool diag_a = std::getenv ("STRATA_DIAG_A" )!= nullptr ; 1490// more distinct experts than buffers: run them in batches 1491for (int b0 = 0 ;b0 < n ;b0 += kMaxSplitMulti ) { 1492const int nb = (std::min )(kMaxSplitMulti ,n - b0 ); 1493mjobs_ = jobs + b0 ; 1494nfmt_ = & f ; 1495narithmetic_ = arithmetic ; 1496mrows_ = (int64_t )nb * f .n_ff ; 1497mtasks_ = numa_n_ > 0 ?numa_plan_phase ((int )f .n_ff ,nb ) :phase_tasks (mrows_ ); 1498const int diag_rows = (int )mrows_ ,diag_tasks = mtasks_ ;// DIAGA: the split before run 1499const auto a = std::chrono::steady_clock::now (); 1500run_phase (5 ,mtasks_ ); 1501const auto b = std::chrono::steady_clock::now (); 1502if (diag_a ) 1503 std::fprintf (stderr ,"DIAGA phase5: jobs=%d n_ff=%lld rows=%d tasks=%d wall=%.3f ms\n" , 1504nb , (long long )f .n_ff ,diag_rows ,diag_tasks , 1505 std::chrono::duration < double , std::milli > (b - a ).count ()); 1506for (int e = 0 ;e < nb ;++ e ) 1507for (int t = 0 ;t < mjobs_ [e ].nt ;++ t ) 1508if (q2_native_kernels (f .d_type ))act_quant_any (split_multi_ [(size_t )e ].ff [t ],FF ,split_multi_ [(size_t )e ].a2 [t ]); 1509else native_quant_h (f ,split_multi_ [(size_t )e ].ff [t ],split_multi_ [(size_t )e ].hq [t ]); 1510const auto c = std::chrono::steady_clock::now (); 1511if (diag_a ) 1512 std::fprintf (stderr ,"DIAGA quant: jobs=%d entries=%d wall=%.3f ms\n" , 1513nb , (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 ()); 1515mrows_ = (int64_t )nb * f .n_embd ; 1516mtasks_ = numa_n_ > 0 ?numa_plan_phase ((int )f .n_embd ,nb ) :phase_tasks (mrows_ ); 1517run_phase (6 ,mtasks_ ); 1518const auto d = std::chrono::steady_clock::now (); 1519if (diag_a ) 1520 std::fprintf (stderr ,"DIAGA phase6: jobs=%d n_embd=%lld rows=%d tasks=%d wall=%.3f ms\n" , 1521nb , (long long )f .n_embd , (int )mrows_ , (int )mtasks_ , 1522 std::chrono::duration < double , std::milli > (d - c ).count ()); 1523ms_multi_gu += std::chrono::duration < double , std::milli > (b - a ).count (); 1524ms_multi_q += std::chrono::duration < double , std::milli > (c - b ).count (); 1525ms_multi_down += std::chrono::duration < double , std::milli > (d - c ).count (); 1526 } 1527multi_bytes += (int64_t )n * (int64_t )f .bytes ; 1528mode_ = 0 ; 1529ms_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 ) { 1533if (n <=0 )return ; 1534const auto t0 = std::chrono::steady_clock::now (); 1535const bool diag_a = std::getenv ("STRATA_DIAG_A" )!= nullptr ; 1536int64_t rows = 0 ,bytes = 0 ; 1537for (int m = 0 ;m < n ;++ m ) {rows += mv [m ].nrows ;bytes += (int64_t )mv [m ].row_bytes * mv [m ].nrows ; } 1538lmv_ = mv ; 1539lmv_n_ = n ; 1540mrows_ = rows ; 1541mtasks_ = phase_tasks (rows ); 1542run_phase (7 ,mtasks_ ); 1543mode_ = 0 ; 1544const double wall = std::chrono::duration < double , std::milli > (std::chrono::steady_clock::now ()- t0 ).count (); 1545if (diag_a ) 1546 std::fprintf (stderr ,"DIAGU groups=%d rows=%lld tasks=%d bytes=%lld wall=%.3f ms = %.1f GB/s\n" , 1547n , (long long )rows ,mtasks_ , (long long )bytes ,wall , (double )bytes /wall /1e6 ); 1548ms_drain_ += wall ; 1549} 1550 1551void ExpertPool ::run (ExpertJob * jobs ,int n ) { 1552if (n <=0 )return ; 1553if (n_ == 1 ) {// no workers: run inline, so a single-core machine still produces a token 1554for (int i = 0 ;i < n ;++ i )s2_expert_vnni_q (jobs [i ].blob ,* jobs [i ].act ,jobs [i ].out ,scratch_ [0 ]); 1555return ; 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. 1562const auto t_a = std::chrono::steady_clock::now (); 1563wait_parked ("before a batch" ); 1564const auto t_b = std::chrono::steady_clock::now (); 1565jobs_ = jobs ; 1566njobs_ = n ; 1567mode_ = 0 ; 1568const 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. 1584if (host_works_ ) { 1585for (;;) { 1586const int ci = claim (e ); 1587if (ci < 0 )break ; 1588hstate_ .store (ci , std::memory_order_relaxed ); 1589hstate_ms_ .store (now_ms (), std::memory_order_relaxed ); 1590const ExpertJob & j = jobs_ [ci ]; 1591s2_expert_vnni_q (j .blob ,* j .act ,j .out ,host_scratch_ ); 1592done_ .fetch_add (1 , std::memory_order_release ); 1593 } 1594 } 1595 1596wait_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. 1599const auto t_c = std::chrono::steady_clock::now (); 1600wait_parked ("after a batch" ); 1601hstate_ .store (kIdle , std::memory_order_relaxed ); 1602hstate_ms_ .store (now_ms (), std::memory_order_relaxed ); 1603const auto t_d = std::chrono::steady_clock::now (); 1604 1605ms_wait_park_ += std::chrono::duration < double , std::milli > (t_b - t_a ).count (); 1606ms_drain_ += std::chrono::duration < double , std::milli > (t_c - t_b ).count (); 1607ms_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 ) { 1617char name [64 ]; 1618if (index >=0 ) std::snprintf (name ,sizeof name ,"%s-%d" ,base ,index ); 1619else std::snprintf (name ,sizeof name ,"%s" ,base ); 1620using SetDesc = HRESULT (WINAPI * )(HANDLE ,PCWSTR ); 1621static const SetDesc fn = (SetDesc )GetProcAddress (GetModuleHandleW (L"kernel32.dll" ),"SetThreadDescription" ); 1622if (fn == nullptr )return ; 1623wchar_t wide [64 ]; 1624int i = 0 ; 1625for (;name [i ]!= '\0' && i < 63 ;++ i )wide [i ]= (wchar_t ) (unsigned char )name [i ]; 1626wide [i ]= L'\0' ; 1627 (void )fn (GetCurrentThread (),wide ); 1628} 1629}// namespace strata::platform 1630#endif