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
@@ -0,0 +1,58 @@
1
+ """Opt-in callback adapter for the Ultralytics trainer callback protocol."""
2
+ from .monitor import TrainingMonitor
3
+ from .resources import sample_resources
4
+
5
+
6
+ def attach_monitor(model, path, *, publish_interval=1.0, resources=False, archive=None, diagnostics=None):
7
+ """Attach before model.train(). Fixed-length, fresh single-process runs only.
8
+
9
+ Callback compatibility depends on Ultralytics version. This adapter observes
10
+ completed batches, not optimizer steps; it never edits training settings.
11
+ """
12
+ state = {"monitor": None, "epoch": 0, "batch": 0}
13
+ def start(trainer):
14
+ if getattr(trainer, "start_epoch", 0) != 0:
15
+ raise ValueError("Resumed training is not supported by this adapter")
16
+ state["monitor"] = TrainingMonitor(path, epochs=int(trainer.epochs),
17
+ batches_per_epoch=len(trainer.train_loader), publish_interval=publish_interval, archive=archive, diagnostics=diagnostics)
18
+ def epoch_start(trainer):
19
+ state["epoch"] = int(trainer.epoch) + 1
20
+ state["batch"] = 0
21
+ def batch_end(trainer):
22
+ state["batch"] += 1
23
+ metrics = {}
24
+ loss = getattr(trainer, "loss_items", None)
25
+ if loss is not None:
26
+ values = loss.detach().flatten().tolist()
27
+ names = getattr(trainer, "loss_names", ())
28
+ metrics = {str(name): value for name,value in zip(names, values)}
29
+ metrics["loss"] = sum(values)
30
+ state["monitor"].batch(epoch=state["epoch"], batch=state["batch"], metrics=metrics)
31
+ def epoch_end(trainer):
32
+ metrics = {}
33
+ for key, value in (getattr(trainer, "metrics", None) or {}).items():
34
+ try:
35
+ metrics[str(key)] = float(value)
36
+ except (TypeError, ValueError):
37
+ continue
38
+ monitor = state["monitor"]
39
+ if monitor.epoch_history and monitor.epoch_history[-1]["epoch"] == state["epoch"]:
40
+ return # Final best-model evaluation can repeat the callback.
41
+ for key, value in (getattr(trainer, "lr", None) or {}).items():
42
+ metrics["lr/" + str(key)] = float(value)
43
+ monitor.epoch_end(state["epoch"], metrics)
44
+ if resources:
45
+ state["monitor"].record_resources(sample_resources())
46
+
47
+ def save(trainer):
48
+ for key in ("last", "best"):
49
+ path = getattr(trainer, key, None)
50
+ if path is not None:
51
+ state["monitor"].artifact(path)
52
+ def end(trainer):
53
+ state["monitor"].finish()
54
+ for event, callback in (("on_train_start", start), ("on_train_epoch_start", epoch_start),
55
+ ("on_train_batch_end", batch_end), ("on_fit_epoch_end", epoch_end), ("on_model_save", save),
56
+ ("on_train_end", end)):
57
+ model.add_callback(event, callback)
58
+ return state
@@ -0,0 +1,462 @@
1
+ Metadata-Version: 2.4
2
+ Name: deepforge-research-toolkit
3
+ Version: 0.7.1
4
+ Summary: Local-first deep learning research studio and dataset validation toolkit
5
+ Author: Alireza Khatibi
6
+ License: MIT
7
+ Keywords: deep-learning,dataset,reproducibility,pytorch
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Operating System :: OS Independent
10
+ Requires-Python: >=3.10
11
+ Description-Content-Type: text/markdown
12
+ License-File: LICENSE
13
+ Provides-Extra: dev
14
+ Requires-Dist: pytest>=8; extra == "dev"
15
+ Requires-Dist: Pillow>=10; extra == "dev"
16
+ Provides-Extra: images
17
+ Requires-Dist: Pillow>=10; extra == "images"
18
+ Provides-Extra: torch
19
+ Requires-Dist: torch; extra == "torch"
20
+ Provides-Extra: resources
21
+ Requires-Dist: psutil>=5.9; extra == "resources"
22
+ Provides-Extra: notebook
23
+ Requires-Dist: ipython>=8; extra == "notebook"
24
+ Dynamic: license-file
25
+
26
+ <div align="center">
27
+ <img src="src/deepforge/assets/xvarna.png" alt="XVARNA" width="340" />
28
+ <h1>DeepForge Studio</h1>
29
+ <p><strong>Professional Research Toolkit · Jade Edition</strong></p>
30
+ <p>Created by <strong>Alireza Khatibi</strong> · XVARNA</p>
31
+ </div>
32
+
33
+ ![Version](https://img.shields.io/badge/version-0.7.1-12664F) ![Python](https://img.shields.io/badge/python-3.10%2B-12664F) ![License](https://img.shields.io/badge/license-MIT-E0C58F)
34
+
35
+ **Inspect · Validate · Evaluate · Reproduce**
36
+
37
+ DeepForge is a local-first research toolkit for deep learning and computer vision. It brings dataset quality checks, leakage audits, YOLO label validation, experiment diagnostics, classification evaluation, model inspection, and reproducibility reporting into one Python package with a desktop interface and a scriptable command-line API.
38
+
39
+ DeepForge Studio is an early-stage open-source project. Version 0.7.1 is a release candidate for research and development, not a clinically validated product or a certified production service. It is not yet published on PyPI.
40
+
41
+ ![DeepForge Studio research dashboard](docs/images/dashboard.png)
42
+
43
+ ## Install and launch
44
+
45
+ Python 3.10 or later is required. The core toolkit uses only the standard library. Pillow enables image decoding and similarity analysis; PyTorch is optional for model inspection. Tkinter is required only for the desktop application.
46
+
47
+ ### Windows
48
+
49
+ Extract the source archive and open its `DeepForge` directory. With Python on PATH, run `scripts\setup-windows.cmd` and then `scripts\launch-windows.cmd`. The setup script creates a project-specific `.venv` and installs the image-analysis dependency. Alternatively, use your existing Python environment:
50
+
51
+ ```powershell
52
+ python -m pip install -e ".[images]"
53
+ python -m deepforge.gui
54
+ ```
55
+
56
+ ### Linux / macOS
57
+
58
+ ```bash
59
+ python -m venv .venv
60
+ source .venv/bin/activate
61
+ python -m pip install -e '.[images]'
62
+ deepforge-studio
63
+ ```
64
+
65
+ A standard Tk installation is needed. On Debian/Ubuntu, install `python3-tk` if your Python distribution does not already include Tk. Check with `python -m tkinter`. Install PyTorch for your hardware using the official [PyTorch installation guide](https://pytorch.org/get-started/locally/) rather than assuming a CUDA build is appropriate. For a default PyTorch installation, `python -m pip install -e '.[torch]'` is also available.
66
+
67
+ The Windows launch scripts have been inspected but not run on Windows in the release preparation environment. The actual desktop UI was exercised on Linux with a virtual display. GPU execution has not been validated.
68
+
69
+ ### Google Colab and VS Code notebooks
70
+
71
+ In Colab, install into the active kernel:
72
+
73
+ ```python
74
+ %pip install "deepforge-research-toolkit[notebook] @ git+https://github.com/AliRezaKhatibi/DeepForge.git"
75
+ ```
76
+
77
+ In VS Code, install the Python and Jupyter extensions, select your Python environment as the notebook kernel, and run `%pip install -e ".[notebook]"` from the repository root in that kernel. Restart the kernel if upgrading an already imported package.
78
+
79
+ Open [the synthetic notebook example](examples/notebook_compatibility.ipynb) ([Colab](https://colab.research.google.com/github/AliRezaKhatibi/DeepForge/blob/main/examples/notebook_compatibility.ipynb)). Install the package before running its cells. The new `NotebookMonitor(path, interval=1.0)` uses an IPython display handle; call `refresh()` after recording batches and `refresh(force=True)` after finishing. Set the TrainingMonitor publish interval to suit the refresh interval. No Tk window, server or background thread is required. Colab files are ephemeral unless explicitly copied to persistent storage. VS Code scripts can continue using the CLI and desktop viewer.
80
+
81
+ CI executes the notebook in standard headless Jupyter kernels on Windows and Linux. This does not establish actual hosted Colab or VS Code frontend rendering compatibility. GPU hardware validation is deferred.
82
+
83
+ ## Research workspaces
84
+
85
+ | Workspace | Purpose | CLI command |
86
+ | --- | --- | --- |
87
+ | Dataset Inspector | Split and class counts for image classification | `dataset` |
88
+ | Exact Duplicates | SHA-256 cross-split duplicate groups | `leakage` |
89
+ | Image Integrity | Decode images, inspect resolution/mode, flag perceptual similarities | `images` |
90
+ | Group Leakage | Detect group, subject, or patient IDs shared across splits | `groups` |
91
+ | YOLO Labels | Check detection labels, class ranges, missing/orphan pairs, invalid boxes | `yolo` |
92
+ | Learning Curves | Best epoch, final metric, possible overfitting signal | `history` |
93
+ | Compare Runs | Rank validation histories and identify rejected CSV files | `compare` |
94
+ | Classification | Accuracy, macro/weighted precision, recall, F1 and confusion matrix | `metrics` |
95
+ | Binary Scores | ROC-AUC, average precision, threshold metrics, Brier score and ECE | `scores` |
96
+ | Model Inspector | Parameters, executed layers, shapes, partial MACs/FLOPs and latency for a configurable MLP | `profile-mlp` |
97
+ | Runtime | Python, PyTorch and optional CUDA information | `env` |
98
+ | Reproducibility | Dependency versions and optional input-file SHA-256 | `manifest` |
99
+
100
+ ### Studio features
101
+
102
+ - A navigable research dashboard, 12 independent workspaces, with a jade, cream and gold visual identity, collapsible sidebar and searchable navigation. Compact windows automatically collapse the input panel after analysis to leave room for the chart.
103
+ - Workspace input values are retained during the session. Search findings, copy individual rows, and hover over plotted points for precise values.
104
+ - Explore binary decision thresholds interactively with live precision, recall and F1 previews; Apply explicitly recomputes the report. Threshold selection belongs on validation data, not the final test set.
105
+ - Background analysis keeps the UI event loop responsive; analyses are run sequentially within a window.
106
+ - Learning curves, confusion matrices, distribution bars, ROC, precision-recall and reliability diagrams.
107
+ - A findings table and full JSON report; JSON and self-contained HTML export with embedded chart previews matching the selected ROC, precision-recall or calibration view.
108
+ - The last 15 successful analyses are available in session memory. Closing the application clears that history unless reports were explicitly exported.
109
+ - Nine workspaces have bundled, clearly synthetic demo inputs. Demo data intentionally includes leakage and label issues to exercise the audits.
110
+ - No account, cloud service or telemetry is required. Input analyses are read-only, and report exports are written to a user-selected output path.
111
+
112
+ ![Training analyzer with validation and training loss](docs/images/training.png)
113
+
114
+ ![Binary score evaluation with ROC visualization](docs/images/scores.png)
115
+
116
+ ![Classification evaluator with confusion matrix](docs/images/metrics.png)
117
+
118
+ <details>
119
+ <summary>Explore more real application screenshots</summary>
120
+
121
+ ![Calibration](docs/images/calibration.png)
122
+ ![Experiment comparison](docs/images/compare.png)
123
+ ![Group leakage](docs/images/groups.png)
124
+ ![YOLO label audit](docs/images/yolo.png)
125
+ ![Searchable findings](docs/images/findings.png)
126
+ ![Compact workspace](docs/images/compact.png)
127
+ ![Compact binary evaluation](docs/images/compact_scores.png)
128
+ ![Focus mode](docs/images/focus.png)
129
+ ![About and credits](docs/images/about.png)
130
+
131
+ </details>
132
+
133
+ All screenshots were captured from the running desktop application with bundled synthetic inputs. No private datasets are included.
134
+
135
+ ### Keyboard shortcuts
136
+
137
+ | Shortcut | Action |
138
+ | --- | --- |
139
+ | Ctrl+K | Find a workspace |
140
+ | Ctrl+B | Toggle sidebar |
141
+ | Ctrl+Enter | Run analysis |
142
+ | Ctrl+S | Export JSON |
143
+
144
+ ### Branding
145
+
146
+ DeepForge Studio was created by Alireza Khatibi under the XVARNA identity. The supplied XVARNA logo was refined into a transparent raster asset for the desktop application and documentation. The software uses the MIT license; brand identity and logo usage are separate from the software license.
147
+
148
+ ## CLI quick examples
149
+
150
+ Run `deepforge --help` or `python -m deepforge --help` for arguments. All CLI reports are JSON. Exit code 2 indicates an invalid input or I/O error. The `leakage` and `groups` commands can return 1 with `--fail-on-leakage` when the respective audit detects overlap.
151
+
152
+ ```bash
153
+ deepforge dataset ./dataset
154
+ deepforge leakage ./dataset --fail-on-leakage
155
+ deepforge images ./dataset --similarity --threshold 4 --max-images 2000
156
+ deepforge groups examples/groups.csv --fail-on-leakage
157
+ deepforge yolo ./detection_dataset --classes 3
158
+ deepforge history examples/history.csv --train-metric train_loss
159
+ deepforge compare examples/runs --train-metric train_loss
160
+ deepforge metrics examples/predictions.csv
161
+ deepforge scores examples/scores.csv --positive-label 1 --threshold 0.5
162
+ deepforge env
163
+ deepforge manifest examples/history.csv
164
+ ```
165
+
166
+ ## Input formats and interpretation
167
+
168
+ ### Classification datasets and image audits
169
+
170
+ ```
171
+ dataset/
172
+ train/cat/a.png
173
+ train/dog/b.jpg
174
+ val/cat/c.png
175
+ test/dog/d.jpg
176
+ ```
177
+
178
+ `dataset` and `leakage` expect class directories under `train`, `val` (or `validation`), and/or `test`. The first counts supported extensions without decoding; the second groups identical file bytes by SHA-256. `images` accepts both class folders and images directly beneath split folders. It uses Pillow, corrects EXIF orientation for inspected sizes and hashes, flags decode failures and reports unsupported DICOM inputs without parsing them.
179
+
180
+ Perceptual similarity is a 64-bit difference hash (dHash) compared by Hamming distance across different splits. The exhaustive comparison is bounded to a configurable, deterministic first 1–5,000 image candidates (default 2,000); pair previews are capped, and reports include explicit truncation indicators. It may miss cropped, rotated or otherwise transformed images, and unrelated flat images can collide. These are candidate matches requiring review, not proof of duplicate identity. Clean reports do not establish patient independence. The image audit inspects a single frame of multi-frame images and rejects images exceeding 40 megapixels.
181
+
182
+ ### Group-aware leakage
183
+
184
+ ```csv
185
+ group_id,split
186
+ subject-a,train
187
+ subject-a,val
188
+ subject-b,test
189
+ ```
190
+
191
+ The manifest must include complete, correct group IDs. Use patient-level identifiers in medical imaging where ethically permitted; do not upload real identifiers or datasets to GitHub. Raw IDs are replaced with local report pseudonyms by default; this is not guaranteed anonymization. `--show-identifiers` is an explicit CLI opt-in. Group audits do not infer patient identities from filenames or image content.
192
+
193
+ ### YOLO object detection
194
+
195
+ ```
196
+ detection_dataset/
197
+ images/train/a.jpg
198
+ labels/train/a.txt
199
+ images/val/b.jpg
200
+ labels/val/b.txt
201
+ ```
202
+
203
+ Each detection row has five fields: `class_id x_center y_center width height`. Coordinates must be finite and normalized, and box dimensions must be positive. The audit flags out-of-frame boxes, duplicate rows, invalid class IDs (upper bound only when `--classes` is supplied), ambiguous image stems and missing/orphan label files. Empty label files may correctly represent background images. This does not inspect semantic annotation correctness, YAML dataset definitions, segmentation polygons, or pose keypoints.
204
+
205
+ ### Experiment diagnostics
206
+
207
+ Use CSV files with strictly increasing numeric epochs and finite numeric validation values. `--mode min` selects the smallest metric, while `--mode max` selects the largest. The earliest epoch wins ties. If a comparable training metric improves while validation deteriorates after the best epoch, the result is a possible overfitting signal, not a causal diagnosis. `compare` processes CSV files in one directory (default cap 100) and ranks reported best validation metrics; compare only runs with equivalent evaluation protocols and appropriate budgets.
208
+
209
+ ### Classification and probability scores
210
+
211
+ Use `y_true,y_pred` for single-label predictions. Confusion matrix rows are true labels, columns predicted labels, using sorted observed labels. Undefined precision/recall/F1 are zero.
212
+
213
+ For binary probability evaluation, use `y_true,score`, specifying the positive class and decision threshold. Scores must be finite probabilities in [0,1], and exactly two observed classes are required. ROC-AUC integrates the ROC curve; average precision uses recall increments at grouped score thresholds (including ties). Brier score measures probability squared error, while ECE depends on the equal-width bins selected. Calibration is descriptive, not a guarantee of trustworthy predictions. Tune thresholds on validation data, not the final test set. Detection mAP, multiclass probability curves and multilabel metrics are not implemented.
214
+
215
+ ### PyTorch model inspection
216
+
217
+ ```python
218
+ import torch
219
+ from deepforge.models import inspect_model
220
+
221
+ model = torch.nn.Sequential(
222
+ torch.nn.Linear(16, 32),
223
+ torch.nn.ReLU(),
224
+ torch.nn.Linear(32, 3),
225
+ )
226
+ print(inspect_model(model))
227
+ ```
228
+
229
+ The desktop Model workspace constructs a limited configurable MLP; the Python API accepts a model you have already constructed. It never loads arbitrary checkpoints or evaluates user-supplied Python source. Parameter/buffer counts deduplicate tensor objects, but shared underlying storage can be counted more than once. Logical byte estimates are not activation memory, optimizer memory, peak GPU memory, latency or FLOPs. Initialize lazy modules before inspection.
230
+
231
+ ## Python API
232
+
233
+ ```python
234
+ from deepforge.audit import audit_groups, audit_yolo, audit_images
235
+ from deepforge.advanced import read_binary_scores, compare_runs
236
+
237
+ report = audit_groups('examples/groups.csv')
238
+ print(report['overlapping_groups'])
239
+ report = read_binary_scores('examples/scores.csv')
240
+ print(report['roc_auc'])
241
+ ```
242
+
243
+ ### API capability map
244
+
245
+ | Module | Public entry points | Purpose |
246
+ | --- | --- | --- |
247
+ | datasets | `inspect_dataset` | Dataset inventory and exact duplicates |
248
+ | audit | `audit_images`, `audit_groups`, `audit_yolo` | Image, group and annotation audits |
249
+ | advanced | `read_binary_scores`, `compare_runs` | Probability evaluation and run comparison |
250
+ | models | `inspect_model` | Model parameter and buffer inspection |
251
+ | profiler | `profile_model`, `profile_mlp`, `profile_operators`, `profile_cuda_peak` | Executed layer trace, partial MACs/FLOPs, logical bytes and forward latency |
252
+ | automation | `run_checks`, `require_pass`, `save_report` | Composable quality gates |
253
+ | training | `TrainingGuard`, `model_check`, `gradient_check` | Pre-update training health checks |
254
+ | monitor | `TrainingMonitor` | Batch progress, ETA, metrics and output files |
255
+ | ultralytics | `attach_monitor` | Opt-in trainer callbacks |
256
+ | resources | `sample_resources` | Optional CPU/RAM and CUDA allocator observations |
257
+ | notebook | `snapshot_html`, `display_snapshot` | Notebook-friendly local snapshots |
258
+
259
+ ## Automated quality gates (Python integration)
260
+
261
+ Install directly from GitHub (PyPI publication is not yet available):
262
+
263
+ ```bash
264
+ python -m pip install "git+https://github.com/AliRezaKhatibi/DeepForge.git"
265
+ ```
266
+
267
+ Use DeepForge as a headless library without launching the desktop interface:
268
+
269
+ ```python
270
+ from deepforge.automation import (
271
+ dataset_check, group_check, run_checks, save_report, require_pass,
272
+ )
273
+
274
+ report = run_checks([
275
+ dataset_check("dataset"),
276
+ group_check("groups.csv"),
277
+ ])
278
+ save_report(report, "quality-report.json")
279
+ require_pass(report) # Raises AuditFailed if a check fails or errors.
280
+ # Start model training only after the gate succeeds.
281
+ ```
282
+
283
+ The default classification dataset gate requires nonempty train, val (or validation), and test splits, and zero exact cross-split duplicates. Adjust required_splits explicitly for other protocols. Group checks require a complete, correct manifest. Optional image and YOLO gates and in-memory classification metrics are also available. Install the images extra for image decoding. Similarity matches require human review; passing these configured checks is not proof of dataset independence. A truncated image scan fails the image gate. Reports may contain sensitive paths and must be reviewed before sharing. Report exports refuse to overwrite existing files.
284
+
285
+ Run a gate in CI or before training with `python examples/quality_gate.py dataset --groups groups.csv`. Custom checks use `Check(name, callable, rules)`, where rules are tuples of (dotted report field, comparison operator, expected value). Supported operators: eq, ne, ge, gt, le, lt. Missing fields and execution errors fail closed. An empty rule set checks execution only.
286
+
287
+ ## PyTorch training health guard
288
+
289
+ Install the optional PyTorch dependency using the appropriate official wheel for your device. DeepForge remains importable without PyTorch.
290
+
291
+ ```python
292
+ from deepforge.training import TrainingGuard
293
+
294
+ guard = TrainingGuard(model, max_gradient_norm=100)
295
+ optimizer.zero_grad(set_to_none=True)
296
+ loss = criterion(model(inputs), targets)
297
+ loss.backward()
298
+ guard.before_step(loss) # Raises AuditFailed on nonfinite loss/gradients or configured norm violation.
299
+ optimizer.step()
300
+ ```
301
+
302
+ Call at optimizer update boundaries, after AMP unscaling when using mixed precision. The norm limit is illustrative, not a universal safe threshold. Missing gradients are reported and optionally rejected with require_all_gradients=True. No gradient clipping, optimizer updates, hooks, or automatic training are performed by DeepForge. Checks synchronize devices and use temporary higher-precision tensors; measure overhead before enabling every step. Sparse COO gradients are supported; other sparse layouts fail closed. A passing report does not establish training convergence or detect every form of vanishing gradients. See examples/pytorch_guard.py for a runnable synthetic example.
303
+
304
+ ## Live training monitor
305
+
306
+ Run the synthetic demo in one terminal and the independent graphical viewer in another:
307
+
308
+ ```bash
309
+ python examples/live_training.py
310
+ deepforge-live live.json
311
+ ```
312
+
313
+ Use TrainingMonitor from deepforge.monitor in any Python training loop. Call batch(epoch=1, batch=1, samples=16, metrics={"loss": loss}) after each completed batch, using one-based consecutive positions. Call finish() at termination (finish(failed=True) on exceptions). Register output files with artifact(path). One writer per snapshot path; the selected JSON file is replaced atomically. Existing snapshot files at that path are overwritten. Metrics are local, bounded to recent history, and nonfinite values become null. The ETA is based on observed average batch speed, not a guarantee; validation, checkpointing and changing batch lengths can affect it. Sample counts are caller supplied.
314
+
315
+ For a fresh fixed-length single-process Ultralytics run, register callbacks before training:
316
+
317
+ ```python
318
+ from ultralytics import YOLO
319
+ from deepforge.ultralytics import attach_monitor
320
+ model = YOLO("your-model.yaml")
321
+ attach_monitor(model, "live.json")
322
+ model.train(data="data.yaml", epochs=10)
323
+ ```
324
+
325
+ The adapter is tested against a synthetic callback protocol, not a real Ultralytics training run. It does not support resume, distributed training or changing epoch lengths. Sample counts are not populated by the adapter. The viewer is a separate Tk window and does not interrupt training. It plots recent loss or the first available metric; registered checkpoint names and sizes are displayed without opening the files. A killed process may leave its last snapshot marked running.
326
+
327
+ ### Validation metrics, resources and notebooks
328
+
329
+ The live viewer provides a selector for available batch metric curves. Call `monitor.epoch_end(epoch, metrics)` after validation to retain epoch-level metrics separately. The Ultralytics adapter records the trainer's reported metrics through the fit-epoch callback. Opt in with `attach_monitor(model, "live.json", resources=True)`; install the resources extra for CPU/RAM measurements. CUDA allocated/reserved bytes describe the current PyTorch allocator, not total GPU utilization. Resource sampling occurs at epoch boundaries.
330
+
331
+ In a Jupyter notebook, use `from deepforge.notebook import display_snapshot` and `display_snapshot("live.json")` to display a snapshot without Tk. Refresh by calling it again; no background polling is started. Install the notebook extra if IPython is unavailable. These features have synthetic tests, not real hosted notebook or GPU validation. Opt-in image previews and batch event archives are described below.
332
+
333
+ ### Live monitor gallery
334
+
335
+ The following screenshots were captured from the running desktop monitor under Linux/Xvfb using **synthetic demo metrics**, not a trained-model benchmark. CPU/RAM figures reflect the capture environment.
336
+
337
+ ![Live training monitor showing batch and epoch progress, ETA, loss and output metadata](docs/images/live-training.png)
338
+
339
+ ![Live training monitor with box loss selected](docs/images/live-box-loss.png)
340
+
341
+ The following image shows the actual notebook renderer output opened in a browser, not a hosted Jupyter session.
342
+
343
+ ![Browser-rendered notebook snapshot](docs/images/live-notebook.png)
344
+
345
+ [Open the notebook HTML example](docs/images/live-notebook.html).
346
+
347
+ ### Reproducing live monitor screenshots
348
+
349
+ The [Live monitor gallery workflow](https://github.com/AliRezaKhatibi/DeepForge/actions/workflows/live-gallery.yml) runs the actual desktop viewer under Xvfb and captures its window using synthetic metrics. Download the `deepforge-live-gallery` artifact from a successful run. The HTML file is the actual notebook renderer output; a browser capture illustrates that HTML, not a hosted Jupyter session. These are demonstrations, not trained-model benchmarks.
350
+
351
+ ## Model architecture profiler (0.7)
352
+
353
+ ```bash
354
+ deepforge profile-mlp --inputs 16 --hidden 32 --outputs 3 --batch 8
355
+ ```
356
+
357
+ ```python
358
+ import torch
359
+ from deepforge.profiler import profile_model
360
+
361
+ model = torch.nn.Sequential(torch.nn.Linear(16, 32),
362
+ torch.nn.ReLU(), torch.nn.Linear(32, 3))
363
+ report = profile_model(model, torch.zeros(8, 16), warmup=2, repeats=5)
364
+ print(report["estimated_macs"], report["estimated_flops_2x_macs"])
365
+ print(report["calls"])
366
+ ```
367
+
368
+ The Model workspace now profiles the built-in MLP, with executed call details in Findings and JSON/HTML reports. Arbitrary trusted, already initialized models are supported through Python, including keyword and nested inputs. The example `examples/profile_architecture.py` exports a self-contained HTML report.
369
+
370
+ **Counting convention:** standard Linear and Conv1d/2d/3d leaf-module calls only, including groups, output dimensions, repeated calls and batch size. One multiply-accumulate is counted as two FLOPs. Bias, activation, normalization, pooling, attention and functional operations are not counted. Unsupported leaf types are reported, but functional operations can remain invisible. This is a partial estimate, not a complete architecture FLOP count or a substitute for a paper's reporting convention. Registered modules, registered leaf modules, and executed leaf calls are distinct; shared parameters are deduplicated in the global inventory, not necessarily in per-module rows.
371
+
372
+ Latency measures a complete uninstrumented forward after warmup, on CPU or synchronized CUDA devices, with median and nearest-rank p95 in milliseconds. Set repeats=0 to disable timing. Measurements depend on batch size, hardware and load. The logical output byte sum is not peak activation memory; CUDA allocator before/after values are process-wide, not model-specific peak VRAM. Model evaluation flags and hooks are restored, but arbitrary custom forwards can still mutate state or consume RNG; profile trusted code only, never concurrently on a training model. GPU timing is not yet verified on real CUDA hardware by CI.
373
+
374
+ ### Extended operator and CUDA peak profiling (0.7.1)
375
+
376
+ ```python
377
+ from deepforge.profiler import profile_operators, profile_cuda_peak
378
+
379
+ ops = profile_operators(model, example_input)
380
+ print(ops["estimated_flops"], ops["operators"])
381
+ # For CUDA models/inputs only, when no other CUDA work is running:
382
+ # peak = profile_cuda_peak(model, example_input)
383
+ ```
384
+
385
+ The operator report uses the native PyTorch profiler's partial FLOP estimates, including selected matrix multiplications and 2-D convolution operations. It is independent of the module-hook estimator: **never add the two totals**. Operators without a positive estimate are listed, not assumed free. CPU event timings include instrumentation overhead and are not device latency.
386
+
387
+ The explicitly opt-in CUDA peak function resets process-wide allocator peak counters for the known CUDA devices, performs a single evaluation forward, and returns baseline and peak allocation/reservation. It cannot restore old peak counters and is not an isolated measurement of model memory or training VRAM. Do not call it while training or profiling concurrent workloads. Actual CUDA hardware is not available in the CPU CI matrix; the CUDA-only test skips when unavailable.
388
+
389
+ The Model Inspector now accepts batch size, charts per-layer estimated MACs, and shows compact input/output shape rows in Findings. The following images were captured from the running Model Inspector under Linux/Xvfb using a synthetic, randomly initialized MLP (64 → 128 → 10, batch size 8). The latency values describe the CI capture machine and are not a hardware benchmark.
390
+
391
+ ![Actual Model Inspector showing per-layer estimated MACs](docs/images/architecture-profiler.png)
392
+
393
+ ![Actual Model Inspector showing executed layers and tensor shapes](docs/images/architecture-layers.png)
394
+
395
+ [Open the matching HTML architecture report](docs/images/architecture-report.html). The gallery workflow reproduces these screenshots and the report.
396
+
397
+ ## Training analytics and persistent events (0.6)
398
+
399
+ ```python
400
+ from deepforge.monitor import TrainingMonitor
401
+
402
+ monitor = TrainingMonitor("live.json", epochs=10, batches_per_epoch=20,
403
+ archive="events.jsonl",
404
+ diagnostics={"train_key": "train_loss", "val_key": "val_loss"})
405
+ monitor.batch(epoch=1, batch=1, samples=3, metrics={"loss": 0.7},
406
+ labels=[0, 0, 1])
407
+ # Optional: publish an explicitly selected, already annotated image:
408
+ # monitor.record_preview("annotated_batch.png")
409
+ ```
410
+
411
+ Call batch for every completed batch in sequence and epoch_end after each completed epoch with comparable scalar train/validation losses. Diagnostics flag possible overfitting or a loss plateau over the configured window, not causal diagnoses of overfitting or underfitting. Optional gradient thresholds require the caller to record gradient_norm and configure thresholds appropriate for the model. Class counts are label counts (objects for detection), not automatically inferred images or dataset-wide imbalance. The preview is opt-in, requires Pillow, stores a bounded PNG in the snapshot and notebook output, and never uploads data. Do not publish private image content or reports. The optional JSONL archive records all batch/epoch events, not images; it must be a new file, is single-writer, and does not implement checkpoint resume.
412
+
413
+ Ultralytics callbacks record learning rates when exposed and ignore repeated final validation callbacks. The CI smoke job exercises a pinned YOLO release on CPU with generated images and labels; the job result is the verification record. Automatic extraction of YOLO batch tensors and sample counts, GPU utilization, resume, and architecture FLOPs are not implemented by this change. See the previous gallery for the established desktop UI; new diagnostics screenshots are not yet captured.
414
+
415
+ ## Tests and release verification
416
+
417
+ ```bash
418
+ python -m pip install -e '.[dev]'
419
+ python -m pytest -q
420
+ ```
421
+
422
+ On Linux with a virtual display, exercise the actual desktop interface using:
423
+
424
+ ```bash
425
+ xvfb-run -a python -m pytest -q
426
+ ```
427
+
428
+ The CI workflow targets Windows and Linux on Python 3.10, 3.13 and 3.14, and includes a separate Linux CPU PyTorch job. Its remote results remain unverified until publication. The release preparation tests, environment and limitations are recorded in [docs/VALIDATION.md](docs/VALIDATION.md).
429
+
430
+ ## Privacy and safe use
431
+
432
+ - Reports may contain relative paths, class labels, input filenames or detailed error text. Review and redact before sharing.
433
+ - Inputs and reports stay local unless you explicitly share them. There is no network API or telemetry in the toolkit.
434
+ - Do not treat the leakage, label or calibration audits as guarantees of dataset independence, correctness, safety or clinical performance.
435
+ - See [SECURITY.md](SECURITY.md) for vulnerability reporting and [CONTRIBUTING.md](CONTRIBUTING.md) for contribution guidance.
436
+
437
+ ## Roadmap
438
+
439
+ Future work: scalable similarity indexing, per-image annotation preview, group-aware split planning, detection mAP, safe model profiling, saved project workspaces, accessibility refinements, and signed desktop installers. No release dates are promised.
440
+
441
+ ## License
442
+
443
+ DeepForge is distributed under the MIT license. See [LICENSE](LICENSE). Third-party dependencies retain their own licenses. The project is not affiliated with PyTorch or Ultralytics.
444
+
445
+ ## Smart checkpoint recovery
446
+
447
+ Create a JSON configuration in Studio using the Checkpoint button, or write one manually with root, run_id and policy (enabled, keep_last, save_every_epochs, max_bytes). YAML requires PyYAML. A mounted Drive directory can be used as root, but remote filesystem durability and locking are not guaranteed.
448
+
449
+ ```python
450
+ from deepforge.checkpoint_config import load_checkpoint_config
451
+ from deepforge.checkpoint_torch import TorchCheckpoint
452
+
453
+ store = load_checkpoint_config("checkpoint.json")
454
+ # Construct model and optimizer before restoring.
455
+ # adapter = TorchCheckpoint(store, model, optimizer, scheduler=scheduler)
456
+ # metadata = {"dataset_fingerprint": "...", "seed": 42, "settings": {}}
457
+ # adapter.save_epoch(epoch, global_step=step, metadata=metadata)
458
+ # state = adapter.restore_latest(expected_metadata=metadata)
459
+ # Continue at state["epoch"] + 1.
460
+ ```
461
+
462
+ Call save_epoch after each completed epoch. Supply dataset fingerprints, splits, augmentation settings and other provenance in metadata. Inspect verified records with `deepforge checkpoint ROOT RUN_ID`. After a crash, only after confirming all writers have stopped, call `store.recover_abandoned_lock(confirmed_no_writer=True)`. Checksums detect corruption, not malicious modification. Use trusted storage. Exact resume depends on framework, sampler, hardware and deterministic operations; mid-epoch progress is not guaranteed. Studio exports configuration rather than modifying running training scripts.
@@ -0,0 +1,53 @@
1
+ deepforge/__init__.py,sha256=-m7Pk6YF5r2oe_HIQ7VkfoQqqsT6ATGiQJUOcBomuQo,91
2
+ deepforge/__main__.py,sha256=k1ocEWawweo1qCJWNFAAvyxz3tcY13dzvCenHszij30,48
3
+ deepforge/advanced.py,sha256=9-BVDTt2ORUayyDlm_G5ZyYaqam-YRMuD8f7D08DxTA,6749
4
+ deepforge/audit.py,sha256=p9uk9kLBe89yrbDNLz_oEw7JDLtKZKp3-qoDy2OuvjU,11009
5
+ deepforge/automation.py,sha256=Yurm-71eEuWZcTJswPi5PkO-aDzRjH9cuNQdLXJI7P4,6049
6
+ deepforge/checkpoint.py,sha256=vU773i2loMukNOW15lQ3MOr1UPtQCJlymi82XY31YyA,6788
7
+ deepforge/checkpoint_config.py,sha256=63skDzq8pyQ23zZUynf_vKpvxhwKz13010xpIagiPug,785
8
+ deepforge/checkpoint_torch.py,sha256=_2zHo0OX6wvzJJnOpKK1qwk5nIVAha3a-SomqH6knp4,2934
9
+ deepforge/checkpoint_yolo.py,sha256=6SqL8pn-h0XAsO33_Q4mbWueYCUxm2JVk1aYG9aevGw,718
10
+ deepforge/cli.py,sha256=xNRh83Q0P_KHKxZsO4SfScAgF7e6srpamFlEvNKAyeI,6710
11
+ deepforge/datasets.py,sha256=AFpl1VT5lhAl8--RMkS-ybaEHXCSnx03gSlhnc1Q69k,2779
12
+ deepforge/diagnostics.py,sha256=OktFzECCRsu3o-Bceshw2_Yziy9b0iJBoP4bNpO_rVg,3340
13
+ deepforge/environment.py,sha256=XhYszfd21vTkPAbAf8W6KRHPPMrqT7eVeQJq551xSi8,1109
14
+ deepforge/gui.py,sha256=tsEVGfiEYwwDUzGIVQ4qm7E-kLZ3HGYHzjevq2K6n9A,44020
15
+ deepforge/gui_data.py,sha256=rtAHnR6KGcOVTiaIo6XVU4VcZcSg2MMDUwZYxTWcSq4,8195
16
+ deepforge/history.py,sha256=nyMrDhaVmmuj_Ojoy_nlZtBBkm1dfu0AJrmG5Ky78Vw,2100
17
+ deepforge/live_view.py,sha256=sQbgnSCVMfpOXw7aPx75u6g1jXF-oYkZGlckyxl2NAA,5713
18
+ deepforge/metrics.py,sha256=xgenn4Nh0yhGtVwfjET03NCfI-AaFTBEeH1gPXxlOXk,2042
19
+ deepforge/models.py,sha256=w6W0-aDtvdhQOfNhEWYyBjInK5qmgCk712M9IXo1ay4,872
20
+ deepforge/monitor.py,sha256=ESvJNZzxEqDo5ALpcXhf6SYPooWBmdYrJSEZNhCGcG0,7599
21
+ deepforge/notebook.py,sha256=W_zeILvX8e6v-3r3Zf2MYPZPgjRfTpriiBz80MYMYms,3351
22
+ deepforge/preview.py,sha256=X4LZ-gPsbt_5dbBL9ne-WAJjB9GqlBm4seE3JV8SIL0,803
23
+ deepforge/profiler.py,sha256=Wt8g1GhjkORjgDlbO_rTV24vAIL3fQcR1f9xGks0CHg,13562
24
+ deepforge/reporting.py,sha256=bjeLeMwQfNv7xUucPhzqH-_Vzip-my2ZMxgh6c72pGI,8363
25
+ deepforge/resources.py,sha256=jEiR9CdRK1terGeboeFjy50QoRC_SXAPmTvvSj85ZQE,784
26
+ deepforge/training.py,sha256=EvgiAuOrbCsWd1APxwrFLWSGO7JeLZOZcNr8oE3zqV4,4812
27
+ deepforge/ultralytics.py,sha256=M0lj3lrn00INWXEuiYzU-oUsoT5HbN055FMEd_r7pu4,2819
28
+ deepforge/assets/icon.png,sha256=r8tnd-UgddViCo1t4gPBx-NtUHgAc_Pe7Hw89mu8SHk,12934
29
+ deepforge/assets/xvarna.png,sha256=43QuqpHXt4K1vo5D_rtAe5sk6gGMS5VotPLvmA3xdqI,1420298
30
+ deepforge/assets/xvarna_about.png,sha256=C4JFP0husO7sAsWqb079gnpBB-dE-jfMFKSP24mHh6s,81533
31
+ deepforge/assets/xvarna_sidebar.png,sha256=SqgXPPGxamOG6DKWKz34bTTNnJ5xOwC9TkPjFq9zWKA,22062
32
+ deepforge/samples/groups.csv,sha256=8vdcpgHQdXIZugc24D_4rFBm7S226gER6VO172ERCgE,100
33
+ deepforge/samples/history.csv,sha256=I9AaBKmfRMEvL-LUVTyXLHcgTNM_1fr0sVNUz9ffyDE,74
34
+ deepforge/samples/predictions.csv,sha256=BbrH49jWwy-ppllabxAf0g63cCpaXTusSKS399kT6VY,46
35
+ deepforge/samples/scores.csv,sha256=XtJ5xHvGZ3ER7UPt3wJkmvPK18JoK0DHPmKB7rHeoVg,69
36
+ deepforge/samples/dataset/test/square/sample_d.png,sha256=cozabsaGs-EdpeTMU_ltOC21k07mID-6wY0T2GveVqg,387
37
+ deepforge/samples/dataset/train/circle/sample_a.png,sha256=Ec2yhi4HmP3XFC9HDG9LTBZXH3429ZHHB8SC_KBxyUo,673
38
+ deepforge/samples/dataset/train/square/sample_b.png,sha256=3qjIAE2lWEwNaXXoXXkaSOhTnAY6ebMLWFLWiZGWWIg,390
39
+ deepforge/samples/dataset/val/circle/sample_c.png,sha256=Ec2yhi4HmP3XFC9HDG9LTBZXH3429ZHHB8SC_KBxyUo,673
40
+ deepforge/samples/runs/baseline.csv,sha256=I9AaBKmfRMEvL-LUVTyXLHcgTNM_1fr0sVNUz9ffyDE,74
41
+ deepforge/samples/runs/refined.csv,sha256=XCUaNlAEDIV4H4KT7pJuCRLocjiyjXLbUFQKX28Vd1M,74
42
+ deepforge/samples/yolo/images/test/sample.png,sha256=0qTEVf_bIxe-0ALVNJ4qxTBx4oQDniKdjjb2LF0DqAs,389
43
+ deepforge/samples/yolo/images/train/sample.png,sha256=0qTEVf_bIxe-0ALVNJ4qxTBx4oQDniKdjjb2LF0DqAs,389
44
+ deepforge/samples/yolo/images/val/sample.png,sha256=0qTEVf_bIxe-0ALVNJ4qxTBx4oQDniKdjjb2LF0DqAs,389
45
+ deepforge/samples/yolo/labels/test/sample.txt,sha256=OPewTWP-K4plfdcrEvdIk1hWvDQpMFmqlvf0Xc3aHIY,18
46
+ deepforge/samples/yolo/labels/train/sample.txt,sha256=OPewTWP-K4plfdcrEvdIk1hWvDQpMFmqlvf0Xc3aHIY,18
47
+ deepforge/samples/yolo/labels/val/sample.txt,sha256=1DTISNVHuDbtdOL60VNSkeXz7HycsBjI67z_DRA7MLE,18
48
+ deepforge_research_toolkit-0.7.1.dist-info/licenses/LICENSE,sha256=jqrDBedF91mUQKvxlhh0UozvHRyZiLjXNQonTjGFLgo,1079
49
+ deepforge_research_toolkit-0.7.1.dist-info/METADATA,sha256=e8O9JyHpU_8bM8_4O9SYY2PXgc6-_Zqcs4Tktg2quEU,31225
50
+ deepforge_research_toolkit-0.7.1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
51
+ deepforge_research_toolkit-0.7.1.dist-info/entry_points.txt,sha256=t1ysaKMB1-TTwJ47G_gd62jlyxaz1OsAr_gXnkXFM4Q,129
52
+ deepforge_research_toolkit-0.7.1.dist-info/top_level.txt,sha256=C7lSVksFRbex9dKClrElzX2S5okzLSAlRtB5f4hM79I,10
53
+ deepforge_research_toolkit-0.7.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,4 @@
1
+ [console_scripts]
2
+ deepforge = deepforge.cli:main
3
+ deepforge-live = deepforge.live_view:main
4
+ deepforge-studio = deepforge.gui:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 DeepForge contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ deepforge