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/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """DeepForge: small, auditable deep learning research utilities."""
2
+
3
+ __version__ = "0.7.1"
deepforge/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
deepforge/advanced.py ADDED
@@ -0,0 +1,117 @@
1
+ """Reproducible binary scoring, experiment comparison and runtime manifests."""
2
+ import csv
3
+ import math
4
+ import platform
5
+ from datetime import datetime, timezone
6
+ from importlib.metadata import PackageNotFoundError, version
7
+ from pathlib import Path
8
+
9
+ from . import __version__
10
+ from .datasets import file_digest
11
+ from .environment import inspect_environment
12
+ from .history import analyze_history
13
+ from .metrics import classification_metrics
14
+
15
+
16
+ def read_binary_scores(path, *, true_column='y_true', score_column='score', positive_label='1', threshold=.5, bins=10):
17
+ if not math.isfinite(threshold) or not 0 <= threshold <= 1 or not 2 <= bins <= 100:
18
+ raise ValueError('Threshold must be in [0, 1]; calibration bins must be in [2, 100]')
19
+ if not positive_label.strip():
20
+ raise ValueError('Positive label must not be empty')
21
+ pairs = []
22
+ with open(path, encoding='utf-8-sig', newline='') as stream:
23
+ reader = csv.DictReader(stream)
24
+ if not {true_column, score_column}.issubset(reader.fieldnames or []):
25
+ raise ValueError('CSV must contain label and score columns')
26
+ for n, row in enumerate(reader, 2):
27
+ label = (row.get(true_column) or '').strip()
28
+ try:
29
+ score = float(row[score_column])
30
+ except (ValueError, TypeError) as exc:
31
+ raise ValueError(f'Invalid score at line {n}') from exc
32
+ if not label or not math.isfinite(score) or not 0 <= score <= 1:
33
+ raise ValueError(f'Expected nonempty label and probability in [0, 1] at line {n}')
34
+ pairs.append((label, score))
35
+ labels = {label for label, _ in pairs}
36
+ if len(labels) != 2 or positive_label not in labels:
37
+ raise ValueError('Exactly two observed labels, including the positive label, are required')
38
+ negative = next(iter(labels - {positive_label}))
39
+ y = [label for label, _ in pairs]
40
+ pred = [positive_label if score >= threshold else negative for _, score in pairs]
41
+ metrics = classification_metrics(y, pred)
42
+ ranked = sorted(((score, label == positive_label) for label, score in pairs), reverse=True)
43
+ p = sum(int(pos) for _, pos in ranked); n = len(ranked) - p
44
+ roc = [{'fpr': 0.0, 'tpr': 0.0, 'threshold': None}]
45
+ pr = [{'recall': 0.0, 'precision': 1.0, 'threshold': None}]
46
+ tp = fp = i = 0
47
+ auc = ap = 0.0
48
+ while i < len(ranked):
49
+ score = ranked[i][0]
50
+ while i < len(ranked) and ranked[i][0] == score:
51
+ if ranked[i][1]: tp += 1
52
+ else: fp += 1
53
+ i += 1
54
+ fpr, tpr, prec = fp/n, tp/p, tp/(tp+fp)
55
+ auc += (fpr - roc[-1]['fpr'])*(tpr + roc[-1]['tpr'])/2
56
+ ap += (tpr - pr[-1]['recall'])*prec
57
+ roc.append({'fpr': fpr, 'tpr': tpr, 'threshold': score})
58
+ pr.append({'recall': tpr, 'precision': prec, 'threshold': score})
59
+ calibration = [{'count': 0, 'prob_sum': 0.0, 'positive': 0} for _ in range(bins)]
60
+ for score, pos in ranked:
61
+ b = calibration[min(bins-1, int(score*bins))]
62
+ b['count'] += 1; b['prob_sum'] += score; b['positive'] += int(pos)
63
+ cal = [{'lower': i/bins, 'upper': (i+1)/bins, 'count': b['count'],
64
+ 'mean_probability': b['prob_sum']/b['count'] if b['count'] else None,
65
+ 'positive_fraction': b['positive']/b['count'] if b['count'] else None} for i,b in enumerate(calibration)]
66
+ brier = sum((score - int(pos))**2 for score, pos in ranked)/len(ranked)
67
+ ece = sum(b['count']/len(ranked)*abs(b['mean_probability']-b['positive_fraction']) for b in cal if b['count'])
68
+ return {'samples': len(ranked), 'positive_label': positive_label, 'negative_label': negative, 'positive_prevalence': p/len(ranked),
69
+ 'threshold': threshold, 'roc_auc': auc, 'average_precision': ap, 'brier_score': brier, 'ece': ece,
70
+ 'threshold_metrics': metrics, 'roc_curve': roc, 'precision_recall_curve': pr, 'calibration': cal,
71
+ 'limitations': 'Scores must be positive-class probabilities. Do not select thresholds on the final test set. ECE depends on binning.'}
72
+
73
+
74
+ def compare_runs(directory, *, metric='val_loss', mode='min', train_metric=None, epoch_column='epoch', max_runs=100):
75
+ directory = Path(directory)
76
+ if not directory.is_dir():
77
+ raise ValueError('Expected a directory containing run CSV files')
78
+ if not 1 <= max_runs <= 1000:
79
+ raise ValueError('Run limit must be 1–1000')
80
+ files = sorted(p for p in directory.glob('*.csv') if p.is_file() and not p.is_symlink() and not p.name.startswith('.'))
81
+ if not files:
82
+ raise ValueError('No CSV files found in the directory')
83
+ results, rejected = [], []
84
+ for p in files[:max_runs]:
85
+ try:
86
+ report = analyze_history(p, metric=metric, mode=mode, train_metric=train_metric, epoch_column=epoch_column)
87
+ except (ValueError, OSError, UnicodeError) as exc:
88
+ rejected.append({'run': p.name, 'error': str(exc).replace(str(p), p.name)})
89
+ else:
90
+ results.append({'run': p.name, **report})
91
+ if not results:
92
+ raise ValueError('No valid runs: ' + '; '.join(r['run']+': '+r['error'] for r in rejected[:3]))
93
+ results.sort(key=lambda r: ((r['best_value'] if mode == 'min' else -r['best_value']), r['run']))
94
+ return {'metric': metric, 'mode': mode, 'files_found': len(files), 'scan_truncated': len(files)>max_runs,
95
+ 'valid_runs': len(results), 'rejected_runs': len(rejected), 'best_run': results[0]['run'], 'ranking': results,
96
+ 'rejected': rejected, 'limitations': 'Rankings compare reported best validation metrics only; comparable splits, metrics and budgets are required.'}
97
+
98
+
99
+ def reproducibility_manifest(path=None, *, include_runtime=True):
100
+ """Fingerprint one explicit input file and report selected dependency versions."""
101
+ packages = {}
102
+ for name in ('numpy', 'pandas', 'torch', 'torchvision', 'pillow', 'scikit-learn', 'ultralytics'):
103
+ try:
104
+ packages[name] = version(name)
105
+ except PackageNotFoundError:
106
+ packages[name] = None
107
+ report = {'schema_version': 1, 'deepforge_version': __version__, 'created_utc': datetime.now(timezone.utc).isoformat(),
108
+ 'python': platform.python_version(), 'packages': packages, 'file': None}
109
+ if path:
110
+ p = Path(path)
111
+ if not p.is_file() or p.is_symlink():
112
+ raise ValueError('Expected a regular input file')
113
+ report['file'] = {'name': p.name, 'size_bytes': p.stat().st_size, 'sha256': file_digest(p)}
114
+ if include_runtime:
115
+ report['runtime'] = inspect_environment()
116
+ report['limitations'] = 'No environment variables, secrets, or full machine identifier collected. A manifest alone does not guarantee deterministic reproduction.'
117
+ return report
Binary file
Binary file
Binary file
Binary file
deepforge/audit.py ADDED
@@ -0,0 +1,192 @@
1
+ """Read-only dataset integrity and group leakage audits."""
2
+ import csv
3
+ import math
4
+ import os
5
+ from collections import Counter, defaultdict
6
+ from pathlib import Path
7
+
8
+ from .datasets import EXTENSIONS, SPLITS
9
+
10
+
11
+ def image_paths(root, *, classification=False):
12
+ """Yield (split, path) from split folders, without following directory symlinks."""
13
+ root = Path(root)
14
+ if not root.is_dir():
15
+ raise ValueError(f"Not a dataset directory: {root}")
16
+ splits = [s for s in SPLITS if (root / s).is_dir() and not (root / s).is_symlink()]
17
+ if not splits or ("val" in splits and "validation" in splits):
18
+ raise ValueError("Expected split directories; use either val or validation, not both")
19
+ for split in splits:
20
+ for folder, dirs, files in os.walk(root / split, followlinks=False):
21
+ folder = Path(folder)
22
+ dirs[:] = sorted(d for d in dirs if not d.startswith('.') and not (folder / d).is_symlink())
23
+ if classification and folder == root / split:
24
+ continue
25
+ for name in sorted(files):
26
+ p = folder / name
27
+ if not name.startswith('.') and p.suffix.lower() in EXTENSIONS and not p.is_symlink() and p.is_file():
28
+ yield split, p
29
+
30
+
31
+ def audit_images(root, *, similarity=False, threshold=4, max_images=2000, max_pairs=2000):
32
+ """Decode images with Pillow and optionally compare 64-bit difference hashes.
33
+
34
+ The bounded exhaustive search compares only scanned, decodable cross-split images.
35
+ A zero Hamming distance is not proof of identity; flat or similar images may collide.
36
+ """
37
+ if not 0 <= threshold <= 64 or not 1 <= max_images <= 5000 or not 1 <= max_pairs <= 10000:
38
+ raise ValueError("Use a threshold of 0–64, image limit of 1–5000 and pair limit of 1–10000")
39
+ try:
40
+ from PIL import Image, ImageOps
41
+ except ImportError as exc:
42
+ raise ValueError("Image audits require Pillow: pip install '.[images]'") from exc
43
+ root = Path(root)
44
+ entries, errors, unsupported, modes, by_split = [], [], [], Counter(), Counter()
45
+ widths, heights = [], []
46
+ scanned = 0
47
+ truncated = False
48
+ for split, path in image_paths(root):
49
+ if scanned >= max_images:
50
+ truncated = True
51
+ break
52
+ scanned += 1
53
+ relative = path.relative_to(root).as_posix()
54
+ if path.suffix.lower() == '.dcm':
55
+ unsupported.append(relative)
56
+ continue
57
+ try:
58
+ with Image.open(path) as im:
59
+ if im.width * im.height > 40_000_000:
60
+ raise ValueError("Image exceeds the 40 megapixel safety limit")
61
+ im.load()
62
+ im = ImageOps.exif_transpose(im)
63
+ w, h = im.size
64
+ if similarity:
65
+ small = im.convert('L').resize((9, 8), Image.Resampling.LANCZOS)
66
+ sample = list(small.get_flattened_data() if hasattr(small, 'get_flattened_data') else small.getdata())
67
+ dh = 0
68
+ for row in range(8):
69
+ for col in range(8):
70
+ dh = (dh << 1) | int(sample[row * 9 + col] > sample[row * 9 + col + 1])
71
+ entries.append((split, relative, dh))
72
+ widths.append(w); heights.append(h); modes[im.mode] += 1; by_split[split] += 1
73
+ except (OSError, ValueError, Image.DecompressionBombError) as exc:
74
+ errors.append({"file": relative, "error": type(exc).__name__, "detail": str(exc).replace(str(path), relative)})
75
+ pairs, comparisons, matched = [], 0, 0
76
+ if similarity:
77
+ for i, (sa, pa, ha) in enumerate(entries):
78
+ for j in range(i + 1, len(entries)):
79
+ sb, pb, hb = entries[j]
80
+ if sa == sb:
81
+ continue
82
+ comparisons += 1
83
+ distance = (ha ^ hb).bit_count()
84
+ if distance <= threshold:
85
+ matched += 1
86
+ if len(pairs) < max_pairs:
87
+ pairs.append({"a": pa, "b": pb, "distance": distance})
88
+ pairs.sort(key=lambda x: (x['distance'], x['a'], x['b']))
89
+ def stats(values):
90
+ return {"min": min(values), "mean": sum(values)/len(values), "max": max(values)} if values else None
91
+ return {"scanned": scanned, "decoded": len(widths), "invalid_images": len(errors), "unsupported_images": len(unsupported),
92
+ "scan_truncated": truncated, "image_limit": max_images, "dimensions": {"width": stats(widths), "height": stats(heights)},
93
+ "modes": dict(modes), "decoded_by_split": dict(by_split), "errors": errors, "unsupported": unsupported,
94
+ "similarity_enabled": similarity, "hash_algorithm": "dHash-64" if similarity else None, "hamming_threshold": threshold if similarity else None,
95
+ "cross_split_comparisons": comparisons, "candidate_pair_count": matched, "candidate_pairs": pairs,
96
+ "pair_list_truncated": matched > len(pairs), "limitations": "Candidate similarities require human review. Unscanned, unsupported and failed images are not compared; patient independence is not established."}
97
+
98
+
99
+ def audit_groups(path, *, group_column="group_id", split_column="split", redact=True):
100
+ """Find group IDs assigned to multiple splits; redact raw identifiers by default."""
101
+ groups = defaultdict(set)
102
+ split_counts = Counter()
103
+ with open(path, encoding='utf-8-sig', newline='') as stream:
104
+ reader = csv.DictReader(stream)
105
+ if not {group_column, split_column}.issubset(reader.fieldnames or []):
106
+ raise ValueError("CSV must contain group and split columns")
107
+ for line, row in enumerate(reader, 2):
108
+ group, split = ((row.get(k) or '').strip() for k in (group_column, split_column))
109
+ split = 'val' if split.lower() == 'validation' else split.lower()
110
+ if not group or split not in {'train', 'val', 'test'}:
111
+ raise ValueError(f"Missing group or invalid split at line {line}")
112
+ groups[group].add(split); split_counts[split] += 1
113
+ if not groups:
114
+ raise ValueError("Group manifest is empty")
115
+ overlaps = [{"group": f"group-{i:06d}" if redact else group, "splits": sorted(splits)}
116
+ for i, (group, splits) in enumerate(sorted(groups.items()), 1) if len(splits) > 1]
117
+ return {"samples": sum(split_counts.values()), "groups": len(groups), "split_counts": dict(split_counts),
118
+ "overlapping_groups": len(overlaps), "overlaps": overlaps, "identifiers_redacted": redact,
119
+ "limitations": "Checks only supplied IDs. Correct identifiers and complete manifests are required; other leakage can remain."}
120
+
121
+
122
+ def audit_yolo(root, *, classes=None, tolerance=1e-6):
123
+ """Audit YOLO detection labels in images/<split> and labels/<split> layout."""
124
+ root = Path(root)
125
+ if classes is not None and classes < 1:
126
+ raise ValueError("Class count must be positive")
127
+ if not math.isfinite(tolerance) or tolerance < 0 or tolerance > .01:
128
+ raise ValueError("Tolerance must be finite and between 0 and 0.01")
129
+ image_root, label_root = root / 'images', root / 'labels'
130
+ if image_root.is_symlink() or label_root.is_symlink() or not label_root.is_dir():
131
+ raise ValueError("Expected real images/ and labels/ directories")
132
+ expected, collisions, orphan_labels, missing, errors, counts, split_boxes = {}, [], [], [], [], Counter(), Counter()
133
+ total_images = 0
134
+ for split, path in image_paths(image_root):
135
+ total_images += 1
136
+ key = path.relative_to(image_root).with_suffix('.txt').as_posix()
137
+ if key in expected:
138
+ collisions.append(key)
139
+ else:
140
+ expected[key] = path
141
+ existing = {}
142
+ for folder, dirs, files in os.walk(label_root, followlinks=False):
143
+ folder = Path(folder)
144
+ dirs[:] = sorted(d for d in dirs if not d.startswith('.') and not (folder / d).is_symlink())
145
+ for name in sorted(files):
146
+ p = folder / name
147
+ if not name.startswith('.') and p.suffix == '.txt' and not p.is_symlink() and p.is_file():
148
+ key = p.relative_to(label_root).as_posix()
149
+ if key.split('/')[0] in SPLITS:
150
+ existing[key] = p
151
+ missing = sorted(set(expected) - set(existing))
152
+ orphan_labels = sorted(set(existing) - set(expected))
153
+ empty = valid_boxes = invalid_rows = 0
154
+ for key in sorted(set(expected) & set(existing)):
155
+ p = existing[key]
156
+ try:
157
+ with p.open(encoding='utf-8-sig') as stream:
158
+ seen = set(); has_rows = False
159
+ for n, line in enumerate(stream, 1):
160
+ if not line.strip():
161
+ continue
162
+ has_rows = True
163
+ try:
164
+ tokens = line.split()
165
+ if len(tokens) != 5:
166
+ raise ValueError('Expected class x_center y_center width height')
167
+ cls = int(tokens[0]); x, y, w, h = map(float, tokens[1:])
168
+ if cls < 0 or (classes is not None and cls >= classes):
169
+ raise ValueError('Class ID outside configured range')
170
+ if not all(math.isfinite(v) for v in (x,y,w,h)):
171
+ raise ValueError('Nonfinite coordinates')
172
+ if not (0 <= x <= 1 and 0 <= y <= 1 and 0 < w <= 1 and 0 < h <= 1):
173
+ raise ValueError('Coordinates must be normalized and sizes positive')
174
+ if min(x-w/2, y-h/2) < -tolerance or max(x+w/2, y+h/2) > 1+tolerance:
175
+ raise ValueError('Box extends outside image')
176
+ box = (cls,x,y,w,h)
177
+ if box in seen:
178
+ raise ValueError('Duplicate box row')
179
+ seen.add(box)
180
+ except ValueError as exc:
181
+ invalid_rows += 1
182
+ errors.append({"file": key, "line": n, "error": str(exc)})
183
+ else:
184
+ valid_boxes += 1; counts[str(cls)] += 1; split_boxes[key.split('/')[0]] += 1
185
+ empty += not has_rows
186
+ except (UnicodeError, OSError) as exc:
187
+ errors.append({"file": key, "line": None, "error": f"Unreadable label: {type(exc).__name__}"})
188
+ return {"images": total_images, "matched_label_files": len(set(expected)&set(existing)), "missing_labels": missing,
189
+ "orphan_labels": orphan_labels, "ambiguous_image_stems": collisions, "empty_label_files": empty,
190
+ "valid_boxes": valid_boxes, "invalid_rows": invalid_rows, "issues": errors, "class_counts": dict(counts),
191
+ "boxes_by_split": dict(split_boxes), "class_count_configured": classes,
192
+ "limitations": "Detection boxes only; empty labels may represent background. Does not verify image content, semantics or segmentation polygons."}
@@ -0,0 +1,143 @@
1
+ """Composable, read-only quality gates for deep learning pipelines."""
2
+ from dataclasses import dataclass, field
3
+ from pathlib import Path
4
+ from typing import Any, Callable
5
+ import json
6
+ import math
7
+ import operator
8
+
9
+ from .datasets import inspect_dataset
10
+ from .audit import audit_groups, audit_images, audit_yolo
11
+ from .metrics import evaluate_csv, classification_metrics
12
+
13
+ _OPERATORS = {"eq": operator.eq, "ne": operator.ne, "ge": operator.ge,
14
+ "gt": operator.gt, "le": operator.le, "lt": operator.lt}
15
+
16
+
17
+ @dataclass(frozen=True)
18
+ class Check:
19
+ name: str
20
+ run: Callable[[], dict]
21
+ rules: tuple = field(default_factory=tuple)
22
+
23
+
24
+ class AuditFailed(RuntimeError):
25
+ """One or more quality checks failed or could not run."""
26
+
27
+
28
+ def _resolve(report, key):
29
+ value = report
30
+ for part in key.split("."):
31
+ value = value[part]
32
+ return value
33
+
34
+
35
+ def run_checks(checks, *, raise_on_failure=False):
36
+ """Execute every check, returning a JSON-compatible report.
37
+
38
+ Rules are (field.path, operator, expected) tuples. Exceptions fail closed.
39
+ A check without rules verifies execution only, not data quality.
40
+ """
41
+ checks = list(checks)
42
+ if not checks:
43
+ raise ValueError("At least one check is required")
44
+ names = [c.name for c in checks]
45
+ if len(set(names)) != len(names):
46
+ raise ValueError("Check names must be unique")
47
+ results = []
48
+ for check in checks:
49
+ entry = {"name": check.name, "status": "error", "rules": []}
50
+ try:
51
+ report = check.run()
52
+ if not isinstance(report, dict):
53
+ raise TypeError("Checks must return dictionaries")
54
+ json.dumps(report, allow_nan=False)
55
+ for key, op, expected in check.rules:
56
+ actual = _resolve(report, key)
57
+ passed = bool(_OPERATORS[op](actual, expected))
58
+ entry["rules"].append({"field": key, "operator": op,
59
+ "expected": expected, "actual": actual,
60
+ "passed": passed})
61
+ entry["report"] = report
62
+ entry["status"] = "passed" if all(r["passed"] for r in entry["rules"]) else "failed"
63
+ json.dumps(entry, allow_nan=False)
64
+ except Exception as exc:
65
+ entry = {"name": check.name, "status": "error",
66
+ "error": type(exc).__name__, "detail": str(exc), "rules": []}
67
+ results.append(entry)
68
+ counts = {s: sum(r["status"] == s for r in results)
69
+ for s in ("passed", "failed", "error")}
70
+ summary = {"schema_version": 1, "ok": counts["passed"] == len(results),
71
+ "counts": counts, "checks": results}
72
+ if raise_on_failure:
73
+ require_pass(summary)
74
+ return summary
75
+
76
+
77
+ def require_pass(report):
78
+ """Stop the calling pipeline when any audit fails."""
79
+ if not report["ok"]:
80
+ names = ", ".join(c["name"] for c in report["checks"] if c["status"] != "passed")
81
+ raise AuditFailed(f"Quality gate failed: {names}")
82
+
83
+
84
+ def save_report(report, path):
85
+ """Write a report to an explicitly selected path without overwriting files."""
86
+ payload = json.dumps(report, indent=2, allow_nan=False) + "\n"
87
+ with Path(path).open("x", encoding="utf-8") as stream:
88
+ stream.write(payload)
89
+
90
+
91
+ def dataset_check(root, *, min_samples=1, required_splits=("train", "val", "test")):
92
+ """Check nonempty required classification splits and exact duplicate leakage."""
93
+ if type(min_samples) is not int or min_samples < 1:
94
+ raise ValueError("min_samples must be a positive integer")
95
+ splits = tuple(required_splits)
96
+ if not splits or any(s not in {"train", "val", "validation", "test"} for s in splits):
97
+ raise ValueError("Invalid required splits")
98
+ def run():
99
+ report = inspect_dataset(root, hash_files=True)
100
+ found = report["splits"]
101
+ report["required_splits_ok"] = all(
102
+ found.get(s, found.get("validation" if s == "val" else "val" if s == "validation" else s, {})).get("total", 0) >= min_samples
103
+ for s in splits)
104
+ return report
105
+ return Check("dataset", run, (("required_splits_ok", "eq", True),
106
+ ("cross_split_duplicate_groups", "eq", 0)))
107
+
108
+
109
+ def group_check(csv, *, group_column="group_id", split_column="split"):
110
+ return Check("groups", lambda: audit_groups(csv, group_column=group_column,
111
+ split_column=split_column), (("overlapping_groups", "eq", 0),))
112
+
113
+
114
+ def image_check(root, *, max_images=2000, similarity=False, threshold=4):
115
+ rules = [("invalid_images", "eq", 0), ("unsupported_images", "eq", 0),
116
+ ("scan_truncated", "eq", False), ("decoded", "gt", 0)]
117
+ if similarity:
118
+ rules.append(("candidate_pair_count", "eq", 0))
119
+ return Check("images", lambda: audit_images(root, max_images=max_images,
120
+ similarity=similarity, threshold=threshold), tuple(rules))
121
+
122
+
123
+ def yolo_check(root, *, classes=None):
124
+ return Check("yolo", lambda: audit_yolo(root, classes=classes),
125
+ (("images", "gt", 0), ("missing_labels", "eq", []),
126
+ ("orphan_labels", "eq", []), ("ambiguous_image_stems", "eq", []),
127
+ ("issues", "eq", []), ("invalid_rows", "eq", 0)))
128
+
129
+
130
+ def classification_check(*, csv=None, y_true=None, y_pred=None,
131
+ min_accuracy=0.0, true_column="y_true", pred_column="y_pred"):
132
+ if not math.isfinite(min_accuracy) or not 0 <= min_accuracy <= 1:
133
+ raise ValueError("min_accuracy must be in [0, 1]")
134
+ if csv is not None:
135
+ if y_true is not None or y_pred is not None:
136
+ raise ValueError("Choose CSV or in-memory labels")
137
+ run = lambda: evaluate_csv(csv, true_column, pred_column)
138
+ else:
139
+ if y_true is None or y_pred is None:
140
+ raise ValueError("Both y_true and y_pred are required")
141
+ truth, pred = list(y_true), list(y_pred)
142
+ run = lambda: classification_metrics(truth, pred)
143
+ return Check("classification", run, (("accuracy", "ge", min_accuracy),))
@@ -0,0 +1,155 @@
1
+ """Checkpoint storage primitives. Payload serialization belongs to adapters."""
2
+ from __future__ import annotations
3
+
4
+ import hashlib
5
+ import logging
6
+ import json
7
+ import os
8
+ import shutil
9
+ import tempfile
10
+ from pathlib import Path
11
+ from dataclasses import dataclass
12
+
13
+
14
+ @dataclass(frozen=True)
15
+ class CheckpointPolicy:
16
+ keep_last: int = 2
17
+ max_bytes: int | None = None
18
+ enabled: bool = True
19
+ save_every_epochs: int = 1
20
+
21
+ def __post_init__(self):
22
+ if self.keep_last < 2 or self.save_every_epochs < 1:
23
+ raise ValueError("retain at least two checkpoints; interval must be positive")
24
+ if self.max_bytes is not None and self.max_bytes < 1:
25
+ raise ValueError("max_bytes must be positive")
26
+
27
+
28
+ def sha256_file(path: Path) -> str:
29
+ digest = hashlib.sha256()
30
+ with path.open("rb") as stream:
31
+ for chunk in iter(lambda: stream.read(1024 * 1024), b""):
32
+ digest.update(chunk)
33
+ return digest.hexdigest()
34
+
35
+
36
+ def atomic_json(path: Path, data: dict) -> None:
37
+ fd, name = tempfile.mkstemp(prefix=".pending-", dir=path.parent)
38
+ try:
39
+ with os.fdopen(fd, "w", encoding="utf-8") as stream:
40
+ json.dump(data, stream, sort_keys=True, allow_nan=False)
41
+ stream.flush()
42
+ os.fsync(stream.fileno())
43
+ os.replace(name, path)
44
+ finally:
45
+ Path(name).unlink(missing_ok=True)
46
+
47
+
48
+ def verify_payload(path: Path, manifest: dict) -> bool:
49
+ """Verify accidental corruption, not authenticity of untrusted files."""
50
+ try:
51
+ return (path.is_file() and not path.is_symlink()
52
+ and path.stat().st_size == manifest["size"]
53
+ and sha256_file(path) == manifest["sha256"])
54
+ except (OSError, KeyError, TypeError):
55
+ return False
56
+
57
+
58
+ def require_capacity(root: Path, incoming_bytes: int,
59
+ policy: CheckpointPolicy, used_bytes: int) -> None:
60
+ if incoming_bytes < 0 or used_bytes < 0:
61
+ raise ValueError("byte counts must be nonnegative")
62
+ if shutil.disk_usage(root).free < incoming_bytes:
63
+ raise OSError("insufficient free storage for safe checkpoint staging")
64
+ if policy.max_bytes is not None and used_bytes + incoming_bytes > policy.max_bytes:
65
+ raise OSError("checkpoint quota exceeded; existing checkpoints preserved")
66
+
67
+
68
+ class CheckpointStore:
69
+ """Single-writer local store; immutable payloads and manifest-last publication."""
70
+
71
+ def __init__(self, root, run_id: str, policy: CheckpointPolicy | None = None):
72
+ import re
73
+ if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_-]{0,127}", run_id):
74
+ raise ValueError("invalid run identifier")
75
+ self.root = Path(root) / run_id
76
+ self.root.mkdir(parents=True, exist_ok=True)
77
+ if self.root.is_symlink():
78
+ raise ValueError("run directory must not be a symlink")
79
+ self.policy = policy or CheckpointPolicy()
80
+
81
+ def _records(self):
82
+ records = []
83
+ for manifest in self.root.glob("epoch-*.json"):
84
+ try:
85
+ if manifest.is_symlink():
86
+ continue
87
+ data = json.loads(manifest.read_text(encoding="utf-8"))
88
+ epoch = data["epoch"]
89
+ if type(epoch) is not int or epoch < 0 or manifest.name != f"epoch-{epoch}.json":
90
+ continue
91
+ payload = self.root / f"epoch-{epoch}.bin"
92
+ if verify_payload(payload, data):
93
+ records.append((epoch, payload, manifest, data))
94
+ except (OSError, ValueError, KeyError, TypeError):
95
+ continue
96
+ return sorted(records, key=lambda item: item[0], reverse=True)
97
+
98
+ def recover_abandoned_lock(self, *, confirmed_no_writer: bool = False):
99
+ """Explicit recovery only after operator confirms all writers stopped."""
100
+ if not confirmed_no_writer:
101
+ raise ValueError("confirm that all writers have stopped before unlocking")
102
+ (self.root / ".writer.lock").unlink(missing_ok=True)
103
+ logging.getLogger(__name__).warning("checkpoint_lock_recovered")
104
+
105
+ def latest(self):
106
+ records = self._records()
107
+ return records[0][1] if records else None
108
+
109
+ def save(self, epoch: int, payload: bytes, *, best: bool = False):
110
+ if type(epoch) is not int or epoch < 0:
111
+ raise ValueError("invalid epoch")
112
+ if not self.policy.enabled or (epoch % self.policy.save_every_epochs and not best):
113
+ return None
114
+ lock = self.root / ".writer.lock"
115
+ fd = os.open(lock, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
116
+ try:
117
+ os.close(fd)
118
+ target = self.root / f"epoch-{epoch}.bin"
119
+ manifest = self.root / f"epoch-{epoch}.json"
120
+ if target.exists() and not manifest.exists() and not target.is_symlink():
121
+ target.unlink() # unpublished payload from interrupted save
122
+ if target.exists() or manifest.exists():
123
+ raise FileExistsError("epoch already exists")
124
+ # Reclaim interrupted, unpublished payloads under the writer lock.
125
+ for orphan in self.root.glob("epoch-*.bin"):
126
+ marker = orphan.with_suffix(".json")
127
+ if orphan.is_file() and not orphan.is_symlink() and not marker.exists() and not marker.is_symlink():
128
+ orphan.unlink()
129
+ used = sum(p.stat().st_size for p in self.root.glob("epoch-*.bin") if not p.is_symlink())
130
+ require_capacity(self.root, len(payload), self.policy, used)
131
+ fd, name = tempfile.mkstemp(prefix=".pending-", dir=self.root)
132
+ try:
133
+ with os.fdopen(fd, "wb") as stream:
134
+ stream.write(payload)
135
+ stream.flush()
136
+ os.fsync(stream.fileno())
137
+ os.replace(name, target)
138
+ atomic_json(manifest, {"epoch": epoch, "size": len(payload),
139
+ "sha256": hashlib.sha256(payload).hexdigest(),
140
+ "best": bool(best)})
141
+ finally:
142
+ Path(name).unlink(missing_ok=True)
143
+ records = self._records()
144
+ protected = {item[0] for item in records[:self.policy.keep_last]}
145
+ best_record = next((item for item in records if item[3].get("best")), None)
146
+ if best_record:
147
+ protected.add(best_record[0])
148
+ for old_epoch, old_payload, old_manifest, _ in records:
149
+ if old_epoch not in protected:
150
+ old_manifest.unlink()
151
+ old_payload.unlink()
152
+ logging.getLogger(__name__).info("checkpoint_saved", extra={"epoch": epoch, "checkpoint_path": str(target)})
153
+ return target
154
+ finally:
155
+ lock.unlink(missing_ok=True)
@@ -0,0 +1,20 @@
1
+ """Explicit checkpoint configuration for training scripts and frontends."""
2
+ import json
3
+ from pathlib import Path
4
+ from .checkpoint import CheckpointPolicy, CheckpointStore
5
+
6
+
7
+ def load_checkpoint_config(path):
8
+ path = Path(path)
9
+ with path.open(encoding="utf-8") as stream:
10
+ if path.suffix.lower() in {".yaml", ".yml"}:
11
+ import yaml
12
+ data = yaml.safe_load(stream)
13
+ else:
14
+ data = json.load(stream)
15
+ if not isinstance(data, dict):
16
+ raise ValueError("configuration must be a mapping")
17
+ if set(data) - {"root", "run_id", "policy"}:
18
+ raise ValueError("unknown checkpoint configuration keys")
19
+ return CheckpointStore(data["root"], data["run_id"],
20
+ CheckpointPolicy(**data.get("policy", {})))