ToTf 0.2.3__tar.gz → 0.2.5__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.
Files changed (42) hide show
  1. {totf-0.2.3 → totf-0.2.5}/PKG-INFO +6 -6
  2. totf-0.2.5/ToTf/__init__.py +14 -0
  3. totf-0.2.5/ToTf/backend.py +14 -0
  4. totf-0.2.5/ToTf/backend_manager.py +227 -0
  5. {totf-0.2.3 → totf-0.2.5}/ToTf.egg-info/PKG-INFO +6 -6
  6. {totf-0.2.3 → totf-0.2.5}/ToTf.egg-info/SOURCES.txt +3 -12
  7. totf-0.2.5/ToTf.egg-info/top_level.txt +1 -0
  8. {totf-0.2.3 → totf-0.2.5}/pyproject.toml +8 -8
  9. {totf-0.2.3 → totf-0.2.5}/setup.py +1 -1
  10. totf-0.2.3/ToTf.egg-info/top_level.txt +0 -2
  11. totf-0.2.3/pytorch/README.md +0 -200
  12. totf-0.2.3/pytorch/__init__.py +0 -28
  13. totf-0.2.3/pytorch/modelview.py +0 -347
  14. totf-0.2.3/pytorch/smartsummary.py +0 -1054
  15. totf-0.2.3/pytorch/trainingmonitor.py +0 -87
  16. totf-0.2.3/pytorch/utils.py +0 -533
  17. totf-0.2.3/tenf/README.md +0 -161
  18. totf-0.2.3/tenf/__init__.py +0 -28
  19. totf-0.2.3/tenf/computation_nodes.py +0 -176
  20. totf-0.2.3/tenf/modelview.py +0 -989
  21. totf-0.2.3/tenf/smartsummary.py +0 -846
  22. totf-0.2.3/tenf/utils.py +0 -611
  23. {totf-0.2.3 → totf-0.2.5}/LICENSE +0 -0
  24. {totf-0.2.3 → totf-0.2.5}/README.md +0 -0
  25. {totf-0.2.3 → totf-0.2.5}/ToTf.egg-info/dependency_links.txt +0 -0
  26. {totf-0.2.3 → totf-0.2.5}/ToTf.egg-info/requires.txt +0 -0
  27. {totf-0.2.3 → totf-0.2.5}/setup.cfg +0 -0
  28. {totf-0.2.3 → totf-0.2.5}/test/test_connection_api.py +0 -0
  29. {totf-0.2.3 → totf-0.2.5}/test/test_connections_visual.py +0 -0
  30. {totf-0.2.3 → totf-0.2.5}/test/test_integration.py +0 -0
  31. {totf-0.2.3 → totf-0.2.5}/test/test_modelview_quick.py +0 -0
  32. {totf-0.2.3 → totf-0.2.5}/test/test_modelview_tf.py +0 -0
  33. {totf-0.2.3 → totf-0.2.5}/test/test_monitor.py +0 -0
  34. {totf-0.2.3 → totf-0.2.5}/test/test_onnx_pytorch.py +0 -0
  35. {totf-0.2.3 → totf-0.2.5}/test/test_onnx_tensorflow.py +0 -0
  36. {totf-0.2.3 → totf-0.2.5}/test/test_pytorch_modelview_quick.py +0 -0
  37. {totf-0.2.3 → totf-0.2.5}/test/test_smartsummary.py +0 -0
  38. {totf-0.2.3 → totf-0.2.5}/test/test_smartsummary_features.py +0 -0
  39. {totf-0.2.3 → totf-0.2.5}/test/test_smartsummary_tf.py +0 -0
  40. {totf-0.2.3 → totf-0.2.5}/test/test_utils_integration.py +0 -0
  41. {totf-0.2.3 → totf-0.2.5}/test/test_utils_pytorch.py +0 -0
  42. {totf-0.2.3 → totf-0.2.5}/test/test_utils_tf.py +0 -0
@@ -1,17 +1,17 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ToTf
3
- Version: 0.2.3
3
+ Version: 0.2.5
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
6
  Author: Akshay, Shyamanth Reddy
7
7
  Author-email: akshay.r2023@vitstudent.ac.in
