deepforge-research-toolkit 0.7.1__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.
Files changed (53) hide show
  1. deepforge/__init__.py +3 -0
  2. deepforge/__main__.py +3 -0
  3. deepforge/advanced.py +117 -0
  4. deepforge/assets/icon.png +0 -0
  5. deepforge/assets/xvarna.png +0 -0
  6. deepforge/assets/xvarna_about.png +0 -0
  7. deepforge/assets/xvarna_sidebar.png +0 -0
  8. deepforge/audit.py +192 -0
  9. deepforge/automation.py +143 -0
  10. deepforge/checkpoint.py +155 -0
  11. deepforge/checkpoint_config.py +20 -0
  12. deepforge/checkpoint_torch.py +62 -0
  13. deepforge/checkpoint_yolo.py +18 -0
  14. deepforge/cli.py +119 -0
  15. deepforge/datasets.py +61 -0
  16. deepforge/diagnostics.py +67 -0
  17. deepforge/environment.py +26 -0
  18. deepforge/gui.py +579 -0
  19. deepforge/gui_data.py +119 -0
  20. deepforge/history.py +41 -0
  21. deepforge/live_view.py +100 -0
  22. deepforge/metrics.py +40 -0
  23. deepforge/models.py +19 -0
  24. deepforge/monitor.py +152 -0
  25. deepforge/notebook.py +73 -0
  26. deepforge/preview.py +20 -0
  27. deepforge/profiler.py +283 -0
  28. deepforge/reporting.py +118 -0
  29. deepforge/resources.py +24 -0
  30. deepforge/samples/dataset/test/square/sample_d.png +0 -0
  31. deepforge/samples/dataset/train/circle/sample_a.png +0 -0
  32. deepforge/samples/dataset/train/square/sample_b.png +0 -0
  33. deepforge/samples/dataset/val/circle/sample_c.png +0 -0
  34. deepforge/samples/groups.csv +6 -0
  35. deepforge/samples/history.csv +5 -0
  36. deepforge/samples/predictions.csv +5 -0
  37. deepforge/samples/runs/baseline.csv +5 -0
  38. deepforge/samples/runs/refined.csv +5 -0
  39. deepforge/samples/scores.csv +9 -0
  40. deepforge/samples/yolo/images/test/sample.png +0 -0
  41. deepforge/samples/yolo/images/train/sample.png +0 -0
  42. deepforge/samples/yolo/images/val/sample.png +0 -0
  43. deepforge/samples/yolo/labels/test/sample.txt +1 -0
  44. deepforge/samples/yolo/labels/train/sample.txt +1 -0
  45. deepforge/samples/yolo/labels/val/sample.txt +1 -0
  46. deepforge/training.py +118 -0
  47. deepforge/ultralytics.py +58 -0
  48. deepforge_research_toolkit-0.7.1.dist-info/METADATA +462 -0
  49. deepforge_research_toolkit-0.7.1.dist-info/RECORD +53 -0
  50. deepforge_research_toolkit-0.7.1.dist-info/WHEEL +5 -0
  51. deepforge_research_toolkit-0.7.1.dist-info/entry_points.txt +4 -0
  52. deepforge_research_toolkit-0.7.1.dist-info/licenses/LICENSE +21 -0
  53. deepforge_research_toolkit-0.7.1.dist-info/top_level.txt +1 -0
