deepsuite 1.0.0__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 (158) hide show
  1. deepsuite/README.md +261 -0
  2. deepsuite/__init__.py +42 -0
  3. deepsuite/callbacks/README.md +79 -0
  4. deepsuite/callbacks/__init__.py +17 -0
  5. deepsuite/callbacks/base.py +111 -0
  6. deepsuite/callbacks/embedding_logger.py +101 -0
  7. deepsuite/callbacks/kendryte.py +122 -0
  8. deepsuite/callbacks/onnx.py +123 -0
  9. deepsuite/callbacks/tensor_rt.py +197 -0
  10. deepsuite/callbacks/tflite.py +74 -0
  11. deepsuite/callbacks/torchscript.py +115 -0
  12. deepsuite/callbacks/tsne_laplace_callback.py +83 -0
  13. deepsuite/config/__init__.py +1 -0
  14. deepsuite/config/config_manager.py +63 -0
  15. deepsuite/heads/README.md +98 -0
  16. deepsuite/heads/__init__.py +7 -0
  17. deepsuite/heads/box.py +35 -0
  18. deepsuite/heads/centernet.py +49 -0
  19. deepsuite/heads/classification.py +17 -0
  20. deepsuite/heads/heatmap.py +31 -0
  21. deepsuite/heads/language_modeling.py +331 -0
  22. deepsuite/layers/README.md +134 -0
  23. deepsuite/layers/__init__.py +21 -0
  24. deepsuite/layers/attention/__init__.py +14 -0
  25. deepsuite/layers/attention/kv_compression.py +181 -0
  26. deepsuite/layers/attention/mla.py +264 -0
  27. deepsuite/layers/attention/rope.py +131 -0
  28. deepsuite/layers/bottleneck.py +152 -0
  29. deepsuite/layers/complex.py +65 -0
  30. deepsuite/layers/dft.py +112 -0
  31. deepsuite/layers/hermite.py +81 -0
  32. deepsuite/layers/laguerre.py +82 -0
  33. deepsuite/layers/moe.py +490 -0
  34. deepsuite/lightning_base/README.md +209 -0
  35. deepsuite/lightning_base/__init__.py +1 -0
  36. deepsuite/lightning_base/continual_learning_manager.py +85 -0
  37. deepsuite/lightning_base/dataset/__init__.py +10 -0
  38. deepsuite/lightning_base/dataset/audio_loader.py +44 -0
  39. deepsuite/lightning_base/dataset/base_loader.py +50 -0
  40. deepsuite/lightning_base/dataset/image_loader.py +64 -0
  41. deepsuite/lightning_base/dataset/text_loader.py +344 -0
  42. deepsuite/lightning_base/dataset/universal_set.py +22 -0
  43. deepsuite/lightning_base/module.py +356 -0
  44. deepsuite/lightning_base/trainer.py +178 -0
  45. deepsuite/loss/README.md +189 -0
  46. deepsuite/loss/__init__.py +54 -0
  47. deepsuite/loss/bbox.py +228 -0
  48. deepsuite/loss/centernet.py +29 -0
  49. deepsuite/loss/classification.py +47 -0
  50. deepsuite/loss/detection.py +198 -0
  51. deepsuite/loss/dfl.py +122 -0
  52. deepsuite/loss/distill.py +24 -0
  53. deepsuite/loss/focal.py +265 -0
  54. deepsuite/loss/heat.py +23 -0
  55. deepsuite/loss/keypoint.py +72 -0
  56. deepsuite/loss/language_modeling.py +339 -0
  57. deepsuite/loss/lwf.py +26 -0
  58. deepsuite/loss/mel.py +62 -0
  59. deepsuite/loss/rmse.py +53 -0
  60. deepsuite/loss/segmentation.py +244 -0
  61. deepsuite/loss/snr.py +94 -0
  62. deepsuite/loss/varifocal.py +146 -0
  63. deepsuite/metric/README.md +224 -0
  64. deepsuite/metric/__init__.py +1 -0
  65. deepsuite/metric/bbox_iou.py +163 -0
  66. deepsuite/metric/confidence_matrix.py +22 -0
  67. deepsuite/metric/detection.py +73 -0
  68. deepsuite/metric/map.py +46 -0
  69. deepsuite/metric/norm.py +22 -0
  70. deepsuite/metric/probiou.py +53 -0
  71. deepsuite/model/README.md +279 -0
  72. deepsuite/model/__init__.py +23 -0
  73. deepsuite/model/backend_adapter.py +72 -0
  74. deepsuite/model/beamforming/__init__.py +1 -0
  75. deepsuite/model/beamforming/beamforming.py +26 -0
  76. deepsuite/model/complex.py +46 -0
  77. deepsuite/model/conv.py +565 -0
  78. deepsuite/model/detection/__init__.py +1 -0
  79. deepsuite/model/detection/centernet.py +291 -0
  80. deepsuite/model/detection/darknet.py +20 -0
  81. deepsuite/model/detection/detection.py +141 -0
  82. deepsuite/model/detection/efficient.py +183 -0
  83. deepsuite/model/detection/head.py +16 -0
  84. deepsuite/model/detection/mobile.py +307 -0
  85. deepsuite/model/detection/resnet.py +157 -0
  86. deepsuite/model/detection/yolo.py +232 -0
  87. deepsuite/model/doa.py +43 -0
  88. deepsuite/model/feature/__init__.py +1 -0
  89. deepsuite/model/feature/darknet.py +97 -0
  90. deepsuite/model/feature/efficientnet.py +285 -0
  91. deepsuite/model/feature/fpn.py +36 -0
  92. deepsuite/model/feature/mobile.py +182 -0
  93. deepsuite/model/feature/resnet.py +128 -0
  94. deepsuite/model/feature/wavenet.py +551 -0
  95. deepsuite/model/feature/yolo.py +157 -0
  96. deepsuite/model/llm/__init__.py +17 -0
  97. deepsuite/model/llm/centernet.py +81 -0
  98. deepsuite/model/llm/deepseek.py +570 -0
  99. deepsuite/model/llm/gpt.py +616 -0
  100. deepsuite/model/loftr/__init__.py +0 -0
  101. deepsuite/model/loftr/coarse_matching.py +265 -0
  102. deepsuite/model/loftr/encoder_layer.py +49 -0
  103. deepsuite/model/loftr/fine_matching.py +127 -0
  104. deepsuite/model/loftr/fine_preprocess.py +89 -0
  105. deepsuite/model/loftr/full_attention.py +36 -0
  106. deepsuite/model/loftr/linear_attention.py +42 -0
  107. deepsuite/model/loftr/loftr.py +206 -0
  108. deepsuite/model/loftr/position_encoding.py +49 -0
  109. deepsuite/model/loftr/resnet_fpn.py +29 -0
  110. deepsuite/model/loftr/transformer.py +47 -0
  111. deepsuite/model/polynomial.py +204 -0
  112. deepsuite/model/residual.py +74 -0
  113. deepsuite/model/rnn.py +104 -0
  114. deepsuite/model/siamese.py +152 -0
  115. deepsuite/model/stn.py +60 -0
  116. deepsuite/model/tracking/__init__.py +0 -0
  117. deepsuite/model/tracking/tracking.py +113 -0
  118. deepsuite/model/tracking.py +61 -0
  119. deepsuite/model/unet.py +502 -0
  120. deepsuite/svm/__init__.py +1 -0
  121. deepsuite/svm/kernels.py +235 -0
  122. deepsuite/svm/svm.py +136 -0
  123. deepsuite/tracker/README.md +292 -0
  124. deepsuite/tracker/__init__.py +1 -0
  125. deepsuite/tracker/inference.py +46 -0
  126. deepsuite/tracker/reid_encoder.py +45 -0
  127. deepsuite/tracker/rnn_tracker.py +20 -0
  128. deepsuite/tracker/tracker.py +441 -0
  129. deepsuite/tracker/tracker_manager.py +183 -0
  130. deepsuite/typing.py +18 -0
  131. deepsuite/utils/README.md +331 -0
  132. deepsuite/utils/__init__.py +1 -0
  133. deepsuite/utils/anchor.py +20 -0
  134. deepsuite/utils/array_calibration.py +88 -0
  135. deepsuite/utils/autocast.py +10 -0
  136. deepsuite/utils/bbox.py +23 -0
  137. deepsuite/utils/complex.py +17 -0
  138. deepsuite/utils/device.py +62 -0
  139. deepsuite/utils/head_expansion.py +19 -0
  140. deepsuite/utils/hermite.py +63 -0
  141. deepsuite/utils/hw.py +120 -0
  142. deepsuite/utils/image.py +21 -0
  143. deepsuite/utils/laguerre.py +60 -0
  144. deepsuite/utils/rnn.py +44 -0
  145. deepsuite/utils/search_space.py +20 -0
  146. deepsuite/utils/summery.py +11 -0
  147. deepsuite/utils/taskAlignedAssigner.py +337 -0
  148. deepsuite/utils/teacher.py +79 -0
  149. deepsuite/utils/tensor.py +26 -0
  150. deepsuite/utils/tsignal.py +175 -0
  151. deepsuite/utils/xy.py +72 -0
  152. deepsuite/viz/README.md +294 -0
  153. deepsuite/viz/__init__.py +1 -0
  154. deepsuite/viz/embedding.py +53 -0
  155. deepsuite-1.0.0.dist-info/METADATA +447 -0
  156. deepsuite-1.0.0.dist-info/RECORD +158 -0
  157. deepsuite-1.0.0.dist-info/WHEEL +4 -0
  158. deepsuite-1.0.0.dist-info/licenses/LICENSE +197 -0