8
8
  License: Apache-2.0
9
- Project-URL: Homepage, https://github.com/yourusername/ToTf
10
- Project-URL: Documentation, https://github.com/yourusername/ToTf#readme
11
- Project-URL: Repository, https://github.com/yourusername/ToTf
12
- Project-URL: Bug Tracker, https://github.com/yourusername/ToTf/issues
9
+ Project-URL: Homepage, https://github.com/Akshay-Ramesh-VITC/ToTf
10
+ Project-URL: Documentation, https://github.com/Akshay-Ramesh-VITC/ToTf#readme
11
+ Project-URL: Repository, https://github.com/Akshay-Ramesh-VITC/ToTf
12
+ Project-URL: Bug Tracker, https://github.com/Akshay-Ramesh-VITC/ToTf/issues
13
13
  Keywords: pytorch,tensorflow,deep-learning,neural-networks,model-visualization,training-monitoring,machine-learning
14
- Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Development Status :: 4 - Beta
15
15
  Classifier: Intended Audience :: Developers
16
16
  Classifier: Intended Audience :: Science/Research
17
17
  Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
@@ -0,0 +1,14 @@
1
+ """
2
+ ToTf - A Cross-Library Compatible Library for PyTorch and TensorFlow
3
+ Provides additional features for ease of use not directly available in Torch or TF
4
+ """
5
+
6
+ from .backend import get_backend, _BACKEND
7
+ from .backend_manager import SmartSummary, TrainingMonitor, ModelView, draw_graph, get_component
8
+ from .backend_manager import toONNX, fromONNX
9
+
10
+ __version__ = "0.2.5"
11
+ __author__ = "Akshay"
12
+ __all__ = ["get_backend", "TrainingMonitor", "SmartSummary", "ModelView", "draw_graph", "get_component", "toONNX", "fromONNX"]
13
+
14
+ # Use backend_manager factories for dynamic dispatch to framework implementations
@@ -0,0 +1,14 @@
1
+ import importlib.util
2
+
3
+ _BACKEND = None
4
+
5
+ if importlib.util.find_spec("torch"):
6
+ _BACKEND = "torch"
7
+ elif importlib.util.find_spec("tensorflow"):
8
+ _BACKEND = "tensorflow"
9
+ else:
10
+ raise ImportError("Neither PyTorch nor TensorFlow is installed. Please install one of them.")
11
+
12
+ def get_backend():
13
+ """Returns the detected backend: 'torch' or 'tensorflow'"""
14
+ return _BACKEND
@@ -0,0 +1,227 @@
1
+ """
2
+ Backend Manager / Dispatcher
3
+
4
+ Provides a unified API that dynamically routes calls to the appropriate
5
+ framework implementation (PyTorch or TensorFlow) based on the provided
6
+ model/tensor types or the detected default backend.
7
+
8
+ Usage:
9
+ from ToTf import SmartSummary
10
+ ss = SmartSummary(model_or_args...)
11
+
12
+ This file avoids heavy imports at module import time and only imports
13
+ framework modules lazily when needed.
14
+ """
15
+ from typing import Any, Optional, Callable, Dict
16
+ import importlib
17
+ import inspect
18
+
19
+ from . import backend as _backend_pkg
20
+
21
+
22
+ def _import_pytorch_module(name: str):
23
+ try:
24
+ return importlib.import_module(f"ToTf.pytorch.{name}")
25
+ except Exception:
26
+ return None
27
+
28
+
29
+ def _import_tensorflow_module(name: str):
30
+ try:
31
+ return importlib.import_module(f"ToTf.tenf.{name}")
32
+ except Exception:
33
+ return None
34
+
35
+
36
+ def _is_torch_tensor(obj: Any) -> bool:
37
+ try:
38
+ import torch
39
+ return isinstance(obj, torch.Tensor) or isinstance(obj, torch.nn.Module)
40
+ except Exception:
41
+ return False
42
+
43
+
44
+ def _is_tf_tensor(obj: Any) -> bool:
45
+ try:
46
+ import tensorflow as tf
47
+ return isinstance(obj, tf.Tensor) or isinstance(obj, tf.keras.Model)
48
+ except Exception:
49
+ return False
50
+
51
+
52
+ def _choose_backend_from_obj(obj: Any) -> Optional[str]:
53
+ if obj is None:
54
+ return None
55
+ if _is_torch_tensor(obj):
56
+ return "torch"
57
+ if _is_tf_tensor(obj):
58
+ return "tensorflow"
59
+ return None
60
+
61
+
62
+ def get_default_backend() -> str:
63
+ return _backend_pkg.get_backend()
64
+
65
+
66
+ def _load_backend_impl(backend_name: str, component: str):
67
+ if backend_name == "torch":
68
+ mod = _import_pytorch_module(component)
69
+ return mod
70
+ elif backend_name == "tensorflow":
71
+ mod = _import_tensorflow_module(component)
72
+ return mod
73
+ return None
74
+
75
+
76
+ def _select_backend_for_args(*args, **kwargs) -> str:
77
+ # Try to pick a backend from any args/kwargs by checking types
78
+ for a in list(args) + list(kwargs.values()):
79
+ b = _choose_backend_from_obj(a)
80
+ if b:
81
+ return b
82
+ # fallback to detected default
83
+ return get_default_backend()
84
+
85
+
86
+ def SmartSummary(*args, **kwargs):
87
+ """Factory that returns a SmartSummary instance from the appropriate backend.
88
+
89
+ Selection order:
90
+ - If first positional arg is a model object (torch.nn.Module or tf.keras.Model)
91
+ we pick the backend accordingly.
92
+ - Otherwise we inspect all args/kwargs for recognizable types (tensors or models).
93
+ - Fallback to the globally detected backend.
94
+ """
95
+ backend_name = None
96
+ if args:
97
+ backend_name = _choose_backend_from_obj(args[0])
98
+ if backend_name is None:
99
+ backend_name = _select_backend_for_args(*args, **kwargs)
100
+
101
+ impl_mod = _load_backend_impl(backend_name, "smartsummary")
102
+ if impl_mod is None:
103
+ raise ImportError(f"SmartSummary backend '{backend_name}' not available")
104
+
105
+ # The implementation exposes SmartSummary class
106
+ SmartSummaryCls = getattr(impl_mod, "SmartSummary", None)
107
+ if SmartSummaryCls is None:
108
+ raise ImportError(f"SmartSummary class not found in backend module {impl_mod}")
109
+
110
+ return SmartSummaryCls(*args, **kwargs)
111
+
112
+
113
+ def TrainingMonitor(*args, **kwargs):
114
+ backend_name = _select_backend_for_args(*args, **kwargs)
115
+ impl_mod = _load_backend_impl(backend_name, "trainingmonitor")
116
+ if impl_mod is None:
117
+ raise ImportError(f"TrainingMonitor backend '{backend_name}' not available")
118
+ TM = getattr(impl_mod, "TrainingMonitor", None)
119
+ if TM is None:
120
+ raise ImportError(f"TrainingMonitor class not found in backend module {impl_mod}")
121
+ return TM(*args, **kwargs)
122
+
123
+
124
+ def ModelView(*args, **kwargs):
125
+ backend_name = _select_backend_for_args(*args, **kwargs)
126
+ impl_mod = _load_backend_impl(backend_name, "modelview")
127
+ if impl_mod is None:
128
+ raise ImportError(f"ModelView backend '{backend_name}' not available")
129
+ MV = getattr(impl_mod, "ModelView", None)
130
+ if MV is None:
131
+ raise ImportError(f"ModelView class not found in backend module {impl_mod}")
132
+ return MV(*args, **kwargs)
133
+
134
+
135
+ def draw_graph(*args, **kwargs):
136
+ """Dispatch to the backend-specific convenience draw_graph function.
137
+
138
+ This will load the backend's `modelview` component and call its
139
+ `draw_graph` function. Selection of backend follows the same rules as
140
+ other factories (inspect args for model/tensor types, then fallback to
141
+ detected default).
142
+ """
143
+ backend_name = _select_backend_for_args(*args, **kwargs)
144
+ impl_mod = _load_backend_impl(backend_name, "modelview")
145
+ if impl_mod is None:
146
+ raise ImportError(f"draw_graph backend '{backend_name}' not available")
147
+ dg = getattr(impl_mod, "draw_graph", None)
148
+ if dg is None:
149
+ raise ImportError(f"draw_graph function not found in backend module {impl_mod}")
150
+ return dg(*args, **kwargs)
151
+
152
+
153
+ # Allow users to register custom backend modules (advanced)
154
+ _CUSTOM: Dict[str, Dict[str, Any]] = {}
155
+
156
+
157
+ def register_backend(name: str, components: Dict[str, Any]):
158
+ _CUSTOM[name] = components
159
+
160
+
161
+ def get_backend_for_obj(obj: Any) -> str:
162
+ b = _choose_backend_from_obj(obj)
163
+ if b:
164
+ return b
165
+ return get_default_backend()
166
+
167
+
168
+ def get_component(component: str, backend_name: Optional[str] = None):
169
+ """Return the backend-specific component module.
170
+
171
+ Args:
172
+ component: name of the component module (e.g. 'utils', 'smartsummary')
173
+ backend_name: 'torch' or 'tensorflow'. If None, uses detected default.
174
+
175
+ Returns:
176
+ Module object or raises ImportError if unavailable.
177
+ """
178
+ if backend_name is None:
179
+ backend_name = get_default_backend()
180
+
181
+ mod = _load_backend_impl(backend_name, component)
182
+ if mod is None:
183
+ raise ImportError(f"Component '{component}' not available for backend '{backend_name}'")
184
+ return mod
185
+
186
+
187
+ def toONNX(*args, backend_name: Optional[str] = None, **kwargs):
188
+ """
189
+ Dispatch to backend-specific toONNX implementation.
190
+
191
+ The function will try to infer backend from the first positional argument
192
+ (model) if available, otherwise use `backend_name` or the default detected backend.
193
+ """
194
+ # Try to infer backend from args
195
+ b = None
196
+ if args:
197
+ b = _choose_backend_from_obj(args[0])
198
+ if b is None:
199
+ b = backend_name or get_default_backend()
200
+
201
+ impl_mod = _load_backend_impl(b, "utils")
202
+ if impl_mod is None:
203
+ raise ImportError(f"toONNX utils not available for backend '{b}'")
204
+
205
+ fn = getattr(impl_mod, "toONNX", None)
206
+ if fn is None:
207
+ raise ImportError(f"toONNX not implemented in backend utils for '{b}'")
208
+
209
+ return fn(*args, **kwargs)
210
+
211
+
212
+ def fromONNX(onnx_path: str, *args, backend_name: Optional[str] = None, **kwargs):
213
+ """
214
+ Dispatch to a backend-agnostic ONNX inference wrapper. This currently uses onnxruntime
215
+ under the hood from each backend utils module for consistency.
216
+ """
217
+ # backend_name is less important here; both backends use onnxruntime wrapper
218
+ b = backend_name or get_default_backend()
219
+ impl_mod = _load_backend_impl(b, "utils")
220
+ if impl_mod is None:
221
+ raise ImportError(f"fromONNX utils not available for backend '{b}'")
222
+
223
+ fn = getattr(impl_mod, "fromONNX", None)
224
+ if fn is None:
225
+ raise ImportError(f"fromONNX not implemented in backend utils for '{b}'")
226
+
227
+ return fn(onnx_path, *args, **kwargs)
@@ -1,17 +1,17 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ToTf
3
- Version: 0.2.3
3
+ Version: 0.2.5
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
6
  Author: Akshay, Shyamanth Reddy
