ToTf 0.2.6__tar.gz → 0.3.0__tar.gz
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.
- {totf-0.2.6 → totf-0.3.0}/PKG-INFO +415 -31
- {totf-0.2.6 → totf-0.3.0}/README.md +413 -29
- {totf-0.2.6 → totf-0.3.0}/ToTf/__init__.py +21 -1
- {totf-0.2.6 → totf-0.3.0}/ToTf/backend_manager.py +110 -0
- {totf-0.2.6 → totf-0.3.0}/ToTf.egg-info/PKG-INFO +415 -31
- {totf-0.2.6 → totf-0.3.0}/ToTf.egg-info/SOURCES.txt +2 -0
- {totf-0.2.6 → totf-0.3.0}/pyproject.toml +1 -2
- {totf-0.2.6 → totf-0.3.0}/setup.py +1 -1
- totf-0.3.0/test/test_phase2_utils.py +218 -0
- totf-0.3.0/test/test_phase3_utils.py +149 -0
- {totf-0.2.6 → totf-0.3.0}/LICENSE +0 -0
- {totf-0.2.6 → totf-0.3.0}/ToTf/backend.py +0 -0
- {totf-0.2.6 → totf-0.3.0}/ToTf.egg-info/dependency_links.txt +0 -0
- {totf-0.2.6 → totf-0.3.0}/ToTf.egg-info/requires.txt +0 -0
- {totf-0.2.6 → totf-0.3.0}/ToTf.egg-info/top_level.txt +0 -0
- {totf-0.2.6 → totf-0.3.0}/setup.cfg +0 -0
- {totf-0.2.6 → totf-0.3.0}/test/test_connection_api.py +0 -0
- {totf-0.2.6 → totf-0.3.0}/test/test_connections_visual.py +0 -0
- {totf-0.2.6 → totf-0.3.0}/test/test_integration.py +0 -0
- {totf-0.2.6 → totf-0.3.0}/test/test_modelview_quick.py +0 -0
- {totf-0.2.6 → totf-0.3.0}/test/test_modelview_tf.py +0 -0
- {totf-0.2.6 → totf-0.3.0}/test/test_monitor.py +0 -0
- {totf-0.2.6 → totf-0.3.0}/test/test_onnx_pytorch.py +0 -0
- {totf-0.2.6 → totf-0.3.0}/test/test_onnx_tensorflow.py +0 -0
- {totf-0.2.6 → totf-0.3.0}/test/test_phase1_utils.py +0 -0
- {totf-0.2.6 → totf-0.3.0}/test/test_pytorch_modelview_quick.py +0 -0
- {totf-0.2.6 → totf-0.3.0}/test/test_smartsummary.py +0 -0
- {totf-0.2.6 → totf-0.3.0}/test/test_smartsummary_features.py +0 -0
- {totf-0.2.6 → totf-0.3.0}/test/test_smartsummary_tf.py +0 -0
- {totf-0.2.6 → totf-0.3.0}/test/test_utils_integration.py +0 -0
- {totf-0.2.6 → totf-0.3.0}/test/test_utils_pytorch.py +0 -0
- {totf-0.2.6 → totf-0.3.0}/test/test_utils_tf.py +0 -0
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: ToTf
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.3.0
|
|
4
4
|
Summary: A Cross-Library Compatible Library for PyTorch and TensorFlow that provides advanced features for ease of use
|
|
5
5
|
Home-page: https://github.com/Akshay-Ramesh-VITC/ToTf
|
|
6
|
-
Author: Akshay
|
|
6
|
+
Author: Akshay
|
|
7
7
|
Author-email: akshay.r2023@vitstudent.ac.in
|
|
8
8
|
License: Apache-2.0
|
|
9
9
|
Project-URL: Homepage, https://github.com/Akshay-Ramesh-VITC/ToTf
|
|
@@ -139,6 +139,31 @@ Framework-agnostic "missing" functions that save time and improve code quality:
|
|
|
139
139
|
- **`freeze_batchnorm(model, freeze_eval=True)`** - Lock BatchNorm affine parameters and freeze running statistics (eval mode) during fine-tuning.
|
|
140
140
|
- **Use case**: Effortless backbone freezing and transfer learning across both frameworks.
|
|
141
141
|
|
|
142
|
+
#### Focal Loss for Class Imbalance
|
|
143
|
+
- **`loss_focal(y_true, y_pred, alpha=0.25, gamma=2.0)`** - Focal loss function for addressing extreme class imbalance in object detection and dense classification.
|
|
144
|
+
- **`FocalLoss(alpha=0.25, gamma=2.0)`** - PyTorch and Keras-compatible Focal Loss class.
|
|
145
|
+
- **Use case**: One-stage detectors, fraud/rare disease detection where easy negatives overwhelm the gradients.
|
|
146
|
+
|
|
147
|
+
#### Dice Loss & IoU Segmentation Metrics
|
|
148
|
+
- **`loss_dice(y_true, y_pred, smooth=1e-6)`** - Soft Dice loss for image segmentation.
|
|
149
|
+
- **`DiceLoss(smooth=1e-6)`** - PyTorch and Keras-compatible Dice Loss class.
|
|
150
|
+
- **`dice_score(y_true, y_pred)`** / **`iou_score(y_true, y_pred)`** - Fast Dice Similarity Coefficient and Jaccard Index metrics.
|
|
151
|
+
- **Use case**: Biomedical and satellite image segmentation with foreground-background class imbalance.
|
|
152
|
+
|
|
153
|
+
#### Numerical Anomaly Tracking (First-NaN / Inf Pinpointing)
|
|
154
|
+
- **`AnomalyDetector(model, check_inputs=True, check_outputs=True, check_gradients=True)`** - Non-intrusive hook monitor that intercepts the exact layer and tensor where NaN or Inf first originates.
|
|
155
|
+
- **`check_anomalies(tensor, name=None)`** - Quick boolean assertion check for tensors.
|
|
156
|
+
- **Use case**: Instantly identifies exploding gradients, numerical instability, or invalid layer inputs without hours of manual debugging.
|
|
157
|
+
|
|
158
|
+
#### Publication-Ready Model Profiling & Benchmarking
|
|
159
|
+
- **`benchmark_model(model, input_shape=..., num_runs=50, warmup=10)`** - Complete model complexity profiler calculating total/trainable params, memory (MB), estimated FLOPs & MACs, latency percentiles (mean, std, p50, p95, p99), throughput (FPS), plus ready-to-paste **Markdown** and **LaTeX** tables.
|
|
160
|
+
- **Use case**: Generate camera-ready complexity and performance tables for research papers, GitHub READMEs, and technical reports.
|
|
161
|
+
|
|
162
|
+
#### Direct In-Memory Weight Transfer (PyTorch <-> TensorFlow)
|
|
163
|
+
- **`transfer_weights(source_model, target_model, layer_mapping=None, verbose=True)`** - Direct zero-disk-overhead in-memory weight mapper between PyTorch and TensorFlow/Keras models.
|
|
164
|
+
- **Automated features**: Automatically handles spatial weight transpositions (PyTorch `[out, in, H, W]` vs Keras `[H, W, in, out]`), Linear/Dense transpositions (`[out, in]` vs `[in, out]`), and aligns BatchNorm gamma, beta, mean, and var.
|
|
165
|
+
- **Use case**: Instant cross-framework model porting, rapid paper replication, and comparing inference speeds between PyTorch and TensorFlow without cumbersome ONNX exports.
|
|
166
|
+
|
|
142
167
|
### 📊 ModelView (PyTorch & TensorFlow)
|
|
143
168
|
Publication-quality neural network architecture diagrams for both frameworks:
|
|
144
169
|
- **PyTorch support** - Wraps torchview for comprehensive PyTorch model visualization
|
|
@@ -1109,6 +1134,210 @@ best_lr = lr_finder.get_best_lr()
|
|
|
1109
1134
|
|
|
1110
1135
|
---
|
|
1111
1136
|
|
|
1137
|
+
### Cross-Framework Reproducibility (`seed_everything`)
|
|
1138
|
+
|
|
1139
|
+
**Problem**: Achieving full determinism and reproducibility across PyTorch, TensorFlow, NumPy, and Python usually requires 10+ lines of framework-specific boilerplate, device flags, and cuBLAS configurations.
|
|
1140
|
+
|
|
1141
|
+
**Solution**: `seed_everything()` configures all random number generators, backend states, and hardware determinism flags in a single call.
|
|
1142
|
+
|
|
1143
|
+
```python
|
|
1144
|
+
from ToTf import seed_everything
|
|
1145
|
+
|
|
1146
|
+
# Basic reproducible seeding (Python, NumPy, PyTorch CPU/CUDA, TensorFlow)
|
|
1147
|
+
seed_everything(42)
|
|
1148
|
+
|
|
1149
|
+
# Strict deterministic execution for scientific benchmarking
|
|
1150
|
+
seed_everything(42, deterministic=True, verbose=True)
|
|
1151
|
+
```
|
|
1152
|
+
|
|
1153
|
+
---
|
|
1154
|
+
|
|
1155
|
+
### Tensor Health & Diagnostics (`inspect_tensor`)
|
|
1156
|
+
|
|
1157
|
+
**Problem**: When debugging unexpected model outputs, vanishing gradients, or shape mismatches, printing a tensor only displays raw numbers or truncated floats, requiring multiple manual `.shape`, `.dtype`, `torch.isnan()`, `.mean()`, and `.std()` calls.
|
|
1158
|
+
|
|
1159
|
+
**Solution**: `inspect_tensor()` provides a comprehensive one-line diagnostic health profile for PyTorch, TensorFlow, and NumPy tensors.
|
|
1160
|
+
|
|
1161
|
+
```python
|
|
1162
|
+
from ToTf import inspect_tensor
|
|
1163
|
+
import torch
|
|
1164
|
+
|
|
1165
|
+
x = torch.randn(32, 64, 128)
|
|
1166
|
+
stats = inspect_tensor(x, name="encoder_activations")
|
|
1167
|
+
```
|
|
1168
|
+
|
|
1169
|
+
**Output:**
|
|
1170
|
+
```
|
|
1171
|
+
======================================================================
|
|
1172
|
+
[TENSOR HEALTH CHECK] 'encoder_activations'
|
|
1173
|
+
======================================================================
|
|
1174
|
+
Framework: PyTorch
|
|
1175
|
+
Shape: (32, 64, 128)
|
|
1176
|
+
Dtype: torch.float32
|
|
1177
|
+
Device: cpu
|
|
1178
|
+
Memory: 1.000 MB
|
|
1179
|
+
Elements: 262,144
|
|
1180
|
+
NaNs: 0 (0.0000%) [OK]
|
|
1181
|
+
Infs: 0 (0.0000%) [OK]
|
|
1182
|
+
Zeros: 0 (0.0000%)
|
|
1183
|
+
Min / Max: -4.521849 / 4.678121
|
|
1184
|
+
Mean / Std: -0.000142 / 0.999812
|
|
1185
|
+
Quantiles: p25=-0.674912, p50=0.000185, p75=0.674391
|
|
1186
|
+
======================================================================
|
|
1187
|
+
```
|
|
1188
|
+
|
|
1189
|
+
---
|
|
1190
|
+
|
|
1191
|
+
### Transfer Learning & Fine-Tuning Toolkit
|
|
1192
|
+
|
|
1193
|
+
**Problem**: Freezing backbones or fine-tuning heads in PyTorch requires navigating parameter generators and setting `param.requires_grad = False`. In TensorFlow/Keras, it requires setting `layer.trainable = False`. Furthermore, PyTorch `BatchNorm` layers continue updating running mean and variance in `.train()` mode even if affine parameters are frozen!
|
|
1194
|
+
|
|
1195
|
+
**Solution**: Framework-agnostic `freeze_layers()`, `unfreeze_layers()`, and `freeze_batchnorm()`.
|
|
1196
|
+
|
|
1197
|
+
```python
|
|
1198
|
+
from ToTf import freeze_layers, unfreeze_layers, freeze_batchnorm
|
|
1199
|
+
|
|
1200
|
+
# Freeze backbone layers up to index 8, or matching a name pattern
|
|
1201
|
+
freeze_layers(model, up_to=8)
|
|
1202
|
+
freeze_layers(model, regex=r"(conv|block[1-3])")
|
|
1203
|
+
|
|
1204
|
+
# Unfreeze only the final classifier head
|
|
1205
|
+
unfreeze_layers(model, last_n=1)
|
|
1206
|
+
|
|
1207
|
+
# Lock BatchNorm weights AND running statistics during fine-tuning
|
|
1208
|
+
freeze_batchnorm(model, freeze_eval=True)
|
|
1209
|
+
```
|
|
1210
|
+
|
|
1211
|
+
---
|
|
1212
|
+
|
|
1213
|
+
### Focal Loss for Class Imbalance
|
|
1214
|
+
|
|
1215
|
+
**Problem**: Standard Cross-Entropy is overwhelmed by vast numbers of easily classified background/negative examples in tasks like object detection, anomaly detection, or medical triage.
|
|
1216
|
+
|
|
1217
|
+
**Solution**: `loss_focal()` and `FocalLoss` dynamically scale the cross-entropy loss, down-weighting easy examples to focus gradient updates on hard, confusing examples.
|
|
1218
|
+
|
|
1219
|
+
```python
|
|
1220
|
+
from ToTf import loss_focal, FocalLoss
|
|
1221
|
+
|
|
1222
|
+
# Functional usage
|
|
1223
|
+
loss = loss_focal(y_true, y_pred, alpha=0.25, gamma=2.0)
|
|
1224
|
+
|
|
1225
|
+
# PyTorch Module / Keras Loss Layer usage
|
|
1226
|
+
criterion = FocalLoss(alpha=0.25, gamma=2.0)
|
|
1227
|
+
loss = criterion(y_true, y_pred)
|
|
1228
|
+
```
|
|
1229
|
+
|
|
1230
|
+
---
|
|
1231
|
+
|
|
1232
|
+
### Dice Loss & Segmentation Metrics
|
|
1233
|
+
|
|
1234
|
+
**Problem**: Pixel-wise cross-entropy struggles with severe foreground-background imbalance in semantic/biomedical segmentation (e.g. small tumors or lesions covering <1% of the image).
|
|
1235
|
+
|
|
1236
|
+
**Solution**: Differentiable soft `loss_dice()` / `DiceLoss`, alongside `dice_score()` and `iou_score()` (Jaccard Index) evaluation metrics.
|
|
1237
|
+
|
|
1238
|
+
```python
|
|
1239
|
+
from ToTf import loss_dice, DiceLoss, dice_score, iou_score
|
|
1240
|
+
|
|
1241
|
+
# Differentiable loss for backpropagation
|
|
1242
|
+
loss = loss_dice(masks_true, masks_pred, smooth=1e-6)
|
|
1243
|
+
|
|
1244
|
+
# Validation evaluation metrics
|
|
1245
|
+
dsc = dice_score(masks_true, masks_pred) # Dice Similarity Coefficient
|
|
1246
|
+
iou = iou_score(masks_true, masks_pred) # Jaccard Index (IoU)
|
|
1247
|
+
print(f"Validation Dice: {dsc:.4f} | IoU: {iou:.4f}")
|
|
1248
|
+
```
|
|
1249
|
+
|
|
1250
|
+
---
|
|
1251
|
+
|
|
1252
|
+
### Numerical Anomaly Tracking (`AnomalyDetector`)
|
|
1253
|
+
|
|
1254
|
+
**Problem**: When NaN or Inf values appear in a deep network, PyTorch and TensorFlow typically do not fail until the loss or backward pass diverges, leaving you with zero visibility into which layer or tensor first went unstable.
|
|
1255
|
+
|
|
1256
|
+
**Solution**: `AnomalyDetector` attaches non-intrusive hooks to all layers, recording the exact layer name, stage (input, output, or backward gradient), tensor shape, and NaN/Inf count where instability first occurs.
|
|
1257
|
+
|
|
1258
|
+
```python
|
|
1259
|
+
from ToTf import AnomalyDetector, check_anomalies
|
|
1260
|
+
|
|
1261
|
+
# Fast single-tensor check
|
|
1262
|
+
has_anomaly = check_anomalies(tensor, name="latent_embedding")
|
|
1263
|
+
|
|
1264
|
+
# Deep layer-by-layer anomaly interceptor
|
|
1265
|
+
detector = AnomalyDetector(model, check_inputs=True, check_outputs=True, check_gradients=True)
|
|
1266
|
+
|
|
1267
|
+
# Run forward & backward passes normally
|
|
1268
|
+
output = model(inputs)
|
|
1269
|
+
loss = criterion(output, targets)
|
|
1270
|
+
loss.backward()
|
|
1271
|
+
|
|
1272
|
+
# Inspect any detected anomalies
|
|
1273
|
+
if detector.has_anomalies():
|
|
1274
|
+
print(detector.summary())
|
|
1275
|
+
for anomaly in detector.anomalies:
|
|
1276
|
+
print(f"Layer '{anomaly['layer_name']}' failed at {anomaly['stage']} with {anomaly['nan_count']} NaNs!")
|
|
1277
|
+
|
|
1278
|
+
# Clean up hooks after debugging
|
|
1279
|
+
detector.remove_hooks()
|
|
1280
|
+
```
|
|
1281
|
+
|
|
1282
|
+
---
|
|
1283
|
+
|
|
1284
|
+
### Publication-Ready Model Profiling (`benchmark_model`)
|
|
1285
|
+
|
|
1286
|
+
**Problem**: Writing research papers and technical documentation requires reporting parameter counts, memory footprint, FLOPs/MACs, latency percentiles, and throughput. Setting up CUDA warmup, timing loops, percentiles, and converting results into Markdown and LaTeX tables is repetitive and error-prone.
|
|
1287
|
+
|
|
1288
|
+
**Solution**: `benchmark_model()` benchmarks models with warmup, calculates parameter and computational complexity, and outputs copy-paste ready Markdown and LaTeX tables.
|
|
1289
|
+
|
|
1290
|
+
```python
|
|
1291
|
+
from ToTf import benchmark_model
|
|
1292
|
+
|
|
1293
|
+
report = benchmark_model(
|
|
1294
|
+
model,
|
|
1295
|
+
input_shape=(8, 3, 64, 64),
|
|
1296
|
+
num_runs=50,
|
|
1297
|
+
warmup=10,
|
|
1298
|
+
device="cpu", # or 'cuda'
|
|
1299
|
+
print_table=True
|
|
1300
|
+
)
|
|
1301
|
+
|
|
1302
|
+
# Access computed metrics
|
|
1303
|
+
print(f"FLOPs: {report['flops_g']:.3f} G | Throughput: {report['fps']:.1f} FPS")
|
|
1304
|
+
|
|
1305
|
+
# Camera-ready LaTeX table for Overleaf / paper submission:
|
|
1306
|
+
print(report['latex_table'])
|
|
1307
|
+
|
|
1308
|
+
# Markdown table for GitHub / Notion documentation:
|
|
1309
|
+
print(report['markdown_table'])
|
|
1310
|
+
```
|
|
1311
|
+
|
|
1312
|
+
---
|
|
1313
|
+
|
|
1314
|
+
### Direct In-Memory Weight Transfer (`transfer_weights`)
|
|
1315
|
+
|
|
1316
|
+
**Problem**: Porting a trained PyTorch model to TensorFlow/Keras (or vice-versa) usually requires saving to ONNX, writing custom conversion scripts, or manually transposing convolution weights and mapping BatchNorm parameters.
|
|
1317
|
+
|
|
1318
|
+
**Solution**: `transfer_weights()` transfers compatible parameters directly in-memory between PyTorch and TensorFlow models without disk I/O, automatically handling convolution kernel transpositions (`[out, in, H, W]` vs `[H, W, in, out]`), dense layer transpositions (`[out, in]` vs `[in, out]`), and aligning BatchNorm weights, biases, running means, and running variances.
|
|
1319
|
+
|
|
1320
|
+
```python
|
|
1321
|
+
from ToTf import transfer_weights
|
|
1322
|
+
|
|
1323
|
+
# PyTorch -> TensorFlow / Keras
|
|
1324
|
+
transfer_weights(torch_model, keras_model, verbose=True)
|
|
1325
|
+
|
|
1326
|
+
# TensorFlow / Keras -> PyTorch
|
|
1327
|
+
transfer_weights(keras_model, torch_model, verbose=True)
|
|
1328
|
+
|
|
1329
|
+
# Optional custom layer name mapping for non-sequential architectures:
|
|
1330
|
+
transfer_weights(
|
|
1331
|
+
source_model,
|
|
1332
|
+
target_model,
|
|
1333
|
+
layer_mapping={"resnet_conv1": "features.0", "classifier": "head"}
|
|
1334
|
+
)
|
|
1335
|
+
```
|
|
1336
|
+
|
|
1337
|
+
---
|
|
1338
|
+
|
|
1339
|
+
---
|
|
1340
|
+
|
|
1112
1341
|
## API Reference
|
|
1113
1342
|
|
|
1114
1343
|
### TrainingMonitor
|
|
@@ -1327,6 +1556,152 @@ LRFinder(model, loss_fn, optimizer=None)
|
|
|
1327
1556
|
|
|
1328
1557
|
---
|
|
1329
1558
|
|
|
1559
|
+
#### seed_everything
|
|
1560
|
+
|
|
1561
|
+
```python
|
|
1562
|
+
seed_everything(seed: int = 42, deterministic: bool = False, benchmark: bool = False, verbose: bool = False)
|
|
1563
|
+
```
|
|
1564
|
+
|
|
1565
|
+
**Parameters:**
|
|
1566
|
+
- `seed` (int): Master seed value (default: 42).
|
|
1567
|
+
- `deterministic` (bool): Enable deterministic algorithms across PyTorch & TensorFlow (may impact performance).
|
|
1568
|
+
- `benchmark` (bool): PyTorch cuDNN benchmark setting.
|
|
1569
|
+
- `verbose` (bool): Print seeding confirmation status.
|
|
1570
|
+
|
|
1571
|
+
---
|
|
1572
|
+
|
|
1573
|
+
#### inspect_tensor
|
|
1574
|
+
|
|
1575
|
+
```python
|
|
1576
|
+
inspect_tensor(tensor: Any, name: Optional[str] = None, print_info: bool = True, quantiles: bool = True) -> Dict[str, Any]
|
|
1577
|
+
```
|
|
1578
|
+
|
|
1579
|
+
**Parameters:**
|
|
1580
|
+
- `tensor`: Input PyTorch tensor, TensorFlow tensor, or NumPy array.
|
|
1581
|
+
- `name` (str, optional): Custom display name for debugging.
|
|
1582
|
+
- `print_info` (bool): Print formatted summary table to console.
|
|
1583
|
+
- `quantiles` (bool): Compute 25th, 50th (median), and 75th percentiles.
|
|
1584
|
+
|
|
1585
|
+
**Returns:** Dictionary with keys `shape`, `dtype`, `device`, `numel`, `memory_mb`, `has_nan`, `nan_count`, `has_inf`, `inf_count`, `zero_pct`, `min`, `max`, `mean`, `std`, and optional `quantiles`.
|
|
1586
|
+
|
|
1587
|
+
---
|
|
1588
|
+
|
|
1589
|
+
#### freeze_layers / unfreeze_layers / freeze_batchnorm
|
|
1590
|
+
|
|
1591
|
+
```python
|
|
1592
|
+
freeze_layers(model: Any, up_to: Optional[int] = None, layer_names: Optional[List[str]] = None, layer_types: Optional[Tuple[Type, ...]] = None, regex: Optional[str] = None) -> int
|
|
1593
|
+
|
|
1594
|
+
unfreeze_layers(model: Any, last_n: Optional[int] = None, layer_names: Optional[List[str]] = None, layer_types: Optional[Tuple[Type, ...]] = None, regex: Optional[str] = None) -> int
|
|
1595
|
+
|
|
1596
|
+
freeze_batchnorm(model: Any, freeze_eval: bool = True) -> int
|
|
1597
|
+
```
|
|
1598
|
+
|
|
1599
|
+
**Parameters:**
|
|
1600
|
+
- `model`: PyTorch `nn.Module` or TensorFlow `tf.keras.Model`.
|
|
1601
|
+
- `up_to`: Index up to which layers should be frozen (exclusive).
|
|
1602
|
+
- `last_n`: Count of trailing layers to unfreeze.
|
|
1603
|
+
- `layer_names`: Explicit list of layer names to match.
|
|
1604
|
+
- `layer_types`: Tuple of layer classes/types to match (e.g. `(nn.Conv2d, nn.Linear)`).
|
|
1605
|
+
- `regex`: Regex pattern matching layer names.
|
|
1606
|
+
- `freeze_eval` (bool): For PyTorch, force BatchNorm modules into eval mode and prevent running statistics from updating.
|
|
1607
|
+
|
|
1608
|
+
**Returns:** Count of modified layers/parameters.
|
|
1609
|
+
|
|
1610
|
+
---
|
|
1611
|
+
|
|
1612
|
+
#### loss_focal / FocalLoss
|
|
1613
|
+
|
|
1614
|
+
```python
|
|
1615
|
+
loss_focal(y_true: Any, y_pred: Any, alpha: float = 0.25, gamma: float = 2.0, reduction: str = 'mean') -> Any
|
|
1616
|
+
|
|
1617
|
+
FocalLoss(alpha: float = 0.25, gamma: float = 2.0, reduction: str = 'mean')
|
|
1618
|
+
```
|
|
1619
|
+
|
|
1620
|
+
**Parameters:**
|
|
1621
|
+
- `alpha` (float): Weighting factor for rare/positive class (default: 0.25).
|
|
1622
|
+
- `gamma` (float): Focusing parameter for hard examples (default: 2.0).
|
|
1623
|
+
- `reduction` (str): `'mean'`, `'sum'`, or `'none'` (default: `'mean'`).
|
|
1624
|
+
|
|
1625
|
+
---
|
|
1626
|
+
|
|
1627
|
+
#### loss_dice / DiceLoss / dice_score / iou_score
|
|
1628
|
+
|
|
1629
|
+
```python
|
|
1630
|
+
loss_dice(y_true: Any, y_pred: Any, smooth: float = 1e-6) -> Any
|
|
1631
|
+
DiceLoss(smooth: float = 1e-6)
|
|
1632
|
+
|
|
1633
|
+
dice_score(y_true: Any, y_pred: Any, smooth: float = 1e-6) -> float
|
|
1634
|
+
iou_score(y_true: Any, y_pred: Any, smooth: float = 1e-6) -> float
|
|
1635
|
+
```
|
|
1636
|
+
|
|
1637
|
+
**Parameters:**
|
|
1638
|
+
- `y_true`, `y_pred`: Ground truth masks and predicted probability/activation masks.
|
|
1639
|
+
- `smooth` (float): Smoothing epsilon to prevent division by zero (default: 1e-6).
|
|
1640
|
+
|
|
1641
|
+
---
|
|
1642
|
+
|
|
1643
|
+
#### AnomalyDetector / check_anomalies
|
|
1644
|
+
|
|
1645
|
+
```python
|
|
1646
|
+
check_anomalies(tensor: Any, name: Optional[str] = None) -> bool
|
|
1647
|
+
|
|
1648
|
+
AnomalyDetector(model: Any, check_inputs: bool = True, check_outputs: bool = True, check_gradients: bool = True)
|
|
1649
|
+
```
|
|
1650
|
+
|
|
1651
|
+
**Methods:**
|
|
1652
|
+
- `has_anomalies() -> bool`: Returns True if any NaN or Inf was captured.
|
|
1653
|
+
- `summary() -> str`: Formatted report of all anomalies encountered.
|
|
1654
|
+
- `reset()`: Clear captured anomaly history.
|
|
1655
|
+
- `remove_hooks()`: Detach all hooks from the model.
|
|
1656
|
+
|
|
1657
|
+
---
|
|
1658
|
+
|
|
1659
|
+
#### benchmark_model
|
|
1660
|
+
|
|
1661
|
+
```python
|
|
1662
|
+
benchmark_model(
|
|
1663
|
+
model: Any,
|
|
1664
|
+
input_shape: Tuple[int, ...],
|
|
1665
|
+
num_runs: int = 50,
|
|
1666
|
+
warmup: int = 10,
|
|
1667
|
+
device: str = 'cpu',
|
|
1668
|
+
print_table: bool = True
|
|
1669
|
+
) -> Dict[str, Any]
|
|
1670
|
+
```
|
|
1671
|
+
|
|
1672
|
+
**Parameters:**
|
|
1673
|
+
- `model`: PyTorch `nn.Module` or TensorFlow `tf.keras.Model`.
|
|
1674
|
+
- `input_shape`: Input tensor shape including or excluding batch (e.g. `(8, 3, 224, 224)`).
|
|
1675
|
+
- `num_runs` (int): Timed evaluation runs (default: 50).
|
|
1676
|
+
- `warmup` (int): Untimed warmup iterations to initialize caches/CUDA kernels (default: 10).
|
|
1677
|
+
- `device` (str): `'cpu'` or `'cuda'` (default: `'cpu'`).
|
|
1678
|
+
- `print_table` (bool): Pretty-print console summary.
|
|
1679
|
+
|
|
1680
|
+
**Returns:** Dictionary with `total_params`, `trainable_params`, `param_memory_mb`, `macs`, `flops`, `latency_mean_ms`, `latency_std_ms`, `latency_p50_ms`, `latency_p95_ms`, `latency_p99_ms`, `fps`, `markdown_table`, and `latex_table`.
|
|
1681
|
+
|
|
1682
|
+
---
|
|
1683
|
+
|
|
1684
|
+
#### transfer_weights
|
|
1685
|
+
|
|
1686
|
+
```python
|
|
1687
|
+
transfer_weights(
|
|
1688
|
+
source_model: Any,
|
|
1689
|
+
target_model: Any,
|
|
1690
|
+
layer_mapping: Optional[Dict[str, str]] = None,
|
|
1691
|
+
verbose: bool = True
|
|
1692
|
+
) -> Dict[str, int]
|
|
1693
|
+
```
|
|
1694
|
+
|
|
1695
|
+
**Parameters:**
|
|
1696
|
+
- `source_model`: Source model (PyTorch `nn.Module` or TensorFlow `tf.keras.Model`).
|
|
1697
|
+
- `target_model`: Target model (PyTorch `nn.Module` or TensorFlow `tf.keras.Model`).
|
|
1698
|
+
- `layer_mapping` (dict, optional): Custom mapping from source layer names to target layer names.
|
|
1699
|
+
- `verbose` (bool): Print layer mapping and transfer details.
|
|
1700
|
+
|
|
1701
|
+
**Returns:** Dictionary with `transferred_layers` and `transferred_params` counts.
|
|
1702
|
+
|
|
1703
|
+
---
|
|
1704
|
+
|
|
1330
1705
|
## Comparison with Alternatives
|
|
1331
1706
|
|
|
1332
1707
|
### SmartSummary vs Other Tools
|
|
@@ -1358,6 +1733,11 @@ LRFinder(model, loss_fn, optimizer=None)
|
|
|
1358
1733
|
- [example_smartsummary_tf.py](example_smartsummary_tf.py) - SmartSummary examples for TensorFlow/Keras (8 detailed scenarios including multi-input models, gradient tracking, and MobileNetV2 analysis)
|
|
1359
1734
|
- [example_utils_tf.py](example_utils_tf.py) - Utility functions examples (6 scenarios: lazy_flatten, NCC loss with Keras, LR finder, Functional API usage)
|
|
1360
1735
|
|
|
1736
|
+
### Cross-Framework & Research Examples
|
|
1737
|
+
- [examples/example_phase1_qol.py](examples/example_phase1_qol.py) - Phase 1: Cross-framework seeding, tensor health check, layer and BatchNorm freezing
|
|
1738
|
+
- [examples/example_phase2_diagnostics_losses.py](examples/example_phase2_diagnostics_losses.py) - Phase 2: Focal Loss, Dice Loss & IoU metrics, and AnomalyDetector for pinpointing first-NaN/Inf origins
|
|
1739
|
+
- [examples/example_phase3_benchmarking_transfer.py](examples/example_phase3_benchmarking_transfer.py) - Phase 3: Paper-ready benchmark profiling (FLOPs/latency/Markdown/LaTeX tables) and direct in-memory PyTorch <-> TensorFlow weight transfer
|
|
1740
|
+
|
|
1361
1741
|
---
|
|
1362
1742
|
|
|
1363
1743
|
## Testing
|
|
@@ -1365,24 +1745,18 @@ LRFinder(model, loss_fn, optimizer=None)
|
|
|
1365
1745
|
Run the test suites to verify everything works:
|
|
1366
1746
|
|
|
1367
1747
|
```bash
|
|
1368
|
-
# Test
|
|
1369
|
-
|
|
1370
|
-
python test/test_integration.py
|
|
1371
|
-
|
|
1372
|
-
# Test SmartSummary (PyTorch)
|
|
1373
|
-
python test/test_smartsummary.py
|
|
1748
|
+
# Test Phase 1 Quality-of-Life & Transfer Learning Utilities
|
|
1749
|
+
pytest test/test_phase1_utils.py -v
|
|
1374
1750
|
|
|
1375
|
-
# Test
|
|
1376
|
-
|
|
1751
|
+
# Test Phase 2 Advanced Diagnostics & Losses
|
|
1752
|
+
pytest test/test_phase2_utils.py -v
|
|
1377
1753
|
|
|
1378
|
-
# Test
|
|
1379
|
-
|
|
1754
|
+
# Test Phase 3 Benchmarking & Weight Transfer
|
|
1755
|
+
pytest test/test_phase3_utils.py -v
|
|
1380
1756
|
|
|
1381
|
-
#
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
# Test Cross-Framework Integration
|
|
1385
|
-
python test/test_utils_integration.py
|
|
1757
|
+
# Run full test suite across all modules (119+ tests)
|
|
1758
|
+
pytest test/ -v
|
|
1759
|
+
```
|
|
1386
1760
|
|
|
1387
1761
|
---
|
|
1388
1762
|
|
|
@@ -1403,6 +1777,7 @@ print(get_backend()) # Returns 'torch' or 'tensorflow'
|
|
|
1403
1777
|
ToTf/
|
|
1404
1778
|
├── __init__.py # Package exports with auto backend detection
|
|
1405
1779
|
├── backend.py # Backend detection (PyTorch/TensorFlow)
|
|
1780
|
+
├── backend_manager.py # Dynamic component dispatching & registration
|
|
1406
1781
|
├── requirements.txt # Dependencies
|
|
1407
1782
|
├── setup.py # Package config
|
|
1408
1783
|
│
|
|
@@ -1417,32 +1792,36 @@ ToTf/
|
|
|
1417
1792
|
│ ├── __init__.py
|
|
1418
1793
|
│ ├── trainingmonitor.py # TrainingMonitor implementation
|
|
1419
1794
|
│ ├── smartsummary.py # SmartSummary implementation (PyTorch)
|
|
1420
|
-
│ └── utils.py #
|
|
1795
|
+
│ └── utils.py # Utilities (seed, inspect, freeze, focal, dice, anomaly, benchmark, transfer)
|
|
1421
1796
|
│
|
|
1422
1797
|
├── tenf/
|
|
1423
1798
|
│ ├── __init__.py
|
|
1424
1799
|
│ ├── smartsummary.py # SmartSummary implementation (TensorFlow)
|
|
1425
|
-
│ ├── modelview.py # ModelView for architecture diagrams
|
|
1426
|
-
│ └── utils.py #
|
|
1800
|
+
│ ├── modelview.py # ModelView for architecture diagrams
|
|
1801
|
+
│ └── utils.py # Utilities (seed, inspect, freeze, focal, dice, anomaly, benchmark, transfer)
|
|
1427
1802
|
│
|
|
1428
|
-
├──
|
|
1803
|
+
├── examples/
|
|
1429
1804
|
│ ├── example_usage.py # TrainingMonitor examples
|
|
1430
1805
|
│ ├── example_smartsummary.py # SmartSummary examples (PyTorch)
|
|
1431
1806
|
│ ├── example_smartsummary_tf.py # SmartSummary examples (TensorFlow)
|
|
1432
1807
|
│ ├── example_modelview_tf.py # ModelView examples (8+ examples)
|
|
1433
|
-
│ ├──
|
|
1434
|
-
│ ├──
|
|
1435
|
-
│
|
|
1808
|
+
│ ├── example_phase1_qol.py # Seeding, inspect_tensor, layer & BN freezing
|
|
1809
|
+
│ ├── example_phase2_diagnostics_losses.py # Focal loss, Dice, IoU, AnomalyDetector
|
|
1810
|
+
│ ├── example_phase3_benchmarking_transfer.py # Model benchmarking & weight transfer
|
|
1811
|
+
│ └── demo_complex_architectures.py # Complex architecture demos
|
|
1436
1812
|
│
|
|
1437
1813
|
├── test/
|
|
1438
1814
|
│ ├── test_monitor.py # TrainingMonitor tests
|
|
1439
1815
|
│ ├── test_integration.py # Integration tests
|
|
1440
1816
|
│ ├── test_smartsummary.py # SmartSummary tests (PyTorch)
|
|
1441
1817
|
│ ├── test_smartsummary_tf.py # SmartSummary tests (TensorFlow)
|
|
1442
|
-
│ ├── test_modelview_tf.py # ModelView tests (41 tests, 9 classes)
|
|
1818
|
+
│ ├── test_modelview_tf.py # ModelView tests (41 tests, 9 classes)
|
|
1443
1819
|
│ ├── test_utils_pytorch.py # Utility functions tests (PyTorch)
|
|
1444
1820
|
│ ├── test_utils_tf.py # Utility functions tests (TensorFlow)
|
|
1445
|
-
│
|
|
1821
|
+
│ ├── test_utils_integration.py # Cross-framework integration tests
|
|
1822
|
+
│ ├── test_phase1_utils.py # Phase 1 tests (19 tests)
|
|
1823
|
+
│ ├── test_phase2_utils.py # Phase 2 tests (6 tests)
|
|
1824
|
+
│ └── test_phase3_utils.py # Phase 3 tests (4 tests)
|
|
1446
1825
|
│
|
|
1447
1826
|
└── verify_modelview.py # Quick ModelView verification script
|
|
1448
1827
|
```
|
|
@@ -1462,17 +1841,22 @@ Contributions are welcome! Please ensure all tests pass before submitting PRs.
|
|
|
1462
1841
|
```bash
|
|
1463
1842
|
# Run all tests
|
|
1464
1843
|
pytest test/ -v
|
|
1465
|
-
|
|
1466
|
-
# Run specific test suites
|
|
1467
|
-
pytest test/test_modelview_tf.py -v # ModelView tests (32 tests)
|
|
1468
|
-
pytest test/test_smartsummary_tf.py -v # SmartSummary tests
|
|
1469
|
-
pytest test/test_utils_tf.py -v # Utilities tests
|
|
1470
1844
|
```
|
|
1471
1845
|
|
|
1472
1846
|
---
|
|
1473
1847
|
|
|
1474
1848
|
## What's New
|
|
1475
1849
|
|
|
1850
|
+
**v0.3.0 - Research & Production Deep Learning Toolkit (Phases 1, 2, & 3)** 🚀
|
|
1851
|
+
- ✅ **Cross-Framework Reproducibility**: `seed_everything()` sets unified seeds, determinism flags, and hardware workspace configs for Python, NumPy, PyTorch (CPU/CUDA), and TensorFlow.
|
|
1852
|
+
- ✅ **Tensor Health & Diagnostics**: `inspect_tensor()` provides instant one-line profiling (shape, dtype, memory, NaNs, Infs, zero sparsity, quantiles).
|
|
1853
|
+
- ✅ **Transfer Learning Toolkit**: `freeze_layers()`, `unfreeze_layers()`, and `freeze_batchnorm()` for seamless backbone locking across PyTorch and Keras.
|
|
1854
|
+
- ✅ **Focal Loss**: `loss_focal()` and `FocalLoss` for imbalanced dense classification and object detection.
|
|
1855
|
+
- ✅ **Dice Loss & IoU**: `loss_dice()`, `DiceLoss`, `dice_score()`, and `iou_score()` for segmentation tasks.
|
|
1856
|
+
- ✅ **First-NaN/Inf Anomaly Interceptor**: `AnomalyDetector` and `check_anomalies()` track exactly which layer and forward/backward stage first produces numerical instability.
|
|
1857
|
+
- ✅ **Camera-Ready Model Benchmarking**: `benchmark_model()` measures FLOPs, MACs, latency percentiles (p50, p95, p99), and throughput (FPS), auto-generating ready-to-publish Markdown and LaTeX tables.
|
|
1858
|
+
- ✅ **Direct In-Memory Weight Transfer**: `transfer_weights()` transfers weights between PyTorch and TensorFlow/Keras without disk I/O or ONNX overhead, automatically handling 2D conv kernel and dense weight matrix transpositions.
|
|
1859
|
+
|
|
1476
1860
|
**v0.2.3 ONNX Support**
|
|
1477
1861
|
- ✅ **toONNX** and **fromONNX** have been added to support ONNX
|
|
1478
1862
|
**v0.2.2 Connection Extraction Fix** 🔧
|