Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Fix Apple Silicon M4+ CPU frequency reported as MHz instead of GHz (#8571)

Daniel Han94cc7eeaa211
diff --git a/studio/backend/main.py b/studio/backend/main.py
index c5c5756dbf1..b28d772476a 100644
--- a/studio/backend/main.py
+++ b/studio/backend/main.py
@@ -1924,7 +1924,12 @@ def get_system_info(current_subject: str = Depends(get_current_subject)):
import os
import time
import logging
- from utils.hardware import get_device, export_capability, video_capability
+ from utils.hardware import (
+ get_device,
+ export_capability,
+ video_capability,
+ cpu_frequency_mhz,
+ )
from utils.hardware.hardware import _backend_label
logger = logging.getLogger(__name__)
@@ -1933,11 +1938,8 @@ def get_system_info(current_subject: str = Depends(get_current_subject)):
memory = psutil.virtual_memory()
- try:
- cpu_freq = psutil.cpu_freq()
- except Exception as e:
- logger.debug(f"Failed to get CPU frequency: {e}")
- cpu_freq = None
+ # Corrects psutil's 1000x-too-small Apple Silicon M4+ reading (issue #8519).
+ cpu_freq_mhz = cpu_frequency_mhz()
try:
disk = psutil.disk_usage(os.path.abspath(os.sep))
@@ -1980,9 +1982,7 @@ def get_system_info(current_subject: str = Depends(get_current_subject)):
"logical_count": psutil.cpu_count(logical = True),
"physical_count": psutil.cpu_count(logical = False),
"usage_percent": psutil.cpu_percent(interval = None),
- "frequency_mhz": round(cpu_freq.current, 2)
- if cpu_freq and cpu_freq.current is not None
- else None,
+ "frequency_mhz": cpu_freq_mhz,
},
"memory": {
"total_gb": round(memory.total / 1024**3, 2),
diff --git a/studio/backend/tests/test_apple_cpu_frequency.py b/studio/backend/tests/test_apple_cpu_frequency.py
new file mode 100644
index 00000000000..1a2a056daf7
--- /dev/null
+++ b/studio/backend/tests/test_apple_cpu_frequency.py
@@ -0,0 +1,291 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Apple Silicon CPU frequency correction (issue #8519).
+
+psutil <= 7.2.2 divides the pmgr voltage-state tables by 1e6 unconditionally, so
+on M4, where Apple switched them from Hz to kHz, it reports "4 MHz" for a 4.5 GHz
+part. cpu_frequency_mhz() re-reads the tables via ioreg, else rescales psutil.
+"""
+
+import platform
+import plistlib
+import types
+
+import pytest
+
+from utils.hardware import hardware
+
+
+def _table(freqs_raw):
+ """Build a voltage-statesN-sram blob: uint32 frequency + uint32 voltage pairs."""
+ blob = b""
+ for raw in freqs_raw:
+ blob += raw.to_bytes(4, "little") + (900).to_bytes(4, "little")
+ return blob
+
+
+# Raw values as the tables actually appear: M1-M3 in Hz, M4+ in kHz.
+_M3_PERF_TABLE = _table([702_000_000, 2_016_000_000, 4_056_000_000])
+_M4_PERF_TABLE = _table([1_050_000, 3_000_000, 4_512_000])
+_M4_EFF_TABLE = _table([1_020_000, 2_592_000])
+_GPU_TABLE = _table([444_000, 1_398_000])
+
+
[email protected](autouse = True)
+def _reset_cache():
+ hardware._apple_cpu_peak_mhz = "unprobed"
+ yield
+ hardware._apple_cpu_peak_mhz = "unprobed"
+
+
+def _fake_psutil(
+ monkeypatch,
+ current,
+ raises = False,
+):
+ def cpu_freq():
+ if raises:
+ raise RuntimeError("no frequency support")
+ if current is None:
+ return None
+ return types.SimpleNamespace(current = current, min = 0.0, max = current)
+
+ monkeypatch.setitem(
+ __import__("sys").modules, "psutil", types.SimpleNamespace(cpu_freq = cpu_freq)
+ )
+
+
+def _fake_ioreg(monkeypatch, entries):
+ def run(cmd, **kwargs):
+ assert cmd[0] == "ioreg"
+ return types.SimpleNamespace(stdout = plistlib.dumps(entries), returncode = 0)
+
+ monkeypatch.setattr(hardware.subprocess, "run", run)
+
+
+class TestVoltageStateFreqs:
+ def test_hz_table_m3(self):
+ assert hardware._voltage_state_freqs_mhz(_M3_PERF_TABLE) == [702.0, 2016.0, 4056.0]
+
+ def test_khz_table_m4(self):
+ assert hardware._voltage_state_freqs_mhz(_M4_PERF_TABLE) == [1050.0, 3000.0, 4512.0]
+
+ def test_skips_zero_and_implausible_entries(self):
+ blob = _table([0, 1, 4_512_000, 90_000_000])
+ assert hardware._voltage_state_freqs_mhz(blob) == [4512.0]
+
+ def test_truncated_trailing_bytes_ignored(self):
+ assert hardware._voltage_state_freqs_mhz(_M4_PERF_TABLE + b"\x01\x02\x03") == [
+ 1050.0,
+ 3000.0,
+ 4512.0,
+ ]
+
+ def test_empty(self):
+ assert hardware._voltage_state_freqs_mhz(b"") == []
+
+
+class TestPeakFromIoregEntries:
+ def test_picks_highest_cpu_cluster(self):
+ entries = [
+ {
+ "IOObjectClass": "AppleARMIODevice",
+ "voltage-states1-sram": _M4_EFF_TABLE,
+ "voltage-states5-sram": _M4_PERF_TABLE,
+ }
+ ]
+ assert hardware._peak_cpu_mhz_from_ioreg_entries(entries) == 4512.0
+
+ def test_ignores_gpu_rails(self):
+ entries = [{"voltage-states2-sram": _GPU_TABLE}]
+ assert hardware._peak_cpu_mhz_from_ioreg_entries(entries) is None
+
+ def test_ignores_unrelated_keys_and_types(self):
+ entries = [
+ {"voltage-states5": _M4_PERF_TABLE, "IORegistryEntryName": "pmgr"},
+ "not-a-dict",
+ ]
+ assert hardware._peak_cpu_mhz_from_ioreg_entries(entries) is None
+
+ def test_renumbered_tables_still_found(self):
+ # M5 renumbered the table indexes; classification is by peak, not index.
+ entries = [{"voltage-states13-sram": _M4_PERF_TABLE}]
+ assert hardware._peak_cpu_mhz_from_ioreg_entries(entries) == 4512.0
+
+
+class TestCpuFrequencyMhz:
+ def test_non_apple_value_passes_through(self, monkeypatch):
+ monkeypatch.setattr(hardware, "is_apple_silicon", lambda: False)
+ _fake_psutil(monkeypatch, 3600.0)
+ assert hardware.cpu_frequency_mhz() == 3600.0
+
+ def test_non_apple_low_value_is_not_rescaled(self, monkeypatch):
+ # A container reporting a genuinely low clock must not be multiplied.
+ monkeypatch.setattr(hardware, "is_apple_silicon", lambda: False)
+ _fake_psutil(monkeypatch, 400.0)
+ assert hardware.cpu_frequency_mhz() == 400.0
+
+ def test_m4_bug_corrected_from_ioreg(self, monkeypatch):
+ monkeypatch.setattr(hardware, "is_apple_silicon", lambda: True)
+ _fake_psutil(monkeypatch, 4.0)
+ _fake_ioreg(monkeypatch, [{"voltage-states5-sram": _M4_PERF_TABLE}])
+ assert hardware.cpu_frequency_mhz() == 4512.0
+
+ def test_m4_bug_falls_back_to_scaling_when_ioreg_fails(self, monkeypatch):
+ monkeypatch.setattr(hardware, "is_apple_silicon", lambda: True)
+ _fake_psutil(monkeypatch, 4.0)
+
+ def boom(cmd, **kwargs):
+ raise OSError("ioreg not found")
+
+ monkeypatch.setattr(hardware.subprocess, "run", boom)
+ assert hardware.cpu_frequency_mhz() == 4000.0
+
+ def test_fixed_psutil_value_is_left_alone(self, monkeypatch):
+ # Once psutil ships giampaolo/psutil#2824 the value is already plausible,
+ # so no ioreg call and no rescale.
+ monkeypatch.setattr(hardware, "is_apple_silicon", lambda: True)
+ _fake_psutil(monkeypatch, 4512.0)
+
+ def fail(cmd, **kwargs):
+ raise AssertionError("ioreg must not run for a plausible value")
+
+ monkeypatch.setattr(hardware.subprocess, "run", fail)
+ assert hardware.cpu_frequency_mhz() == 4512.0
+
+ def test_ioreg_probe_is_cached(self, monkeypatch):
+ monkeypatch.setattr(hardware, "is_apple_silicon", lambda: True)
+ _fake_psutil(monkeypatch, 4.0)
+ calls = []
+
+ def run(cmd, **kwargs):
+ calls.append(cmd)
+ return types.SimpleNamespace(
+ stdout = plistlib.dumps([{"voltage-states5-sram": _M4_PERF_TABLE}]),
+ returncode = 0,
+ )
+
+ monkeypatch.setattr(hardware.subprocess, "run", run)
+ assert hardware.cpu_frequency_mhz() == 4512.0
+ assert hardware.cpu_frequency_mhz() == 4512.0
+ assert len(calls) == 1
+
+ def test_failed_probe_is_cached_too(self, monkeypatch):
+ monkeypatch.setattr(hardware, "is_apple_silicon", lambda: True)
+ _fake_psutil(monkeypatch, 4.0)
+ calls = []
+
+ def run(cmd, **kwargs):
+ calls.append(cmd)
+ return types.SimpleNamespace(stdout = b"", returncode = 1)
+
+ monkeypatch.setattr(hardware.subprocess, "run", run)
+ assert hardware.cpu_frequency_mhz() == 4000.0
+ assert hardware.cpu_frequency_mhz() == 4000.0
+ assert len(calls) == 1
+
+ @pytest.mark.parametrize("current", [None, 0.0, -1.0, float("nan"), "fast"])
+ def test_missing_or_bogus_value_without_ioreg_returns_none(self, monkeypatch, current):
+ monkeypatch.setattr(hardware, "is_apple_silicon", lambda: True)
+ _fake_psutil(monkeypatch, current)
+ _fake_ioreg(monkeypatch, [])
+ assert hardware.cpu_frequency_mhz() is None
+
+ def test_psutil_failure_returns_none(self, monkeypatch):
+ monkeypatch.setattr(hardware, "is_apple_silicon", lambda: False)
+ _fake_psutil(monkeypatch, 3600.0, raises = True)
+ assert hardware.cpu_frequency_mhz() is None
+
+ def test_psutil_failure_on_apple_falls_back_to_ioreg(self, monkeypatch):
+ # psutil raises on M5, where the table indexes it hardcodes are absent.
+ monkeypatch.setattr(hardware, "is_apple_silicon", lambda: True)
+ _fake_psutil(monkeypatch, None, raises = True)
+ _fake_ioreg(monkeypatch, [{"voltage-states13-sram": _M4_PERF_TABLE}])
+ assert hardware.cpu_frequency_mhz() == 4512.0
+
+ def test_psutil_failure_with_no_ioreg_returns_none(self, monkeypatch):
+ monkeypatch.setattr(hardware, "is_apple_silicon", lambda: True)
+ _fake_psutil(monkeypatch, None, raises = True)
+ _fake_ioreg(monkeypatch, [])
+ assert hardware.cpu_frequency_mhz() is None
+
+ def test_psutil_without_cpu_freq_at_all_falls_back_to_ioreg(self, monkeypatch):
+ # GitHub's Apple Silicon runners: no attribute, so the call raises.
+ import sys
+
+ monkeypatch.setattr(hardware, "is_apple_silicon", lambda: True)
+ monkeypatch.setitem(sys.modules, "psutil", types.SimpleNamespace())
+ _fake_ioreg(monkeypatch, [{"voltage-states5-sram": _M4_PERF_TABLE}])
+ assert hardware.cpu_frequency_mhz() == 4512.0
+
+ def test_zero_reading_on_apple_still_reaches_ioreg(self, monkeypatch):
+ # Some M5 builds return 0.0 rather than raising.
+ monkeypatch.setattr(hardware, "is_apple_silicon", lambda: True)
+ _fake_psutil(monkeypatch, 0.0)
+ _fake_ioreg(monkeypatch, [{"voltage-states5-sram": _M4_PERF_TABLE}])
+ assert hardware.cpu_frequency_mhz() == 4512.0
+
+ def test_concurrent_first_calls_probe_once(self, monkeypatch):
+ import concurrent.futures
+ import threading
+ import time
+
+ monkeypatch.setattr(hardware, "is_apple_silicon", lambda: True)
+ _fake_psutil(monkeypatch, 4.0)
+ calls = []
+ calls_lock = threading.Lock()
+
+ def run(cmd, **kwargs):
+ with calls_lock:
+ calls.append(cmd)
+ time.sleep(0.05)
+ return types.SimpleNamespace(
+ stdout = plistlib.dumps([{"voltage-states5-sram": _M4_PERF_TABLE}]),
+ returncode = 0,
+ )
+
+ monkeypatch.setattr(hardware.subprocess, "run", run)
+ with concurrent.futures.ThreadPoolExecutor(max_workers = 12) as pool:
+ results = list(pool.map(lambda _: hardware.cpu_frequency_mhz(), range(12)))
+ assert results == [4512.0] * 12
+ assert len(calls) == 1
+
+
+ not (platform.system() == "Darwin" and platform.machine() == "arm64"),
+ reason = "Apple Silicon only: reads this host's real IORegistry tables",
+)
+class TestOnRealAppleSilicon:
+ """Runs unmocked on macOS CI, where the tables are the real thing."""
+
+ def test_reported_frequency_is_plausible(self):
+ mhz = hardware.cpu_frequency_mhz()
+ if mhz is None:
+ # Virtualised Apple Silicon (GitHub's macos-14/15 runners) has
+ # neither cpu_freq nor pmgr tables; the UI just omits the row.
+ pytest.skip("neither psutil nor ioreg exposes a CPU clock on this host")
+ assert hardware._MIN_PLAUSIBLE_CPU_MHZ <= mhz <= hardware._MAX_PLAUSIBLE_CPU_MHZ
+
+ def test_ioreg_reader_agrees_with_psutil(self):
+ # On M1-M3 psutil is already correct, so the ioreg reader must match it;
+ # on M4+ psutil is the broken side, so compare against its x1000 rescale.
+ import psutil
+
+ peak = hardware._read_apple_cpu_peak_mhz()
+ if peak is None:
+ pytest.skip("no voltage-state tables exposed on this host")
+ # Nothing to compare against where psutil has no reading of its own: an
+ # M5 raises, a virtualised host has no cpu_freq. The tables still work.
+ reader = getattr(psutil, "cpu_freq", None)
+ if reader is None:
+ pytest.skip("psutil exposes no cpu_freq on this host")
+ try:
+ sample = reader()
+ except Exception as exception:
+ pytest.skip(f"psutil cannot read the clock on this host ({exception})")
+ if sample is None or not getattr(sample, "current", 0):
+ pytest.skip("psutil reports no clock on this host")
+ raw = sample.current
+ expected = raw if raw >= hardware._MIN_PLAUSIBLE_CPU_MHZ else raw * 1000
+ assert peak == pytest.approx(expected, rel = 0.15)
diff --git a/studio/backend/utils/hardware/__init__.py b/studio/backend/utils/hardware/__init__.py
index 50417af3dd6..a69df539fc2 100644
--- a/studio/backend/utils/hardware/__init__.py
+++ b/studio/backend/utils/hardware/__init__.py
@@ -19,6 +19,7 @@ from .hardware import (
get_gpu_summary,
get_package_versions,
get_gpu_utilization,
+ cpu_frequency_mhz,
get_visible_gpu_utilization,
rocm_windows_free_is_untrusted,
trusted_mem_get_info,
@@ -98,6 +99,7 @@ __all__ = [
"get_gpu_summary",
"get_package_versions",
"get_gpu_utilization",
+ "cpu_frequency_mhz",
"get_visible_gpu_utilization",
"rocm_windows_free_is_untrusted",
"trusted_mem_get_info",
diff --git a/studio/backend/utils/hardware/hardware.py b/studio/backend/utils/hardware/hardware.py
index 0972358b859..31d72f7df8c 100644
--- a/studio/backend/utils/hardware/hardware.py
+++ b/studio/backend/utils/hardware/hardware.py
@@ -1281,6 +1281,130 @@ def _read_apple_gpu_stats() -> Dict[str, Any]:
}
+# ── CPU frequency on Apple Silicon ──────────────────────────────────────────
+# psutil divides the pmgr "voltage-statesN-sram" IORegistry tables by 1e6 to
+# reach MHz, but Apple switched them from Hz to kHz on M4, so psutil <= 7.2.2
+# shows a 4.5 GHz M4 Pro as "4 MHz" in Settings > System (issue #8519). Upstream
+# fix is giampaolo/psutil#2824, merged and unreleased; until it ships we read the
+# tables ourselves through ioreg with that PR's heuristics, else rescale psutil's
+# value. A fixed psutil is already plausible, so neither correction runs.
+
+# Apple clocks are 0.6-4.6 GHz, so a raw Hz entry sits above 1e8 and kHz below.
+_CPU_FREQ_UNIT_THRESHOLD = 100_000_000
+_MIN_PLAUSIBLE_CPU_MHZ = 500
+_MAX_PLAUSIBLE_CPU_MHZ = 20000
+# Below this a table is a GPU/NPU rail: above every Apple GPU peak so far, under
+# the slowest CPU cluster shipped (M1 E-core, 2064 MHz).
+_CPU_CLUSTER_MIN_PEAK_MHZ = 2000
+_VOLTAGE_STATES_KEY = re.compile(r"^voltage-states\d+-sram$")
+
+# Fixed for the life of the host and /api/system polls every few seconds, so
+# probe once. The sentinel separates "not probed yet" from "probed, unavailable".
+_apple_cpu_peak_mhz: Any = "unprobed"
+_apple_cpu_peak_lock = threading.Lock()
+
+
+def _voltage_state_freqs_mhz(blob: bytes) -> list:
+ """Plausible MHz from a voltage-statesN-sram blob.
+
+ Each entry is 8 bytes: little-endian uint32 frequency then uint32 voltage.
+ """
+ freqs = []
+ for offset in range(0, len(blob) - 7, 8):
+ raw = int.from_bytes(blob[offset : offset + 4], "little")
+ if raw == 0:
+ continue
+ mhz = raw / 1e6 if raw > _CPU_FREQ_UNIT_THRESHOLD else raw / 1e3
+ if _MIN_PLAUSIBLE_CPU_MHZ <= mhz <= _MAX_PLAUSIBLE_CPU_MHZ:
+ freqs.append(mhz)
+ return freqs
+
+
+def _peak_cpu_mhz_from_ioreg_entries(entries) -> Optional[float]:
+ """Highest CPU-cluster peak across pmgr voltage-state tables, or None."""
+ peaks = []
+ for entry in entries:
+ if not isinstance(entry, dict):
+ continue
+ for key, value in entry.items():
+ if not isinstance(value, (bytes, bytearray)) or not _VOLTAGE_STATES_KEY.match(str(key)):
+ continue
+ freqs = _voltage_state_freqs_mhz(bytes(value))
+ # M5 renumbered the indexes, so classify by peak, not by index.
+ if freqs and max(freqs) >= _CPU_CLUSTER_MIN_PEAK_MHZ:
+ peaks.append(max(freqs))
+ return max(peaks) if peaks else None
+
+
+def _read_apple_cpu_peak_mhz() -> Optional[float]:
+ """Read peak CPU MHz from the pmgr IORegistry node. None if unavailable."""
+ global _apple_cpu_peak_mhz
+ if _apple_cpu_peak_mhz != "unprobed":
+ return _apple_cpu_peak_mhz
+
+ # /api/system is polled from several worker threads; unlocked, a burst of
+ # first requests spawns one ioreg each and a slow failing probe landing last
+ # poisons the cache for the rest of the run.
+ with _apple_cpu_peak_lock:
+ if _apple_cpu_peak_mhz != "unprobed":
+ return _apple_cpu_peak_mhz
+
+ peak = None
+ try:
+ import plistlib
+
+ result = subprocess.run(
+ ["ioreg", "-a", "-r", "-c", "AppleARMIODevice", "-d", "1"],
+ capture_output = True,
+ # Same budget as the AGX probe above. The call is made once per
+ # process but from inside a /api/system request, so it must not
+ # be able to hold a worker thread for long.
+ timeout = 2,
+ )
+ entries = plistlib.loads(result.stdout) if result.stdout else []
+ if isinstance(entries, dict):
+ entries = [entries]
+ peak = _peak_cpu_mhz_from_ioreg_entries(entries)
+ except Exception as e:
+ logger.debug("Apple CPU frequency ioreg probe failed: %s", e)
+
+ _apple_cpu_peak_mhz = peak
+ return peak
+
+
+def cpu_frequency_mhz() -> Optional[float]:
+ """Current CPU clock in MHz, corrected for the psutil Apple Silicon unit bug.
+
+ Returns None when no frequency is available (psutil reports nothing inside
+ many containers and VMs).
+ """
+ freq = None
+ try:
+ import psutil
+ freq = psutil.cpu_freq()
+ except Exception as e:
+ # Not fatal on Apple Silicon: the IORegistry read below stands in. psutil
+ # raises here on M5, whose tables are not at the indexes it hardcodes.
+ logger.debug("Failed to get CPU frequency: %s", e)
+
+ current = getattr(freq, "current", None) if freq else None
+ usable = isinstance(current, (int, float)) and current == current and current > 0
+
+ if not is_apple_silicon():
+ return round(float(current), 2) if usable else None
+ if usable and current >= _MIN_PLAUSIBLE_CPU_MHZ:
+ return round(float(current), 2)
+
+ exact = _read_apple_cpu_peak_mhz()
+ if exact is not None:
+ return round(exact, 2)
+ if not usable:
+ return None
+ # No tables: recover the magnitude from psutil's kHz-as-Hz reading. It
+ # truncates in integer arithmetic, so this lands on the GHz step, not the peak.
+ return round(float(current) * 1000, 2)
+
+
def _rocm_linux_sysfs_gpu_busy_pct() -> Optional[float]:
"""Query AMD GPU compute utilization via Linux DRM sysfs gpu_busy_percent."""
if platform.system() != "Linux":
diff --git a/tests/test_import_fixes_drift.py b/tests/test_import_fixes_drift.py
index 8596bf259db..e47d232b6aa 100644
--- a/tests/test_import_fixes_drift.py
+++ b/tests/test_import_fixes_drift.py
@@ -21,6 +21,7 @@ import importlib
import importlib.util
import inspect
import os
+import platform
import re
import sys
from pathlib import Path
@@ -758,3 +759,50 @@ def test_bitsandbytes_rocm_detection_helpers_recognizable():
"decline to patch it and Windows ROCm import-time noise / "
"wrong ROCM_GPU_ARCH may return."
)
+
+
+# ===========================================================================
+# psutil -- cpu_freq shape the Apple Silicon M4+ unit fix relies on
+# ===========================================================================
+
+
+def test_psutil_cpu_freq_shape_and_wiring():
+ """``patch_psutil_cpu_freq``: the wrapper rebuilds psutil's scpufreq
+ namedtuple, so fail if that surface moves or the patch is never called."""
+ psutil = pytest.importorskip("psutil")
+
+ if getattr(psutil, "cpu_freq", None) is None:
+ # On macOS psutil decides at runtime whether to expose cpu_freq at all
+ # (an absent one is normal on virtualised Apple Silicon), so its absence
+ # is only drift off that platform.
+ if platform.system() == "Darwin" and platform.machine() == "arm64":
+ pytest.skip("this Apple Silicon host exposes no psutil.cpu_freq")
+ pytest.fail(
+ "DRIFT DETECTED: psutil.cpu_freq is gone -- patch_psutil_cpu_freq "
+ "would silently stop correcting Apple Silicon M4+ readings."
+ )
+ assert callable(psutil.cpu_freq)
+ namedtuple_type = None
+ for module_name in ("_ntuples", "_common"):
+ namedtuple_type = getattr(getattr(psutil, module_name, None), "scpufreq", None)
+ if namedtuple_type is not None:
+ break
+ if namedtuple_type is None:
+ pytest.fail(
+ "DRIFT DETECTED: psutil no longer exposes scpufreq in _ntuples or "
+ "_common, so the M5 fallback cannot build a return value."
+ )
+ assert hasattr(namedtuple_type, "_replace") and namedtuple_type._fields[:3] == (
+ "current",
+ "min",
+ "max",
+ ), (
+ "DRIFT DETECTED: psutil.scpufreq changed shape; the Apple Silicon "
+ "rescale in patch_psutil_cpu_freq assumes (current, min, max)."
+ )
+
+ source = Path(__file__).resolve().parent.parent / "unsloth" / "_gpu_init.py"
+ assert "patch_psutil_cpu_freq()" in source.read_text(encoding = "utf-8"), (
+ "DRIFT DETECTED: patch_psutil_cpu_freq is defined but never called in "
+ "_gpu_init.py, so real imports never install it."
+ )
diff --git a/tests/test_psutil_apple_cpu_freq.py b/tests/test_psutil_apple_cpu_freq.py
new file mode 100644
index 00000000000..b5a4e0b87ef
--- /dev/null
+++ b/tests/test_psutil_apple_cpu_freq.py
@@ -0,0 +1,431 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""``patch_psutil_cpu_freq`` -- Apple Silicon M4+ CPU frequency units (#8519).
+
+psutil <= 7.2.2 divides the pmgr voltage-state tables by 1e6 unconditionally,
+but Apple switched them from Hz to kHz on M4, so ``psutil.cpu_freq()`` comes
+back ~1000x too small. Runs on every OS: the platform is faked, so Linux and
+Windows CI exercise the same paths a Mac would.
+"""
+
+from __future__ import annotations
+
+import platform
+import plistlib
+import sys
+import types
+
+import pytest
+
+from unsloth import import_fixes as IF
+
+
+def _table(raw_freqs):
+ """A voltage-statesN-sram blob: uint32 frequency + uint32 voltage pairs."""
+ blob = b""
+ for raw in raw_freqs:
+ blob += raw.to_bytes(4, "little") + (900).to_bytes(4, "little")
+ return blob
+
+
+# Raw values as the tables actually appear: M1-M3 in Hz, M4+ in kHz.
+_M3_PERF_TABLE = _table([702_000_000, 2_016_000_000, 4_056_000_000])
+_M4_PERF_TABLE = _table([1_050_000, 3_000_000, 4_512_000])
+_M4_EFF_TABLE = _table([1_020_000, 2_592_000])
+_GPU_TABLE = _table([444_000, 1_398_000])
+
+
+def _scpufreq(
+ current,
+ minimum = 0.0,
+ maximum = 0.0,
+):
+ import psutil
+ return psutil._ntuples.scpufreq(current, minimum, maximum)
+
+
[email protected](autouse = True)
+def _reset_probe_cache():
+ IF._apple_cpu_freq_range = "unprobed"
+ yield
+ IF._apple_cpu_freq_range = "unprobed"
+
+
+def fake_m4(monkeypatch):
+ """Pretend this interpreter is running on Apple Silicon."""
+ monkeypatch.setattr(sys, "platform", "darwin")
+ monkeypatch.setattr(platform, "machine", lambda: "arm64")
+
+
+def _fake_ioreg(monkeypatch, entries):
+ import subprocess
+ def run(cmd, **kwargs):
+ assert cmd[0] == "ioreg"
+ return types.SimpleNamespace(stdout = plistlib.dumps(entries), returncode = 0)
+
+ monkeypatch.setattr(subprocess, "run", run)
+
+
+def _install_fake_psutil(monkeypatch, sample):
+ """Swap psutil.cpu_freq for one returning `sample` (value or callable)."""
+ import psutil
+
+ def cpu_freq(percpu = False):
+ return sample(percpu) if callable(sample) else sample
+
+ monkeypatch.setattr(psutil, "cpu_freq", cpu_freq)
+ return psutil
+
+
+class TestVoltageStateDecoding:
+ def test_hz_table_m3(self):
+ assert IF._apple_voltage_state_freqs_mhz(_M3_PERF_TABLE) == [702.0, 2016.0, 4056.0]
+
+ def test_khz_table_m4(self):
+ assert IF._apple_voltage_state_freqs_mhz(_M4_PERF_TABLE) == [1050.0, 3000.0, 4512.0]
+
+ def test_zero_and_implausible_entries_dropped(self):
+ assert IF._apple_voltage_state_freqs_mhz(_table([0, 1, 4_512_000, 90_000_000])) == [4512.0]
+
+ def test_trailing_partial_entry_ignored(self):
+ assert IF._apple_voltage_state_freqs_mhz(_M4_PERF_TABLE + b"\x01\x02\x03") == [
+ 1050.0,
+ 3000.0,
+ 4512.0,
+ ]
+
+ def test_empty_blob(self):
+ assert IF._apple_voltage_state_freqs_mhz(b"") == []
+
+
+class TestFreqRangeFromEntries:
+ def test_spans_all_cpu_clusters(self):
+ entries = [
+ {
+ "voltage-states1-sram": _M4_EFF_TABLE,
+ "voltage-states5-sram": _M4_PERF_TABLE,
+ }
+ ]
+ assert IF._apple_cpu_freq_range_from_ioreg_entries(entries) == (1020.0, 4512.0)
+
+ def test_gpu_rails_excluded(self):
+ assert (
+ IF._apple_cpu_freq_range_from_ioreg_entries([{"voltage-states2-sram": _GPU_TABLE}])
+ is None
+ )
+
+ def test_renumbered_tables_still_found(self):
+ # M5 renumbered the indexes; classification is by peak, not by index.
+ entries = [{"voltage-states13-sram": _M4_PERF_TABLE}]
+ assert IF._apple_cpu_freq_range_from_ioreg_entries(entries) == (1050.0, 4512.0)
+
+ def test_non_dict_and_non_bytes_values_ignored(self):
+ entries = [
+ "not-a-dict",
+ {"voltage-states5-sram": "not-bytes", "IORegistryEntryName": "pmgr"},
+ ]
+ assert IF._apple_cpu_freq_range_from_ioreg_entries(entries) is None
+
+
+class TestPatchApplication:
+ def test_no_op_off_darwin(self, monkeypatch):
+ monkeypatch.setattr(sys, "platform", "linux")
+ import psutil
+
+ before = psutil.cpu_freq
+ IF.patch_psutil_cpu_freq()
+ assert psutil.cpu_freq is before
+
+ def test_no_op_on_intel_mac(self, monkeypatch):
+ monkeypatch.setattr(sys, "platform", "darwin")
+ monkeypatch.setattr(platform, "machine", lambda: "x86_64")
+ import psutil
+
+ before = psutil.cpu_freq
+ IF.patch_psutil_cpu_freq()
+ assert psutil.cpu_freq is before
+
+ def test_no_op_when_psutil_has_no_cpu_freq(self, monkeypatch, fake_m4):
+ # GitHub's Apple Silicon runners ship exactly this psutil: no cpu_freq
+ # attribute at all. There is nothing to wrap, and adding one would
+ # advertise support psutil deliberately does not claim.
+ import psutil
+
+ monkeypatch.delattr(psutil, "cpu_freq", raising = False)
+ IF.patch_psutil_cpu_freq()
+ assert not hasattr(psutil, "cpu_freq")
+
+ def test_caller_argument_mistakes_keep_their_error(self, monkeypatch, fake_m4):
+ # The wrapper stands in for psutil globally, so a TypeError from a bad
+ # call must not be mistaken for psutil declining to read the clock.
+ import psutil
+
+ def cpu_freq(percpu = False):
+ raise RuntimeError("psutil declines")
+
+ monkeypatch.setattr(psutil, "cpu_freq", cpu_freq)
+ _fake_ioreg(monkeypatch, [{"voltage-states5-sram": _M4_PERF_TABLE}])
+ IF.patch_psutil_cpu_freq()
+ assert psutil.cpu_freq().current == 4512.0 # the supported call still recovers
+ with pytest.raises(TypeError):
+ psutil.cpu_freq(unknown = True)
+ with pytest.raises(TypeError):
+ psutil.cpu_freq(False, False)
+
+ def test_probe_lock_exists_before_any_call(self):
+ # A lazily built lock is two locks when two threads reach it at once,
+ # and then neither excludes the other.
+ import threading
+ assert isinstance(IF._apple_cpu_freq_lock, type(threading.Lock()))
+
+ def test_patch_is_idempotent(self, monkeypatch, fake_m4):
+ psutil = _install_fake_psutil(monkeypatch, _scpufreq(4.0, 1.0, 4.0))
+ IF.patch_psutil_cpu_freq()
+ first = psutil.cpu_freq
+ IF.patch_psutil_cpu_freq()
+ assert psutil.cpu_freq is first
+
+ def test_m4_reading_corrected_from_ioreg(self, monkeypatch, fake_m4):
+ psutil = _install_fake_psutil(monkeypatch, _scpufreq(4.0, 1.0, 4.0))
+ _fake_ioreg(
+ monkeypatch,
+ [{"voltage-states1-sram": _M4_EFF_TABLE, "voltage-states5-sram": _M4_PERF_TABLE}],
+ )
+ IF.patch_psutil_cpu_freq()
+ result = psutil.cpu_freq()
+ assert (result.current, result.min, result.max) == (4512.0, 1020.0, 4512.0)
+
+ def test_falls_back_to_rescaling_without_ioreg(self, monkeypatch, fake_m4):
+ import subprocess
+
+ psutil = _install_fake_psutil(monkeypatch, _scpufreq(4.0, 1.0, 4.0))
+
+ def boom(cmd, **kwargs):
+ raise OSError("ioreg not found")
+
+ monkeypatch.setattr(subprocess, "run", boom)
+ IF.patch_psutil_cpu_freq()
+ result = psutil.cpu_freq()
+ assert (result.current, result.min, result.max) == (4000.0, 1000.0, 4000.0)
+
+ def test_plausible_reading_untouched(self, monkeypatch, fake_m4):
+ # M1-M3 today, and every chip once psutil ships giampaolo/psutil#2824.
+ import subprocess
+
+ psutil = _install_fake_psutil(monkeypatch, _scpufreq(4056.0, 702.0, 4056.0))
+ monkeypatch.setattr(
+ subprocess,
+ "run",
+ lambda *a, **k: pytest.fail("ioreg must not run for a plausible value"),
+ )
+ IF.patch_psutil_cpu_freq()
+ result = psutil.cpu_freq()
+ assert (result.current, result.min, result.max) == (4056.0, 702.0, 4056.0)
+
+ def test_percpu_list_is_corrected_elementwise(self, monkeypatch, fake_m4):
+ samples = [_scpufreq(4.0, 1.0, 4.0), _scpufreq(2.5, 1.0, 2.5)]
+ psutil = _install_fake_psutil(
+ monkeypatch, lambda percpu: list(samples) if percpu else samples[0]
+ )
+ _fake_ioreg(monkeypatch, [{"voltage-states5-sram": _M4_PERF_TABLE}])
+ IF.patch_psutil_cpu_freq()
+ percpu = psutil.cpu_freq(percpu = True)
+ assert isinstance(percpu, list) and len(percpu) == 2
+ assert all(sample.current == 4512.0 for sample in percpu)
+ assert psutil.cpu_freq().current == 4512.0
+
+ def test_return_type_and_signature_preserved(self, monkeypatch, fake_m4):
+ import psutil as real_psutil
+
+ psutil = _install_fake_psutil(monkeypatch, _scpufreq(4.0, 1.0, 4.0))
+ _fake_ioreg(monkeypatch, [{"voltage-states5-sram": _M4_PERF_TABLE}])
+ IF.patch_psutil_cpu_freq()
+ assert isinstance(psutil.cpu_freq(), real_psutil._ntuples.scpufreq)
+ assert psutil.cpu_freq.__name__ == "cpu_freq"
+
+ @pytest.mark.parametrize("sample", [None, "junk", 0.0])
+ def test_unusable_readings_without_tables_pass_through(self, monkeypatch, fake_m4, sample):
+ value = sample if sample in (None, "junk") else _scpufreq(0.0, 0.0, 0.0)
+ psutil = _install_fake_psutil(monkeypatch, value)
+ _fake_ioreg(monkeypatch, [])
+ IF.patch_psutil_cpu_freq()
+ assert psutil.cpu_freq() == value
+
+ def test_psutil_exception_is_covered_by_ioreg(self, monkeypatch, fake_m4):
+ # psutil raises on M5, where the table indexes it hardcodes are absent.
+ def boom(percpu = False):
+ raise RuntimeError("no voltage-states table at the expected index")
+
+ import psutil
+
+ monkeypatch.setattr(psutil, "cpu_freq", boom)
+ _fake_ioreg(monkeypatch, [{"voltage-states13-sram": _M4_PERF_TABLE}])
+ IF.patch_psutil_cpu_freq()
+ result = psutil.cpu_freq()
+ assert (result.current, result.min, result.max) == (4512.0, 1050.0, 4512.0)
+
+ def test_psutil_exception_still_raises_without_ioreg(self, monkeypatch, fake_m4):
+ import psutil
+ import subprocess
+
+ def boom(percpu = False):
+ raise RuntimeError("no voltage-states table at the expected index")
+
+ monkeypatch.setattr(psutil, "cpu_freq", boom)
+ monkeypatch.setattr(subprocess, "run", lambda *a, **k: (_ for _ in ()).throw(OSError()))
+ IF.patch_psutil_cpu_freq()
+ with pytest.raises(RuntimeError):
+ psutil.cpu_freq()
+
+ def test_percpu_exception_is_covered_too(self, monkeypatch, fake_m4):
+ # macOS has no per-core clock, so psutil's own percpu answer there is a
+ # one-element list; the stand-in keeps that shape for both call forms.
+ import psutil
+
+ def boom(percpu = False):
+ raise RuntimeError("no voltage-states table at the expected index")
+
+ monkeypatch.setattr(psutil, "cpu_freq", boom)
+ _fake_ioreg(monkeypatch, [{"voltage-states5-sram": _M4_PERF_TABLE}])
+ IF.patch_psutil_cpu_freq()
+ for call in (lambda: psutil.cpu_freq(percpu = True), lambda: psutil.cpu_freq(True)):
+ result = call()
+ assert isinstance(result, list) and len(result) == 1
+ assert result[0].current == 4512.0
+
+ def test_empty_percpu_list_is_covered(self, monkeypatch, fake_m4):
+ # giampaolo/psutil#2382 returns [] when the clock is undeterminable.
+ psutil = _install_fake_psutil(monkeypatch, lambda percpu: [] if percpu else None)
+ _fake_ioreg(monkeypatch, [{"voltage-states5-sram": _M4_PERF_TABLE}])
+ IF.patch_psutil_cpu_freq()
+ assert psutil.cpu_freq().current == 4512.0
+ percpu = psutil.cpu_freq(percpu = True)
+ assert isinstance(percpu, list) and percpu[0].current == 4512.0
+
+ def test_none_stays_none_without_tables(self, monkeypatch, fake_m4):
+ import subprocess
+
+ psutil = _install_fake_psutil(monkeypatch, lambda percpu: [] if percpu else None)
+ monkeypatch.setattr(subprocess, "run", lambda *a, **k: (_ for _ in ()).throw(OSError()))
+ IF.patch_psutil_cpu_freq()
+ assert psutil.cpu_freq() is None
+ assert psutil.cpu_freq(percpu = True) == []
+
+ @pytest.mark.parametrize("bogus", [0.0, -1.0, float("nan")])
+ def test_unusable_apple_reading_recovers_from_tables(self, monkeypatch, fake_m4, bogus):
+ psutil = _install_fake_psutil(monkeypatch, _scpufreq(bogus, 0.0, 0.0))
+ _fake_ioreg(monkeypatch, [{"voltage-states5-sram": _M4_PERF_TABLE}])
+ IF.patch_psutil_cpu_freq()
+ assert psutil.cpu_freq().current == 4512.0
+
+ @pytest.mark.parametrize("bogus", [0.0, -1.0])
+ def test_unusable_apple_reading_is_left_alone_without_tables(self, monkeypatch, fake_m4, bogus):
+ import subprocess
+
+ psutil = _install_fake_psutil(monkeypatch, _scpufreq(bogus, 0.0, 0.0))
+ monkeypatch.setattr(subprocess, "run", lambda *a, **k: (_ for _ in ()).throw(OSError()))
+ IF.patch_psutil_cpu_freq()
+ assert psutil.cpu_freq().current == bogus
+
+ def test_concurrent_first_calls_probe_once(self, monkeypatch, fake_m4):
+ import concurrent.futures
+ import subprocess
+ import threading
+ import time
+
+ calls = []
+ calls_lock = threading.Lock()
+
+ def run(cmd, **kwargs):
+ with calls_lock:
+ calls.append(cmd)
+ time.sleep(0.05)
+ return types.SimpleNamespace(
+ stdout = plistlib.dumps([{"voltage-states5-sram": _M4_PERF_TABLE}]), returncode = 0
+ )
+
+ psutil = _install_fake_psutil(monkeypatch, _scpufreq(4.0, 1.0, 4.0))
+ monkeypatch.setattr(subprocess, "run", run)
+ IF.patch_psutil_cpu_freq()
+ with concurrent.futures.ThreadPoolExecutor(max_workers = 12) as pool:
+ results = list(pool.map(lambda _: psutil.cpu_freq().current, range(12)))
+ assert results == [4512.0] * 12
+ assert len(calls) == 1
+
+ def test_probe_runs_once_across_calls(self, monkeypatch, fake_m4):
+ import subprocess
+
+ calls = []
+
+ def run(cmd, **kwargs):
+ calls.append(cmd)
+ return types.SimpleNamespace(
+ stdout = plistlib.dumps([{"voltage-states5-sram": _M4_PERF_TABLE}]), returncode = 0
+ )
+
+ psutil = _install_fake_psutil(monkeypatch, _scpufreq(4.0, 1.0, 4.0))
+ monkeypatch.setattr(subprocess, "run", run)
+ IF.patch_psutil_cpu_freq()
+ for _ in range(5):
+ assert psutil.cpu_freq().current == 4512.0
+ assert len(calls) == 1
+
+
+ not (sys.platform == "darwin" and platform.machine() == "arm64"),
+ reason = "Apple Silicon only: reads this host's real IORegistry tables",
+)
+def _raw_apple_reading():
+ """This host's own psutil reading, or None when it has none to give.
+
+ psutil gates cpu_freq on a runtime probe on macOS, so on Apple Silicon the
+ attribute can be missing outright (virtualised runners) or present and
+ raising (M5, whose tables are not at the indexes psutil hardcodes). Both are
+ supported hosts, so a test that needs a raw reading skips rather than fails.
+ """
+ import psutil
+
+ reader = getattr(psutil, "cpu_freq", None)
+ if reader is None:
+ return None
+ try:
+ sample = reader()
+ except Exception:
+ return None
+ current = getattr(sample, "current", None)
+ return current if isinstance(current, (int, float)) and current > 0 else None
+
+
+class TestOnRealAppleSilicon:
+ def test_reported_frequency_is_plausible(self):
+ import psutil
+
+ IF.patch_psutil_cpu_freq()
+ reader = getattr(psutil, "cpu_freq", None)
+ if reader is None:
+ # Nothing was wrapped, so there is nothing to assert about. Studio's
+ # own helper covers this host, and its test asserts that path.
+ pytest.skip("psutil exposes no cpu_freq on this host")
+ try:
+ sample = reader()
+ except Exception as exception:
+ # psutil declined and the tables were unreadable too, so the wrapper
+ # correctly re-raised rather than inventing a number.
+ pytest.skip(f"no CPU clock available on this host ({exception})")
+ if sample is None:
+ pytest.skip("psutil reports the clock as undeterminable on this host")
+ assert IF._APPLE_MIN_PLAUSIBLE_CPU_MHZ <= sample.current <= IF._APPLE_MAX_PLAUSIBLE_CPU_MHZ
+
+ def test_ioreg_reader_agrees_with_unaffected_psutil(self):
+ # On M1-M3 psutil is already right, so our reader must match it. On M4+
+ # psutil is the broken one, so compare against its x1000 rescale instead.
+ freq_range = IF._apple_cpu_freq_range_mhz()
+ if freq_range is None:
+ pytest.skip("ioreg voltage-state tables unavailable on this host")
+ raw = _raw_apple_reading()
+ if raw is None:
+ pytest.skip("psutil has no reading of its own on this host to compare against")
+ expected = raw if raw >= IF._APPLE_MIN_PLAUSIBLE_CPU_MHZ else raw * 1000
+ assert freq_range[1] == pytest.approx(expected, rel = 0.15)
diff --git a/unsloth/_gpu_init.py b/unsloth/_gpu_init.py
index 86abefe4a10..b285b88b027 100644
--- a/unsloth/_gpu_init.py
+++ b/unsloth/_gpu_init.py
@@ -198,6 +198,7 @@ from .import_fixes import (
patch_ipykernel_hf_xet,
patch_trackio,
patch_datasets,
+ patch_psutil_cpu_freq,
patch_enable_input_require_grads,
patch_unsafe_trainer_rng_load,
fix_openenv_no_vllm,
@@ -238,6 +239,8 @@ ignore_logger_messages()
patch_ipykernel_hf_xet()
patch_trackio()
patch_datasets()
+# Apple Silicon M4+ only: psutil <= 7.2.2 reads the clock 1000x too small.
+patch_psutil_cpu_freq()
patch_enable_input_require_grads()
patch_unsafe_trainer_rng_load()
fix_openenv_no_vllm()
@@ -274,6 +277,7 @@ del ignore_logger_messages
del patch_ipykernel_hf_xet
del patch_trackio
del patch_datasets
+del patch_psutil_cpu_freq
del patch_enable_input_require_grads
del fix_openenv_no_vllm
del patch_openspiel_env_async
diff --git a/unsloth/import_fixes.py b/unsloth/import_fixes.py
index d031ac13022..bf45ff3d8de 100644
--- a/unsloth/import_fixes.py
+++ b/unsloth/import_fixes.py
@@ -27,6 +27,7 @@ import logging
import textwrap
import warnings
import sys
+import threading
import functools
import inspect
@@ -804,6 +805,204 @@ def patch_datasets():
)
+# psutil divides the pmgr "voltage-statesN-sram" IORegistry tables by 1e6 to
+# reach MHz, but Apple switched them from Hz to kHz on M4, so psutil <= 7.2.2
+# reads a 4.5 GHz M4 Pro back as 4 MHz (unslothai/unsloth#8519). Upstream fix is
+# giampaolo/psutil#2824, merged and unreleased; its heuristics are mirrored here.
+#
+# Studio's backend keeps the same correction in
+# studio/backend/utils/hardware/hardware.py, since the API server never imports
+# unsloth. Keep both in sync; delete both once a fixed psutil is our floor.
+#
+# Apple clocks are 0.6-4.6 GHz, so a raw Hz entry sits above 1e8 and kHz below.
+_APPLE_CPU_FREQ_UNIT_THRESHOLD = 100_000_000
+_APPLE_MIN_PLAUSIBLE_CPU_MHZ = 500
+_APPLE_MAX_PLAUSIBLE_CPU_MHZ = 20000
+# Below this a table is a GPU/NPU rail: above every Apple GPU peak so far, under
+# the slowest CPU cluster shipped (M1 E-core, 2064 MHz).
+_APPLE_CPU_CLUSTER_MIN_PEAK_MHZ = 2000
+_APPLE_VOLTAGE_STATES_KEY = re.compile(r"^voltage-states\d+-sram$")
+# Fixed for the life of the host, so probe once. The sentinel separates "not
+# probed yet" from "probed, unavailable".
+_apple_cpu_freq_range = "unprobed"
+# At import, not on first use: two threads reaching a lazy initialiser build a
+# lock each and then exclude nothing.
+_apple_cpu_freq_lock = threading.Lock()
+
+
+def _apple_voltage_state_freqs_mhz(blob):
+ """Plausible MHz from one voltage-statesN-sram blob.
+
+ Entries are 8 bytes: little-endian uint32 frequency, then uint32 voltage.
+ """
+ freqs = []
+ for offset in range(0, len(blob) - 7, 8):
+ raw = int.from_bytes(blob[offset : offset + 4], "little")
+ if raw == 0:
+ continue
+ mhz = raw / 1e6 if raw > _APPLE_CPU_FREQ_UNIT_THRESHOLD else raw / 1e3
+ if _APPLE_MIN_PLAUSIBLE_CPU_MHZ <= mhz <= _APPLE_MAX_PLAUSIBLE_CPU_MHZ:
+ freqs.append(mhz)
+ return freqs
+
+
+def _apple_cpu_freq_range_from_ioreg_entries(entries):
+ """(min_mhz, max_mhz) across the CPU-cluster tables, or None."""
+ lows, peaks = [], []
+ for entry in entries:
+ if not isinstance(entry, dict):
+ continue
+ for key, value in entry.items():
+ if not isinstance(value, (bytes, bytearray)):
+ continue
+ if not _APPLE_VOLTAGE_STATES_KEY.match(str(key)):
+ continue
+ freqs = _apple_voltage_state_freqs_mhz(bytes(value))
+ # M5 renumbered the indexes, so classify by peak, not by index.
+ if freqs and max(freqs) >= _APPLE_CPU_CLUSTER_MIN_PEAK_MHZ:
+ lows.append(min(freqs))
+ peaks.append(max(freqs))
+ if not peaks:
+ return None
+ return (min(lows), max(peaks))
+
+
+def _apple_cpu_freq_range_mhz():
+ """Read (min, max) CPU MHz from the pmgr IORegistry node, cached."""
+ global _apple_cpu_freq_range
+ if _apple_cpu_freq_range != "unprobed":
+ return _apple_cpu_freq_range
+
+ # Unlocked, every thread spawns its own ioreg and a slow failing probe landing
+ # last overwrites a good reading with None.
+ with _apple_cpu_freq_lock:
+ if _apple_cpu_freq_range != "unprobed":
+ return _apple_cpu_freq_range
+
+ freq_range = None
+ try:
+ import plistlib
+ import subprocess
+
+ result = subprocess.run(
+ ["ioreg", "-a", "-r", "-c", "AppleARMIODevice", "-d", "1"],
+ capture_output = True,
+ timeout = 2,
+ )
+ entries = plistlib.loads(result.stdout) if result.stdout else []
+ if isinstance(entries, dict):
+ entries = [entries]
+ freq_range = _apple_cpu_freq_range_from_ioreg_entries(entries)
+ except Exception as exception:
+ logger.info("Unsloth: could not read Apple CPU frequencies from ioreg (%s)", exception)
+
+ _apple_cpu_freq_range = freq_range
+ return freq_range
+
+
+def _corrected_apple_cpu_freq(sample):
+ """Rescale one psutil scpufreq sample that was read in the wrong unit."""
+ current = getattr(sample, "current", None)
+ usable = isinstance(current, (int, float)) and current == current and current > 0
+ if usable and current >= _APPLE_MIN_PLAUSIBLE_CPU_MHZ:
+ return sample # already plausible: a fixed psutil, or not an affected chip
+
+ freq_range = _apple_cpu_freq_range_mhz()
+ if freq_range is not None:
+ low, peak = freq_range
+ # macOS has no per-instant clock, so psutil reports the peak as `current`.
+ return sample._replace(current = peak, min = low, max = peak)
+ if not usable:
+ return sample # 0, negative or NaN and no tables: nothing to say
+ # No tables: recover the magnitude instead. psutil truncates in integer
+ # arithmetic, so this lands on the GHz step (4 -> 4000 MHz), not the peak.
+ return sample._replace(
+ current = current * 1000,
+ min = getattr(sample, "min", 0.0) * 1000,
+ max = getattr(sample, "max", 0.0) * 1000,
+ )
+
+
+def patch_psutil_cpu_freq():
+ """Fix psutil.cpu_freq() reporting kHz-derived MHz on Apple Silicon M4+."""
+ if sys.platform != "darwin":
+ return
+ import platform as _platform
+
+ if _platform.machine() != "arm64":
+ return # Rosetta / Intel Macs read a different, unaffected code path
+ if importlib.util.find_spec("psutil") is None:
+ return
+ try:
+ import psutil
+ except Exception:
+ return
+
+ original_cpu_freq = getattr(psutil, "cpu_freq", None)
+ if original_cpu_freq is None or getattr(original_cpu_freq, "__unsloth_patched__", False):
+ return
+
+ def _percpu_requested(args, kwargs):
+ return bool(args[0]) if args else bool(kwargs.get("percpu", False))
+
+ def _scpufreq_type():
+ # psutil 7.x keeps the namedtuple in _ntuples, older releases in _common.
+ for module_name in ("_ntuples", "_common"):
+ namedtuple_type = getattr(getattr(psutil, module_name, None), "scpufreq", None)
+ if namedtuple_type is not None:
+ return namedtuple_type
+ return None
+
+ def _from_tables(percpu):
+ """The IORegistry reading in psutil's own return shape, or None.
+
+ macOS has no per-core clock, so psutil's percpu answer is a one-element
+ list of the same sample; matching that keeps percpu callers whole.
+ """
+ namedtuple_type = _scpufreq_type()
+ if namedtuple_type is None:
+ return None
+ freq_range = _apple_cpu_freq_range_mhz()
+ if freq_range is None:
+ return None
+ low, peak = freq_range
+ sample = namedtuple_type(peak, low, peak)
+ return [sample] if percpu else sample
+
+ @functools.wraps(original_cpu_freq)
+ def cpu_freq(*args, **kwargs):
+ try:
+ result = original_cpu_freq(*args, **kwargs)
+ except TypeError:
+ # Arguments psutil does not take are the caller's mistake, not psutil
+ # declining to answer. This function replaces psutil's globally, so
+ # swallowing that would hide the error everywhere, not just here.
+ raise
+ except Exception:
+ # psutil raises on M5, whose renumbered tables are not at the indexes
+ # it hardcodes. With no tables either, its error is the honest answer.
+ stand_in = _from_tables(_percpu_requested(args, kwargs))
+ if stand_in is None:
+ raise
+ return stand_in
+ try:
+ # percpu = True returns a list of samples, otherwise a single one.
+ if isinstance(result, list):
+ # Empty is giampaolo/psutil#2382's "undeterminable".
+ if not result:
+ return _from_tables(percpu = True) or result
+ return [_corrected_apple_cpu_freq(sample) for sample in result]
+ if result is None:
+ stand_in = _from_tables(percpu = False)
+ return result if stand_in is None else stand_in
+ return _corrected_apple_cpu_freq(result)
+ except Exception:
+ return result # never let a cosmetic fix break a caller
+
+ cpu_freq.__unsloth_patched__ = True
+ psutil.cpu_freq = cpu_freq
+
+
def check_fbgemm_gpu_version():
if importlib.util.find_spec("fbgemm_gpu") is None:
return