dmlops 0.2.10__py3-none-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
dmlops/_envprobe.py ADDED
@@ -0,0 +1,163 @@
1
+ """Best-effort environment probing for the experiment Summary environment card.
2
+
3
+ Wire schema (snake_case) mirrors what the platform's own workers write into
4
+ ``environment.json``; the web parser converts to its internal camelCase shape.
5
+ ``docker_image`` is intentionally omitted — external runs have no platform
6
+ image, and the UI hides the image block when the field is absent.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import os
12
+ import platform
13
+ import subprocess
14
+ import sys
15
+ import time
16
+ from typing import Any
17
+
18
+
19
+ def _meminfo_mb() -> tuple[int | None, int | None]:
20
+ """(total, available) MB from /proc/meminfo, or (None, None)."""
21
+ try:
22
+ total = avail = None
23
+ with open("/proc/meminfo", "r", encoding="utf-8") as fh:
24
+ for line in fh:
25
+ key, _, rest = line.partition(":")
26
+ value = rest.strip().split()
27
+ if not value:
28
+ continue
29
+ mb = int(int(value[0]) / 1024) # kB → MB
30
+ if key == "MemTotal":
31
+ total = mb
32
+ elif key == "MemAvailable":
33
+ avail = mb
34
+ return total, avail
35
+ except OSError:
36
+ return None, None
37
+
38
+
39
+ def _cpu_model() -> str | None:
40
+ try:
41
+ with open("/proc/cpuinfo", "r", encoding="utf-8") as fh:
42
+ for line in fh:
43
+ if line.lower().startswith("model name"):
44
+ return line.split(":", 1)[1].strip() or None
45
+ except OSError:
46
+ pass
47
+ return platform.processor() or None
48
+
49
+
50
+ def _nvidia_smi_gpus() -> list[dict[str, Any]] | None:
51
+ """Parse `nvidia-smi --query-gpu` CSV; None when unavailable."""
52
+ try:
53
+ out = subprocess.run(
54
+ [
55
+ "nvidia-smi",
56
+ "--query-gpu=index,name,driver_version,memory.total,memory.used",
57
+ "--format=csv,noheader,nounits",
58
+ ],
59
+ capture_output=True,
60
+ timeout=10,
61
+ )
62
+ except (OSError, subprocess.SubprocessError):
63
+ return None
64
+ if out.returncode != 0:
65
+ return None
66
+ gpus: list[dict[str, Any]] = []
67
+ for line in out.stdout.decode("utf-8", "replace").splitlines():
68
+ parts = [p.strip() for p in line.split(",")]
69
+ if len(parts) < 5:
70
+ continue
71
+ try:
72
+ gpus.append(
73
+ {
74
+ "index": int(parts[0]),
75
+ "name": parts[1],
76
+ "driver_version": parts[2] or None,
77
+ "mem_total_mb": int(float(parts[3])),
78
+ "mem_free_mb": max(int(float(parts[3])) - int(float(parts[4])), 0),
79
+ "used": True,
80
+ }
81
+ )
82
+ except ValueError:
83
+ continue
84
+ return gpus or None
85
+
86
+
87
+ def _torch_info() -> tuple[Any, str | None, str | None, list[dict[str, Any]]]:
88
+ """Lazy torch import: (module, version, cuda_version, gpu_list)."""
89
+ try:
90
+ import torch # type: ignore
91
+ except Exception:
92
+ return None, None, None, []
93
+ version = getattr(torch, "__version__", None)
94
+ cuda = getattr(torch, "version", None)
95
+ cuda_version = getattr(cuda, "cuda", None) if cuda else None
96
+ gpus: list[dict[str, Any]] = []
97
+ try:
98
+ count = int(torch.cuda.device_count()) if torch.cuda.is_available() else 0
99
+ for index in range(count):
100
+ name = torch.cuda.get_device_name(index) or f"GPU {index}"
101
+ entry: dict[str, Any] = {"index": index, "name": name, "used": True}
102
+ try:
103
+ free_b, total_b = torch.cuda.mem_get_info(index)
104
+ entry["mem_total_mb"] = int(total_b // (1024 * 1024))
105
+ entry["mem_free_mb"] = int(free_b // (1024 * 1024))
106
+ except Exception:
107
+ pass
108
+ gpus.append(entry)
109
+ except Exception:
110
+ pass
111
+ return torch, version, cuda_version, gpus
112
+
113
+
114
+ def probe_environment(env_pip: bool = False) -> dict[str, Any]:
115
+ """Assemble the environment.json payload. Everything is best-effort:
116
+ missing values are omitted (the UI renders '—' for absent fields)."""
117
+ torch, torch_version, cuda_version, torch_gpus = _torch_info()
118
+ gpus = _nvidia_smi_gpus()
119
+ if gpus is None:
120
+ # Fall back to torch's view (no driver_version without nvidia-smi).
121
+ gpus = torch_gpus
122
+
123
+ device = None
124
+ try:
125
+ if torch is not None:
126
+ device = "cuda" if torch.cuda.is_available() else "cpu"
127
+ except Exception:
128
+ device = None
129
+
130
+ total_mb, avail_mb = _meminfo_mb()
131
+ host: dict[str, Any] = {
132
+ "os": platform.system() or None,
133
+ "kernel": platform.release() or None,
134
+ "cpu_model": _cpu_model(),
135
+ "cpu_cores": os.cpu_count(),
136
+ "mem_total_mb": total_mb,
137
+ "mem_available_mb": avail_mb,
138
+ }
139
+ python: dict[str, Any] = {"version": platform.python_version()}
140
+ if torch_version:
141
+ python["torch"] = torch_version
142
+ if cuda_version:
143
+ python["cuda"] = cuda_version
144
+
145
+ env: dict[str, Any] = {
146
+ "captured_at": int(time.time()),
147
+ "device": device,
148
+ "host": host,
149
+ "gpus": gpus,
150
+ "python": python,
151
+ }
152
+ if env_pip:
153
+ try:
154
+ out = subprocess.run(
155
+ [sys.executable, "-m", "pip", "freeze"],
156
+ capture_output=True,
157
+ timeout=30,
158
+ )
159
+ if out.returncode == 0:
160
+ env["pip"] = out.stdout.decode("utf-8", "replace").splitlines()[:200]
161
+ except (OSError, subprocess.SubprocessError):
162
+ pass
163
+ return env
@@ -0,0 +1,239 @@
1
+ # ------------------------------------------------------------------------
2
+ # VENDORED from docker/customize-algo-images/runtime/mlops_metrics.py
3
+ # — do not edit; keep behavior identical to the in-image MlopsMetrics writer
4
+ # so SDK-produced rows and image-produced rows are structurally the same.
5
+ #
6
+ # DIVERGENCE from the runtime writer: ±inf leaves are dropped here because
7
+ # the events POST path cannot carry `Infinity` (invalid JSON — the whole
8
+ # batch would 400 and poison the spool); the in-image writer keeps inf in
9
+ # the JSONL file and the server skips that line at ingest.
10
+ # ------------------------------------------------------------------------
11
+ """Metric-tree cleaning/merging helpers (scheme A''').
12
+
13
+ L1 eval metrics (``AP50-95``, ``AP50``, ``AP75``, ``AR``, ``precision``, ``recall``, ``f1``)
14
+ use three layers: ``L1 → modality (box|keypoint|mask) → mean|class_name``.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import difflib
20
+ import math
21
+ from typing import Any
22
+
23
+ DEFAULT_HERO = "AP50-95/box/mean"
24
+
25
+ MODALITY_L1S = frozenset({"AP50-95", "AP50", "AP75", "AR", "precision", "recall", "f1"})
26
+ MODALITIES = frozenset({"box", "keypoint", "mask"})
27
+
28
+ _PER_CLASS_FIELDS = (
29
+ ("ap", "AP50-95"),
30
+ ("ar", "AR"),
31
+ ("f1", "f1"),
32
+ ("precision", "precision"),
33
+ ("recall", "recall"),
34
+ )
35
+
36
+
37
+ def _as_float(value: Any) -> float | None:
38
+ if value is None:
39
+ return None
40
+ try:
41
+ if hasattr(value, "detach"):
42
+ value = value.detach()
43
+ if hasattr(value, "cpu"):
44
+ value = value.cpu()
45
+ if hasattr(value, "item"):
46
+ value = value.item()
47
+ out = float(value)
48
+ except (TypeError, ValueError):
49
+ return None
50
+ if not math.isfinite(out): # NaN and ±inf (see divergence note above)
51
+ return None
52
+ return out
53
+
54
+
55
+ def _clean_leaf_map(obj: dict[str, Any]) -> dict[str, float]:
56
+ out: dict[str, float] = {}
57
+ for key, raw in obj.items():
58
+ fv = _as_float(raw)
59
+ if fv is not None:
60
+ out[str(key)] = fv
61
+ return out
62
+
63
+
64
+ def _clean_metrics_tree(obj: dict[str, Any]) -> dict[str, Any]:
65
+ out: dict[str, Any] = {}
66
+ for key, raw in obj.items():
67
+ if isinstance(raw, dict):
68
+ if key in MODALITY_L1S:
69
+ branch = _clean_modality_branch(raw)
70
+ if branch:
71
+ out[key] = branch
72
+ else:
73
+ sub = _clean_leaf_map(raw) if _is_leaf_map(raw) else _clean_metrics_tree(raw)
74
+ if sub:
75
+ out[key] = sub
76
+ else:
77
+ fv = _as_float(raw)
78
+ if fv is not None:
79
+ out[str(key)] = fv
80
+ return out
81
+
82
+
83
+ def _is_leaf_map(obj: dict[str, Any]) -> bool:
84
+ return all(not isinstance(v, dict) for v in obj.values())
85
+
86
+
87
+ def _clean_modality_branch(branch: dict[str, Any]) -> dict[str, dict[str, float]]:
88
+ out: dict[str, dict[str, float]] = {}
89
+ for modality, values in branch.items():
90
+ mod = str(modality)
91
+ if mod not in MODALITIES or not isinstance(values, dict):
92
+ continue
93
+ cleaned = _clean_leaf_map(values)
94
+ if cleaned:
95
+ out[mod] = cleaned
96
+ return out
97
+
98
+
99
+ def _merge_modality_branch(
100
+ metrics: dict[str, Any],
101
+ l1: str,
102
+ branch: dict[str, Any] | None,
103
+ ) -> None:
104
+ if not branch:
105
+ return
106
+ cleaned = _clean_modality_branch(branch)
107
+ if not cleaned:
108
+ return
109
+ existing = metrics.setdefault(l1, {})
110
+ if not isinstance(existing, dict):
111
+ return
112
+ for modality, values in cleaned.items():
113
+ mod_obj = existing.setdefault(modality, {})
114
+ if isinstance(mod_obj, dict):
115
+ mod_obj.update(values)
116
+
117
+
118
+ def _apply_per_class(metrics: dict[str, Any], per_class: list[dict[str, Any]] | None) -> None:
119
+ for prow in per_class or []:
120
+ name = str(prow.get("name") or "").strip()
121
+ if not name:
122
+ continue
123
+ modality = str(prow.get("modality") or "box").strip()
124
+ if modality not in MODALITIES:
125
+ modality = "box"
126
+ for src_key, l1 in _PER_CLASS_FIELDS:
127
+ fv = _as_float(prow.get(src_key))
128
+ if fv is None:
129
+ continue
130
+ l1_obj = metrics.setdefault(l1, {})
131
+ if not isinstance(l1_obj, dict):
132
+ continue
133
+ mod_obj = l1_obj.setdefault(modality, {})
134
+ if isinstance(mod_obj, dict):
135
+ mod_obj[name] = fv
136
+
137
+
138
+ def resolve_metric_path(metrics: dict[str, Any], path: str) -> float | None:
139
+ parts = [p for p in path.split("/") if p]
140
+ cur: Any = metrics
141
+ for part in parts:
142
+ if not isinstance(cur, dict) or part not in cur:
143
+ return None
144
+ cur = cur[part]
145
+ return _as_float(cur)
146
+
147
+
148
+ def first_leaf_path(metrics: dict[str, Any]) -> str | None:
149
+ """Slash path of the first numeric leaf in insertion order (clean tree precondition)."""
150
+ for key, value in metrics.items():
151
+ if isinstance(value, dict):
152
+ sub = first_leaf_path(value)
153
+ if sub is not None:
154
+ return f"{key}/{sub}"
155
+ else:
156
+ return key
157
+ return None
158
+
159
+
160
+ def fallback_hero_path(metrics: dict[str, Any]) -> str | None:
161
+ """First numeric leaf under a dict branch (insertion order); a bare
162
+ top-level scalar only when no dict branch yields a leaf."""
163
+ for key, value in metrics.items():
164
+ if isinstance(value, dict):
165
+ sub = first_leaf_path(value)
166
+ if sub is not None:
167
+ return f"{key}/{sub}"
168
+ for key, value in metrics.items():
169
+ if not isinstance(value, dict):
170
+ return key
171
+ return None
172
+
173
+
174
+ def leaf_paths(metrics: dict[str, Any], *, limit: int = 8) -> list[str]:
175
+ """Slash paths of numeric leaves in insertion order, capped at `limit`
176
+ (used to list valid hero paths in fallback warnings)."""
177
+ out: list[str] = []
178
+
179
+ def walk(node: dict[str, Any], prefix: str) -> None:
180
+ for key, value in node.items():
181
+ if len(out) >= limit:
182
+ return
183
+ if isinstance(value, dict):
184
+ walk(value, f"{prefix}{key}/")
185
+ else:
186
+ out.append(f"{prefix}{key}")
187
+
188
+ walk(metrics, "")
189
+ return out
190
+
191
+
192
+ def dropped_leaves(raw: dict[str, Any]) -> list[tuple[str, Any]]:
193
+ """Slash paths + raw values of leaves dropped for being non-numeric.
194
+ Mirrors the _as_float unwrap chain; NaN/None drops stay silent by design."""
195
+ out: list[tuple[str, Any]] = []
196
+
197
+ def walk(node: dict[str, Any], prefix: str) -> None:
198
+ for key, value in node.items():
199
+ path = f"{prefix}{key}"
200
+ if isinstance(value, dict):
201
+ walk(value, f"{path}/")
202
+ continue
203
+ if value is None:
204
+ continue
205
+ probe = value
206
+ try:
207
+ if hasattr(probe, "detach"):
208
+ probe = probe.detach()
209
+ if hasattr(probe, "cpu"):
210
+ probe = probe.cpu()
211
+ if hasattr(probe, "item"):
212
+ probe = probe.item()
213
+ float(probe)
214
+ except (TypeError, ValueError):
215
+ out.append((path, value))
216
+
217
+ walk(raw, "")
218
+ return out
219
+
220
+
221
+ def closest_path(query: str, candidates: list[str], *, cutoff: float = 0.6) -> str | None:
222
+ """Best fuzzy match for `query` among full slash paths (hero hints)."""
223
+ matches = difflib.get_close_matches(query, candidates, n=1, cutoff=cutoff)
224
+ return matches[0] if matches else None
225
+
226
+
227
+ def closest_leaf(query: str, paths: list[str], *, cutoff: float = 0.6) -> str | None:
228
+ """Best fuzzy match for a bare key against leaf names; returns the full path."""
229
+ by_name: dict[str, str] = {}
230
+ for p in paths:
231
+ by_name.setdefault(p.rsplit("/", 1)[-1], p)
232
+ matches = difflib.get_close_matches(query, list(by_name), n=1, cutoff=cutoff)
233
+ return by_name[matches[0]] if matches else None
234
+
235
+
236
+ def short_repr(value: Any, *, limit: int = 40) -> str:
237
+ """repr() capped at `limit` chars (tensor reprs are huge)."""
238
+ r = repr(value)
239
+ return r if len(r) <= limit else r[: limit - 3] + "..."
dmlops/_resource.py ADDED
@@ -0,0 +1,151 @@
1
+ """Whole-machine resource sampler for external runs (TELEMETRY.md §3).
2
+
3
+ Mirrors the worker-side server sampler: one JSONL row every 5s with
4
+ ``{ts, cpu_pct, mem_mb, mem_limit_mb, gpus?}`` — epoch-seconds ``ts`` (NOT
5
+ the RFC3339 string used by metrics rows; the web resource charts require a
6
+ number). CPU/memory come from ``/proc`` (Linux only), GPU from
7
+ ``nvidia-smi``; a source that is unavailable is simply omitted, and a tick
8
+ with no source at all produces no row.
9
+
10
+ Live rows stream through the events channel (``resourceSamples``) so the
11
+ Summary page charts update in real time; ``Run.finish()`` additionally
12
+ uploads the full snapshot as the ``resource_usage.jsonl`` artifact.
13
+
14
+ Set ``MLOPS_SDK_RESOURCE_SAMPLING=0`` (or ``false``/``no``) to disable.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import os
20
+ import subprocess
21
+ import threading
22
+ import time
23
+ from typing import Any
24
+
25
+ INTERVAL_SEC = 5.0
26
+ BASENAME = "resource_usage.jsonl"
27
+
28
+ _DISABLED_VALUES = {"0", "false", "no"}
29
+
30
+
31
+ def sampling_enabled() -> bool:
32
+ return (os.environ.get("MLOPS_SDK_RESOURCE_SAMPLING") or "").strip().lower() not in _DISABLED_VALUES
33
+
34
+
35
+ def _read_cpu_times() -> tuple[int, int] | None:
36
+ """(busy, total) jiffies from /proc/stat; None off-Linux."""
37
+ try:
38
+ with open("/proc/stat", encoding="utf-8") as fh:
39
+ fields = fh.readline().split()[1:]
40
+ values = [int(v) for v in fields[:8]]
41
+ except (OSError, ValueError, IndexError):
42
+ return None
43
+ idle = values[3] + (values[4] if len(values) > 4 else 0) # idle + iowait
44
+ total = sum(values)
45
+ return total - idle, total
46
+
47
+
48
+ def _read_memory() -> tuple[int, int] | None:
49
+ """(used_mb, total_mb) from /proc/meminfo; None off-Linux."""
50
+ total_kb = avail_kb = None
51
+ try:
52
+ with open("/proc/meminfo", encoding="utf-8") as fh:
53
+ for line in fh:
54
+ if line.startswith("MemTotal:"):
55
+ total_kb = int(line.split()[1])
56
+ elif line.startswith("MemAvailable:"):
57
+ avail_kb = int(line.split()[1])
58
+ if total_kb is not None and avail_kb is not None:
59
+ break
60
+ except (OSError, ValueError, IndexError):
61
+ return None
62
+ if total_kb is None or avail_kb is None:
63
+ return None
64
+ return int((total_kb - avail_kb) / 1024), int(total_kb / 1024)
65
+
66
+
67
+ def _read_gpus() -> list[dict[str, Any]] | None:
68
+ """Per-GPU util/memory via nvidia-smi; None when unavailable."""
69
+ try:
70
+ proc = subprocess.run(
71
+ [
72
+ "nvidia-smi",
73
+ "--query-gpu=index,utilization.gpu,memory.used,memory.total",
74
+ "--format=csv,noheader,nounits",
75
+ ],
76
+ capture_output=True,
77
+ text=True,
78
+ timeout=2,
79
+ )
80
+ except (OSError, subprocess.SubprocessError):
81
+ return None
82
+ if proc.returncode != 0:
83
+ return None
84
+ gpus: list[dict[str, Any]] = []
85
+ try:
86
+ for line in proc.stdout.strip().splitlines():
87
+ index, util, used, total = (part.strip() for part in line.split(","))
88
+ gpus.append(
89
+ {
90
+ "index": int(index),
91
+ "util_pct": float(util),
92
+ "mem_used_mb": int(float(used)),
93
+ "mem_total_mb": int(float(total)),
94
+ }
95
+ )
96
+ except ValueError:
97
+ return None
98
+ return gpus or None
99
+
100
+
101
+ class ResourceSampler(threading.Thread):
102
+ """Daemon thread sampling whole-machine usage every ``INTERVAL_SEC``."""
103
+
104
+ def __init__(self, run: Any) -> None:
105
+ super().__init__(name=f"mlops-resource-{run._id[:8]}", daemon=True)
106
+ self._run = run
107
+ self._stop = threading.Event()
108
+ self._rows: list[dict[str, Any]] = []
109
+ self._lock = threading.Lock()
110
+ self._prev_cpu: tuple[int, int] | None = None
111
+
112
+ def run(self) -> None: # noqa: D102 - thread entry
113
+ self._prev_cpu = _read_cpu_times() # priming frame; first row at t≈INTERVAL
114
+ while not self._stop.wait(INTERVAL_SEC):
115
+ row = self.sample_once()
116
+ if row is None:
117
+ continue
118
+ with self._lock:
119
+ self._rows.append(row)
120
+ if not self._run._finished and not self._run._cancelled.is_set():
121
+ self._run._uploader.submit(
122
+ {"type": "events", "payload": {"resourceSamples": [row]}}
123
+ )
124
+
125
+ def stop(self) -> None:
126
+ self._stop.set()
127
+ self.join(timeout=2)
128
+
129
+ def rows_snapshot(self) -> list[dict[str, Any]]:
130
+ with self._lock:
131
+ return list(self._rows)
132
+
133
+ def sample_once(self) -> dict[str, Any] | None:
134
+ row: dict[str, Any] = {"ts": int(time.time())}
135
+ cpu = _read_cpu_times()
136
+ if cpu is not None:
137
+ if self._prev_cpu is not None:
138
+ busy_delta = cpu[0] - self._prev_cpu[0]
139
+ total_delta = cpu[1] - self._prev_cpu[1]
140
+ if total_delta > 0:
141
+ row["cpu_pct"] = round(100.0 * busy_delta / total_delta, 1)
142
+ self._prev_cpu = cpu
143
+ mem = _read_memory()
144
+ if mem is not None:
145
+ row["mem_mb"], row["mem_limit_mb"] = mem
146
+ gpus = _read_gpus()
147
+ if gpus is not None:
148
+ row["gpus"] = gpus
149
+ if "cpu_pct" not in row and "mem_mb" not in row and "gpus" not in row:
150
+ return None
151
+ return row