get_config
sleap_nn.config.get_config
¶
This module contains functions to get the configuration for the data, model, and trainer.
Functions:
Name | Description |
---|---|
get_aug_config |
Create an augmentation configuration for training data. |
get_backbone_config |
Create a backbone configuration for neural network architecture. |
get_data_config |
Train a pose-estimation model with SLEAP-NN framework. |
get_head_configs |
Create head configurations for pose estimation model outputs. |
get_model_config |
Train a pose-estimation model with SLEAP-NN framework. |
get_trainer_config |
Train a pose-estimation model with SLEAP-NN framework. |
get_aug_config(intensity_aug=None, geometric_aug=None)
¶
Create an augmentation configuration for training data.
This method creates an AugmentationConfig
object based on the user-provided parameters
for intensity and geometric augmentations. The function supports both string-based
preset configurations and custom dictionary-based configurations.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
intensity_aug
|
Optional[Union[str, List[str], Dict[str, Any]]]
|
Intensity augmentation configuration. Can be:
- String: One of ["uniform_noise", "gaussian_noise", "contrast", "brightness"]
- List of strings: Multiple intensity augmentations from the allowed values
- Dictionary: Custom configuration matching |
None
|
geometric_aug
|
Optional[Union[str, List[str], Dict[str, Any]]]
|
Geometric augmentation configuration. Can be:
- String: One of ["rotation", "scale", "translate", "erase_scale", "mixup"]
- List of strings: Multiple geometric augmentations from the allowed values
- Dictionary: Custom configuration matching |
None
|
Returns:
Name | Type | Description |
---|---|---|
AugmentationConfig |
Configured augmentation object with intensity and geometric settings. |
Examples:
String-based configuration¶
aug_config = get_aug_config("contrast", "rotation")
List-based configuration¶
aug_config = get_aug_config(["contrast", "brightness"], ["scale", "translate"])
Dictionary-based configuration¶
intensity_dict = { "uniform_noise_min": 0.0, "uniform_noise_max": 0.1, "uniform_noise_p": 0.5, "contrast_p": 1.0 } geometric_dict = { "rotation": 15.0, "scale": (0.9, 1.1), "affine_p": 1.0 } aug_config = get_aug_config(intensity_dict, geometric_dict)
Raises:
Type | Description |
---|---|
ValueError
|
If invalid augmentation options are provided. |
Source code in sleap_nn/config/get_config.py
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 |
|
get_backbone_config(backbone_cfg)
¶
Create a backbone configuration for neural network architecture.
This method creates a BackboneConfig
object based on the user-provided parameters
for the neural network backbone architecture. The function supports both string-based
preset configurations and custom dictionary-based configurations for UNet, ConvNeXt,
and Swin Transformer architectures.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
backbone_cfg
|
Union[str, Dict[str, Any]]
|
Backbone configuration. Can be: - String: One of the preset backbone types: - UNet variants: ["unet", "unet_medium_rf", "unet_large_rf"] - ConvNeXt variants: ["convnext", "convnext_tiny", "convnext_small", "convnext_base", "convnext_large"] - SwinT variants: ["swint", "swint_tiny", "swint_small", "swint_base"] - Dictionary: Custom configuration with structure: { "unet": {UNetConfig parameters}, "convnext": {ConvNextConfig parameters}, "swint": {SwinTConfig parameters} } Only one backbone type should be specified in the dictionary. |
required |
Returns:
Name | Type | Description |
---|---|---|
BackboneConfig |
Configured backbone object with architecture-specific settings. |
Examples:
String-based configuration¶
backbone_config = get_backbone_config("unet") backbone_config = get_backbone_config("convnext_tiny") backbone_config = get_backbone_config("swint_base")
Dictionary-based configuration¶
unet_dict = { "unet": { "in_channels": 3, "filters": 64, "max_stride": 32, "output_stride": 2, "kernel_size": 3, "filters_rate": 2.0 } } backbone_config = get_backbone_config(unet_dict)
convnext_dict = { "convnext": { "model_type": "tiny", "in_channels": 3, "pre_trained_weights": "ConvNeXt_Tiny_Weights" } } backbone_config = get_backbone_config(convnext_dict)
Raises:
Type | Description |
---|---|
ValueError
|
If invalid backbone type is provided. |
Source code in sleap_nn/config/get_config.py
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 |
|
get_data_config(train_labels_path=None, val_labels_path=None, validation_fraction=0.1, test_file_path=None, provider='LabelsReader', user_instances_only=True, data_pipeline_fw='torch_dataset', cache_img_path=None, use_existing_imgs=False, delete_cache_imgs_after_training=True, ensure_rgb=False, ensure_grayscale=False, scale=1.0, max_height=None, max_width=None, crop_size=None, min_crop_size=100, use_augmentations_train=False, intensity_aug=None, geometry_aug=None)
¶
Train a pose-estimation model with SLEAP-NN framework.
This method creates a config object based on the parameters provided by the user,
and starts training by passing this config to the ModelTrainer
class.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
train_labels_path
|
Optional[List[str]]
|
List of paths to training data ( |
None
|
val_labels_path
|
Optional[List[str]]
|
List of paths to validation data ( |
None
|
validation_fraction
|
float
|
Float between 0 and 1 specifying the fraction of the
training set to sample for generating the validation set. The remaining
labeled frames will be left in the training set. If the |
0.1
|
test_file_path
|
Optional[str]
|
Path to test dataset ( |
None
|
provider
|
str
|
Provider class to read the input sleap files. Only "LabelsReader" supported for the training pipeline. Default: "LabelsReader". |
'LabelsReader'
|
user_instances_only
|
bool
|
|
True
|
data_pipeline_fw
|
str
|
Framework to create the data loaders. One of [ |
'torch_dataset'
|
cache_img_path
|
Optional[str]
|
Path to save |
None
|
use_existing_imgs
|
bool
|
Use existing train and val images/ chunks in the |
False
|
delete_cache_imgs_after_training
|
bool
|
If |
True
|
ensure_rgb
|
bool
|
(bool) True if the input image should have 3 channels (RGB image). If input has only one |
False
|
is replicated along the channel axis. If the image has three channels and this is set to False, then we retain the three channels. Default
|
|
required | |
ensure_grayscale
|
bool
|
(bool) True if the input image should only have a single channel. If input has three channels (RGB) and this |
False
|
image. If the source image has only one channel and this is set to False, then we retain the single channel input. Default
|
|
required | |
scale
|
float
|
Factor to resize the image dimensions by, specified as a float. Default: 1.0. |
1.0
|
max_height
|
Optional[int]
|
Maximum height the image should be padded to. If not provided, the original image size will be retained. Default: None. |
None
|
max_width
|
Optional[int]
|
Maximum width the image should be padded to. If not provided, the original image size will be retained. Default: None. |
None
|
crop_size
|
Optional[int]
|
Crop size of each instance for centered-instance model.
If |
None
|
min_crop_size
|
Optional[int]
|
Minimum crop size to be used if |
100
|
use_augmentations_train
|
bool
|
True if the data augmentation should be applied to the training data, else False. Default: False. |
False
|
intensity_aug
|
Optional[Union[str, List[str], Dict[str, Any]]]
|
One of ["uniform_noise", "gaussian_noise", "contrast", "brightness"]
or list of strings from the above allowed values. To have custom values, pass
a dict with the structure in |
None
|
geometry_aug
|
Optional[Union[str, List[str], Dict[str, Any]]]
|
One of ["rotation", "scale", "translate", "erase_scale", "mixup"].
or list of strings from the above allowed values. To have custom values, pass
a dict with the structure in |
None
|
Source code in sleap_nn/config/get_config.py
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 566 567 |
|
get_head_configs(head_cfg)
¶
Create head configurations for pose estimation model outputs.
This method creates a HeadConfig
object based on the user-provided parameters
for the pose estimation model head layers. The function supports both string-based
preset configurations and custom dictionary-based configurations for different model
types including Single Instance, Centroid, Centered Instance, Bottom-Up, and
Multi-Class variants.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
head_cfg
|
Union[str, Dict[str, Any]]
|
Head configuration. Can be: - String: One of the preset head types: - ["single_instance", "centroid", "centered_instance", "bottomup", "multi_class_bottomup", "multi_class_topdown"] - Dictionary: Custom configuration with structure: { "single_instance": { "confmaps": {SingleInstanceConfMapsConfig parameters} }, "centroid": { "confmaps": {CentroidConfMapsConfig parameters} }, "centered_instance": { "confmaps": {CenteredInstanceConfMapsConfig parameters} }, "bottomup": { "confmaps": {BottomUpConfMapsConfig parameters}, "pafs": {PAFConfig parameters} }, "multi_class_bottomup": { "confmaps": {BottomUpConfMapsConfig parameters}, "class_maps": {ClassMapConfig parameters} }, "multi_class_topdown": { "confmaps": {CenteredInstanceConfMapsConfig parameters}, "class_vectors": {ClassVectorsConfig parameters} } } Only one head type should be specified in the dictionary. |
required |
Returns:
Name | Type | Description |
---|---|---|
HeadConfig |
Configured head object with model-specific settings. |
Examples:
String-based configuration¶
head_configs = get_head_configs("single_instance") head_configs = get_head_configs("bottomup") head_configs = get_head_configs("multi_class_topdown")
Dictionary-based configuration¶
single_instance_dict = { "single_instance": { "confmaps": { "part_names": ["head", "tail"], "sigma": 2.5, "output_stride": 2 } } } head_configs = get_head_configs(single_instance_dict)
bottomup_dict = { "bottomup": { "confmaps": { "part_names": ["head", "tail"], "sigma": 5.0, "output_stride": 4, "loss_weight": 1.0 }, "pafs": { "edges": [("head", "tail")], "sigma": 15.0, "output_stride": 4, "loss_weight": 1.0 } } } head_configs = get_head_configs(bottomup_dict)
multi_class_dict = { "multi_class_topdown": { "confmaps": { "part_names": ["head", "tail"], "sigma": 5.0, "output_stride": 16, "loss_weight": 1.0 }, "class_vectors": { "classes": None, # Auto-inferred from track names "num_fc_layers": 1, "num_fc_units": 64, "output_stride": 16, "loss_weight": 1.0 } } } head_configs = get_head_configs(multi_class_dict)
Raises:
Type | Description |
---|---|
ValueError
|
If invalid head type is provided. |
Source code in sleap_nn/config/get_config.py
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 |
|
get_model_config(init_weight='default', pretrained_backbone_weights=None, pretrained_head_weights=None, backbone_config='unet', head_configs=None)
¶
Train a pose-estimation model with SLEAP-NN framework.
This method creates a config object based on the parameters provided by the user,
and starts training by passing this config to the ModelTrainer
class.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
init_weight
|
str
|
model weights initialization method. "default" uses kaiming uniform initialization and "xavier" uses Xavier initialization method. Default: "default". |
'default'
|
pretrained_backbone_weights
|
Optional[str]
|
Path of the |
None
|
pretrained_head_weights
|
Optional[str]
|
Path of the |
None
|
backbone_config
|
Union[str, Dict[str, Any]]
|
One of ["unet", "unet_medium_rf", "unet_large_rf", "convnext",
"convnext_tiny", "convnext_small", "convnext_base", "convnext_large", "swint",
"swint_tiny", "swint_small", "swint_base"]. If custom values need to be set,
then pass a dictionary with the structure:
{
"unet((or) convnext (or)swint)":
{(params in the corresponding architecture given in |
'unet'
|
head_configs
|
Union[str, Dict[str, Any]]
|
One of ["bottomup", "centered_instance", "centroid", "single_instance", "multi_class_bottomup", "multi_class_topdown"].
The default |
None
|
Source code in sleap_nn/config/get_config.py
570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 |
|
get_trainer_config(batch_size=1, shuffle_train=False, num_workers=0, ckpt_save_top_k=1, ckpt_save_last=None, trainer_num_devices=None, trainer_device_indices=None, trainer_accelerator='auto', enable_progress_bar=True, min_train_steps_per_epoch=200, train_steps_per_epoch=None, visualize_preds_during_training=False, keep_viz=False, max_epochs=10, seed=None, use_wandb=False, save_ckpt=False, ckpt_dir=None, run_name=None, resume_ckpt_path=None, wandb_entity=None, wandb_project=None, wandb_name=None, wandb_api_key=None, wandb_mode=None, wandb_save_viz_imgs_wandb=False, wandb_resume_prv_runid=None, wandb_group_name=None, optimizer='Adam', learning_rate=0.001, amsgrad=False, lr_scheduler=None, early_stopping=False, early_stopping_min_delta=0.0, early_stopping_patience=1, online_mining=False, hard_to_easy_ratio=2.0, min_hard_keypoints=2, max_hard_keypoints=None, loss_scale=5.0, zmq_publish_port=None, zmq_controller_port=None, zmq_controller_timeout=10)
¶
Train a pose-estimation model with SLEAP-NN framework.
This method creates a config object based on the parameters provided by the user,
and starts training by passing this config to the ModelTrainer
class.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
batch_size
|
int
|
Number of samples per batch or batch size for training data. Default: 4. |
1
|
shuffle_train
|
bool
|
True to have the train data reshuffled at every epoch. Default: False. |
False
|
num_workers
|
int
|
Number of subprocesses to use for data loading. 0 means that the data will be loaded in the main process. Default: 0. |
0
|
ckpt_save_top_k
|
int
|
If save_top_k == k, the best k models according to the quantity monitored will be saved. If save_top_k == 0, no models are saved. If save_top_k == -1, all models are saved. Please note that the monitors are checked every every_n_epochs epochs. if save_top_k >= 2 and the callback is called multiple times inside an epoch, the name of the saved file will be appended with a version count starting with v1 unless enable_version_counter is set to False. Default: 1. |
1
|
ckpt_save_last
|
Optional[bool]
|
When True, saves a last.ckpt whenever a checkpoint file gets saved. On a local filesystem, this will be a symbolic link, and otherwise a copy of the checkpoint file. This allows accessing the latest checkpoint in a deterministic manner. Default: False. |
None
|
trainer_num_devices
|
Optional[Union[str, int]]
|
Number of devices to use or "auto" to let Lightning decide. If |
None
|
trainer_device_indices
|
Optional[List[int]]
|
List of device indices to use. For example, |
None
|
trainer_accelerator
|
str
|
One of the ("cpu", "gpu", "mps", "auto"). "auto" recognises
the machine the model is running on and chooses the appropriate accelerator for
the |
'auto'
|
enable_progress_bar
|
bool
|
When True, enables printing the logs during training. Default: False. |
True
|
min_train_steps_per_epoch
|
int
|
Minimum number of iterations in a single epoch. (Useful if model
is trained with very few data points). Refer |
200
|
train_steps_per_epoch
|
Optional[int]
|
Number of minibatches (steps) to train for in an epoch. If set to |
None
|
visualize_preds_during_training
|
bool
|
If set to |
False
|
keep_viz
|
bool
|
If set to |
False
|
max_epochs
|
int
|
Maximum number of epochs to run. Default: 100. |
10
|
seed
|
Optional[int]
|
Seed value for the current experiment. If None, no seeding is applied. Default: None. |
None
|
save_ckpt
|
bool
|
True to enable checkpointing. Default: False. |
False
|
ckpt_dir
|
Optional[str]
|
Directory path where the |
None
|
run_name
|
Optional[str]
|
Name of the current run. The ckpts will be created in |
None
|
resume_ckpt_path
|
Optional[str]
|
Path to |
None
|
use_wandb
|
bool
|
True to enable wandb logging. Default: False. |
False
|
wandb_entity
|
Optional[str]
|
Entity of wandb project. Default: None. (The default entity in the user profile settings is used) |
None
|
wandb_project
|
Optional[str]
|
Project name for the current wandb run. Default: None. |
None
|
wandb_name
|
Optional[str]
|
Name of the current wandb run. Default: None. |
None
|
wandb_api_key
|
Optional[str]
|
API key. The API key is masked when saved to config files. Default: None. |
None
|
wandb_mode
|
Optional[str]
|
"offline" if only local logging is required. Default: None. |
None
|
wandb_save_viz_imgs_wandb
|
bool
|
If set to |
False
|
wandb_resume_prv_runid
|
Optional[str]
|
Previous run ID if training should be resumed from a previous ckpt. Default: None |
None
|
wandb_group_name
|
Optional[str]
|
Group name for the wandb run. Default: None. |
None
|
optimizer
|
str
|
Optimizer to be used. One of ["Adam", "AdamW"]. Default: "Adam". |
'Adam'
|
learning_rate
|
float
|
Learning rate of type float. Default: 1e-3. |
0.001
|
amsgrad
|
bool
|
Enable AMSGrad with the optimizer. Default: False. |
False
|
lr_scheduler
|
Optional[Union[str, Dict[str, Any]]]
|
One of ["step_lr", "reduce_lr_on_plateau"] (the default values in
|
None
|
early_stopping
|
bool
|
True if early stopping should be enabled. Default: False. |
False
|
early_stopping_min_delta
|
float
|
Minimum change in the monitored quantity to qualify as an improvement, i.e. an absolute change of less than or equal to min_delta, will count as no improvement. Default: 0.0. |
0.0
|
early_stopping_patience
|
int
|
Number of checks with no improvement after which training will be stopped. Under the default configuration, one check happens after every training epoch. Default: 1. |
1
|
online_mining
|
bool
|
If True, online hard keypoint mining (OHKM) will be enabled. When this is enabled, the loss is computed per keypoint (or edge for PAFs) and sorted from lowest (easy) to highest (hard). The hard keypoint loss will be scaled to have a higher weight in the total loss, encouraging the training to focus on tricky body parts that are more difficult to learn. If False, no mining will be performed and all keypoints will be weighted equally in the loss. |
False
|
hard_to_easy_ratio
|
float
|
The minimum ratio of the individual keypoint loss with respect to the lowest keypoint loss in order to be considered as "hard". This helps to switch focus on across groups of keypoints during training. |
2.0
|
min_hard_keypoints
|
int
|
The minimum number of keypoints that will be considered as
"hard", even if they are not below the |
2
|
max_hard_keypoints
|
Optional[int]
|
The maximum number of hard keypoints to apply scaling to. This can help when there are few very easy keypoints which may skew the ratio and result in loss scaling being applied to most keypoints, which can reduce the impact of hard mining altogether. |
None
|
loss_scale
|
float
|
Factor to scale the hard keypoint losses by for oks. |
5.0
|
zmq_publish_port
|
Optional[int]
|
(int) Specifies the port to which the training logs (loss values) should be sent to. |
None
|
zmq_controller_port
|
Optional[int]
|
(int) Specifies the port to listen to to stop the training (specific to SLEAP GUI). |
None
|
zmq_controller_timeout
|
int
|
(int) Polling timeout in microseconds specified as an integer. This controls how long the poller should wait to receive a response and should be set to a small value to minimize the impact on training speed. |
10
|
Source code in sleap_nn/config/get_config.py
648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 |
|