7
7
  Author-email: akshay.r2023@vitstudent.ac.in
8
8
  License: Apache-2.0
9
- Project-URL: Homepage, https://github.com/yourusername/ToTf
10
- Project-URL: Documentation, https://github.com/yourusername/ToTf#readme
11
- Project-URL: Repository, https://github.com/yourusername/ToTf
12
- Project-URL: Bug Tracker, https://github.com/yourusername/ToTf/issues
9
+ Project-URL: Homepage, https://github.com/Akshay-Ramesh-VITC/ToTf
10
+ Project-URL: Documentation, https://github.com/Akshay-Ramesh-VITC/ToTf#readme
11
+ Project-URL: Repository, https://github.com/Akshay-Ramesh-VITC/ToTf
12
+ Project-URL: Bug Tracker, https://github.com/Akshay-Ramesh-VITC/ToTf/issues
13
13
  Keywords: pytorch,tensorflow,deep-learning,neural-networks,model-visualization,training-monitoring,machine-learning
14
- Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Development Status :: 4 - Beta
15
15
  Classifier: Intended Audience :: Developers
16
16
  Classifier: Intended Audience :: Science/Research
17
17
  Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
@@ -2,23 +2,14 @@ LICENSE
2
2
  README.md
3
3
  pyproject.toml
4
4
  setup.py
