API Reference¶
Class extension¶
deeptool.core ¶
Notebook-friendly primitives: class extension and hyperparameter capture.
HyperParameters ¶
Mixin that saves __init__ arguments as attributes and in self.hparams.
Source code in deeptool/core.py
save_hyperparameters ¶
Store the calling __init__'s arguments on the instance.
Reads the declared arguments of the calling frame — positional and keyword-only — so local variables are never captured.
Call super().__init__() first and save_hyperparameters() second.
Each class stores its own arguments, but self.hparams holds the last
call's, so the subclass has to run last to win.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ignore
|
Iterable[str]
|
Argument names to leave out of both the attributes and
|
()
|
Source code in deeptool/core.py
add_to_class ¶
Register the decorated function as a method on Class.
Lets you define a class in one notebook cell and attach methods from later cells, without re-running the class definition.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
Class
|
type
|
The class to attach the method to. |
required |
Returns:
| Type | Description |
|---|---|
Callable[[Callable], Callable]
|
A decorator that registers the function and returns it unchanged, so the |
Callable[[Callable], Callable]
|
name stays usable in the cell that defined it. |
Source code in deeptool/core.py
Data¶
deeptool.data ¶
Data loading contract: training and validation loaders on one object.
DataModule ¶
Bases: HyperParameters
Base class supplying training and validation dataloaders.
Subclasses implement get_dataloader(train) and nothing else.
Call super().__init__() before save_hyperparameters(), or the parent's
defaults overwrite the subclass arguments:
class ToyData(DataModule):
def __init__(self, batch_size=32):
super().__init__()
self.save_hyperparameters()
Source code in deeptool/data.py
get_tensorloader ¶
get_tensorloader(tensors: Sequence[Tensor], train: bool, indices: slice = slice(0, None)) -> torch_data.DataLoader
Wrap a tuple of tensors in a DataLoader.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tensors
|
Sequence[Tensor]
|
Tensors sliced together; the last one holds the targets. |
required |
train
|
bool
|
Shuffles when true. |
required |
indices
|
slice
|
Slice applied to every tensor, for splitting training from validation. |
slice(0, None)
|
Returns:
| Type | Description |
|---|---|
DataLoader
|
A |
Source code in deeptool/data.py
Model¶
deeptool.module ¶
Model contract: nn.Module plus hyperparameter capture and plotting hooks.
Module ¶
Bases: Module, HyperParameters
Base class for your models.
You fill in three things: forward (or just assign self.net), loss, and
configure_optimizers. In a notebook you can attach them from later cells
with @add_to_class.
board and trainer are injected by Trainer.fit.
Source code in deeptool/module.py
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 | |
configure_optimizers ¶
configure_optimizers() -> torch.optim.Optimizer | tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LRScheduler | torch.optim.lr_scheduler.ReduceLROnPlateau]
Build an optimizer and, optionally, a learning-rate scheduler.
Returns:
| Type | Description |
|---|---|
Optimizer | tuple[Optimizer, LRScheduler | ReduceLROnPlateau]
|
An optimizer, or |
Optimizer | tuple[Optimizer, LRScheduler | ReduceLROnPlateau]
|
follows |
Optimizer | tuple[Optimizer, LRScheduler | ReduceLROnPlateau]
|
validation loss whenever validation runs. |
Source code in deeptool/module.py
log ¶
Aggregate one custom scalar under its unchanged name for this interval.
When a live board is attached, the same value is also plotted using the model's current training or validation phase. Calling this method before a Trainer is attached is a no-op.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Free-form metric name stored in progress history. |
required |
value
|
Tensor | float
|
A scalar tensor or plain number. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in deeptool/module.py
plot ¶
Draw one scalar on the live board. A no-op when there is no board.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Curve name. Rendered as |
required |
value
|
Tensor | float
|
A scalar tensor or plain float. |
required |
train
|
bool
|
Selects the training or validation curve. Training points use the active Trainer progress unit on the x-axis. |
required |
Source code in deeptool/module.py
Trainer¶
deeptool.trainer ¶
Training loop: device placement, epochs, loss aggregation, early stopping.
Trainer ¶
Bases: HyperParameters
Runs the training loop over a Module and a DataModule.
All configuration lives on the constructor; fit takes only the model and
the data. One Trainer therefore represents one training setup, and
trainer.hparams records it in full.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_epochs
|
int | None
|
Upper bound on epochs. Supply this or |
None
|
device
|
device | str | None
|
Where to train. Defaults to |
None
|
gradient_clip_val
|
float
|
Clips gradient norm after backward when above zero. |
0
|
plot
|
bool
|
Draws a live loss curve in the notebook. |
True
|
snapshot_best
|
bool
|
Keeps weights from the best monitored progress point. |
True
|
best_path
|
str | Path | None
|
Writes that snapshot to this file instead of memory. |
None
|
best_with_optim
|
bool
|
Also stores optimizer state in the snapshot file, so it can resume training. |
False
|
patience
|
int | None
|
Stops after this many monitor checks without improvement. |
None
|
log_dir
|
str | Path | None
|
Writes run metadata and flushed JSONL progress rows here. |
None
|
monitor
|
str
|
Exact scalar key used for best snapshots and early stopping. |
'val_loss'
|
mode
|
Literal['min', 'max']
|
Whether lower ( |
'min'
|
max_steps
|
int | None
|
Upper bound on completed optimizer updates. Supply this or
|
None
|
log_every_n_steps
|
int
|
Step interval between training records. |
1
|
val_every_n_steps
|
int | None
|
Optional step interval between validation runs. Without it, step mode validates only at the final step. |
None
|
scheduler_interval
|
Literal['auto', 'epoch', 'step']
|
Normal scheduler cadence. |
'auto'
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If training limits, intervals, monitor, mode, or patience are invalid. |
Source code in deeptool/trainer.py
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 | |
best_val_loss
property
¶
Lowest validation loss seen, or None before the first check.
best_epoch
property
¶
Epoch that produced the best score, or None in step mode.
best_step
property
¶
Step that produced the best score, or None in epoch mode.
plot_x ¶
Return the live-plot coordinate for the active training unit.
Source code in deeptool/trainer.py
materialize_lazy_parameters ¶
Materialize lazy layers with a dummy forward pass.
nn.LazyLinear and friends have no parameters until the first forward,
so building an optimizer before one would fail.
Source code in deeptool/trainer.py
restore_best ¶
Load weights from the best value of the configured monitor.
fit never does this on its own. Until you call it the model holds the
last epoch's weights, so you can compare the two.
Only model weights are restored; optimizer state is left alone.
Returns:
| Type | Description |
|---|---|
int
|
The epoch or step value that was restored. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If |
Source code in deeptool/trainer.py
save_checkpoint ¶
Save model, optimizer, progress, and hyperparameters to a file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Destination file. |
required |
Source code in deeptool/trainer.py
load_checkpoint
staticmethod
¶
Restore a checkpoint into model in place.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Checkpoint file. |
required |
model
|
Module
|
Model to restore into. |
required |
optim
|
Optimizer | None
|
Optimizer to restore as well, for resuming training. Leave it out to restore weights only, for inference. |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Stored progress ( |
Source code in deeptool/trainer.py
predict ¶
Run the trained model over data and collect per-sample results.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataModule
|
A |
required |
train
|
bool
|
Uses the training split instead of validation. |
False
|
keep_inputs
|
bool
|
Also collect the input tensors, for visualizing individual samples. |
False
|
Returns:
| Type | Description |
|---|---|
Predictions
|
A |
Source code in deeptool/trainer.py
default_device ¶
Pick the first available accelerator, in the order cuda, mps, cpu.
Returns:
| Type | Description |
|---|---|
device
|
A |
Source code in deeptool/trainer.py
Evaluation¶
deeptool.evaluate ¶
Post-hoc evaluation: collect predictions over a whole dataset at once.
Predictions ¶
The result of predict.
Stores only the raw outputs and targets; everything else is derived as a
property and recomputed each time rather than cached.
preds, probs, confidence, correct and accuracy are
classification only. For a regression model, use outputs directly.
Attributes:
| Name | Type | Description |
|---|---|---|
outputs |
Raw model output, shape |
|
targets |
Ground truth, shape |
|
inputs |
Input tensors, present only when |
Source code in deeptool/evaluate.py
correct
property
¶
Boolean tensor of whether each prediction matches its target.
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
predict ¶
predict(model: Module, dataloader: Iterable[Sequence[Tensor]], device: device | str | None = None, keep_inputs: bool = False) -> Predictions
Run the model over an entire dataloader and collect per-sample results.
Results are moved to CPU as they arrive, so the dataset never accumulates in accelerator memory and downstream code gets the CPU tensors it expects.
Puts the model in eval mode and leaves it there. Trainer.fit_epoch calls
model.train() at the start of every epoch, so resuming training is safe.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Module
|
A model following the |
required |
dataloader
|
Iterable[Sequence[Tensor]]
|
Batches to run through the model. |
required |
device
|
device | str | None
|
Where to run inference. Defaults to the model's own device. |
None
|
keep_inputs
|
bool
|
Also collect |
False
|
Returns:
| Type | Description |
|---|---|
Predictions
|
A |
Source code in deeptool/evaluate.py
Live plotting¶
deeptool.board ¶
Live training curves that update in place inside a notebook cell.
ProgressBoard ¶
Bases: HyperParameters
A live plot that accumulates one curve per label.
Each draw call buffers a point. Once every_n points have arrived they
are averaged into a single point on the curve and the figure is redrawn.
In a notebook the previous output is replaced with the new figure. In a plain script the data still accumulates but nothing is rendered.
Source code in deeptool/board.py
Run recording¶
deeptool.record ¶
Persistent JSONL training records and run comparison plots.
RunRecorder ¶
Write one run's metadata and completed epoch rows to disk.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
log_dir
|
str | Path
|
Directory containing |
required |
Source code in deeptool/record.py
meta ¶
Atomically replace this run's metadata document.
Source code in deeptool/record.py
epoch ¶
Append and immediately flush one completed epoch row.
load_runs ¶
Load immediate child runs below root from their JSONL histories.
Missing metrics are represented by None so every metric stays aligned
with its run's epoch list.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
root
|
str | Path
|
Directory whose child directories represent runs. |
required |
Returns:
| Type | Description |
|---|---|
RunData
|
Run names mapped to metric names and aligned value lists. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If |
ValueError
|
If a non-empty history line is not a JSON object. |
Source code in deeptool/record.py
plot_runs ¶
Plot every recorded metric, overlaying all runs that contain it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str | Path | Mapping[str, Mapping[str, list[Any]]]
|
A run root accepted by |
required |
Returns:
| Type | Description |
|---|---|
list[Figure]
|
One Matplotlib figure per metric, excluding |
Source code in deeptool/record.py
Checkpointing¶
deeptool.checkpoint ¶
Checkpoint saving and restoring, and best-validation-loss snapshots.
BestSnapshot ¶
Keeps model weights from the best value of one monitored scalar.
With path unset the snapshot lives in memory as a deepcopy; with a path
it is written to that file.
Score and progress are tracked even when enabled is False. Disabling only
skips the copy or write.
Attributes:
| Name | Type | Description |
|---|---|---|
score |
Best monitored score, or |
|
progress_name |
Whether |
|
progress |
Epoch or step that produced the best score. |
Source code in deeptool/checkpoint.py
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 | |
update ¶
update(score: float, progress_name: Literal['epoch', 'step'], progress: int, model: Module, optim: Optimizer) -> bool
Record an improved score and snapshot the weights.
Does nothing when score is not strictly better in the configured
direction.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
score
|
float
|
Finite monitored value for this progress point. |
required |
progress_name
|
Literal['epoch', 'step']
|
Whether |
required |
progress
|
int
|
Epoch or step stored when this is a new best. |
required |
model
|
Module
|
Model whose |
required |
optim
|
Optimizer
|
Optimizer, used only when |
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
Source code in deeptool/checkpoint.py
restore ¶
Restore model to the best weights and return its progress value.
Only model weights are restored; optimizer state is left alone. The point is to evaluate with the best model, not to resume training.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Module
|
Model to restore into. |
required |
Returns:
| Type | Description |
|---|---|
int
|
The epoch or step value that was restored. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If no snapshot exists — either there was no validation data, or snapshotting was disabled. |
Source code in deeptool/checkpoint.py
save_checkpoint ¶
save_checkpoint(model: Module, optim: Optimizer, epoch: int, path: str | Path, *, step: int | None = None) -> None
Save model and optimizer state, epoch and hyperparameters to one file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Module
|
Model to save. |
required |
optim
|
Optimizer
|
Optimizer to save. |
required |
epoch
|
int
|
Epoch index to record. |
required |
path
|
str | Path
|
Destination file. |
required |
step
|
int | None
|
Optional completed optimizer-step count. |
None
|
Source code in deeptool/checkpoint.py
load_checkpoint ¶
Restore a checkpoint into model in place.
Warning
hparams can hold arbitrary Python objects, so this reads with
weights_only=False. Only load checkpoints you trust.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Checkpoint file. |
required |
model
|
Module
|
Model to restore into. |
required |
optim
|
Optimizer | None
|
Optimizer to restore as well, for resuming training. Leave it out to restore weights only, for inference. |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Stored progress ( |
Source code in deeptool/checkpoint.py
Dashboard launcher¶
deeptool.dashboard ¶
Command-line launcher for the optional Streamlit run dashboard.
main ¶
Validate options and launch the packaged Streamlit application.