deepforge/gui_data.py ADDED
@@ -0,0 +1,119 @@
1
+ """UI-independent adapters for the desktop workspace."""
2
+ import csv
3
+ from .datasets import inspect_dataset
4
+ from .history import analyze_history
5
+ from .metrics import evaluate_csv
6
+ from .environment import inspect_environment
7
+ from .models import inspect_model
8
+ from .audit import audit_images, audit_groups, audit_yolo
9
+ from .advanced import read_binary_scores, compare_runs, reproducibility_manifest
10
+
11
+ TOOLS = {
12
+ "Dataset": ("Dataset inspector", "Inspect image counts and class balance by split."),
13
+ "Leakage": ("Leakage detector", "Find byte-identical images across dataset splits."),
14
+ "Training": ("Training analyzer", "Identify the best epoch and inspect learning curves."),
15
+ "Metrics": ("Classification evaluator", "Compare predictions and visualize the confusion matrix."),
16
+ "Model": ("Model inspector", "Profile a locally constructed PyTorch MLP: parameters, tensor shapes, MACs and latency."),
17
+ "Environment": ("Environment inspector", "Review Python, PyTorch and CUDA availability."),
18
+ "Images": ("Image integrity & similarity", "Decode images and flag bounded cross-split perceptual matches."),
19
+ "Groups": ("Group leakage audit", "Detect patient, subject or group IDs shared across splits."),
20
+ "YOLO": ("YOLO label audit", "Validate normalized detection boxes, class IDs and label pairing."),
21
+ "Compare": ("Experiment comparison", "Rank comparable validation histories and report rejected runs."),
22
+ "Scores": ("Binary score evaluation", "Measure ROC-AUC, average precision, calibration and threshold metrics."),
23
+ "Manifest": ("Reproducibility manifest", "Capture runtime, dependency versions and optional file SHA-256."),
24
+ }
25
+
26
+
27
+ def analyze(tool, options):
28
+ """Run an explicitly selected analysis. Returns a report and optional chart data."""
29
+ if tool in ("Dataset", "Leakage"):
30
+ report = inspect_dataset(options["path"], hash_files=tool == "Leakage")
31
+ chart = {"type": "bars", "values": [(s, v["total"]) for s, v in report["splits"].items()]}
32
+ elif tool == "Training":
33
+ args = {k: options[k] for k in ("metric", "mode", "epoch_column")}
34
+ args["train_metric"] = options.get("train_metric") or None
35
+ report = analyze_history(options["path"], **args)
36
+ with open(options["path"], encoding="utf-8-sig", newline="") as f:
37
+ rows = list(csv.DictReader(f))
38
+ chart = {"type": "lines", "x": [float(r[args["epoch_column"]]) for r in rows],
39
+ "series": {k: [float(r[k]) for r in rows] for k in dict.fromkeys(filter(None, [args["metric"], args["train_metric"]]))}}
40
+ elif tool == "Metrics":
41
+ report = evaluate_csv(options["path"], options["true_column"], options["pred_column"])
42
+ chart = {"type": "matrix", "labels": report["labels"], "values": report["confusion_matrix"]}
43
+ elif tool == "Model":
44
+ sizes = [int(options[k]) for k in ("inputs", "hidden", "outputs")]
45
+ from .profiler import profile_mlp
46
+ report = profile_mlp(*sizes, batch=int(options.get("batch", "1")), warmup=1, repeats=3)
47
+ chart = {"type": "bars", "values": [(f"{r['name']} {r['type']}", r["estimated_macs"]) for r in report["calls"] if r["estimated_macs"] is not None]}
48
+ elif tool == "Images":
49
+ report = audit_images(options['path'], similarity=options.get('similarity', 'yes') == 'yes', threshold=int(options.get('threshold', '4')), max_images=int(options.get('max_images', '2000')))
50
+ chart = {'type': 'bars', 'values': [('Decoded', report['decoded']), ('Invalid', report['invalid_images']), ('Unsupported', report['unsupported_images'])]}
51
+ elif tool == "Groups":
52
+ report = audit_groups(options['path'], group_column=options.get('group_column', 'group_id'), split_column=options.get('split_column', 'split'))
53
+ chart = {'type': 'bars', 'values': list(report['split_counts'].items())}
54
+ elif tool == "YOLO":
55
+ report = audit_yolo(options['path'], classes=int(options['classes']) if options.get('classes') else None)
56
+ chart = {'type': 'bars', 'values': list(report['class_counts'].items()) or [('Valid boxes', 0)]}
57
+ elif tool == "Compare":
58
+ report = compare_runs(options['path'], metric=options.get('metric', 'val_loss'), mode=options.get('mode', 'min'), train_metric=options.get('train_metric') or None, epoch_column=options.get('epoch_column', 'epoch'))
59
+ chart = {'type': 'bars', 'values': [(r['run'], r['best_value']) for r in report['ranking'][:12]]}
60
+ elif tool == "Scores":
61
+ report = read_binary_scores(options['path'], true_column=options.get('true_column', 'y_true'), score_column=options.get('score_column', 'score'), positive_label=options.get('positive_label', '1'), threshold=float(options.get('threshold', '.5')))
62
+ chart = {'type': 'roc', 'x': [r['fpr'] for r in report['roc_curve']], 'y': [r['tpr'] for r in report['roc_curve']]}
63
+ elif tool == "Manifest":
64
+ report, chart = reproducibility_manifest(options.get('path') or None), None
65
+ elif tool == "Environment":
66
+ report, chart = inspect_environment(), None
67
+ else:
68
+ raise ValueError(f"Unknown tool: {tool}")
69
+ return report, chart
70
+
71
+
72
+ def summary(tool, report):
73
+ if tool in ("Dataset", "Leakage"):
74
+ values = [("Image files", f'{report["total"]:,}'), ("Splits", str(len(report["splits"])))]
75
+ if tool == "Leakage":
76
+ values.append(("Duplicate groups", str(report["cross_split_duplicate_groups"])))
77
+ return values
78
+ if tool == "Training":
79
+ return [("Epochs", str(report["epochs_logged"])), ("Best epoch", f'{report["best_epoch"]:g}'), ("Best metric", f'{report["best_value"]:.5g}')]
80
+ if tool == "Metrics":
81
+ return [("Samples", str(report["samples"])), ("Accuracy", f'{report["accuracy"]:.1%}'), ("Macro F1", f'{report["macro"]["f1"]:.3f}')]
82
+ if tool == "Model":
83
+ return [("Parameters", f'{report["parameters"]:,}'), ("Partial MACs", f'{report["estimated_macs"]:,}'), ("Median ms", f'{report["latency"]["median_ms"]:.3f}')]
84
+ if tool == "Images":
85
+ return [('Decoded', str(report['decoded'])), ('Invalid', str(report['invalid_images'])), ('Similar pairs', str(report['candidate_pair_count']))]
86
+ if tool == "Groups":
87
+ return [('Samples', str(report['samples'])), ('Groups', str(report['groups'])), ('Overlaps', str(report['overlapping_groups']))]
88
+ if tool == "YOLO":
89
+ return [('Images', str(report['images'])), ('Valid boxes', str(report['valid_boxes'])), ('Label issues', str(len(report['issues'])+len(report['missing_labels'])+len(report['orphan_labels'])+len(report['ambiguous_image_stems'])))]
90
+ if tool == "Compare":
91
+ return [('Valid runs', str(report['valid_runs'])), ('Rejected', str(report['rejected_runs'])), ('Best value', f"{report['ranking'][0]['best_value']:.5g}")]
92
+ if tool == "Scores":
93
+ return [('ROC-AUC', f"{report['roc_auc']:.4f}"), ('Average precision', f"{report['average_precision']:.4f}"), ('Brier score', f"{report['brier_score']:.4f}")]
94
+ if tool == "Manifest":
95
+ return [('Python', report['python']), ('Packages tracked', str(len(report['packages']))), ('Fingerprint', 'SHA-256' if report['file'] else 'Not requested')]
96
+ torch = report["pytorch"]
97
+ return [("Python", report["python"]), ("Platform", report["system"]), ("CUDA", "Available" if torch.get("cuda_available") else "Unavailable / unknown")]
98
+
99
+
100
+ def preview_threshold(report, threshold):
101
+ """Exact confusion counts from the accumulated ROC curve, including ties.
102
+
103
+ This is a preview of the recorded probabilities, not a recommendation.
104
+ """
105
+ threshold = float(threshold)
106
+ if not 0 <= threshold <= 1:
107
+ raise ValueError('Threshold must be in [0, 1]')
108
+ p = round(report['samples'] * report['positive_prevalence'])
109
+ n = report['samples'] - p
110
+ point = report['roc_curve'][0]
111
+ for candidate in report['roc_curve'][1:]:
112
+ if candidate['threshold'] < threshold:
113
+ break
114
+ point = candidate
115
+ tp, fp = round(point['tpr'] * p), round(point['fpr'] * n)
116
+ fn, tn = p-tp, n-fp
117
+ return {'tp':tp, 'fp':fp, 'fn':fn, 'tn':tn,
118
+ 'precision':tp/(tp+fp) if tp+fp else 0.0,
119
+ 'recall':tp/p, 'f1':2*tp/(2*tp+fp+fn) if 2*tp+fp+fn else 0.0}
deepforge/history.py ADDED
@@ -0,0 +1,41 @@
1
+ """Summarize finite numeric training histories without inferring causality."""
2
+ import csv
3
+ import math
4
+
5
+
6
+ def _number(row, column, line):
7
+ try:
8
+ value = float(row[column])
9
+ except (ValueError, TypeError, KeyError) as exc:
10
+ raise ValueError(f"Invalid {column!r} at CSV line {line}") from exc
11
+ if not math.isfinite(value):
12
+ raise ValueError(f"Nonfinite {column!r} at CSV line {line}")
13
+ return value
14
+
15
+
16
+ def analyze_history(path, *, metric="val_loss", mode="min", train_metric=None, epoch_column="epoch"):
17
+ if mode not in {"min", "max"}:
18
+ raise ValueError("mode must be min or max")
19
+ with open(path, encoding="utf-8-sig", newline="") as stream:
20
+ reader = csv.DictReader(stream)
21
+ required = {epoch_column, metric} | ({train_metric} if train_metric else set())
22
+ if not reader.fieldnames or not required.issubset(reader.fieldnames):
23
+ raise ValueError(f"Missing CSV columns: {sorted(required - set(reader.fieldnames or []))}")
24
+ rows = list(reader)
25
+ if not rows:
26
+ raise ValueError("Training history is empty")
27
+ epochs = [_number(r, epoch_column, i) for i, r in enumerate(rows, 2)]
28
+ if any(b <= a for a, b in zip(epochs, epochs[1:])):
29
+ raise ValueError("Epochs must be strictly increasing")
30
+ values = [_number(r, metric, i) for i, r in enumerate(rows, 2)]
31
+ best = (min if mode == "min" else max)(range(len(values)), key=values.__getitem__)
32
+ worse = values[-1] > values[best] if mode == "min" else values[-1] < values[best]
33
+ result = {"metric": metric, "mode": mode, "epochs_logged": len(rows), "best_epoch": epochs[best],
34
+ "best_value": values[best], "final_epoch": epochs[-1], "final_value": values[-1],
35
+ "validation_worse_than_best": worse}
36
+ if train_metric:
37
+ train = [_number(r, train_metric, i) for i, r in enumerate(rows, 2)]
38
+ improved = train[-1] < train[best] if mode == "min" else train[-1] > train[best]
39
+ result["possible_overfitting_signal"] = bool(worse and improved)
40
+ result["train_metric"] = train_metric
41
+ return result
deepforge/live_view.py ADDED
@@ -0,0 +1,100 @@
1
+ """Read-only Tk desktop viewer for a local training snapshot."""
2
+ import argparse
3
+ import json
4
+ from pathlib import Path
5
+
6
+
7
+ def main(argv=None):
8
+ parser = argparse.ArgumentParser(description=__doc__)
9
+ parser.add_argument("snapshot")
10
+ args = parser.parse_args(argv)
11
+ import tkinter as tk
12
+ from tkinter import ttk
13
+ root = tk.Tk()
14
+ root.title("DeepForge | Live Training · XVARNA")
15
+ root.geometry("960x700")
16
+ root.minsize(620, 480)
17
+ jade, cream, gold = "#123B32", "#F3EFE5", "#E8C77D"
18
+ root.configure(bg=cream)
19
+ tk.Label(root, text="DEEPFORGE / LIVE TRAINING", bg=jade, fg=gold,
20
+ font=("Arial", 20, "bold"), pady=18).pack(fill="x")
21
+ status = tk.StringVar(value="Waiting for snapshot")
22
+ tk.Label(root, textvariable=status, bg=cream, fg=jade,
23
+ font=("Arial", 14, "bold"), pady=12).pack()
24
+ progress = ttk.Progressbar(root, maximum=100)
25
+ progress.pack(fill="x", padx=24, pady=8)
26
+ details = tk.StringVar()
27
+ tk.Label(root, textvariable=details, bg=cream, fg=jade, justify="left").pack(pady=8)
28
+ metric_choice = tk.StringVar(value="loss")
29
+ metric_select = ttk.Combobox(root, textvariable=metric_choice, state="readonly")
30
+ metric_select.pack(fill="x", padx=24)
31
+ chart = tk.Canvas(root, bg="#FFFCF5", highlightthickness=0, height=220)
32
+ chart.pack(fill="both", expand=True, padx=24, pady=8)
33
+ preview_label = tk.Label(root, bg=cream)
34
+ preview_label.image = None
35
+ preview_value = None
36
+ artifacts = tk.StringVar()
37
+ tk.Label(root, textvariable=artifacts, bg=cream, fg=jade, justify="left",
38
+ wraplength=580).pack(pady=8)
39
+ def duration(value):
40
+ return "unknown" if value is None else f"{int(value)//60}m {int(value)%60:02d}s"
41
+ def refresh():
42
+ nonlocal preview_value
43
+ try:
44
+ data = json.loads(Path(args.snapshot).read_text(encoding="utf-8"))
45
+ if data["schema_version"] != 1:
46
+ raise ValueError("Unsupported snapshot schema")
47
+ status.set(f'{data["status"].upper()} | Epoch {data["epoch"]}/{data["epochs"]} | Batch {data["batch"]}/{data["batches_per_epoch"]}')
48
+ progress["value"] = 100 * data["progress"]
49
+ details.set(f'{data["progress"]:.1%} • {data["completed_batches"]}/{data["total_batches"]} batches • {data["samples"]} samples\n'
50
+ f'Elapsed {duration(data["elapsed_seconds"])} • ETA {duration(data["eta_seconds"])} • {data["batches_per_second"]:.2f} batches/s • {data["samples_per_second"]:.1f} samples/s')
51
+ chart.delete("all")
52
+ w, h = max(chart.winfo_width(), 100), max(chart.winfo_height(), 100)
53
+ history = data["history"]
54
+ keys = sorted({k for row in history for k,v in row["metrics"].items() if v is not None})
55
+ metric_select["values"] = keys
56
+ key = metric_choice.get() if metric_choice.get() in keys else (keys[0] if keys else None)
57
+ if key:
58
+ metric_choice.set(key)
59
+ chart.create_text(15, 15, anchor="nw", text=f"Recent {key or 'metric'} history", fill=jade, font=("Arial", 12, "bold"))
60
+ pts = [(r["step"], r["metrics"][key]) for r in history if key and r["metrics"].get(key) is not None]
61
+ if pts:
62
+ lo, hi = min(v for _,v in pts), max(v for _,v in pts)
63
+ x0, x1 = pts[0][0], pts[-1][0]
64
+ coords = [(40 + (x-x0)/max(x1-x0,1)*(w-65), h-30-(v-lo)/max(hi-lo,1e-12)*(h-70)) for x,v in pts]
65
+ if len(coords)>1:
66
+ chart.create_line(*[v for xy in coords for v in xy], fill=jade, width=2)
67
+ for x,y in coords[-1:]:
68
+ chart.create_oval(x-4,y-4,x+4,y+4,fill=gold,outline=jade)
69
+ chart.create_text(w-15, 15, anchor="ne", text=f"{pts[-1][1]:.5g}", fill=jade)
70
+ validation = data.get("epoch_history", [])
71
+ extra = "\nValidation: " + " | ".join(f"{k}: {v:.4g}" if isinstance(v, (int, float)) else f"{k}: {v}" for k, v in validation[-1]["metrics"].items()) if validation else ""
72
+ extra += "\nResources: " + " | ".join(f"{k}: {v:.4g}" if isinstance(v, (int, float)) else f"{k}: {v}" for k, v in data["resources"].items()) if data.get("resources") else ""
73
+ findings = data.get("diagnostics", {}).get("findings", [])
74
+ if findings:
75
+ extra += "\nDiagnostics: " + " | ".join(str(x["code"]) for x in findings)
76
+ distribution = data.get("batch_distribution", {}).get("counts", {})
77
+ if distribution:
78
+ extra += "\nBatch labels: " + str(distribution)
79
+ encoded = data.get("preview_png")
80
+ if encoded != preview_value:
81
+ if encoded is None:
82
+ preview_label.pack_forget()
83
+ preview_label.image = None
84
+ elif isinstance(encoded, str) and len(encoded) <= 800000 and encoded.startswith("iVBORw0KGgo"):
85
+ image = tk.PhotoImage(data=encoded, format="png")
86
+ preview_label.image = image
87
+ preview_label.configure(image=image)
88
+ preview_label.pack(pady=4)
89
+ preview_value = encoded
90
+ artifacts.set("Output files: " + (" | ".join(f'{a["name"]} ({a["bytes"] if a["exists"] else "missing"} bytes)' for a in data["artifacts"][-5:]) or "None registered") + extra)
91
+ except (OSError, ValueError, KeyError, TypeError, tk.TclError) as exc:
92
+ status.set(f"Snapshot unavailable: {type(exc).__name__}")
93
+ root.after(1000, refresh)
94
+ root.after(100, refresh)
95
+ root.mainloop()
96
+ return 0
97
+
98
+
99
+ if __name__ == "__main__":
100
+ raise SystemExit(main())
deepforge/metrics.py ADDED
@@ -0,0 +1,40 @@
1
+ """Single-label multiclass classification metrics with explicit zero division."""
2
+ import csv
3
+ from collections import Counter
4
+
5
+
6
+ def _ratio(n, d):
7
+ return n / d if d else 0.0
8
+
9
+
10
+ def classification_metrics(y_true, y_pred):
11
+ y_true, y_pred = list(y_true), list(y_pred)
12
+ if not y_true or len(y_true) != len(y_pred):
13
+ raise ValueError("Labels must have equal, nonzero lengths")
14
+ if any(not isinstance(x, str) or not x.strip() for x in y_true + y_pred):
15
+ raise ValueError("Labels must be nonempty strings")
16
+ labels = sorted(set(y_true) | set(y_pred))
17
+ pairs = Counter(zip(y_true, y_pred))
18
+ matrix = [[pairs[a, b] for b in labels] for a in labels]
19
+ per_class = {}
20
+ for i, label in enumerate(labels):
21
+ tp = matrix[i][i]
22
+ support = sum(matrix[i])
23
+ predicted = sum(row[i] for row in matrix)
24
+ precision, recall = _ratio(tp, predicted), _ratio(tp, support)
25
+ per_class[label] = {"precision": precision, "recall": recall,
26
+ "f1": _ratio(2 * precision * recall, precision + recall), "support": support}
27
+ averages = {m: sum(v[m] for v in per_class.values()) / len(labels) for m in ("precision", "recall", "f1")}
28
+ weighted = {m: sum(v[m] * v["support"] for v in per_class.values()) / len(y_true) for m in averages}
29
+ return {"samples": len(y_true), "accuracy": sum(matrix[i][i] for i in range(len(labels))) / len(y_true),
30
+ "labels": labels, "confusion_matrix": matrix, "per_class": per_class,
31
+ "macro": averages, "weighted": weighted, "zero_division": 0}
32
+
33
+
34
+ def evaluate_csv(path, true_column="y_true", pred_column="y_pred"):
35
+ with open(path, encoding="utf-8-sig", newline="") as stream:
36
+ reader = csv.DictReader(stream)
37
+ if not reader.fieldnames or not {true_column, pred_column}.issubset(reader.fieldnames):
38
+ raise ValueError("CSV must contain the requested label columns")
39
+ rows = list(reader)
40
+ return classification_metrics([r[true_column] for r in rows], [r[pred_column] for r in rows])
deepforge/models.py ADDED
@@ -0,0 +1,19 @@
1
+ """Inspect a caller-provided PyTorch model; never deserialize checkpoints."""
2
+
3
+
4
+ def inspect_model(model):
5
+ """Count unique registered parameters and buffers, not peak GPU memory or FLOPs."""
6
+ params = list(model.parameters())
7
+ buffers = list(model.buffers())
8
+ def unique(items):
9
+ return list({id(x): x for x in items}.values())
10
+ params, buffers = unique(params), unique(buffers)
11
+ def count(items):
12
+ return sum(p.numel() for p in items)
13
+ def size(items):
14
+ return sum(p.numel() * p.element_size() for p in items)
15
+ total = count(params)
16
+ trainable = count([p for p in params if p.requires_grad])
17
+ return {"parameters": total, "trainable_parameters": trainable,
18
+ "frozen_parameters": total - trainable, "buffer_elements": count(buffers),
19
+ "parameter_bytes": size(params), "buffer_bytes": size(buffers)}
deepforge/monitor.py ADDED
@@ -0,0 +1,152 @@
1
+ """Local, atomic training snapshots for an independent graphical viewer."""
2
+ import json
3
+ import math
4
+ import os
5
+ import tempfile
6
+ import time
7
+ from pathlib import Path
8
+ from .diagnostics import diagnose, class_distribution
9
+
10
+
11
+ def _count(value, name, minimum=0):
12
+ if type(value) is not int or value < minimum:
13
+ raise ValueError(f"{name} must be an integer >= {minimum}")
14
+ return value
15
+
16
+
17
+ class TrainingMonitor:
18
+ """Single writer per snapshot path. Record completed batches, not optimizer steps."""
19
+ def __init__(self, path, *, epochs, batches_per_epoch, history_limit=500,
20
+ publish_interval=1.0, archive=None, diagnostics=None):
21
+ self.path = Path(path)
22
+ self.epochs = _count(epochs, "epochs", 1)
23
+ self.batches = _count(batches_per_epoch, "batches_per_epoch", 1)
24
+ self.limit = _count(history_limit, "history_limit", 1)
25
+ if not math.isfinite(publish_interval) or publish_interval < 0:
26
+ raise ValueError("publish_interval must be finite and nonnegative")
27
+ self.interval = publish_interval
28
+ self.started = time.monotonic()
29
+ self.last_write = -math.inf
30
+ self.completed = self.samples = 0
31
+ self.history = []
32
+ self.metrics = {}
33
+ self.epoch_history = []
34
+ self.resources = {}
35
+ self.artifacts = []
36
+ self.status = "running"
37
+ self.diagnostic_options = dict(diagnostics or {})
38
+ diagnose([], **self.diagnostic_options)
39
+ self.batch_distribution = {}
40
+ self.preview = None
41
+ self.archive = Path(archive) if archive is not None else None
42
+ if self.archive is not None:
43
+ if self.archive.resolve() == self.path.resolve():
44
+ raise ValueError("Archive and snapshot must be different files")
45
+ with self.archive.open("x", encoding="utf-8") as stream:
46
+ stream.write(json.dumps({"event": "start", "epochs": self.epochs, "batches_per_epoch": self.batches}) + "\n")
47
+ self._publish(force=True)
48
+
49
+ def batch(self, *, epoch, batch, samples=0, metrics=None, labels=None):
50
+ if self.status != "running":
51
+ raise RuntimeError("Monitor already finished")
52
+ _count(epoch, "epoch", 1)
53
+ _count(batch, "batch", 1)
54
+ _count(samples, "samples")
55
+ if epoch > self.epochs or batch > self.batches:
56
+ raise ValueError("Batch position outside configured schedule")
57
+ step = (epoch - 1) * self.batches + batch
58
+ if step != self.completed + 1:
59
+ raise ValueError("Record each completed batch exactly once in order")
60
+ values = {}
61
+ for key, raw in (metrics or {}).items():
62
+ value = float(raw.detach().item() if hasattr(raw, "detach") else raw)
63
+ values[str(key)] = value if math.isfinite(value) else None
64
+ distribution = class_distribution(labels) if labels is not None else {}
65
+ self.batch_distribution = distribution
66
+ self.completed = step
67
+ self.samples += samples
68
+ self.metrics = values
69
+ self.history.append({"step": step, "metrics": values})
70
+ self.history = self.history[-self.limit:]
71
+ self._append({"event": "batch", "step": step, "samples": samples, "metrics": values, "labels": distribution})
72
+ self._publish(force=step == self.epochs * self.batches)
73
+
74
+ def epoch_end(self, epoch, metrics):
75
+ """Record finite scalar validation metrics after a completed epoch."""
76
+ _count(epoch, "epoch", 1)
77
+ if self.status != "running" or epoch > self.completed // self.batches:
78
+ raise ValueError("Epoch has not completed or monitor has stopped")
79
+ if self.epoch_history and epoch <= self.epoch_history[-1]["epoch"]:
80
+ raise ValueError("Epoch metrics must be recorded once in order")
81
+ values = {}
82
+ for key, raw in metrics.items():
83
+ value = float(raw.detach().item() if hasattr(raw, "detach") else raw)
84
+ values[str(key)] = value if math.isfinite(value) else None
85
+ self.epoch_history.append({"epoch": epoch, "metrics": values})
86
+ self._append({"event": "epoch", "epoch": epoch, "metrics": values})
87
+ self._publish(force=True)
88
+
89
+ def _append(self, event):
90
+ if self.archive is not None:
91
+ with self.archive.open("a", encoding="utf-8") as stream:
92
+ stream.write(json.dumps(event, allow_nan=False) + "\n")
93
+
94
+ def record_preview(self, path):
95
+ """Explicitly publish an image preview; do not archive image content."""
96
+ from .preview import image_preview
97
+ self.preview = image_preview(path)
98
+ self._publish(force=True)
99
+
100
+ def record_resources(self, resources):
101
+ """Record caller-supplied, JSON-compatible resource measurements."""
102
+ json.dumps(resources, allow_nan=False)
103
+ self.resources = json.loads(json.dumps(resources))
104
+ self._publish(force=True)
105
+
106
+ def artifact(self, path):
107
+ """Register an explicitly selected output; never inspect file contents."""
108
+ p = Path(path)
109
+ item = {"name": p.name, "exists": p.is_file(),
110
+ "bytes": p.stat().st_size if p.is_file() else None}
111
+ self.artifacts = [a for a in self.artifacts if a["name"] != item["name"]]
112
+ self.artifacts = (self.artifacts + [item])[-100:]
113
+ self._publish(force=True)
114
+
115
+ def finish(self, *, failed=False):
116
+ self.status = "failed" if failed else ("completed" if self.completed == self.epochs * self.batches else "stopped")
117
+ self._append({"event": "finish", "status": self.status})
118
+ self._publish(force=True)
119
+
120
+ def snapshot(self):
121
+ elapsed = max(0.0, time.monotonic() - self.started)
122
+ total = self.epochs * self.batches
123
+ rate = self.completed / elapsed if elapsed else 0.0
124
+ return {"schema_version": 1, "status": self.status,
125
+ "epochs": self.epochs, "batches_per_epoch": self.batches,
126
+ "epoch": (self.completed - 1) // self.batches + 1 if self.completed else 0,
127
+ "batch": (self.completed - 1) % self.batches + 1 if self.completed else 0,
128
+ "completed_batches": self.completed, "total_batches": total,
129
+ "progress": self.completed / total, "samples": self.samples,
130
+ "elapsed_seconds": elapsed, "batches_per_second": rate,
131
+ "samples_per_second": self.samples / elapsed if elapsed else 0.0,
132
+ "eta_seconds": (total - self.completed) / rate if rate and self.status == "running" else (0 if self.status == "completed" else None),
133
+ "metrics": dict(self.metrics), "history": list(self.history),
134
+ "artifacts": list(self.artifacts), "epoch_history": list(self.epoch_history),
135
+ "resources": dict(self.resources), "diagnostics": diagnose(self.epoch_history, **self.diagnostic_options),
136
+ "batch_distribution": dict(self.batch_distribution), "preview_png": self.preview}
137
+
138
+ def _publish(self, *, force=False):
139
+ now = time.monotonic()
140
+ if not force and now - self.last_write < self.interval:
141
+ return
142
+ payload = json.dumps(self.snapshot(), allow_nan=False)
143
+ # Same-directory replacement prevents the reader seeing partial JSON.
144
+ fd, tmp = tempfile.mkstemp(dir=self.path.parent, prefix=".deepforge-", suffix=".tmp")
145
+ try:
146
+ with os.fdopen(fd, "w", encoding="utf-8") as stream:
147
+ stream.write(payload)
148
+ os.replace(tmp, self.path)
149
+ finally:
150
+ if os.path.exists(tmp):
151
+ os.unlink(tmp)
152
+ self.last_write = now
deepforge/notebook.py ADDED
@@ -0,0 +1,73 @@
1
+ """Render a local training snapshot in Jupyter without a desktop display."""
2
+ import html
3
+ import json
4
+ from pathlib import Path
5
+
6
+
7
+ def snapshot_html(path):
8
+ data = json.loads(Path(path).read_text(encoding="utf-8"))
9
+ if data["schema_version"] != 1:
10
+ raise ValueError("Unsupported snapshot schema")
11
+ esc = lambda value: html.escape(str(value), quote=True)
12
+ progress = min(100, max(0, float(data["progress"]) * 100))
13
+ rows = []
14
+ for label, value in (
15
+ ("Status", data["status"]), ("Epoch", f'{data["epoch"]}/{data["epochs"]}'),
16
+ ("Batch", f'{data["batch"]}/{data["batches_per_epoch"]}'),
17
+ ("Elapsed (s)", round(data["elapsed_seconds"], 1)),
18
+ ("ETA (s)", None if data["eta_seconds"] is None else round(data["eta_seconds"], 1)),
19
+ ("Batches/s", round(data["batches_per_second"], 2)),
20
+ ):
21
+ rows.append((label, value))
22
+ rows.extend(data["metrics"].items())
23
+ if data.get("epoch_history"):
24
+ rows.extend(("Validation: " + k, v) for k,v in data["epoch_history"][-1]["metrics"].items())
25
+ rows.extend(data.get("resources", {}).items())
26
+ rows.extend(("Output: " + a["name"], a["bytes"]) for a in data["artifacts"])
27
+ rows.extend(("Diagnostic", item["code"]) for item in data.get("diagnostics", {}).get("findings", []))
28
+ rows.extend(("Batch class " + k, v) for k,v in data.get("batch_distribution", {}).get("counts", {}).items())
29
+ encoded = data.get("preview_png")
30
+ preview = ""
31
+ if isinstance(encoded, str) and len(encoded) <= 800000 and encoded.startswith("iVBORw0KGgo"):
32
+ preview = f'<img alt="Opt-in batch preview" style="max-width:100%" src="data:image/png;base64,{esc(encoded)}">'
33
+ table = "".join(f"<tr><th>{esc(k)}</th><td>{esc(v)}</td></tr>" for k,v in rows)
34
+ return ('<section style="background:#F3EFE5;color:#123B32;padding:16px;border-radius:12px">'
35
+ '<h2>DeepForge · XVARNA</h2>'
36
+ f'<progress max="100" value="{progress:.4f}"></progress> {progress:.1f}%'
37
+ f'<table>{table}</table>{preview}</section>')
38
+
39
+
40
+ def display_snapshot(path, *, display_id=None):
41
+ """Display or update one notebook output. Caller controls refresh timing."""
42
+ from IPython.display import HTML, display
43
+ return display(HTML(snapshot_html(path)), display_id=display_id)
44
+
45
+
46
+ class NotebookMonitor:
47
+ """Refresh a single inline output from an existing TrainingMonitor snapshot.
48
+
49
+ Call refresh from the training thread after recording batches or epochs.
50
+ No background thread, GUI, or browser server is required.
51
+ """
52
+ def __init__(self, path, *, interval=1.0):
53
+ import math
54
+ if not math.isfinite(interval) or interval < 0:
55
+ raise ValueError("interval must be finite and nonnegative")
56
+ self.path = Path(path)
57
+ self.interval = interval
58
+ self._last = None
59
+ self._handle = None
60
+
61
+ def refresh(self, *, force=False):
62
+ import time
63
+ from IPython.display import HTML, display
64
+ now = time.monotonic()
65
+ if not force and self._last is not None and now - self._last < self.interval:
66
+ return False
67
+ output = HTML(snapshot_html(self.path))
68
+ if self._handle is None:
69
+ self._handle = display(output, display_id=True)
70
+ else:
71
+ self._handle.update(output)
72
+ self._last = now
73
+ return True
deepforge/preview.py ADDED
@@ -0,0 +1,20 @@
1
+ """Explicit opt-in local previews. Never scan or upload input images."""
2
+ import base64
3
+ import io
4
+ from pathlib import Path
5
+
6
+
7
+ def image_preview(path):
8
+ """Return a bounded PNG preview of a caller-selected, already annotated image."""
9
+ from PIL import Image, ImageOps
10
+ with Image.open(Path(path)) as image:
11
+ if image.width * image.height > 40_000_000:
12
+ raise ValueError("Preview image exceeds 40 megapixels")
13
+ image = ImageOps.exif_transpose(image).convert("RGB")
14
+ image.thumbnail((480, 320), Image.Resampling.LANCZOS)
15
+ stream = io.BytesIO()
16
+ image.save(stream, format="PNG")
17
+ payload = stream.getvalue()
18
+ if len(payload) > 600_000:
19
+ raise ValueError("Preview exceeds size limit")
20
+ return base64.b64encode(payload).decode("ascii")