5
+ ToTf/__init__.py
6
+ ToTf/backend.py
7
+ ToTf/backend_manager.py
5
8
  ToTf.egg-info/PKG-INFO
6
9
  ToTf.egg-info/SOURCES.txt
7
10
  ToTf.egg-info/dependency_links.txt
8
11
  ToTf.egg-info/requires.txt
9
12
  ToTf.egg-info/top_level.txt
10
- pytorch/README.md
11
- pytorch/__init__.py
12
- pytorch/modelview.py
13
- pytorch/smartsummary.py
14
- pytorch/trainingmonitor.py
15
- pytorch/utils.py
16
- tenf/README.md
17
- tenf/__init__.py
18
- tenf/computation_nodes.py
19
- tenf/modelview.py
20
- tenf/smartsummary.py
21
- tenf/utils.py
22
13
  test/test_connection_api.py
23
14
  test/test_connections_visual.py
24
15
  test/test_integration.py
@@ -0,0 +1 @@
1
+ ToTf
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "ToTf"
7
- version = "0.2.3"
7
+ version = "0.2.5"
8
8
  description = "A Cross-Library Compatible Library for PyTorch and TensorFlow that provides advanced features for ease of use"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.8"
@@ -23,7 +23,7 @@ keywords = [
23
23
  "machine-learning"
24
24
  ]