deepsuite/README.md ADDED
@@ -0,0 +1,261 @@
1
+ # DeepSuite
2
+
3
+ This is the main directory for the DeepSuite source code.
4
+
5
+ ## Module Overview
6
+
7
+ Each subdirectory contains its own README.md with detailed documentation.
8
+
9
+ ### 🧠 Language Models & NLP
10
+
11
+ - **[layers/](layers/)** - Neural Network Layers
12
+
13
+ - Attention Mechanisms (MLA, RoPE, KV-Compression)
14
+ - Mixture-of-Experts (MoE)
15
+ - Specialized Layers (Complex, Hermite, Laguerre)
16
+
17
+ - **[modules/](modules/)** - PyTorch Lightning Modules
18
+
19
+ - GPT-2/GPT-3
20
+ - DeepSeek-V3 with MLA and MoE
21
+ - YOLO, CenterNet
22
+
23
+ - **[heads/](heads/)** - Output Heads
24
+
25
+ - Language Model Head
26
+ - Multi-Token Prediction Head
27
+ - Classification, Detection, Heatmap Heads
28
+
29
+ - **[loss/](loss/)** - Loss Functions
30
+ - Language Modeling Losses
31
+ - Multi-Token Prediction Loss
32
+ - Detection Losses (Focal, GIoU, DFL)
33
+ - Knowledge Distillation
34
+
35
+ ### 👁️ Computer Vision
36
+
37
+ - **[model/](model/)** - Model Architectures
38
+
39
+ - Object Detection (YOLO, CenterNet, EfficientDet)
40
+ - Feature Extraction (ResNet, EfficientNet, DarkNet, FPN)
41
+ - Tracking
42
+
43
+ - **[tracker/](tracker/)** - Multi-Object Tracking
44
+
45
+ - SORT, DeepSORT, ByteTrack
46
+ - Re-Identification
47
+ - Tracking Pipeline
48
+
49
+ - **[metric/](metric/)** - Evaluation Metrics
50
+ - Mean Average Precision (mAP)
51
+ - Detection Metrics
52
+ - Confusion Matrix
53
+
54
+ ### 🎵 Audio Processing
55
+
56
+ - **[model/beamforming/](model/beamforming/)** - Audio Beamforming
57
+ - See also: `model/complex.py`, `model/doa.py`, `model/rnn.py`
58
+
59
+ ### ⚙️ Training & Utilities
60
+
61
+ - **[lightning_base/](lightning_base/)** - PyTorch Lightning Base
62
+
63
+ - Base Lightning Module
64
+ - Dataset Loaders (Text, Image, Audio)
65
+ - Continual Learning Manager
66
+
67
+ - **[callbacks/](callbacks/)** - Training Callbacks
68
+
69
+ - TorchScript, TensorRT Export
70
+ - Embedding Logger
71
+ - t-SNE Visualization
72
+
73
+ - **[utils/](utils/)** - Utility Functions
74
+
75
+ - Bounding Box Operations
76
+ - Image Processing
77
+ - Tensor Utilities
78
+ - Device Management
79
+
80
+ - **[viz/](viz/)** - Visualization
81
+ - Embedding Visualization (t-SNE, UMAP, PCA)
82
+
83
+ ### 🔧 Specialized
84
+
85
+ - **[config/](config/)** - Configuration Management
86
+ - **[svm/](svm/)** - Support Vector Machines
87
+ - **[conv/](conv/)** - Convolutional Neural Networks
88
+
89
+ ## Quick Access
90
+
91
+ ### Key Files
92
+
93
+ ```
94
+ src/deepsuite/
95
+ ├── modules/
96
+ │ ├── gpt.py # GPT-2/GPT-3 Implementation
97
+ │ ├── deepseek.py # DeepSeek-V3 Implementation
98
+ │ ├── yolo.py # YOLO Object Detection
99
+ │ └── centernet.py # CenterNet Detection
100
+
101
+ ├── layers/
102
+ │ ├── attention/ # Attention Mechanisms
103
+ │ │ ├── mla.py # Multi-Head Latent Attention
104
+ │ │ └── rope.py # Rotary Position Embeddings
105
+ │ └── moe.py # Mixture-of-Experts
106
+
107
+ ├── lightning_base/dataset/
108
+ │ ├── text_loader.py # Text Dataset for LLMs
109
+ │ ├── image_loader.py # Image Dataset
110
+ │ └── audio_loader.py # Audio Dataset
111
+
112
+ └── loss/
113
+ ├── classification.py # Cross-Entropy, Focal Loss
114
+ ├── mtp_loss.py # Multi-Token Prediction Loss
115
+ └── detection.py # Detection Losses
116
+ ```
117
+
118
+ ## Usage
119
+
120
+ ### Import Examples
121
+
122
+ ```python
123
+ # Language Models
124
+ from deepsuite.modules import GPTModule, DeepSeekModule
125
+ from deepsuite.layers.attention import MultiHeadLatentAttention
126
+ from deepsuite.layers import DeepSeekMoE
127
+
128
+ # Object Detection
129
+ from deepsuite.modules import YOLOModule, CenterNetModule
130
+ from deepsuite.model.detection import YOLO, CenterNet
131
+
132
+ # Datasets
133
+ from deepsuite.lightning_base.dataset import TextDataLoader, ImageDataLoader
134
+
135
+ # Losses
136
+ from deepsuite.loss import CrossEntropyLoss, MTPLoss, FocalLoss, GIoULoss
137
+
138
+ # Metrics
139
+ from deepsuite.metric import MeanAveragePrecision, DetectionMetrics
140
+
141
+ # Tracking
142
+ from deepsuite.tracker import ObjectTracker, DeepSORTTracker
143
+
144
+ # Utils
145
+ from deepsuite.utils import bbox, image, device
146
+
147
+ # Visualization
148
+ from deepsuite.viz import EmbeddingVisualizer
149
+ ```
150
+
151
+ ## Documentation
152
+
153
+ ### READMEs
154
+
155
+ Each module has its own README.md:
156
+
157
+ - [callbacks/README.md](callbacks/README.md) - Training Callbacks
158
+ - [heads/README.md](heads/README.md) - Output Heads
159
+ - [layers/README.md](layers/README.md) - Neural Network Layers
160
+ - [lightning_base/README.md](lightning_base/README.md) - Lightning Base Components
161
+ - [loss/README.md](loss/README.md) - Loss Functions
162
+ - [metric/README.md](metric/README.md) - Evaluation Metrics
163
+ - [model/README.md](model/README.md) - Model Architectures
164
+ - [modules/README.md](modules/README.md) - Lightning Modules
165
+ - [tracker/README.md](tracker/README.md) - Object Tracking
166
+ - [utils/README.md](utils/README.md) - Utility Functions
167
+ - [viz/README.md](viz/README.md) - Visualization Tools
168
+
169
+ ### Complete Documentation
170
+
171
+ See [docs/modules_overview.md](../../docs/modules_overview.md) for a complete overview of all modules.
172
+
173
+ ### Specific Topics
174
+
175
+ - [docs/llm_modules.md](../../docs/llm_modules.md) - Language Models (GPT, DeepSeek-V3)
176
+ - [docs/llm_loss_head.md](../../docs/llm_loss_head.md) - LLM Losses & Heads
177
+ - [docs/moe.md](../../docs/moe.md) - Mixture-of-Experts
178
+ - [docs/text_dataset.md](../../docs/text_dataset.md) - Text Data Loading
179
+
180
+ ## Development
181
+
182
+ ### Code Style
183
+
184
+ ```bash
185
+ # Format
186
+ ruff format src/deepsuite
187
+
188
+ # Lint
189
+ ruff check src/deepsuite
190
+
191
+ # Type Checking
192
+ mypy src/deepsuite
193
+ ```
194
+
195
+ ### Testing
196
+
197
+ ```bash
198
+ # All tests
199
+ pytest tests/
200
+
201
+ # Specific module
202
+ pytest tests/test_tensor_rt_export_callback.py
203
+ ```
204
+
205
+ ## Architecture Principles
206
+
207
+ ### 1. Modularity
208
+
209
+ Each component is independently usable:
210
+
211
+ ```python
212
+ # Layer alone
213
+ from deepsuite.layers import DeepSeekMoE
214
+ moe = DeepSeekMoE(d_model=2048, ...)
215
+
216
+ # In custom model
217
+ class MyModel(nn.Module):
218
+ def __init__(self):
219
+ self.moe = DeepSeekMoE(...)
220
+ ```
221
+
222
+ ### 2. Lightning Integration
223
+
224
+ All main models are Lightning Modules:
225
+
226
+ ```python
227
+ from deepsuite.modules import DeepSeekModule
228
+ import pytorch_lightning as pl
229
+
230
+ model = DeepSeekModule(...)
231
+ trainer = pl.Trainer(...)
232
+ trainer.fit(model, datamodule)
233
+ ```
234
+
235
+ ### 3. Composability
236
+
237
+ Components can be freely combined:
238
+
239
+ ```python
240
+ from deepsuite.heads import LMHead
241
+ from deepsuite.loss import CrossEntropyLoss
242
+ from deepsuite.metric import Perplexity
243
+
244
+ class CustomModule(pl.LightningModule):
245
+ def __init__(self):
246
+ self.backbone = ...
247
+ self.head = LMHead(...)
248
+ self.loss_fn = CrossEntropyLoss(...)
249
+ self.metric = Perplexity()
250
+ ```
251
+
252
+ ## More Information
253
+
254
+ - **Main Project**: [README.md](../../README.md)
255
+ - **Documentation**: [docs/](../../docs/)
256
+ - **Examples**: [examples/](../../examples/)
257
+ - **Tests**: [tests/](../../tests/)
258
+
259
+ ---
260
+
261
+ **Version**: 0.2.0 | **License**: Apache 2.0
deepsuite/__init__.py ADDED
@@ -0,0 +1,42 @@
1
+ """APTT - Advanced PyTorch Training Toolkit.
2
+
3
+ A PyTorch Lightning-based framework for deep learning with focus on:
4
+ - Object Detection (YOLO, CenterNet)
5
+ - Object Tracking
6
+ - Continual Learning
7
+ - Audio/Signal Processing
8
+ """
9
+
10
+ __version__ = "1.0.3"
11
+
12
+ # Core Lightning Modules
13
+ from deepsuite.lightning_base.continual_learning_manager import ContinualLearningManager
14
+
15
+ # Base Classes
16
+ from deepsuite.lightning_base.module import BaseModule
17
+ from deepsuite.lightning_base.trainer import BaseTrainer
18
+ from deepsuite.model.backend_adapter import BackboneAdapter
19
+ from deepsuite.model.detection.centernet import CenterNetModel
20
+
21
+ # Model Architectures
22
+ from deepsuite.model.detection.yolo import YOLO
23
+ from deepsuite.modules.centernet import CenterNetModule
24
+ from deepsuite.modules.tracking import TrackingModule
25
+ from deepsuite.modules.yolo import Yolo
26
+
27
+ __all__ = [
28
+ # Version
29
+ "__version__",
30
+ # Lightning Modules (end-to-end trainable)
31
+ "Yolo",
32
+ "CenterNetModule",
33
+ "TrackingModule",
34
+ # Base Classes
35
+ "BaseModule",
36
+ "BaseTrainer",
37
+ "ContinualLearningManager",
38
+ # Model Architectures
39
+ "YOLO",
40
+ "CenterNetModel",
41
+ "BackboneAdapter",
42
+ ]
@@ -0,0 +1,79 @@
1
+ # Callbacks
2
+
3
+ PyTorch Lightning callbacks for export, optimization, and visualization.
4
+
5
+ ## Modules
6
+
7
+ ### Export & Optimization
8
+
9
+ - **`torchscript.py`** - TorchScript export for production deployment
10
+ - **`tensor_rt.py`** - TensorRT optimization for NVIDIA GPUs
11
+
12
+ ### Logging & Visualization
13
+
14
+ - **`embedding_logger.py`** - Embedding visualization during training
15
+ - **`tsne_laplace_callback.py`** - t-SNE and Laplace eigenmap visualization
16
+
17
+ ### Base
18
+
19
+ - **`base.py`** - Base callback class and shared functionality
20
+
21
+ ## Usage
22
+
23
+ ### TorchScript Export
24
+
25
+ ```python
26
+ from deepsuite.callbacks import TorchScriptCallback
27
+
28
+ trainer = pl.Trainer(
29
+ callbacks=[
30
+ TorchScriptCallback(
31
+ export_path="model.pt",
32
+ method="script" # oder "trace"
33
+ )
34
+ ]
35
+ )
36
+ ```
37
+
38
+ ### TensorRT Optimization
39
+
40
+ ```python
41
+ from deepsuite.callbacks import TensorRTCallback
42
+
43
+ trainer = pl.Trainer(
44
+ callbacks=[
45
+ TensorRTCallback(
46
+ export_path="model.engine",
47
+ precision="fp16",
48
+ workspace_size=1 << 30 # 1GB
49
+ )
50
+ ]
51
+ )
52
+ ```
53
+
54
+ ### Embedding Visualization
55
+
56
+ ```python
57
+ from deepsuite.callbacks import EmbeddingLoggerCallback
58
+
59
+ trainer = pl.Trainer(
60
+ callbacks=[
61
+ EmbeddingLoggerCallback(
62
+ log_every_n_epochs=5,
63
+ num_samples=1000
64
+ )
65
+ ]
66
+ )
67
+ ```
68
+
69
+ ## Features
70
+
71
+ - ✅ Automatischer Export am Ende des Trainings
72
+ - ✅ Validierung der exportierten Modelle
73
+ - ✅ Integration mit TensorBoard und Weights & Biases
74
+ - ✅ Flexible Konfiguration per Callback-Parameter
75
+ - ✅ Fehlerbehandlung und Logging
76
+
77
+ ## Weitere Informationen
78
+
79
+ Siehe Hauptdokumentation: [docs/modules_overview.md](../../../docs/modules_overview.md)
@@ -0,0 +1,17 @@
1
+ """Export-Callback Paket."""
2
+
3
+ from .base import ExportBaseCallback
4
+ from .kendryte import KendryteExportCallback
5
+ from .onnx import ONNXExportCallback
6
+ from .tensor_rt import TensorRTExportCallback
7
+ from .tflite import TFLiteExportCallback
8
+ from .torchscript import TorchScriptExportCallback
9
+
10
+ __all__ = [
11
+ "ExportBaseCallback",
12
+ "KendryteExportCallback",
13
+ "ONNXExportCallback",
14
+ "TFLiteExportCallback",
15
+ "TensorRTExportCallback",
16
+ "TorchScriptExportCallback",
17
+ ]
@@ -0,0 +1,111 @@
1
+ """Basisklasse für Modell-Export-Callbacks.
2
+
3
+ Stellt Hilfsfunktionen bereit, um automatisch Beispielbatches zu laden und
4
+ auf das korrekte Gerät zu verschieben, sodass Export-Callbacks (z. B. ONNX,
5
+ TorchScript, TensorRT) konsistent arbeiten können.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+ from loguru import logger
14
+ import pytorch_lightning as pl
15
+ import torch
16
+
17
+ from deepsuite.utils.device import get_best_device
18
+
19
+
20
+ class ExportBaseCallback(pl.callbacks.ModelCheckpoint):
21
+ """Basisklasse für Export-Callbacks mit Batch-Autoloading."""
22
+
23
+ output_dir: Path
24
+ example_input: Any | None
25
+
26
+ def __init__(self, output_dir: str = "models", **kwargs: Any) -> None:
27
+ """Initialisiert den Export-Callback.
28
+
29
+ Args:
30
+ output_dir: Zielverzeichnis für Exports.
31
+ **kwargs: Zusätzliche Argumente, werden an ModelCheckpoint weitergegeben.
32
+ """
33
+ super().__init__(**kwargs)
34
+ self.output_dir = Path(output_dir)
35
+ self.output_dir.mkdir(parents=True, exist_ok=True)
36
+ self.example_input = None # Wird später automatisch gesetzt
37
+
38
+ def get_example_input(self, trainer: pl.Trainer) -> Any | None:
39
+ """Lädt einen Beispielbatch und speichert ihn in `example_input`.
40
+
41
+ Args:
42
+ trainer: PyTorch-Lightning-Trainer.
43
+
44
+ Returns:
45
+ Optional[Any]: Beispielinputbatch (ggf. Tensor oder Strukturen) oder None.
46
+
47
+ Beispiel:
48
+ ```python
49
+ from pytorch_lightning import Trainer
50
+ from deepsuite.callbacks.base import ExportBaseCallback
51
+
52
+ trainer = Trainer(callbacks=[ExportBaseCallback()])
53
+ trainer.fit(model)
54
+ ```
55
+ """
56
+ if self.example_input is None: # Nur einmal laden
57
+ try:
58
+ datamodule = trainer.datamodule
59
+ if datamodule is None:
60
+ logger.error("❌ No DataModule found.")
61
+ return None
62
+
63
+ dataloader = datamodule.train_dataloader()
64
+ if dataloader is None:
65
+ logger.error("❌ No train_dataloader() found.")
66
+ return None
67
+
68
+ batch = next(iter(dataloader)) # Einen Batch entnehmen
69
+
70
+ if isinstance(batch, (tuple, list)):
71
+ self.example_input = batch[0]
72
+ else:
73
+ self.example_input = batch
74
+
75
+ # Auf dasselbe Gerät wie das Modell verschieben
76
+ if trainer.model is not None:
77
+ device = trainer.model.device
78
+ self.example_input = self._move_batch_to_device(self.example_input, device)
79
+
80
+ logger.info(
81
+ "✅ Example batch automatically loaded and moved to the correct device."
82
+ )
83
+
84
+ except Exception as e:
85
+ logger.error(f"❌ Could not load example batch: {e}")
86
+ return None
87
+
88
+ return self.example_input
89
+
90
+ def _move_batch_to_device(self, batch: Any, device: str | torch.device | None = None) -> Any:
91
+ """Verschiebt einen Batch rekursiv auf das angegebene Gerät.
92
+
93
+ Args:
94
+ batch: Tensor oder (verschachtelte) Liste/Tuple/Dict aus Tensors.
95
+ device: Zielgerät als str ('cuda', 'cpu') oder torch.device, oder None.
96
+
97
+ Returns:
98
+ Any: Der auf das Zielgerät verschobene Batch.
99
+ """
100
+ if device is None:
101
+ device_str: str | torch.device = get_best_device()
102
+ else:
103
+ device_str = device
104
+
105
+ if isinstance(batch, torch.Tensor):
106
+ return batch.to(device_str)
107
+ if isinstance(batch, (tuple, list)):
108
+ return type(batch)(self._move_batch_to_device(b, device_str) for b in batch)
109
+ if isinstance(batch, dict):
110
+ return {k: self._move_batch_to_device(v, device_str) for k, v in batch.items()}
111
+ return batch
@@ -0,0 +1,101 @@
1
+ """Embedding Logger module."""
2
+
3
+ from pytorch_lightning import Callback
4
+ from pytorch_lightning.loggers.tensorboard import TensorBoardLogger
5
+ import torch
6
+
7
+ from deepsuite.viz.embedding import log_embedding_plot_to_mlflow
8
+
9
+
10
+ class EmbeddingLoggerCallback(Callback):
11
+ """Logs embedding vectors during validation to TensorBoard and optionally MLflow.
12
+
13
+ This callback collects embeddings and corresponding labels from a limited
14
+ number of validation batches. At the end of the epoch, it visualizes them
15
+ in TensorBoard and optionally logs a TSNE plot to MLflow.
16
+
17
+ Example:
18
+ >>> callback = EmbeddingLoggerCallback(num_batches=3, log_to_mlflow=True)
19
+ >>> trainer = Trainer(callbacks=[callback])
20
+ """
21
+
22
+ def __init__(self, num_batches: int = 1, log_to_mlflow: bool = True) -> None:
23
+ """Initializes the embedding logging callback.
24
+
25
+ Args:
26
+ num_batches (int): Number of validation batches to collect for embedding visualization.
27
+ log_to_mlflow (bool): Whether to log a TSNE plot of embeddings to MLflow.
28
+ """
29
+ self.num_batches = num_batches
30
+ self.embeddings = []
31
+ self.labels = []
32
+ self.log_to_mlflow = log_to_mlflow
33
+
34
+ def on_validation_batch_end(
35
+ self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx=0
36
+ ):
37
+ """Collects embeddings and labels from the current batch during validation.
38
+
39
+ Args:
40
+ trainer (Trainer): The PyTorch Lightning trainer.
41
+ pl_module (LightningModule): The current Lightning model.
42
+ outputs: The outputs from the validation step (unused).
43
+ batch (Tuple[Tensor, Tensor]): The input batch, typically (x, y).
44
+ batch_idx (int): The index of the current batch.
45
+ dataloader_idx (int): Index of the current dataloader (unused).
46
+ """
47
+ if batch_idx >= self.num_batches:
48
+ return
49
+
50
+ x, y = batch
51
+ with torch.no_grad():
52
+ if hasattr(pl_module, "extract_features"):
53
+ features = pl_module.extract_features(x.to(pl_module.device))
54
+ else:
55
+ features = pl_module(x.to(pl_module.device))
56
+
57
+ self.embeddings.append(features.cpu())
58
+ self.labels.append(y.cpu())
59
+
60
+ def on_validation_epoch_end(self, trainer, pl_module):
61
+ """Logs collected embeddings to TensorBoard and optionally to MLflow.
62
+
63
+ At the end of the validation epoch, this method concatenates the stored
64
+ embeddings and labels, then logs them as an embedding projector to
65
+ TensorBoard. If `log_to_mlflow` is True and `pl_module.use_mlflow` is set,
66
+ it also logs a TSNE image to MLflow.
67
+
68
+ Args:
69
+ trainer (Trainer): The PyTorch Lightning trainer.
70
+ pl_module (LightningModule): The current Lightning model.
71
+ """
72
+ if not self.embeddings or not self.labels:
73
+ return
74
+
75
+ embeddings = torch.cat(self.embeddings, dim=0)
76
+ labels = torch.cat(self.labels, dim=0)
77
+
78
+ # TensorBoard Logging
79
+ tb_logger = None
80
+ for logger in trainer.loggers if isinstance(trainer.loggers, list) else [trainer.logger]:
81
+ if isinstance(logger, TensorBoardLogger):
82
+ tb_logger = logger.experiment # SummaryWriter
83
+ break
84
+
85
+ if tb_logger:
86
+ tb_logger.add_embedding(
87
+ mat=embeddings,
88
+ metadata=labels.tolist(),
89
+ global_step=trainer.global_step,
90
+ tag="val_embeddings",
91
+ )
92
+
93
+ # MLflow Logging
94
+ if self.log_to_mlflow and getattr(pl_module, "use_mlflow", False):
95
+ log_embedding_plot_to_mlflow(
96
+ embeddings=embeddings, labels=labels, step=trainer.global_step
97
+ )
98
+
99
+ # Puffer leeren
100
+ self.embeddings.clear()
101
+ self.labels.clear()