setup: recommend P-cores + half the E-cores as CPU expert workers on hybrid CPUs (#642)

On a hybrid CPU (Intel 12th gen+, AMD Zen 5 + Zen 5c) setup writes --pool-workers
N into the run config: the performance cores but the host loop's one, plus half
of the efficiency cores. An E-core runs the expert kernels ~2.2x slower and each
layer waits for its slowest part; Hardin22 measured 15 workers at 165 / 116 tok/s
against 106 / 84 with all 23 on an i9-14900KF (#642). A recommendation only: the
line is in the config, a saved calibration's measured count wins, and a CPU whose
cores are all alike gets the same config as before.

The engine's pool, with every core allowed (the default affinity), now orders the
P-cores first on a hybrid CPU, so a smaller pool runs on the P-cores and the first
E-cores rather than on whatever the OS numbered first (from Hardin22's fork).
Non-hybrid CPUs: unchanged.

Co-Authored-By: Hardin22 <119073350+Hardin22@users.noreply.github.com>
This commit is contained in:
Niko1221andHardin22 committed 2026-10-03 18:17:18 +02:00
1 parent 09817da397
commit ad0df801ae
5 files changed
+141

No files matched your search

+66
View File
@@ -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("<II", raw, at) # PROCESSOR_RELATIONSHIP (Flags,
if size <= 0: # EfficiencyClass, ...)
break
if rel == 0:
classes.append(raw[at + 9])
at += size
else:
seen = {}
for cpu in sorted(Path("/sys/devices/system/cpu").glob("cpu[0-9]*"), key=lambda p: int(p.name[3:])):
cap = cpu / "cpu_capacity"
pkg, core = cpu / "topology" / "physical_package_id", cpu / "topology" / "core_id"
if not cap.exists():
return None
key = (pkg.read_text().strip(), core.read_text().strip()) if pkg.exists() and core.exists() else cpu.name
seen.setdefault(key, int(cap.read_text().strip()))
classes = list(seen.values())
except (OSError, ValueError, AttributeError):
return None
if not classes or max(classes) == min(classes):
return None
p = sum(1 for c in classes if c == max(classes))
return p, len(classes) - p
def hybrid_pool_workers(cores) -> 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
+9
View File
@@ -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);
}
+1
View File
@@ -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),
+64
View File
@@ -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()
+1
View File
@@ -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),