train
sleap_nn.train
¶
Entry point for sleap_nn training.
Functions:
| Name | Description |
|---|---|
run_training |
Create ModelTrainer instance and start training. |
train |
Train a pose-estimation model with SLEAP-NN framework. |
run_training(config, train_labels=None, val_labels=None)
¶
Create ModelTrainer instance and start training.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
DictConfig
|
Training configuration as a DictConfig. |
required |
train_labels
|
Optional[List[Labels]]
|
List of Labels objects for training. |
None
|
val_labels
|
Optional[List[Labels]]
|
List of Labels objects for validation. If not provided, the labels will be loaded from paths in the config. |
None
|
Source code in sleap_nn/train.py
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 566 567 568 569 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 | |
train(train_labels_path=None, val_labels_path=None, validation_fraction=0.1, use_same_data_for_val=False, 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, crop_padding=None, use_augmentations_train=True, intensity_aug=None, geometry_aug='rotation', init_weight='default', pretrained_backbone_weights=None, pretrained_head_weights=None, backbone_config='unet', head_configs=None, batch_size=1, shuffle_train=True, 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=42, 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, wandb_delete_local_logs=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 |
|---|---|---|---|
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
|
use_same_data_for_val
|
bool
|
If |
False
|
test_file_path
|
Optional[Union[str, List[str]]]
|
Path or list of paths to test dataset(s) ( |
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
channel when this is set to |
False
|
ensure_grayscale
|
bool
|
(bool) True if the input image should only have a single channel. If input has three channels (RGB) and this
is set to True, then we convert the image to grayscale (single-channel)
image. If the source image has only one channel and this is set to False, then we retain the single channel input. Default: |
False
|
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 original image should be resized and padded to. If not provided, the original image size will be retained. Default: None. |
None
|
max_width
|
Optional[int]
|
Maximum width the original image should be resized and 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
|
crop_padding
|
Optional[int]
|
Padding in pixels to add around instance bounding box when computing
crop size. If |
None
|
use_augmentations_train
|
bool
|
True if the data augmentation should be applied to the training data, else False. Default: True. |
True
|
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 |
'rotation'
|
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
|
batch_size
|
int
|
Number of samples per batch or batch size for training data. Default: 1. |
1
|
shuffle_train
|
bool
|
True to have the train data reshuffled at every epoch. Default: True. |
True
|
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: None. |
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: True. |
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: 10. |
10
|
seed
|
Optional[int]
|
Seed value for the current experiment. Ensures deterministic train/val splits across runs. Default: 42. |
42
|
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
|
wandb_delete_local_logs
|
Optional[bool]
|
If True, delete local wandb logs folder after training. If False, keep the folder. If None (default), automatically delete if logging online (wandb_mode != "offline") and keep if logging offline. 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/train.py
644 645 646 647 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 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 | |