diff --git a/setup.py b/setup.py index bc5cdd30..c59245ee 100644 --- a/setup.py +++ b/setup.py @@ -297,6 +297,70 @@ def page_file_gb(): return max(0.0, (m.ullTotalPageFile - m.ullTotalPhys) / 2**30) +def cpu_cores(): + """#642: (performance cores, efficiency cores) of a hybrid CPU (Intel 12th gen+, AMD Zen 5 + Zen 5c), counted + as the engine's pool counts them (detect_cpu_topology: physical cores, by Windows' EfficiencyClass or Linux's + cpu_capacity); None on a CPU whose cores are all alike, or when the OS does not say.""" + classes = [] # one entry per physical core: its efficiency/capacity class + try: + if WIN: + k32 = ctypes.windll.kernel32 + n = ctypes.c_ulong(0) + k32.GetLogicalProcessorInformationEx(0, None, ctypes.byref(n)) # RelationProcessorCore: the size + if not n.value: + return None + buf = ctypes.create_string_buffer(n.value) + if not k32.GetLogicalProcessorInformationEx(0, buf, ctypes.byref(n)): + return None + raw, at = buf.raw[:n.value], 0 + while at + 10 <= len(raw): # SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX: Relationship, Size, then + rel, size = struct.unpack_from(" int | None: + """#642 (Hardin22's measurement): on a hybrid CPU the expert pool runs best on the P-cores but the host loop's one + plus HALF of the E-cores - an E-core runs the expert kernels ~2.2x slower and each layer waits for its slowest + part (i9-14900KF, 8P + 16E: 15 workers decoded 165 / 116 tok/s against 106 / 84 with all 23). None: not hybrid + (the engine's own default, one worker per physical core but the host's, stays).""" + if not cores: + return None + p, e = cores + return max(1, p - 1 + e // 2) + + +def recommend_pool_workers(args: list) -> list: + """`args` with setup's recommended `--pool-workers` for a hybrid CPU, unless they set one already (a calibration's + measured count, or the user's own). A recommendation: the config line can be edited or removed.""" + n = hybrid_pool_workers(cpu_cores()) + if n is None or "--pool-workers" in args: + return args + p, e = cpu_cores() + ok(f"hybrid CPU ({p} performance + {e} efficiency cores): {n} CPU expert workers - the performance cores and half " + "of the efficiency cores (--pool-workers in the config; START-HERE --calibrate measures it on this PC)") + return [*args, "--pool-workers", str(n)] + + def cpu_info(): """(name, avx2, avx512): avx512 means everything Strata's fast AVX-512 kernels use (F, BW, VL, VNNI, VBMI), the same test the engine makes (cpu_avx512_ok), not just AVX-512F.""" @@ -3664,6 +3728,8 @@ def main() -> int: import calibrate as CAL cfg["args"] = CAL.apply(cfg["args"], cal.get("settings") or {}) ok("the settings tuned for this PC earlier are used" + (f" ({cal['date']})" if cal.get("date") else "")) + else: # #642: measured counts (a calibration) win over the rule + cfg["args"] = recommend_pool_workers(cfg["args"]) write_config(cfg_path, cfg) script = write_run_script(tag, cfg_path, port) # offered only when someone answers: --yes installs and adopted earlier installs are not held up by it diff --git a/src/kernels/cpu/pool.cpp b/src/kernels/cpu/pool.cpp index 45e43470..1919d2e9 100644 --- a/src/kernels/cpu/pool.cpp +++ b/src/kernels/cpu/pool.cpp @@ -95,6 +95,12 @@ CpuTopology detect_cpu_topology(bool skip_first, PoolAffinity affinity) { } if (affinity == PoolAffinity::All || !topo.is_hybrid) { + // #642 (from Hardin22's fork): on a hybrid CPU the P-cores first (the host takes the first of them), so a + // pool smaller than the core count (setup's --pool-workers for a hybrid CPU) runs on the P-cores and the + // first E-cores rather than on whatever the OS numbered first. All cores alike: the order is unchanged. + if (topo.is_hybrid) + std::stable_sort(descs.begin(), descs.end(), + [](const CoreDesc& x, const CoreDesc& y) { return x.efficiency > y.efficiency; }); for (const auto& c : descs) topo.worker_cores.push_back(c.lps[0]); if (skip_first && !topo.worker_cores.empty()) { topo.host_core = topo.worker_cores.front(); @@ -219,6 +225,9 @@ CpuTopology detect_cpu_topology(bool skip_first, PoolAffinity affinity) { } if (affinity == PoolAffinity::All || !topo.is_hybrid) { + if (topo.is_hybrid) // #642: the P-cores first (see the Windows branch) + std::stable_sort(all_cpus.begin(), all_cpus.end(), + [](const CoreLinux& x, const CoreLinux& y) { return x.cap > y.cap; }); for (const auto& cl : all_cpus) { if (!cl.is_sibling) topo.worker_cores.push_back(cl.cpu); } diff --git a/tools/test_setup_golden.py b/tools/test_setup_golden.py index 054c1c14..08f75a16 100644 --- a/tools/test_setup_golden.py +++ b/tools/test_setup_golden.py @@ -100,6 +100,7 @@ def install(ram, found, argv, answers=None, extra=(), avx512=False, configs=()): mock.patch.object(setup, "amd_gpus", lambda: []), mock.patch.object(setup, "ram_gb", lambda: ram), mock.patch.object(setup, "cpu_info", lambda: ("Test CPU", True, avx512)), + mock.patch.object(setup, "cpu_cores", lambda: None), # #642: not a hybrid CPU mock.patch.object(setup, "page_file_gb", lambda: 16.0), mock.patch.object(setup, "is_wsl", lambda: False), mock.patch.object(setup, "free_gb", lambda p: 900.0), diff --git a/tools/test_setup_hybrid.py b/tools/test_setup_hybrid.py new file mode 100644 index 00000000..b07d2e3c --- /dev/null +++ b/tools/test_setup_hybrid.py @@ -0,0 +1,64 @@ +"""#642: setup recommends the expert pool's worker count on a hybrid CPU (the P-cores but the host loop's one, plus +half of the E-cores) and writes nothing new anywhere else; a calibration's measured count wins over the rule. + + python -m unittest tools.test_setup_hybrid +""" +from __future__ import annotations + +import sys +import unittest +from pathlib import Path +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) +sys.path.insert(0, str(ROOT / "tools")) +import setup # noqa: E402 +from test_setup_golden import PROFILES, install # noqa: E402 + + +class HybridWorkers(unittest.TestCase): + def test_rule(self): + self.assertIsNone(setup.hybrid_pool_workers(None)) + self.assertEqual(setup.hybrid_pool_workers((8, 16)), 15) # i9-14900K: the fork's measured 15 + self.assertEqual(setup.hybrid_pool_workers((6, 8)), 9) # i5-13600K + self.assertEqual(setup.hybrid_pool_workers((4, 8)), 7) # Ryzen AI 9 HX 370 (Zen 5 + Zen 5c) + self.assertEqual(setup.hybrid_pool_workers((1, 1)), 1) + + def test_recommend_keeps_a_given_count(self): + with mock.patch.object(setup, "cpu_cores", lambda: (8, 16)), mock.patch.object(setup, "ok", lambda *a: None): + self.assertEqual(setup.recommend_pool_workers(["--spec", "4"]), ["--spec", "4", "--pool-workers", "15"]) + given = ["--pool-workers", "12"] + self.assertEqual(setup.recommend_pool_workers(given), given) + with mock.patch.object(setup, "cpu_cores", lambda: None): + self.assertEqual(setup.recommend_pool_workers(["--spec", "4"]), ["--spec", "4"]) + + def test_install_on_a_hybrid_cpu(self): + ram, found = PROFILES["96GB-1x16GB"] + hybrid = [mock.patch.object(setup, "cpu_cores", lambda: (8, 16))] + code, text, cfg, _ = install(ram, found, ["--family", "qwen", "--no-start", "--model", "Q2_0"], extra=hybrid) + self.assertEqual(code, 0, text) + a = cfg["args"] + self.assertEqual(a[a.index("--pool-workers") + 1], "15") + self.assertIn("hybrid CPU (8 performance + 16 efficiency cores)", text) + # the same PC without the hybrid CPU: the config is the one it always was (no --pool-workers) + code, text, plain, _ = install(ram, found, ["--family", "qwen", "--no-start", "--model", "Q2_0"]) + self.assertEqual(code, 0, text) + self.assertNotIn("--pool-workers", plain["args"]) + i = a.index("--pool-workers") + self.assertEqual(a[:i] + a[i + 2:], plain["args"]) + + def test_calibration_wins(self): + ram, found = PROFILES["96GB-1x16GB"] + cal = {"settings": {"--pool-workers": "11"}, "date": "2026-10-03"} + extra = [mock.patch.object(setup, "cpu_cores", lambda: (8, 16)), + mock.patch.object(setup, "saved_calibration", lambda cfg: cal)] + code, text, cfg, _ = install(ram, found, ["--family", "qwen", "--no-start", "--model", "Q2_0"], extra=extra) + self.assertEqual(code, 0, text) + a = cfg["args"] + self.assertEqual(a[a.index("--pool-workers") + 1], "11") + self.assertEqual(a.count("--pool-workers"), 1) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/test_setup_unsloth.py b/tools/test_setup_unsloth.py index a010b5e8..c489497c 100644 --- a/tools/test_setup_unsloth.py +++ b/tools/test_setup_unsloth.py @@ -164,6 +164,7 @@ class Main(unittest.TestCase): mock.patch.object(setup, "amd_gpus", lambda *a: list(amd)), mock.patch.object(setup, "ram_gb", lambda: ram), mock.patch.object(setup, "cpu_info", lambda: ("Test CPU", True, True)), + mock.patch.object(setup, "cpu_cores", lambda: None), # #642: not a hybrid CPU mock.patch.object(setup, "page_file_gb", lambda: 16.0), mock.patch.object(setup, "free_gb", lambda p: free), mock.patch.object(setup, "pip_install", lambda *a, **k: None),