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)
¶
Create ModelTrainer instance and start training.
Source code in sleap_nn/train.py
train(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, init_weight='default', pretrained_backbone_weights=None, pretrained_head_weights=None, backbone_config='unet', head_configs=None, 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 |
---|---|---|---|
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
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 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
|
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: 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: 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. 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/train.py
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 |
|