25
25
  classifiers = [
26
- "Development Status :: 3 - Alpha",
26
+ "Development Status :: 4 - Beta",
27
27
  "Intended Audience :: Developers",
28
28
  "Intended Audience :: Science/Research",
29
29
  "Topic :: Scientific/Engineering :: Artificial Intelligence",
@@ -105,13 +105,13 @@ test = [
105
105
  ]
106
106
 
107
107
  [project.urls]
108
- Homepage = "https://github.com/yourusername/ToTf"
109
- Documentation = "https://github.com/yourusername/ToTf#readme"
110
- Repository = "https://github.com/yourusername/ToTf"
111
- "Bug Tracker" = "https://github.com/yourusername/ToTf/issues"
108
+ Homepage = "https://github.com/Akshay-Ramesh-VITC/ToTf"
109
+ Documentation = "https://github.com/Akshay-Ramesh-VITC/ToTf#readme"
110
+ Repository = "https://github.com/Akshay-Ramesh-VITC/ToTf"
111
+ "Bug Tracker" = "https://github.com/Akshay-Ramesh-VITC/ToTf/issues"
112
112
 
113
- [tool.setuptools]
114
- packages = ["pytorch", "tenf"]
113
+ [tool.setuptools.packages.find]
114
+ include = ["ToTf"]
115
115
 
116
116
  [tool.setuptools.package-data]
117
117
  "*" = ["*.md", "*.json"]
@@ -9,7 +9,7 @@ with open("README.md", "r", encoding="utf-8") as fh:
9
9
 
10
10
  setup(
11
11
  name="ToTf",
12
- version="0.2.2",
12
+ version="0.2.5",
13
13
  author="Akshay",
14
14
  author_email="akshay.r2023@vitstudent.ac.in",
15
15
  description="A Cross-Library Compatible Library for PyTorch and TensorFlow",
@@ -1,2 +0,0 @@
1
- pytorch
2
- tenf
@@ -1,200 +0,0 @@
1
- # PyTorch Module for ToTf
2
-
3
- This module contains PyTorch-specific implementations.
4
-
5
- ## Modules
6
-
7
- ### TrainingMonitor
8
-
9
- A comprehensive training monitor that integrates seamlessly with PyTorch training loops.
10
-
11
- ### SmartSummary
12
-
13
- Advanced model analysis tool that goes beyond basic `model.summary()` with bottleneck detection and gradient tracking.
14
-
15
- ---
16
-
17
- ## TrainingMonitor
18
-
19
- A comprehensive training monitor that integrates seamlessly with PyTorch training loops.
20
-
21
- ### Features
22
- - Real-time progress bars with metric display
23
- - Automatic CSV logging with timestamps
24
- - Running averages for all metrics
25
- - RAM and VRAM monitoring
26
- - Crash-resistant (auto-flush)
27
-
28
- ### Usage Example
29
-
30
- ```python
31
- from ToTf import TrainingMonitor
32
-
33
- # Wrap your DataLoader
34
- epochs = 5
35
-
36
- for epoch in range(epochs):
37
- monitor = TrainingMonitor(
38
- train_loader,
39
- desc=f"Epoch {epoch + 1}",
40
- log_file=f"train_log_epoch_{epoch + 1}.csv"
41
- )
42
-
43
- # Iterate through batches
44
- for batch in monitor:
45
- # Your training logic here
46
- loss = training_step(batch)
47
-
48
- # Log metrics
49
- monitor.log({
50
- 'loss': loss.item(),
51
- 'lr': optimizer.param_groups[0]['lr']
52
- })
53
- ```
54
-
55
- ### CSV Output Format
56
-
57
- The log file contains:
58
- - `timestamp`: Time of logging
59
- - `step`: Current step number
60
- - `<metric_name>`: Your logged metrics (running average)
61
- - `RAM_pct`: RAM usage percentage
62
- - `VRAM_gb`: GPU memory usage in GB
63
-
64
- ### Notes
65
-
66
- - The monitor automatically tracks running averages of all metrics
67
- - Metrics are flushed to disk after each log call for crash safety
68
- - VRAM is only logged when CUDA is available
69
- - Compatible with any PyTorch DataLoader or iterable
70
-
71
- ---
72
-
73
- ## SmartSummary
74
-
75
- Advanced model summary with bottleneck detection and gradient analysis.
76
-
77
- ### Features
78
- - **Comprehensive Analysis**: Shows layer types, shapes, and parameters
79
- - **Bottleneck Detection**: Identifies layers that may slow down training
80
- - **Gradient Tracking**: Monitors gradient variance to find unstable layers
81
- - **Memory Estimation**: Calculates memory usage per layer
82
- - **Export Options**: Save to file or export as dictionary
83
- - **Works with Complex Models**: Handles nested architectures and residual connections
84
-
85
- ### Usage Example
86
-
87
- ```python
88
- from ToTf import SmartSummary
89
- import torch.nn as nn
90
-
91
- # Create your model
92
- model = YourModel()
93
-
94
- # Basic analysis
95
- summary = SmartSummary(model, input_size=(3, 224, 224))
96
- summary.show()
97
-
98
- # With gradient tracking
99
- summary = SmartSummary(
100
- model,
101
- input_size=(3, 224, 224),
102
- track_gradients=True # Requires backward pass
103
- )
104
- summary.show()
105
-
106
- # Get bottlenecks programmatically
107
- bottlenecks = summary.get_bottlenecks(top_n=5)
108
- for bn in bottlenecks:
109
- print(f"Bottleneck: {bn['layer']}")
110
- print(f" Score: {bn['score']:.2f}")
111
- print(f" Reasons: {', '.join(bn['reasons'])}")
112
- print(f" Parameters: {bn['params']:,}")
113
-
114
- # Export analysis
115
- summary.save_to_file("model_analysis.txt")
116
- data = summary.to_dict()
117
- ```
118
-
119
- ### Parameters
120
-
121
- - `model` (nn.Module): PyTorch model to analyze
122
- - `input_size` (Tuple, optional): Input tensor shape excluding batch dimension
123
- - Example: `(3, 224, 224)` for RGB images
124
- - If omitted, only parameter counting is performed
125
- - `batch_size` (int): Batch size for shape inference (default: 1)
126
- - `device` (str): Device for analysis - 'cpu' or 'cuda' (default: 'cpu')
127
- - `track_gradients` (bool): Whether to track gradient statistics (default: False)
128
- - Requires a forward and backward pass
129
- - Useful for identifying training instabilities
130
-
131
- ### Methods
132
-
133
- - `show(show_bottlenecks=True)`: Display formatted summary table
134
- - `get_bottlenecks(top_n=5)`: Get list of bottleneck layers
135
- - `to_dict()`: Export complete analysis as dictionary
136
- - `save_to_file(filename)`: Save summary to text file
137
-
138
- ### Bottleneck Detection
139
-
140
- SmartSummary identifies bottlenecks based on:
141
-
142
- 1. **Parameter Count**: Layers with >10% of total parameters
143
- 2. **Gradient Variance**: High variance indicates potential instability
144
- 3. **Output Size**: Large intermediate tensors (>10MB)
145
-
146
- Each bottleneck is scored and ranked. Higher scores indicate more critical bottlenecks.
147
-
148
- ### Output Format
149
-
150
- The summary table shows:
151
- - **Layer (type)**: Layer class name
152
- - **Output Shape**: Tensor dimensions after this layer
153
- - **Param #**: Number of parameters in this layer
154
- - **Trainable**: Whether layer has trainable parameters (✓/✗)
155
- - **Gradient Stats** (if tracking enabled): Variance, mean, and max
156
-
157
- ### Comparison with Other Tools
158
-
159
- | Feature | SmartSummary | torchsummary | torchinfo | model.summary() |
160
- |---------|--------------|--------------|-----------|-----------------|
161
- | Basic layer info | ✓ | ✓ | ✓ | ✓ |
162
- | Bottleneck detection | ✓ | ✗ | ✗ | ✗ |
163
- | Gradient tracking | ✓ | ✗ | ✗ | ✗ |
164
- | Memory estimation | ✓ | ✓ | ✓ | ✗ |
165
- | Export to file/dict | ✓ | ✗ | ✓ | ✗ |
166
- | Complex models | ✓ | Limited | ✓ | Limited |
167
- | PyTorch native | ✓ | ✓ | ✓ | N/A (TF) |
168
-
169
- ### Advanced Example
170
-
171
- ```python
172
- # Compare different architectures
173
- models = {
174
- "ResNet18": resnet18(),
175
- "VGG16": vgg16(),
176
- "EfficientNet": efficientnet_b0()
177
- }
178
-
179
- for name, model in models.items():
180
- print(f"\n{'='*50}")
181
- print(f"Analyzing {name}")
182
- print(f"{'='*50}")
183
-
184
- summary = SmartSummary(model, input_size=(3, 224, 224))
185
- bottlenecks = summary.get_bottlenecks(top_n=3)
186
-
187
- print(f"Total parameters: {summary.total_params:,}")
188
- print(f"Top bottleneck: {bottlenecks[0]['layer']}")
189
- print(f" Score: {bottlenecks[0]['score']:.2f}")
190
- ```
191
-
192
- ### Notes
193
-
194
- - The monitor automatically tracks running averages of all metrics
195
- - Metrics are flushed to disk after each log call for crash safety
196
- - VRAM is only logged when CUDA is available
197
- - Compatible with any PyTorch DataLoader or iterable
198
- - For very large models, omit `input_size` to skip forward pass
199
- - Gradient tracking adds overhead - use during model design phase
200
- - Works with models containing skip connections, attention mechanisms, etc.
@@ -1,28 +0,0 @@
1
- """
2
- PyTorch-specific modules for ToTf
3
- """
4
-
5
- from .trainingmonitor import TrainingMonitor
6
- from .smartsummary import SmartSummary
7
- from .modelview import ModelView, draw_graph
8
- from .utils import (
9
- lazy_flatten,
10
- get_flatten_size,
11
- loss_ncc,
12
- ncc_score,
13
- LRFinder,
14
- find_lr
15
- )
16
-
17
- __all__ = [
18
- "TrainingMonitor",
19
- "SmartSummary",
20
- "ModelView",
21
- "draw_graph",
22
- "lazy_flatten",
23
- "get_flatten_size",
24
- "loss_ncc",
25
- "ncc_score",
26
- "LRFinder",
27
- "find_lr"
28
- ]