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.
- deepforge/__init__.py +3 -0
- deepforge/__main__.py +3 -0
- deepforge/advanced.py +117 -0
- deepforge/assets/icon.png +0 -0
- deepforge/assets/xvarna.png +0 -0
- deepforge/assets/xvarna_about.png +0 -0
- deepforge/assets/xvarna_sidebar.png +0 -0
- deepforge/audit.py +192 -0
- deepforge/automation.py +143 -0
- deepforge/checkpoint.py +155 -0
- deepforge/checkpoint_config.py +20 -0
- deepforge/checkpoint_torch.py +62 -0
- deepforge/checkpoint_yolo.py +18 -0
- deepforge/cli.py +119 -0
- deepforge/datasets.py +61 -0
- deepforge/diagnostics.py +67 -0
- deepforge/environment.py +26 -0
- deepforge/gui.py +579 -0
- deepforge/gui_data.py +119 -0
- deepforge/history.py +41 -0
- deepforge/live_view.py +100 -0
- deepforge/metrics.py +40 -0
- deepforge/models.py +19 -0
- deepforge/monitor.py +152 -0
- deepforge/notebook.py +73 -0
- deepforge/preview.py +20 -0
- deepforge/profiler.py +283 -0
- deepforge/reporting.py +118 -0
- deepforge/resources.py +24 -0
- deepforge/samples/dataset/test/square/sample_d.png +0 -0
- deepforge/samples/dataset/train/circle/sample_a.png +0 -0
- deepforge/samples/dataset/train/square/sample_b.png +0 -0
- deepforge/samples/dataset/val/circle/sample_c.png +0 -0
- deepforge/samples/groups.csv +6 -0
- deepforge/samples/history.csv +5 -0
- deepforge/samples/predictions.csv +5 -0
- deepforge/samples/runs/baseline.csv +5 -0
- deepforge/samples/runs/refined.csv +5 -0
- deepforge/samples/scores.csv +9 -0
- deepforge/samples/yolo/images/test/sample.png +0 -0
- deepforge/samples/yolo/images/train/sample.png +0 -0
- deepforge/samples/yolo/images/val/sample.png +0 -0
- deepforge/samples/yolo/labels/test/sample.txt +1 -0
- deepforge/samples/yolo/labels/train/sample.txt +1 -0
- deepforge/samples/yolo/labels/val/sample.txt +1 -0
- deepforge/training.py +118 -0
- deepforge/ultralytics.py +58 -0
- deepforge_research_toolkit-0.7.1.dist-info/METADATA +462 -0
- deepforge_research_toolkit-0.7.1.dist-info/RECORD +53 -0
- deepforge_research_toolkit-0.7.1.dist-info/WHEEL +5 -0
- deepforge_research_toolkit-0.7.1.dist-info/entry_points.txt +4 -0
- deepforge_research_toolkit-0.7.1.dist-info/licenses/LICENSE +21 -0
- deepforge_research_toolkit-0.7.1.dist-info/top_level.txt +1 -0
deepforge/profiler.py
ADDED
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
"""Explicit forward-pass profiling of trusted, already constructed PyTorch models.
|
|
2
|
+
|
|
3
|
+
MAC estimates cover executed standard Linear and Conv1d/2d/3d leaves only.
|
|
4
|
+
No checkpoint loading, source evaluation, or external profiling dependency.
|
|
5
|
+
"""
|
|
6
|
+
import math
|
|
7
|
+
import statistics
|
|
8
|
+
import time
|
|
9
|
+
from collections import Counter
|
|
10
|
+
from .models import inspect_model
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _torch():
|
|
14
|
+
try:
|
|
15
|
+
import torch
|
|
16
|
+
except ImportError as exc:
|
|
17
|
+
raise ValueError("Install the optional torch dependency to profile a model") from exc
|
|
18
|
+
return torch
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _tensors(value, torch):
|
|
22
|
+
if isinstance(value, torch.Tensor):
|
|
23
|
+
yield value
|
|
24
|
+
elif isinstance(value, (tuple, list)):
|
|
25
|
+
for item in value:
|
|
26
|
+
yield from _tensors(item, torch)
|
|
27
|
+
elif isinstance(value, dict):
|
|
28
|
+
for item in value.values():
|
|
29
|
+
yield from _tensors(item, torch)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _spec(value, torch):
|
|
33
|
+
"""Describe tensor metadata only, without serializing input/output values."""
|
|
34
|
+
return [{"shape": list(t.shape), "dtype": str(t.dtype),
|
|
35
|
+
"device": str(t.device), "bytes": t.numel()*t.element_size()}
|
|
36
|
+
for t in _tensors(value, torch)]
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _direct_parameters(module):
|
|
40
|
+
return sum(p.numel() for p in module.parameters(recurse=False))
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _macs(module, output, torch):
|
|
44
|
+
if not isinstance(output, torch.Tensor):
|
|
45
|
+
return None
|
|
46
|
+
if type(module) is torch.nn.Linear:
|
|
47
|
+
return output.numel()*module.in_features
|
|
48
|
+
if type(module) in (torch.nn.Conv1d, torch.nn.Conv2d, torch.nn.Conv3d):
|
|
49
|
+
return output.numel()*(module.in_channels//module.groups)*math.prod(module.kernel_size)
|
|
50
|
+
return None
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def profile_model(model, *args, kwargs=None, warmup=2, repeats=5, max_rows=10000):
|
|
54
|
+
"""Profile an explicit example forward, then time complete uninstrumented forwards.
|
|
55
|
+
|
|
56
|
+
The model is temporarily put in evaluation/inference mode; registered hooks
|
|
57
|
+
are removed and each original training flag restored even on failure.
|
|
58
|
+
Arbitrary custom forwards may have side effects; use trusted code only.
|
|
59
|
+
Measured latency is for the entire input batch. Only CPU and CUDA timing
|
|
60
|
+
are supported; synchronization is included. Set repeats=0 to omit timing.
|
|
61
|
+
"""
|
|
62
|
+
torch = _torch()
|
|
63
|
+
if type(warmup) is not int or not 0 <= warmup <= 1000:
|
|
64
|
+
raise ValueError("warmup must be an integer in [0, 1000]")
|
|
65
|
+
if type(repeats) is not int or not 0 <= repeats <= 1000:
|
|
66
|
+
raise ValueError("repeats must be an integer in [0, 1000]")
|
|
67
|
+
if type(max_rows) is not int or not 1 <= max_rows <= 100000:
|
|
68
|
+
raise ValueError("max_rows must be an integer in [1, 100000]")
|
|
69
|
+
kwargs = dict(kwargs or {})
|
|
70
|
+
if not isinstance(model, torch.nn.Module):
|
|
71
|
+
raise TypeError("model must be a torch.nn.Module")
|
|
72
|
+
registered = list(model.named_modules())
|
|
73
|
+
leaves = [(name, module) for name, module in registered if not list(module.children())]
|
|
74
|
+
flags = [(module, module.training) for _, module in registered]
|
|
75
|
+
inventory = inspect_model(model)
|
|
76
|
+
modules = [{"name": name or "<root>", "type": type(module).__name__,
|
|
77
|
+
"direct_parameters": _direct_parameters(module),
|
|
78
|
+
"leaf": not list(module.children())}
|
|
79
|
+
for name, module in registered]
|
|
80
|
+
tensors = list(model.parameters()) + list(model.buffers()) + list(_tensors((args, kwargs), torch))
|
|
81
|
+
devices = {t.device for t in tensors}
|
|
82
|
+
cuda_devices = sorted((d for d in devices if d.type == "cuda"), key=str)
|
|
83
|
+
if repeats and any(d.type not in ("cpu", "cuda") for d in devices):
|
|
84
|
+
raise ValueError("Latency measurement supports CPU and CUDA only")
|
|
85
|
+
|
|
86
|
+
def sync():
|
|
87
|
+
for device in cuda_devices:
|
|
88
|
+
torch.cuda.synchronize(device)
|
|
89
|
+
|
|
90
|
+
def memory():
|
|
91
|
+
return [{"device": str(d),
|
|
92
|
+
"allocated_bytes": torch.cuda.memory_allocated(d),
|
|
93
|
+
"reserved_bytes": torch.cuda.memory_reserved(d)}
|
|
94
|
+
for d in cuda_devices]
|
|
95
|
+
|
|
96
|
+
calls, unsupported = [], Counter()
|
|
97
|
+
handles = []
|
|
98
|
+
total_macs = total_bytes = count = counted = 0
|
|
99
|
+
|
|
100
|
+
def hook(name):
|
|
101
|
+
def observe(module, inputs, kw, output):
|
|
102
|
+
nonlocal total_macs, total_bytes, count, counted
|
|
103
|
+
count += 1
|
|
104
|
+
out = _spec(output, torch)
|
|
105
|
+
size = sum(t["bytes"] for t in out)
|
|
106
|
+
macs = _macs(module, output, torch)
|
|
107
|
+
total_bytes += size
|
|
108
|
+
if macs is None:
|
|
109
|
+
unsupported[type(module).__name__] += 1
|
|
110
|
+
else:
|
|
111
|
+
total_macs += macs
|
|
112
|
+
counted += 1
|
|
113
|
+
if len(calls) < max_rows:
|
|
114
|
+
calls.append({"call": count, "name": name or "<root>",
|
|
115
|
+
"type": type(module).__name__,
|
|
116
|
+
"inputs": _spec((inputs, kw), torch),
|
|
117
|
+
"outputs": out, "output_logical_bytes": size,
|
|
118
|
+
"estimated_macs": macs,
|
|
119
|
+
"estimated_flops_2x_macs": None if macs is None else 2*macs})
|
|
120
|
+
return observe
|
|
121
|
+
|
|
122
|
+
before = memory()
|
|
123
|
+
timings = []
|
|
124
|
+
try:
|
|
125
|
+
model.eval()
|
|
126
|
+
with torch.inference_mode():
|
|
127
|
+
for name, module in leaves:
|
|
128
|
+
handles.append(module.register_forward_hook(hook(name), with_kwargs=True))
|
|
129
|
+
try:
|
|
130
|
+
output = model(*args, **kwargs)
|
|
131
|
+
output_spec = _spec(output, torch)
|
|
132
|
+
del output
|
|
133
|
+
finally:
|
|
134
|
+
for handle in handles:
|
|
135
|
+
handle.remove()
|
|
136
|
+
handles.clear()
|
|
137
|
+
if repeats:
|
|
138
|
+
for _ in range(warmup):
|
|
139
|
+
model(*args, **kwargs)
|
|
140
|
+
sync()
|
|
141
|
+
for _ in range(repeats):
|
|
142
|
+
sync()
|
|
143
|
+
start = time.perf_counter()
|
|
144
|
+
model(*args, **kwargs)
|
|
145
|
+
sync()
|
|
146
|
+
timings.append((time.perf_counter()-start)*1000)
|
|
147
|
+
after = memory()
|
|
148
|
+
finally:
|
|
149
|
+
for handle in handles:
|
|
150
|
+
handle.remove()
|
|
151
|
+
for module, flag in flags:
|
|
152
|
+
module.training = flag
|
|
153
|
+
|
|
154
|
+
timing = None
|
|
155
|
+
if timings:
|
|
156
|
+
ordered = sorted(timings)
|
|
157
|
+
timing = {"repeats": repeats, "warmup": warmup,
|
|
158
|
+
"min_ms": ordered[0], "median_ms": statistics.median(ordered),
|
|
159
|
+
"mean_ms": statistics.mean(ordered),
|
|
160
|
+
"p95_ms": ordered[math.ceil(.95*len(ordered))-1]}
|
|
161
|
+
return {**inventory, "registered_modules": len(registered),
|
|
162
|
+
"registered_leaf_modules": len(leaves), "executed_leaf_calls": count,
|
|
163
|
+
"estimated_leaf_calls": counted, "modules": modules, "calls": calls,
|
|
164
|
+
"calls_truncated": count > len(calls),
|
|
165
|
+
"estimated_macs": total_macs, "estimated_flops_2x_macs": 2*total_macs,
|
|
166
|
+
"unestimated_leaf_types": dict(unsupported),
|
|
167
|
+
"input_tensors": _spec((args, kwargs), torch), "output_tensors": output_spec,
|
|
168
|
+
"leaf_output_logical_bytes_sum": total_bytes,
|
|
169
|
+
"devices": sorted(str(d) for d in devices),
|
|
170
|
+
"latency": timing, "cuda_allocator_before": before,
|
|
171
|
+
"cuda_allocator_after": after,
|
|
172
|
+
"limitations": [
|
|
173
|
+
"MACs count standard Linear and Conv1d/2d/3d leaf calls only; FLOPs = 2*MACs, excluding bias, activation, normalization, pooling, attention and functional operations.",
|
|
174
|
+
"Counts are partial, not total network FLOPs; one execution path and one input batch only. Registered modules and executed calls are different counts.",
|
|
175
|
+
"Logical tensor bytes can count shared storage and views multiple times; not peak activation or training memory.",
|
|
176
|
+
"CUDA allocator observations are process-wide, not model-specific or peak GPU memory; timing depends on device load and synchronization.",
|
|
177
|
+
"Trusted forwards can mutate custom state or consume RNG even in eval/inference mode. Avoid concurrent training and profiling of the same model."
|
|
178
|
+
]}
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def profile_mlp(inputs, hidden, outputs, *, batch=1, warmup=2, repeats=5):
|
|
182
|
+
"""Bounded built-in CPU example for CLI and desktop usage."""
|
|
183
|
+
sizes = (inputs, hidden, outputs)
|
|
184
|
+
if any(type(n) is not int or not 1 <= n <= 4096 for n in sizes):
|
|
185
|
+
raise ValueError("Layer widths must be integers between 1 and 4096")
|
|
186
|
+
if inputs*hidden + hidden*outputs > 10_000_000:
|
|
187
|
+
raise ValueError("The example is limited to 10 million weights")
|
|
188
|
+
if type(batch) is not int or not 1 <= batch <= 256:
|
|
189
|
+
raise ValueError("batch must be an integer between 1 and 256")
|
|
190
|
+
torch = _torch()
|
|
191
|
+
model = torch.nn.Sequential(torch.nn.Linear(inputs, hidden),
|
|
192
|
+
torch.nn.ReLU(), torch.nn.Linear(hidden, outputs))
|
|
193
|
+
report = profile_model(model, torch.zeros(batch, inputs), warmup=warmup, repeats=repeats)
|
|
194
|
+
report["architecture"] = list(sizes)
|
|
195
|
+
return report
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def profile_operators(model, *args, kwargs=None, max_rows=200):
|
|
199
|
+
"""Profile a single trusted forward with PyTorch's operator FLOP estimates.
|
|
200
|
+
|
|
201
|
+
CPU activity records dispatch events even for CUDA tensors. The native
|
|
202
|
+
estimator only supports selected operators (e.g. matrix multiplication
|
|
203
|
+
and 2-D convolutions); zero or missing estimates do not imply zero cost.
|
|
204
|
+
Never add these estimates to the separate module-hook MAC/FLOP totals.
|
|
205
|
+
"""
|
|
206
|
+
torch = _torch()
|
|
207
|
+
if not isinstance(model, torch.nn.Module):
|
|
208
|
+
raise TypeError("model must be a torch.nn.Module")
|
|
209
|
+
if type(max_rows) is not int or not 1 <= max_rows <= 10000:
|
|
210
|
+
raise ValueError("max_rows must be between 1 and 10000")
|
|
211
|
+
kwargs = dict(kwargs or {})
|
|
212
|
+
flags = [(module, module.training) for module in model.modules()]
|
|
213
|
+
devices = {t.device for t in list(model.parameters()) + list(model.buffers()) +
|
|
214
|
+
list(_tensors((args, kwargs), torch))}
|
|
215
|
+
try:
|
|
216
|
+
model.eval()
|
|
217
|
+
with torch.inference_mode():
|
|
218
|
+
with torch.profiler.profile(activities=[torch.profiler.ProfilerActivity.CPU],
|
|
219
|
+
record_shapes=True, with_flops=True) as trace:
|
|
220
|
+
model(*args, **kwargs)
|
|
221
|
+
for device in devices:
|
|
222
|
+
if device.type == "cuda":
|
|
223
|
+
torch.cuda.synchronize(device)
|
|
224
|
+
rows = [{"operator": event.key, "calls": int(event.count),
|
|
225
|
+
"estimated_flops": int(event.flops or 0),
|
|
226
|
+
"self_cpu_us": float(event.self_cpu_time_total)}
|
|
227
|
+
for event in trace.key_averages()]
|
|
228
|
+
rows.sort(key=lambda row: (-row["estimated_flops"], -row["calls"], row["operator"]))
|
|
229
|
+
return {"method": "torch.profiler.with_flops", "estimated_flops": sum(r["estimated_flops"] for r in rows),
|
|
230
|
+
"operators_with_positive_estimate": sum(r["estimated_flops"] > 0 for r in rows),
|
|
231
|
+
"operators_without_positive_estimate": sum(r["estimated_flops"] == 0 for r in rows),
|
|
232
|
+
"operator_types": len(rows), "operators": rows[:max_rows],
|
|
233
|
+
"rows_truncated": len(rows) > max_rows,
|
|
234
|
+
"limitations": ["Partial native operator estimates; zero may mean unestimated.",
|
|
235
|
+
"Do not add to module-hook FLOPs; overlap is possible.",
|
|
236
|
+
"CPU dispatch time includes instrumentation effects; not GPU latency.",
|
|
237
|
+
"Trusted custom forwards can mutate state."]}
|
|
238
|
+
finally:
|
|
239
|
+
for module, flag in flags:
|
|
240
|
+
module.training = flag
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def profile_cuda_peak(model, *args, kwargs=None):
|
|
244
|
+
"""Measure process-wide CUDA allocator peaks over one explicit forward.
|
|
245
|
+
|
|
246
|
+
This opt-in function resets per-device allocator peak counters and cannot
|
|
247
|
+
restore previous peaks. Do not run during training or concurrent CUDA work.
|
|
248
|
+
"""
|
|
249
|
+
torch = _torch()
|
|
250
|
+
if not isinstance(model, torch.nn.Module):
|
|
251
|
+
raise TypeError("model must be a torch.nn.Module")
|
|
252
|
+
kwargs = dict(kwargs or {})
|
|
253
|
+
devices = sorted({t.device for t in list(model.parameters()) + list(model.buffers()) +
|
|
254
|
+
list(_tensors((args, kwargs), torch)) if t.device.type == "cuda"}, key=str)
|
|
255
|
+
if not devices:
|
|
256
|
+
raise ValueError("A CUDA model or CUDA input is required")
|
|
257
|
+
flags = [(module, module.training) for module in model.modules()]
|
|
258
|
+
try:
|
|
259
|
+
model.eval()
|
|
260
|
+
with torch.inference_mode():
|
|
261
|
+
for device in devices:
|
|
262
|
+
torch.cuda.synchronize(device)
|
|
263
|
+
before = {d: (torch.cuda.memory_allocated(d), torch.cuda.memory_reserved(d)) for d in devices}
|
|
264
|
+
for device in devices:
|
|
265
|
+
torch.cuda.reset_peak_memory_stats(device)
|
|
266
|
+
output = model(*args, **kwargs)
|
|
267
|
+
for device in devices:
|
|
268
|
+
torch.cuda.synchronize(device)
|
|
269
|
+
rows = []
|
|
270
|
+
for device in devices:
|
|
271
|
+
allocated, reserved = before[device]
|
|
272
|
+
peak = torch.cuda.max_memory_allocated(device)
|
|
273
|
+
peak_reserved = torch.cuda.max_memory_reserved(device)
|
|
274
|
+
rows.append({"device": str(device), "baseline_allocated_bytes": allocated,
|
|
275
|
+
"baseline_reserved_bytes": reserved, "peak_allocated_bytes": peak,
|
|
276
|
+
"peak_reserved_bytes": peak_reserved,
|
|
277
|
+
"peak_above_baseline_bytes": max(0, peak-allocated)})
|
|
278
|
+
del output
|
|
279
|
+
return {"devices": rows, "scope": "process-wide CUDA allocator, single forward",
|
|
280
|
+
"peak_counters_reset": True}
|
|
281
|
+
finally:
|
|
282
|
+
for module, flag in flags:
|
|
283
|
+
module.training = flag
|
deepforge/reporting.py
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
"""Portable offline report export, with escaped data and explicit provenance."""
|
|
2
|
+
import html
|
|
3
|
+
import json
|
|
4
|
+
from datetime import datetime, timezone
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from . import __version__
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def _e(value):
|
|
10
|
+
return html.escape(str(value), quote=True)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def table_rows(report):
|
|
14
|
+
"""Flatten primary values for a concise preview; raw JSON remains authoritative."""
|
|
15
|
+
rows = []
|
|
16
|
+
def walk(prefix, value, depth=0):
|
|
17
|
+
if isinstance(value, dict) and depth < 3:
|
|
18
|
+
for k, v in value.items():
|
|
19
|
+
walk(f'{prefix} / {k}' if prefix else k, v, depth+1)
|
|
20
|
+
elif isinstance(value, (list, dict)):
|
|
21
|
+
rows.append((prefix, f'{len(value):,} entries (see JSON)'))
|
|
22
|
+
elif isinstance(value, float):
|
|
23
|
+
rows.append((prefix, f'{value:.7g}'))
|
|
24
|
+
else:
|
|
25
|
+
rows.append((prefix, str(value)))
|
|
26
|
+
walk('', report)
|
|
27
|
+
return rows
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def finding_rows(report, limit=200):
|
|
31
|
+
"""Show concrete audit findings before summary fields, with a documented cap."""
|
|
32
|
+
rows = []
|
|
33
|
+
fields = ('duplicates', 'candidate_pairs', 'errors', 'overlaps', 'missing_labels',
|
|
34
|
+
'orphan_labels', 'ambiguous_image_stems', 'issues', 'ranking', 'rejected', 'calls', 'operators')
|
|
35
|
+
for key in fields:
|
|
36
|
+
value = report.get(key)
|
|
37
|
+
if not isinstance(value, list):
|
|
38
|
+
continue
|
|
39
|
+
for i, item in enumerate(value, 1):
|
|
40
|
+
if len(rows) == limit:
|
|
41
|
+
rows.append(('Additional findings', 'Preview limited; inspect the complete JSON report.'))
|
|
42
|
+
return rows
|
|
43
|
+
if key == 'ranking':
|
|
44
|
+
display = f"{item['run']} | best {item['best_value']:.6g} at epoch {item['best_epoch']:g}"
|
|
45
|
+
elif key == 'calls':
|
|
46
|
+
ins = ", ".join(str(t["shape"]) for t in item["inputs"])
|
|
47
|
+
outs = ", ".join(str(t["shape"]) for t in item["outputs"])
|
|
48
|
+
display = f"{item['name']} | {item['type']} | {ins} -> {outs} | MACs: {item['estimated_macs']}"
|
|
49
|
+
elif isinstance(item, dict):
|
|
50
|
+
display = json.dumps(item, ensure_ascii=False, allow_nan=False)
|
|
51
|
+
else:
|
|
52
|
+
display = str(item)
|
|
53
|
+
rows.append((f"{key.replace('_', ' ').title()} / {i}", display))
|
|
54
|
+
return rows
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def chart_svg(chart):
|
|
58
|
+
"""Create a static, self-contained SVG chart for reports, without external assets."""
|
|
59
|
+
if not chart:
|
|
60
|
+
return ''
|
|
61
|
+
w,h=820,350
|
|
62
|
+
x0,y0,x1,y1=110,32,770,295
|
|
63
|
+
colors=('#12664f','#8a651e','#476f9a','#a3353d')
|
|
64
|
+
parts=[f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {w} {h}" role="img" aria-label="Analysis chart" style="width:100%;height:auto;background:white;border-radius:8px">']
|
|
65
|
+
def line(x,y,xx,yy,stroke='#d8e0e7',width=1,dash=''):
|
|
66
|
+
parts.append(f'<line x1="{x:.2f}" y1="{y:.2f}" x2="{xx:.2f}" y2="{yy:.2f}" stroke="{stroke}" stroke-width="{width}"{dash}/>')
|
|
67
|
+
def text(x,y,value,anchor='middle',size=12,color='#394c63'):
|
|
68
|
+
parts.append(f'<text x="{x:.2f}" y="{y:.2f}" text-anchor="{anchor}" font-family="system-ui,sans-serif" font-size="{size}" fill="{color}">{_e(value)}</text>')
|
|
69
|
+
kind=chart.get('type')
|
|
70
|
+
if kind=='bars':
|
|
71
|
+
values=chart['values'][:12]; lo=min([0]+[v for _,v in values]); hi=max([0]+[v for _,v in values]); span=hi-lo or 1
|
|
72
|
+
x0=180; zero=x0+(0-lo)/span*(x1-x0); step=(y1-y0)/max(1,len(values))
|
|
73
|
+
for i in range(5):
|
|
74
|
+
x=x0+(x1-x0)*i/4;line(x,y0,x,y1);text(x,y1+22,f'{lo+span*i/4:.3g}')
|
|
75
|
+
for i,(label,value) in enumerate(values):
|
|
76
|
+
yy=y0+(i+.5)*step;xx=x0+(value-lo)/span*(x1-x0);text(x0-8,yy+4,str(label)[:25],'end');parts.append(f'<rect x="{min(zero,xx):.2f}" y="{yy-min(12,step*.3):.2f}" width="{abs(xx-zero):.2f}" height="{min(24,step*.6):.2f}" rx="2" fill="{colors[i%4]}"/>');text(xx+5 if value>=0 else xx-5,yy+4,f'{value:.4g}','start' if value>=0 else 'end')
|
|
77
|
+
elif kind in ('lines','roc','probability'):
|
|
78
|
+
xs=chart['x']; series=chart['series'] if kind=='lines' else {chart.get('title','ROC'):chart['y']}; ys=[v for vs in series.values() for v in vs]
|
|
79
|
+
lo,hi=(0,1) if kind in ('roc','probability') else (min(ys),max(ys)); xmin,xmax=(0,1) if kind in ('roc','probability') else (xs[0],xs[-1]); span=hi-lo or 1; dx=xmax-xmin or 1
|
|
80
|
+
for i in range(5):
|
|
81
|
+
y=y1-(y1-y0)*i/4;line(x0,y,x1,y);text(x0-9,y+4,f'{lo+span*i/4:.3g}','end');x=x0+(x1-x0)*i/4;text(x,y1+20,f'{xmin+dx*i/4:.3g}')
|
|
82
|
+
if kind=='roc' or (kind=='probability' and chart.get('baseline') is None): line(x0,y1,x1,y0,'#98a6b6',1,' stroke-dasharray="5 5"')
|
|
83
|
+
elif kind=='probability':
|
|
84
|
+
yy=y1-chart['baseline']*(y1-y0);line(x0,yy,x1,yy,'#98a6b6',1,' stroke-dasharray="5 5"')
|
|
85
|
+
for i,(label,vs) in enumerate(series.items()):
|
|
86
|
+
points=' '.join(f'{x0+(x-xmin)/dx*(x1-x0):.2f},{y1-(v-lo)/span*(y1-y0):.2f}' for x,v in zip(xs,vs));parts.append(f'<polyline points="{points}" fill="none" stroke="{colors[i%4]}" stroke-width="2.7"/>');text(x0+i*160,19,label,'start',color=colors[i%4])
|
|
87
|
+
text((x0+x1)/2,335,'Epoch' if kind=='lines' else chart.get('xlabel','False positive rate'))
|
|
88
|
+
elif kind=='matrix':
|
|
89
|
+
labels=chart['labels'];matrix=chart['values'];n=len(labels)
|
|
90
|
+
if n>20 or n==0:return ''
|
|
91
|
+
cell=min(240/n,440/n);start=(w-n*cell)/2;top=60;maxv=max(max(r) for r in matrix) or 1
|
|
92
|
+
text(w/2,16,'Confusion matrix · rows = true · columns = predicted')
|
|
93
|
+
for i,label in enumerate(labels):
|
|
94
|
+
text(start-8,top+(i+.5)*cell+4,str(label)[:15],'end',10);text(start+(i+.5)*cell,top-10,str(label)[:15],size=10)
|
|
95
|
+
for j,value in enumerate(matrix[i]):
|
|
96
|
+
t=value/maxv;x=start+j*cell;y=top+i*cell;fill=f'#{int(232-170*t):02x}{int(241-100*t):02x}{int(243-95*t):02x}'
|
|
97
|
+
parts.append(f'<rect x="{x:.2f}" y="{y:.2f}" width="{cell:.2f}" height="{cell:.2f}" fill="{fill}" stroke="white"/>')
|
|
98
|
+
if cell>=19:text(x+cell/2,y+cell/2+4,value,color='white' if t>.65 else '#183c33')
|
|
99
|
+
else:return ''
|
|
100
|
+
parts.append('</svg>')
|
|
101
|
+
return ''.join(parts)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def export_report(path, tool, report, *, cards=(), fmt=None, chart=None):
|
|
105
|
+
path = Path(path)
|
|
106
|
+
fmt = fmt or path.suffix.lower().lstrip('.')
|
|
107
|
+
if fmt == 'json':
|
|
108
|
+
path.write_text(json.dumps(report, indent=2, ensure_ascii=False, allow_nan=False)+'\n', encoding='utf-8')
|
|
109
|
+
return
|
|
110
|
+
if fmt != 'html':
|
|
111
|
+
raise ValueError('Use JSON or HTML export')
|
|
112
|
+
raw = json.dumps(report, indent=2, ensure_ascii=False, allow_nan=False)
|
|
113
|
+
top = ''.join(f'<article><small>{_e(k)}</small><strong>{_e(v)}</strong></article>' for k,v in cards)
|
|
114
|
+
rows = ''.join(f'<tr><th scope="row">{_e(k)}</th><td>{_e(v)}</td></tr>' for k,v in finding_rows(report)+table_rows(report))
|
|
115
|
+
doc = f'''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>DeepForge | {_e(tool)}</title>
|
|
116
|
+
<style>body{{font:16px system-ui,sans-serif;background:#f3efe5;color:#183c33;margin:0}}main{{max-width:1050px;margin:0 auto;padding:44px 24px}}header{{border-bottom:2px solid #8a651e;padding-bottom:20px}}small{{color:#536b60}}h1{{font-size:36px;margin:8px 0}}section{{display:flex;flex-wrap:wrap;gap:12px;margin:24px 0}}article{{background:white;border:1px solid #dddcd0;border-radius:10px;padding:18px;flex:1;min-width:160px}}article strong{{display:block;font-size:24px;margin-top:8px;color:#12664f}}table{{border-collapse:collapse;width:100%;background:white}}th,td{{text-align:left;padding:10px 14px;border-bottom:1px solid #e2e7ea;overflow-wrap:anywhere}}th{{width:45%;font-weight:500}}pre{{background:#123b32;color:#f5f0e9;padding:20px;overflow:auto;border-radius:8px}}@media print{{body{{background:white}}main{{padding:0}}pre{{white-space:pre-wrap;color:#111;background:white}}}}</style>
|
|
117
|
+
<main><header><small>DEEPFORGE STUDIO · XVARNA · v{_e(__version__)} · LOCAL ANALYSIS</small><h1>{_e(tool)}</h1><small>Exported {_e(datetime.now(timezone.utc).isoformat())} · Review findings and sensitive paths before sharing.</small></header><section>{top}</section>{('<h2>Visualization</h2>'+chart_svg(chart)) if chart else ''}<h2>Results overview</h2><table>{rows}</table><h2>Complete report</h2><pre>{_e(raw)}</pre><footer><small>DeepForge Studio · Created by Alireza Khatibi · XVARNA</small></footer></main></html>'''
|
|
118
|
+
path.write_text(doc, encoding='utf-8')
|
deepforge/resources.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""Optional resource sampling; no network calls or external processes."""
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
def sample_resources():
|
|
5
|
+
result = {}
|
|
6
|
+
try:
|
|
7
|
+
import psutil
|
|
8
|
+
except ImportError:
|
|
9
|
+
pass
|
|
10
|
+
else:
|
|
11
|
+
result["cpu_percent"] = psutil.cpu_percent(interval=None)
|
|
12
|
+
result["ram_percent"] = psutil.virtual_memory().percent
|
|
13
|
+
result["process_rss_bytes"] = psutil.Process().memory_info().rss
|
|
14
|
+
try:
|
|
15
|
+
import torch
|
|
16
|
+
except ImportError:
|
|
17
|
+
pass
|
|
18
|
+
else:
|
|
19
|
+
if torch.cuda.is_initialized():
|
|
20
|
+
device = torch.cuda.current_device()
|
|
21
|
+
result["cuda_device"] = device
|
|
22
|
+
result["cuda_allocated_bytes"] = torch.cuda.memory_allocated(device)
|
|
23
|
+
result["cuda_reserved_bytes"] = torch.cuda.memory_reserved(device)
|
|
24
|
+
return result
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
0 0.5 0.5 0.5 0.5
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
0 0.5 0.5 0.5 0.5
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
0 0.1 0.1 0.5 0.5
|
deepforge/training.py
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
"""Opt-in PyTorch training health checks; never modify model or optimizer state."""
|
|
2
|
+
import math
|
|
3
|
+
from .automation import Check, AuditFailed, run_checks
|
|
4
|
+
from .models import inspect_model
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def _torch():
|
|
8
|
+
try:
|
|
9
|
+
import torch
|
|
10
|
+
except ImportError as exc:
|
|
11
|
+
raise RuntimeError("Install the optional torch dependency") from exc
|
|
12
|
+
return torch
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _positive_limit(value, name):
|
|
16
|
+
if value is not None and (not math.isfinite(value) or value <= 0):
|
|
17
|
+
raise ValueError(f"{name} must be finite and positive")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def model_check(model, *, max_parameters=None):
|
|
21
|
+
"""Check initialized model size using the existing model inspector."""
|
|
22
|
+
if max_parameters is not None and (type(max_parameters) is not int or max_parameters < 1):
|
|
23
|
+
raise ValueError("max_parameters must be a positive integer")
|
|
24
|
+
rules = [("parameters", "gt", 0)]
|
|
25
|
+
if max_parameters is not None:
|
|
26
|
+
rules.append(("parameters", "le", max_parameters))
|
|
27
|
+
return Check("model", lambda: inspect_model(model), tuple(rules))
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def loss_check(loss):
|
|
31
|
+
"""Check a scalar loss without retaining its computation graph."""
|
|
32
|
+
def run():
|
|
33
|
+
value = float(loss.detach().item() if hasattr(loss, "detach") else loss)
|
|
34
|
+
return {"finite": math.isfinite(value),
|
|
35
|
+
"loss": value if math.isfinite(value) else None}
|
|
36
|
+
return Check("loss", run, (("finite", "eq", True),))
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def gradient_report(model):
|
|
40
|
+
"""Inspect registered trainable gradients after backward and AMP unscale.
|
|
41
|
+
|
|
42
|
+
Sparse COO gradients are coalesced without modifying the original.
|
|
43
|
+
Other sparse layouts are explicitly unsupported. Norms are global L2
|
|
44
|
+
norms; missing gradients are reported, not assumed to be errors.
|
|
45
|
+
"""
|
|
46
|
+
torch = _torch()
|
|
47
|
+
missing, nonfinite, unsupported = [], [], []
|
|
48
|
+
present = 0
|
|
49
|
+
norm = 0.0
|
|
50
|
+
with torch.no_grad():
|
|
51
|
+
for name, parameter in model.named_parameters():
|
|
52
|
+
if not parameter.requires_grad:
|
|
53
|
+
continue
|
|
54
|
+
grad = parameter.grad
|
|
55
|
+
if grad is None:
|
|
56
|
+
missing.append(name)
|
|
57
|
+
continue
|
|
58
|
+
present += 1
|
|
59
|
+
grad = grad.detach()
|
|
60
|
+
if grad.layout == torch.sparse_coo:
|
|
61
|
+
grad = grad.coalesce().values()
|
|
62
|
+
elif grad.layout != torch.strided:
|
|
63
|
+
unsupported.append(name)
|
|
64
|
+
continue
|
|
65
|
+
if not bool(torch.isfinite(grad).all().item()):
|
|
66
|
+
nonfinite.append(name)
|
|
67
|
+
continue
|
|
68
|
+
dtype = torch.complex128 if grad.is_complex() else torch.float64
|
|
69
|
+
value = float(torch.linalg.vector_norm(grad.to(dtype=dtype)).item())
|
|
70
|
+
norm = math.hypot(norm, value)
|
|
71
|
+
valid = not nonfinite and not unsupported and math.isfinite(norm)
|
|
72
|
+
return {"present": present, "missing": missing, "nonfinite": nonfinite,
|
|
73
|
+
"unsupported": unsupported, "finite": valid,
|
|
74
|
+
"global_l2": norm if valid else None}
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def gradient_check(model, *, max_norm=None, require_all=False):
|
|
78
|
+
_positive_limit(max_norm, "max_norm")
|
|
79
|
+
rules = [("finite", "eq", True), ("present", "gt", 0)]
|
|
80
|
+
if require_all:
|
|
81
|
+
rules.append(("missing", "eq", []))
|
|
82
|
+
if max_norm is not None:
|
|
83
|
+
rules.append(("global_l2", "le", max_norm))
|
|
84
|
+
def run():
|
|
85
|
+
report = gradient_report(model)
|
|
86
|
+
# Keep nonfinite reports serializable and allow rules to fail normally.
|
|
87
|
+
report["within_norm_limit"] = (report["global_l2"] is not None and
|
|
88
|
+
(max_norm is None or report["global_l2"] <= max_norm))
|
|
89
|
+
return report
|
|
90
|
+
if max_norm is not None:
|
|
91
|
+
rules[-1] = ("within_norm_limit", "eq", True)
|
|
92
|
+
return Check("gradients", run, tuple(rules))
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
class TrainingGuard:
|
|
96
|
+
"""Explicit pre-step guard. Call after backward, before optimizer.step.
|
|
97
|
+
|
|
98
|
+
No hooks, background workers, optimizer changes, or automatic clipping.
|
|
99
|
+
Checks synchronize devices and can slow training. With AMP call after
|
|
100
|
+
scaler.unscale_(optimizer); with accumulation call at update boundaries.
|
|
101
|
+
"""
|
|
102
|
+
def __init__(self, model, *, max_gradient_norm=None, require_all_gradients=False):
|
|
103
|
+
_positive_limit(max_gradient_norm, "max_gradient_norm")
|
|
104
|
+
self.model = model
|
|
105
|
+
self.max_gradient_norm = max_gradient_norm
|
|
106
|
+
self.require_all_gradients = require_all_gradients
|
|
107
|
+
|
|
108
|
+
def before_step(self, loss, *, raise_on_failure=True):
|
|
109
|
+
report = run_checks([
|
|
110
|
+
loss_check(loss),
|
|
111
|
+
gradient_check(self.model, max_norm=self.max_gradient_norm,
|
|
112
|
+
require_all=self.require_all_gradients),
|
|
113
|
+
])
|
|
114
|
+
if raise_on_failure and not report["ok"]:
|
|
115
|
+
error = AuditFailed("Training health check failed before optimizer step")
|
|
116
|
+
error.report = report
|
|
117
|
+
raise error
|
|
118
|
+
return report
|