File size: 6,977 Bytes
43e7a09
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
import platform
import subprocess
import sys
import threading
import warnings
from typing import TYPE_CHECKING, Any

if TYPE_CHECKING:
    from trackio.run import Run

psutil: Any = None
PSUTIL_AVAILABLE = False
_monitor_lock = threading.Lock()


def _ensure_psutil():
    global PSUTIL_AVAILABLE, psutil
    if PSUTIL_AVAILABLE:
        return psutil
    try:
        import psutil as _psutil

        psutil = _psutil
        PSUTIL_AVAILABLE = True
        return psutil
    except ImportError:
        raise ImportError(
            "psutil is required for Apple Silicon monitoring. "
            "Install it with: pip install psutil"
        )


def is_apple_silicon() -> bool:
    """Check if running on Apple Silicon (M1/M2/M3/M4)."""
    if platform.system() != "Darwin":
        return False

    try:
        result = subprocess.run(
            ["sysctl", "-n", "machdep.cpu.brand_string"],
            capture_output=True,
            text=True,
            timeout=1,
        )
        cpu_brand = result.stdout.strip()
        return "Apple" in cpu_brand
    except Exception:
        return False


def get_gpu_info() -> dict[str, Any]:
    """Get Apple GPU information using ioreg."""
    try:
        result = subprocess.run(
            ["ioreg", "-r", "-d", "1", "-w", "0", "-c", "IOAccelerator"],
            capture_output=True,
            text=True,
            timeout=2,
        )

        if result.returncode == 0 and result.stdout:
            lines = result.stdout.strip().split("\n")
            for line in lines:
                if "IOAccelerator" in line and "class" in line:
                    return {"detected": True, "type": "Apple GPU"}
        else:
            print("Error collecting Apple GPU info. ioreg stdout was:", file=sys.stderr)
            print(result.stdout, file=sys.stderr)
            print("ioreg stderr was:", file=sys.stderr)
            print(result.stderr, file=sys.stderr)

        result = subprocess.run(
            ["system_profiler", "SPDisplaysDataType"],
            capture_output=True,
            text=True,
            timeout=3,
        )

        if result.returncode == 0 and "Apple" in result.stdout:
            for line in result.stdout.split("\n"):
                if "Chipset Model:" in line:
                    model = line.split(":")[-1].strip()
                    return {"detected": True, "type": model}

    except Exception:
        pass

    return {"detected": False}


def apple_gpu_available() -> bool:
    """
    Check if Apple GPU monitoring is available.

    Returns True if running on Apple Silicon (M-series chips) and psutil is installed.
    """
    try:
        _ensure_psutil()
        return is_apple_silicon()
    except ImportError:
        return False
    except Exception:
        return False


def collect_apple_metrics() -> dict:
    """
    Collect system metrics for Apple Silicon.

    Returns:
        Dictionary of system metrics including CPU, memory, and GPU info.
    """
    if not PSUTIL_AVAILABLE:
        try:
            _ensure_psutil()
        except ImportError:
            return {}

    metrics = {}

    try:
        cpu_percent = psutil.cpu_percent(interval=0.1, percpu=False)
        metrics["cpu/utilization"] = cpu_percent
    except Exception:
        pass

    try:
        cpu_percents = psutil.cpu_percent(interval=0.1, percpu=True)
        for i, percent in enumerate(cpu_percents):
            metrics[f"cpu/{i}/utilization"] = percent
    except Exception:
        pass

    try:
        cpu_freq = psutil.cpu_freq()
        if cpu_freq:
            metrics["cpu/frequency"] = cpu_freq.current
            if cpu_freq.max > 0:
                metrics["cpu/frequency_max"] = cpu_freq.max
    except Exception:
        pass

    try:
        mem = psutil.virtual_memory()
        metrics["memory/used"] = mem.used / (1024**3)
        metrics["memory/total"] = mem.total / (1024**3)
        metrics["memory/available"] = mem.available / (1024**3)
        metrics["memory/percent"] = mem.percent
    except Exception:
        pass

    try:
        swap = psutil.swap_memory()
        metrics["swap/used"] = swap.used / (1024**3)
        metrics["swap/total"] = swap.total / (1024**3)
        metrics["swap/percent"] = swap.percent
    except Exception:
        pass

    try:
        sensors_temps = psutil.sensors_temperatures()
        if sensors_temps:
            for name, entries in sensors_temps.items():
                for i, entry in enumerate(entries):
                    label = entry.label or f"{name}_{i}"
                    metrics[f"temp/{label}"] = entry.current
    except Exception:
        pass

    gpu_info = get_gpu_info()
    if gpu_info.get("detected"):
        metrics["gpu/detected"] = 1
        if "type" in gpu_info:
            pass

    return metrics


class AppleGpuMonitor:
    def __init__(self, run: "Run", interval: float = 10.0):
        self._run = run
        self._interval = interval
        self._stop_flag = threading.Event()
        self._thread: "threading.Thread | None" = None

    def start(self):
        if not is_apple_silicon():
            warnings.warn(
                "auto_log_gpu=True but not running on Apple Silicon. "
                "Apple GPU logging disabled."
            )
            return

        if not PSUTIL_AVAILABLE:
            try:
                _ensure_psutil()
            except ImportError:
                warnings.warn(
                    "auto_log_gpu=True but psutil not installed. "
                    "Install with: pip install psutil"
                )
                return

        self._thread = threading.Thread(target=self._monitor_loop, daemon=True)
        self._thread.start()

    def stop(self):
        self._stop_flag.set()
        if self._thread is not None:
            self._thread.join(timeout=2.0)

    def _monitor_loop(self):
        while not self._stop_flag.is_set():
            try:
                metrics = collect_apple_metrics()
                if metrics:
                    self._run.log_system(metrics)
            except Exception:
                pass

            self._stop_flag.wait(timeout=self._interval)


def log_apple_gpu(run: "Run | None" = None) -> dict:
    """
    Log Apple Silicon system metrics to the current or specified run.

    Args:
        run: Optional Run instance. If None, uses current run from context.

    Returns:
        dict: The system metrics that were logged.

    Example:
        ```python
        import trackio

        run = trackio.init(project="my-project")
        trackio.log({"loss": 0.5})
        trackio.log_apple_gpu()
        ```
    """
    from trackio import context_vars

    if run is None:
        run = context_vars.current_run.get()
        if run is None:
            raise RuntimeError("Call trackio.init() before trackio.log_apple_gpu().")

    metrics = collect_apple_metrics()
    if metrics:
        run.log_system(metrics)
    return metrics