dmlops 0.2.10__py3-none-any.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/_run.py ADDED
@@ -0,0 +1,755 @@
1
+ """The Run object: one external experiment tracked by the platform."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import atexit
6
+ import enum
7
+ import json
8
+ import os
9
+ import sys
10
+ import threading
11
+ import time
12
+ import traceback
13
+ import uuid as uuid_module
14
+ import warnings
15
+ from datetime import datetime, timezone
16
+ from pathlib import Path
17
+ from typing import Any
18
+ from urllib.parse import urlsplit
19
+
20
+ from . import _auth, _tui
21
+ from ._envprobe import probe_environment
22
+ from ._metrics_clean import (
23
+ DEFAULT_HERO,
24
+ _apply_per_class,
25
+ _clean_leaf_map,
26
+ _clean_metrics_tree,
27
+ _merge_modality_branch,
28
+ closest_leaf,
29
+ closest_path,
30
+ dropped_leaves,
31
+ fallback_hero_path,
32
+ leaf_paths,
33
+ resolve_metric_path,
34
+ short_repr,
35
+ )
36
+ from ._resource import BASENAME as RESOURCE_USAGE_BASENAME
37
+ from ._resource import ResourceSampler, sampling_enabled
38
+ from ._spool import Heartbeat, Uploader
39
+ from ._status import UploadStatusLine, status_line_enabled
40
+ from ._tee import TerminalCapture
41
+ from ._transport import Transport
42
+ from ._uploader import iter_directory, warn_upload_failed
43
+ from .exceptions import MlopsCancelled, MlopsConflict, MlopsError
44
+
45
+ SAVE_DIR_FILE_CAP = 5000
46
+ DEFAULT_UPLOAD_TIMEOUT = 1800.0
47
+
48
+
49
+ def _upload_timeout() -> float:
50
+ raw = (os.environ.get("MLOPS_SDK_UPLOAD_TIMEOUT") or "").strip()
51
+ try:
52
+ value = float(raw)
53
+ except ValueError:
54
+ return DEFAULT_UPLOAD_TIMEOUT
55
+ return value if value > 0 else DEFAULT_UPLOAD_TIMEOUT
56
+
57
+
58
+ class Job(str, enum.Enum):
59
+ """Experiment job type (mirrors server experiments.job_type)."""
60
+
61
+ TRAIN = "train"
62
+ VAL = "val"
63
+ EXPORT = "export"
64
+
65
+
66
+ class Task(str, enum.Enum):
67
+ """Experiment task type (mirrors server task_type values)."""
68
+
69
+ IMAGE_CLASSIFICATION = "image_classification"
70
+ OBJECT_DETECTION = "object_detection"
71
+ INSTANCE_SEGMENTATION = "instance_segmentation"
72
+ KEYPOINT_DETECTION = "keypoint_detection"
73
+
74
+
75
+ _active_run: "Run | None" = None
76
+ _original_excepthook = sys.excepthook
77
+ _original_sys_exit = sys.exit
78
+ _hook_installed = False
79
+
80
+ _WARNED: set[tuple[str, ...]] = set()
81
+
82
+
83
+ def _caller_location() -> str:
84
+ """file:line of the first frame outside this module (the user's call site)."""
85
+ frame = sys._getframe(1)
86
+ while frame is not None and frame.f_code.co_filename == __file__:
87
+ frame = frame.f_back
88
+ if frame is None:
89
+ return "<unknown>"
90
+ return f"{frame.f_code.co_filename}:{frame.f_lineno}"
91
+
92
+
93
+ def _docs_url(server: str) -> str:
94
+ override = (os.environ.get("MLOPS_DOCS_URL") or "").strip().rstrip("/")
95
+ if override:
96
+ return f"{override}/experiments/external-runs/#runlog_metric"
97
+ parts = urlsplit(server)
98
+ return f"{parts.scheme}://{parts.hostname}:13081/experiments/external-runs/#runlog_metric"
99
+
100
+
101
+ def _utc_ts() -> str:
102
+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
103
+
104
+
105
+ class Run:
106
+ """Handle for one external experiment.
107
+
108
+ Created by ``mlops.create_experiment()``; do not construct directly. Public surface:
109
+ ``log_metric`` / ``upload`` / ``finish`` plus read-only ``id`` / ``url`` / ``status``.
110
+ """
111
+
112
+ def __init__(
113
+ self,
114
+ transport: Transport,
115
+ experiment: dict[str, Any],
116
+ *,
117
+ out_dir: "str | os.PathLike[str] | None",
118
+ capture_output: bool,
119
+ env_pip: bool,
120
+ ) -> None:
121
+ self._transport = transport
122
+ self._id = str(experiment["id"])
123
+ self._server = transport.server
124
+ self._out_dir = Path(out_dir) if out_dir is not None else None
125
+ self._status = "in_progress"
126
+ self._finished = False
127
+ self._finish_lock = threading.Lock()
128
+ self._cancelled = threading.Event()
129
+ self._auto_step = 0
130
+ self._saved_paths: set[str] = set()
131
+
132
+ # Terminal upload status line: only with capture (the tee provides
133
+ # erase/redraw coordination) on a real TTY; MLOPS_SDK_STATUS_LINE=0
134
+ # opts out. Created before the tee so it writes to the original
135
+ # stderr and never reaches the Web Logs.
136
+ self._status_line = (
137
+ UploadStatusLine(sys.stderr)
138
+ if (capture_output and status_line_enabled(sys.stderr))
139
+ else None
140
+ )
141
+ self._uploader = Uploader(transport, self._id, self, status=self._status_line)
142
+ self._heartbeat = Heartbeat(transport, self._id, self)
143
+ self._capture = (
144
+ TerminalCapture(self._enqueue_log_lines, status=self._status_line)
145
+ if capture_output
146
+ else None
147
+ )
148
+
149
+ self._uploader.start()
150
+ self._heartbeat.start()
151
+ if self._capture is not None:
152
+ try:
153
+ self._capture.install()
154
+ except Exception as exc: # capture failure must not break training
155
+ warnings.warn(f"[mlops] terminal capture disabled: {exc}")
156
+
157
+ # Environment card: environment.json via the artifact channel.
158
+ try:
159
+ env = probe_environment(env_pip=env_pip)
160
+ self._save_bytes(json.dumps(env).encode("utf-8"), "environment.json")
161
+ except Exception as exc:
162
+ warnings.warn(f"[mlops] environment probe failed: {exc}")
163
+
164
+ # Whole-machine resource sampling (live resourceSamples + final
165
+ # resource_usage.jsonl artifact); MLOPS_SDK_RESOURCE_SAMPLING=0 opts out.
166
+ self._sampler = ResourceSampler(self) if sampling_enabled() else None
167
+ if self._sampler is not None:
168
+ self._sampler.start()
169
+
170
+ _install_hooks(self)
171
+ atexit.register(self._atexit_finish)
172
+
173
+ # -- read-only properties --------------------------------------------
174
+ @property
175
+ def id(self) -> str:
176
+ return self._id
177
+
178
+ @property
179
+ def url(self) -> str:
180
+ return f"{self._server}/experiments/{self._id}"
181
+
182
+ @property
183
+ def status(self) -> str:
184
+ return self._status
185
+
186
+ # -- metrics ----------------------------------------------------------
187
+ def log_metric(
188
+ self,
189
+ metrics: "dict[str, Any] | None" = None,
190
+ *,
191
+ epoch: "int | float | None" = None,
192
+ step: "int | None" = None,
193
+ split: str = "train",
194
+ hero: "str | None" = None,
195
+ loss: "dict[str, Any] | None" = None,
196
+ lr: "dict[str, Any] | None" = None,
197
+ ap5095: "dict[str, Any] | None" = None,
198
+ ap50: "dict[str, Any] | None" = None,
199
+ ap75: "dict[str, Any] | None" = None,
200
+ ar: "dict[str, Any] | None" = None,
201
+ precision: "dict[str, Any] | None" = None,
202
+ recall: "dict[str, Any] | None" = None,
203
+ f1: "dict[str, Any] | None" = None,
204
+ others: "dict[str, Any] | None" = None,
205
+ per_class: "list[dict[str, Any]] | None" = None,
206
+ ) -> None:
207
+ """Record one metrics point (same contract as the in-image
208
+ ``MlopsMetrics`` writer; keyword arguments merge like
209
+ ``MlopsMetrics.append_val`` and apply to any split).
210
+
211
+ ``hero`` is a slash path to a numeric leaf inside ``metrics`` (e.g.
212
+ ``loss/total``, ``AP50-95/box/mean``). An explicit but unresolvable
213
+ hero warns and falls back to the first leaf under a dict branch;
214
+ when omitted, val/export rows try ``AP50-95/box/mean`` first, then
215
+ the same fallback. Bare top-level numeric keys (e.g.
216
+ ``{"total": 0.5}``) warn and are skipped by the fallback.
217
+ Warnings name the call site and show Got/Expected (plus a
218
+ did-you-mean hint and docs link); non-numeric leaf values are
219
+ dropped with a warning (NaN/None stay silent).
220
+
221
+ ``epoch``/``step`` accept ints or values truncatable to int
222
+ (``int()`` truncation, same as the in-image writer). ``split``
223
+ must be ``"train"``, ``"val"``, or ``"export"``; anything else
224
+ warns once and the row is skipped (the server would silently
225
+ drop it).
226
+
227
+ Raises ``MlopsCancelled`` when the server cancelled this run.
228
+ """
229
+ if self._cancelled.is_set():
230
+ raise MlopsCancelled("run was cancelled on the server")
231
+ if split not in ("train", "val", "export"):
232
+ warn_key = ("split", split)
233
+ if warn_key not in _WARNED:
234
+ _WARNED.add(warn_key)
235
+ warnings.warn(
236
+ f"[mlops] log_metric() — invalid split {split!r} at {_caller_location()} — "
237
+ "expected 'train', 'val', or 'export'; row skipped",
238
+ stacklevel=2,
239
+ )
240
+ return
241
+ payload: dict[str, Any] = dict(metrics or {})
242
+ _merge_modality_branch(payload, "AP50-95", ap5095)
243
+ _merge_modality_branch(payload, "AP50", ap50)
244
+ _merge_modality_branch(payload, "AP75", ap75)
245
+ _merge_modality_branch(payload, "AR", ar)
246
+ _merge_modality_branch(payload, "precision", precision)
247
+ _merge_modality_branch(payload, "recall", recall)
248
+ _merge_modality_branch(payload, "f1", f1)
249
+ if loss:
250
+ cleaned = _clean_leaf_map(loss)
251
+ if cleaned:
252
+ payload["loss"] = cleaned
253
+ if lr:
254
+ cleaned = _clean_leaf_map(lr)
255
+ if cleaned:
256
+ payload["lr"] = cleaned
257
+ if others:
258
+ cleaned = _clean_leaf_map(others)
259
+ if cleaned:
260
+ payload["others"] = cleaned
261
+ _apply_per_class(payload, per_class)
262
+
263
+ clean = _clean_metrics_tree(payload)
264
+ if not clean:
265
+ return
266
+ bare_keys = [k for k, v in clean.items() if not isinstance(v, dict)]
267
+ if bare_keys:
268
+ warn_key = ("bare", *bare_keys)
269
+ if warn_key not in _WARNED:
270
+ _WARNED.add(warn_key)
271
+ shown = bare_keys[:5]
272
+ got = "{" + ", ".join(f"{k!r}: {clean[k]!r}" for k in shown) + "}"
273
+ if len(bare_keys) > 5:
274
+ got += f" … and {len(bare_keys) - 5} more"
275
+ nested = [p for p in leaf_paths(clean, limit=50) if "/" in p]
276
+ first = bare_keys[0]
277
+ match = next((p for p in nested if p.rsplit("/", 1)[-1] == first), None)
278
+ branch = match.rsplit("/", 1)[0] if match else "<branch>"
279
+ expected = f"{{'{branch}': {{{first!r}: {clean[first]!r}}}}}"
280
+ comment = " # expected shape"
281
+ if len(bare_keys) > 1:
282
+ comment += f"; {len(bare_keys) - 1} more bare key(s) omitted"
283
+ lines = [
284
+ f"[mlops] log_metric() — bare top-level metric key(s) at {_caller_location()}",
285
+ f" Got: {got}",
286
+ f" Expected: {expected}{comment}",
287
+ ]
288
+ if match is None:
289
+ hint = closest_leaf(first, nested)
290
+ if hint:
291
+ lines.append(f" Hint: did you mean '{hint}'?")
292
+ lines.append(
293
+ " Note: bare keys draw flat curves and are skipped when picking the fallback hero"
294
+ )
295
+ lines.append(f" Docs: {_docs_url(self._server)}")
296
+ warnings.warn("\n".join(lines), stacklevel=2)
297
+ dropped = dropped_leaves(payload)
298
+ if dropped:
299
+ warn_key = ("dropped", *(p for p, _ in dropped))
300
+ if warn_key not in _WARNED:
301
+ _WARNED.add(warn_key)
302
+ shown = dropped[:5]
303
+ got = "{" + ", ".join(f"{p!r}: {short_repr(v)}" for p, v in shown) + "}"
304
+ if len(dropped) > 5:
305
+ got += f" … and {len(dropped) - 5} more"
306
+ warnings.warn(
307
+ "\n".join(
308
+ [
309
+ f"[mlops] log_metric() — non-numeric leaf value(s) dropped at {_caller_location()}",
310
+ f" Got: {got}",
311
+ " Expected: numeric leaf values (int/float or numeric string)",
312
+ " Note: dropped keys never reach metrics, curves, or hero selection",
313
+ f" Docs: {_docs_url(self._server)}",
314
+ ]
315
+ ),
316
+ stacklevel=2,
317
+ )
318
+ if epoch is None and step is None:
319
+ self._auto_step += 1
320
+ step = self._auto_step
321
+ row: dict[str, Any] = {
322
+ "ts": _utc_ts(),
323
+ "split": split,
324
+ "metrics": clean,
325
+ }
326
+ if epoch is not None:
327
+ row["epoch"] = int(epoch)
328
+ if step is not None:
329
+ row["step"] = int(step)
330
+ hero_key = hero if hero is not None else (
331
+ DEFAULT_HERO if split in ("val", "export") else None
332
+ )
333
+ if hero_key and resolve_metric_path(clean, hero_key) is not None:
334
+ row["heroMetric"] = hero_key
335
+ else:
336
+ # Fallback keeps heroMetric non-empty: explicit-but-unresolvable
337
+ # hero (typo) or no hero at all (train rows, val/export without
338
+ # the default AP path) → first leaf under a dict branch.
339
+ fallback = fallback_hero_path(clean)
340
+ if fallback:
341
+ if hero is not None:
342
+ warn_key = ("hero", hero)
343
+ if warn_key not in _WARNED:
344
+ _WARNED.add(warn_key)
345
+ all_paths = leaf_paths(clean, limit=9)
346
+ valid = ", ".join(f"'{p}'" for p in all_paths[:8])
347
+ if len(all_paths) > 8:
348
+ valid += ", …"
349
+ lines = [
350
+ f"[mlops] log_metric() — hero does not resolve to a numeric leaf at {_caller_location()}",
351
+ f" Got: hero={hero!r}",
352
+ f" Expected: a slash path to a numeric leaf in this row — valid: {valid}",
353
+ ]
354
+ hint = closest_path(hero, leaf_paths(clean, limit=50))
355
+ if hint:
356
+ lines.append(f" Hint: did you mean '{hint}'?")
357
+ lines.append(f" Applied: fallback hero '{fallback}' written for this row")
358
+ lines.append(f" Docs: {_docs_url(self._server)}")
359
+ warnings.warn("\n".join(lines), stacklevel=2)
360
+ row["heroMetric"] = fallback
361
+ self._uploader.submit({"type": "events", "payload": {"lines": [row]}})
362
+
363
+ # -- artifacts --------------------------------------------------------
364
+ def upload(
365
+ self,
366
+ source: "str | os.PathLike[str]",
367
+ *,
368
+ recursive: bool = True,
369
+ include_hidden: bool = False,
370
+ ) -> None:
371
+ """Upload a file or a whole directory as experiment artifacts.
372
+
373
+ ``source`` must be a path to an existing file or directory (bytes
374
+ and file objects are no longer accepted — write them to a file
375
+ first). The artifact path is the file name; for directories it is
376
+ ``<root dir name>/<relative path>``. Classification (weights /
377
+ checkpoint / export / artifact) is done server-side by extension.
378
+
379
+ Directory walks are recursive by default (``recursive=False`` keeps
380
+ only top-level files) and skip hidden entries — any file or
381
+ directory whose name starts with ``.`` — unless
382
+ ``include_hidden=True``. ``recursive``/``include_hidden`` affect
383
+ directory sources only; an explicitly named hidden single file is
384
+ always uploaded. Symlinks and special files are skipped; a
385
+ directory is truncated to 5000 files.
386
+
387
+ Uploading a path that was already uploaded in this run is skipped
388
+ with a warning (single file) or one aggregated warning (directory).
389
+ Per-file failures warn, never raise.
390
+ """
391
+ if self._finished:
392
+ warnings.warn("[mlops] upload() after finish() ignored", stacklevel=2)
393
+ return
394
+ if self._cancelled.is_set():
395
+ warnings.warn("[mlops] upload() after server cancel ignored", stacklevel=2)
396
+ return
397
+ if not isinstance(source, (str, os.PathLike)):
398
+ raise MlopsError(
399
+ f"upload() source must be a file or directory path, got "
400
+ f"{type(source).__name__} — bytes/file objects are no longer supported"
401
+ )
402
+ root = Path(source)
403
+ if root.is_dir():
404
+ base = root.name or "out"
405
+ files = iter_directory(
406
+ root, recursive=recursive, include_hidden=include_hidden
407
+ )
408
+ if len(files) > SAVE_DIR_FILE_CAP:
409
+ warnings.warn(
410
+ f"[mlops] directory save truncated to {SAVE_DIR_FILE_CAP} files "
411
+ f"({len(files)} found)",
412
+ stacklevel=2,
413
+ )
414
+ files = files[:SAVE_DIR_FILE_CAP]
415
+ skipped: list[str] = []
416
+ for full, rel in files:
417
+ target = f"{base}/{rel}"
418
+ if target in self._saved_paths:
419
+ skipped.append(target)
420
+ continue
421
+ self._saved_paths.add(target)
422
+ self._uploader.submit({"type": "save", "source": full, "path": target})
423
+ if skipped:
424
+ shown = ", ".join(skipped[:3])
425
+ if len(skipped) > 3:
426
+ shown += " …"
427
+ warnings.warn(
428
+ f"[mlops] upload(): {len(skipped)} file(s) already uploaded — skipped: {shown}",
429
+ stacklevel=2,
430
+ )
431
+ return
432
+ if not root.exists():
433
+ raise MlopsError(f"upload() source does not exist: {root}")
434
+ target = root.name
435
+ if target in self._saved_paths:
436
+ warnings.warn(
437
+ f"[mlops] upload(): '{target}' already uploaded — skipped",
438
+ stacklevel=2,
439
+ )
440
+ return
441
+ self._saved_paths.add(target)
442
+ self._uploader.submit({"type": "save", "source": root, "path": target})
443
+
444
+ def _save_bytes(self, data: bytes, path: str) -> None:
445
+ """Internal bytes upload (environment.json, resource snapshot)."""
446
+ if path in self._saved_paths:
447
+ return
448
+ self._saved_paths.add(path)
449
+ self._uploader.submit({"type": "save", "source": data, "path": path})
450
+
451
+ # -- finish -----------------------------------------------------------
452
+ def finish(
453
+ self,
454
+ status: str = "success",
455
+ *,
456
+ error: "str | BaseException | None" = None,
457
+ ) -> None:
458
+ """Close the run: harvest ``out_dir`` (if declared), flush the spool,
459
+ then POST finish. Idempotent; ``error`` forces ``status="failed"``
460
+ with the traceback as the server-side error message.
461
+
462
+ Waits for all pending artifact uploads to complete before finishing,
463
+ up to ``MLOPS_SDK_UPLOAD_TIMEOUT`` seconds (default 1800); artifacts
464
+ still uploading past that limit are abandoned with a named warning.
465
+ """
466
+ if status not in ("success", "failed", "cancelled"):
467
+ raise MlopsError(
468
+ f"invalid finish status {status!r} — expected 'success', 'failed', or 'cancelled'"
469
+ )
470
+ with self._finish_lock:
471
+ if self._finished:
472
+ return
473
+ if error is not None:
474
+ status = "failed"
475
+ # A server-side cancel always wins over an implicit/explicit
476
+ # success report (e.g. the atexit success default).
477
+ if status == "success" and self._cancelled.is_set():
478
+ status = "cancelled"
479
+ # Harvest before setting the finished guard: upload() rejects new
480
+ # items after that point. The lock also deduplicates concurrent
481
+ # finish calls while directory enumeration is in progress.
482
+ # The resource snapshot goes first so the SDK's
483
+ # resource_usage.jsonl precedes any same-named out_dir file in
484
+ # the artifacts array (the web charts use the first match).
485
+ if self._sampler is not None:
486
+ self._sampler.stop()
487
+ rows = self._sampler.rows_snapshot()
488
+ if rows:
489
+ self._save_bytes(
490
+ "".join(json.dumps(r) + "\n" for r in rows).encode("utf-8"),
491
+ RESOURCE_USAGE_BASENAME,
492
+ )
493
+ if self._out_dir is not None:
494
+ if self._out_dir.is_dir():
495
+ self._harvest_out_dir()
496
+ else:
497
+ warnings.warn(
498
+ f"[mlops] out_dir '{self._out_dir}' does not exist at finish — nothing harvested",
499
+ stacklevel=2,
500
+ )
501
+ self._finished = True
502
+ try:
503
+ # Wait for artifact saves to finish (bounded): a large upload must
504
+ # not be orphaned when the process exits right after finish().
505
+ save_timeout = _upload_timeout()
506
+ save_deadline = time.monotonic() + save_timeout
507
+ while (
508
+ self._uploader.pending_saves() > 0
509
+ and time.monotonic() < save_deadline
510
+ ):
511
+ time.sleep(0.2)
512
+ remaining = self._uploader.pending_saves()
513
+ if remaining:
514
+ msg = (
515
+ f"[mlops] finish(): {remaining} artifact(s) still uploading after "
516
+ f"{save_timeout:.0f}s (MLOPS_SDK_UPLOAD_TIMEOUT) — abandoning them"
517
+ )
518
+ warnings.warn(msg, stacklevel=2)
519
+ # The uploader thread may be blocked inside a large PUT and
520
+ # never flush the tee'd copy of this warning — post it
521
+ # directly so it is visible in the web logs (Terminal tab).
522
+ # Best-effort: logging must never break finish.
523
+ try:
524
+ self._transport.request(
525
+ "POST",
526
+ f"/api/experiments/{self._id}/events",
527
+ {"logLines": [msg]},
528
+ )
529
+ except Exception:
530
+ pass
531
+ # Then drain events (small) as before.
532
+ deadline = time.monotonic() + 5.0
533
+ while self._uploader.pending() and time.monotonic() < deadline:
534
+ time.sleep(0.1)
535
+ self._uploader.flush_and_stop(timeout=max(0.0, deadline - time.monotonic()))
536
+ self._heartbeat.stop()
537
+
538
+ body: dict[str, Any] = {"status": status}
539
+ if error is not None:
540
+ body["error"] = (
541
+ error if isinstance(error, str) else "".join(
542
+ traceback.format_exception(type(error), error, error.__traceback__)
543
+ )
544
+ )
545
+ try:
546
+ self._transport.request(
547
+ "POST", f"/api/experiments/{self._id}/finish", body, timeout=60.0
548
+ )
549
+ self._status = status
550
+ except MlopsConflict:
551
+ raise
552
+ except MlopsError as exc:
553
+ warnings.warn(f"[mlops] finish call failed: {exc}", stacklevel=2)
554
+ finally:
555
+ self._teardown_hooks()
556
+
557
+ def _harvest_out_dir(self) -> None:
558
+ assert self._out_dir is not None
559
+ try:
560
+ self.upload(self._out_dir)
561
+ except Exception as exc:
562
+ warn_upload_failed(str(self._out_dir), exc)
563
+
564
+ # -- internal ---------------------------------------------------------
565
+ def _enqueue_log_lines(self, lines: list[str]) -> None:
566
+ # No _finished guard: finish() emits its upload-timeout/abandon
567
+ # warnings after setting the flag, and they must still reach the
568
+ # web logs. Uploader.submit() itself drops items once stopping, so
569
+ # nothing is enqueued after flush_and_stop.
570
+ if self._cancelled.is_set():
571
+ return
572
+ self._uploader.submit({"type": "events", "payload": {"logLines": lines}})
573
+
574
+ def _set_cancelled(self) -> None:
575
+ self._cancelled.set()
576
+
577
+ def _atexit_finish(self) -> None:
578
+ # Normal interpreter exit with no explicit finish → report success.
579
+ # The sys.exit wrapper reports its explicit status before atexit runs,
580
+ # so anything reaching here finished without an explicit status.
581
+ if not self._finished:
582
+ try:
583
+ self.finish("success")
584
+ except Exception:
585
+ pass
586
+
587
+ def _teardown_hooks(self) -> None:
588
+ global _active_run
589
+ if self._capture is not None:
590
+ try:
591
+ self._capture.restore()
592
+ except Exception:
593
+ pass
594
+ if self._status_line is not None:
595
+ self._status_line.erase()
596
+ if _active_run is self:
597
+ _active_run = None
598
+
599
+
600
+ def _install_hooks(run: Run) -> None:
601
+ """Install process-exit wrappers and keep the active-run reference.
602
+
603
+ - ordinary uncaught exception → finish(failed, traceback) → original hook
604
+ - MlopsCancelled / KeyboardInterrupt → finish(cancelled) → original hook
605
+ - sys.exit(None/0) → finish(success); other codes → finish(failed)
606
+ - the original sys.exit always runs, preserving the process exit status
607
+ """
608
+ global _active_run, _hook_installed
609
+ _active_run = run
610
+
611
+ if _hook_installed:
612
+ return
613
+
614
+ def _hook(exc_type: Any, exc: BaseException, tb: Any) -> None:
615
+ run_ref = _active_run
616
+ if run_ref is not None and not run_ref._finished:
617
+ try:
618
+ if exc_type is SystemExit:
619
+ code = exc.code
620
+ if code is None or (isinstance(code, int) and code == 0):
621
+ run_ref.finish("success")
622
+ else:
623
+ run_ref.finish("failed", error=f"SystemExit({code})")
624
+ elif issubclass(exc_type, MlopsCancelled):
625
+ run_ref.finish("cancelled")
626
+ elif issubclass(exc_type, KeyboardInterrupt):
627
+ run_ref.finish("cancelled")
628
+ else:
629
+ run_ref.finish("failed", error=exc)
630
+ except Exception:
631
+ pass
632
+ _original_excepthook(exc_type, exc, tb)
633
+
634
+ def _exit(code: Any = None) -> None:
635
+ run_ref = _active_run
636
+ try:
637
+ if run_ref is not None and not run_ref._finished:
638
+ try:
639
+ if code is None or (isinstance(code, int) and code == 0):
640
+ run_ref.finish("success")
641
+ else:
642
+ run_ref.finish("failed", error=f"SystemExit({code})")
643
+ except Exception:
644
+ pass
645
+ finally:
646
+ _original_sys_exit(code)
647
+
648
+ sys.excepthook = _hook
649
+ sys.exit = _exit
650
+ _hook_installed = True
651
+
652
+
653
+ def create_experiment(
654
+ *,
655
+ job: "Job | str",
656
+ name: "str | None" = None,
657
+ description: str = "",
658
+ task: "Task | str | None" = None,
659
+ total: "int | None" = None,
660
+ out_dir: "str | os.PathLike[str] | None" = None,
661
+ env_pip: bool = False,
662
+ capture_output: bool = True,
663
+ export_format: "str | None" = None,
664
+ ) -> Run:
665
+ """Register a new external run and return its handle.
666
+
667
+ ``job`` is required: ``"train"``, ``"val"``, or ``"export"`` (or the
668
+ matching ``mlops.Job`` member). ``name`` is optional — when omitted a
669
+ name like ``train-20261125-103015-a3f9`` is generated from the job, the
670
+ local time, and the run id.
671
+
672
+ ``task`` optionally tags the experiment with one of ``"image_classification"``,
673
+ ``"object_detection"``, ``"instance_segmentation"``, or ``"keypoint_detection"``
674
+ (or the matching ``mlops.Task`` member) so the UI can show a task badge.
675
+
676
+ ``total`` optionally sets the total number of epochs (or steps) for the
677
+ run. The progress axis follows the metrics actually reported: when
678
+ metrics record ``epoch`` the total counts epochs, otherwise steps; when
679
+ both are recorded, epochs win. It can only be set at creation time.
680
+
681
+ ``export_format`` optionally tags an export run's format (e.g.
682
+ ``"onnx"``); the server stores it as ``hyperparams.format`` and the
683
+ experiment card shows it as the Format stat. Only valid with
684
+ ``job="export"``.
685
+
686
+ Installs the failure/cancellation hooks (``sys.excepthook`` + ``atexit``):
687
+ uncaught exceptions report ``failed``, Ctrl+C reports ``cancelled``, a
688
+ silent interpreter exit reports ``success``.
689
+ """
690
+ try:
691
+ job_value = Job(job).value
692
+ except ValueError:
693
+ raise MlopsError(
694
+ f"invalid job {job!r} — expected 'train', 'val', or 'export'"
695
+ ) from None
696
+ if export_format is not None:
697
+ if job_value != "export":
698
+ raise MlopsError("export_format is only valid for job='export'")
699
+ export_format = export_format.strip()
700
+ if not export_format:
701
+ raise MlopsError("export_format must be a non-empty string")
702
+ if task is None:
703
+ task_value = None
704
+ else:
705
+ try:
706
+ task_value = Task(task).value
707
+ except ValueError:
708
+ raise MlopsError(
709
+ f"invalid task {task!r} — expected 'image_classification', "
710
+ "'object_detection', 'instance_segmentation', or 'keypoint_detection'"
711
+ ) from None
712
+ if total is not None:
713
+ if isinstance(total, bool) or not isinstance(total, int) or total <= 0:
714
+ raise MlopsError(
715
+ f"invalid total {total!r} — expected a positive integer"
716
+ ) from None
717
+ name = (name or "").strip() or None
718
+ run_uuid = str(uuid_module.uuid4())
719
+ if name is None:
720
+ name = f"{job_value}-{datetime.now():%Y%m%d-%H%M%S}-{run_uuid[:4]}"
721
+ transport = _auth.require_transport()
722
+ body: dict[str, Any] = {
723
+ "runUuid": run_uuid,
724
+ "name": name,
725
+ "description": description,
726
+ "jobType": job_value,
727
+ }
728
+ if task_value is not None:
729
+ body["taskType"] = task_value
730
+ if total is not None:
731
+ body["total"] = total
732
+ if export_format is not None:
733
+ body["exportFormat"] = export_format
734
+ experiment = transport.request(
735
+ "POST",
736
+ "/api/experiments/external",
737
+ body,
738
+ timeout=60.0,
739
+ )
740
+ existing = _active_run
741
+ if existing is not None and not existing._finished:
742
+ warnings.warn(
743
+ "[mlops] another run is still active in this process — hooks and "
744
+ "terminal capture are shared; prefer one active run per process",
745
+ stacklevel=2,
746
+ )
747
+ run = Run(
748
+ transport,
749
+ experiment,
750
+ out_dir=out_dir,
751
+ capture_output=capture_output,
752
+ env_pip=env_pip,
753
+ )
754
+ _tui.print_experiment_created(run.url)
755
+ return run