Utils
get_builtin_activation_type(activation, **kwargs)
Returns activation class by its name from torch.nn namespace. This function support all modules available from torch.nn and also their lower-case aliases. On top of that, it supports a few aliaes: leaky_relu (LeakyReLU), swish (silu).
act_cls = get_activation_type("LeakyReLU", inplace=True, slope=0.01) act = act_cls()
Parameters:
Name | Type | Description | Default |
---|---|---|---|
activation |
Union[str, None]
|
Activation function name (E.g. ReLU). If None - return nn.Identity |
required |
Returns:
Type | Description |
---|---|
Type[nn.Module]
|
Type of the activation function that is ready to be instantiated |
Source code in V3_2/src/super_gradients/training/utils/activations_utils.py
8 9 10 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 |
|
batch_distance2bbox(points, distance, max_shapes=None)
Decode distance prediction to bounding box for batch.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
points |
Tensor
|
[B, ..., 2], "xy" format |
required |
distance |
Tensor
|
[B, ..., 4], "ltrb" format |
required |
max_shapes |
Optional[Tensor]
|
[B, 2], "h,w" format, Shape of the image. |
None
|
Returns:
Type | Description |
---|---|
Tensor
|
Tensor: Decoded bboxes, "x1y1x2y2" format. |
Source code in V3_2/src/super_gradients/training/utils/bbox_utils.py
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
|
Callback
Base callback class with all the callback methods. Derived classes may override one or many of the available events to receive callbacks when such events are triggered by the training loop.
The order of the events is as follows:
on_training_start(context) # called once before training starts, good for setting up the warmup LR
for epoch in range(epochs):
on_train_loader_start(context)
for batch in train_loader:
on_train_batch_start(context)
on_train_batch_loss_end(context) # called after loss has been computed
on_train_batch_backward_end(context) # called after .backward() was called
on_train_batch_gradient_step_start(context) # called before the optimizer step about to happen (gradient clipping, logging of gradients)
on_train_batch_gradient_step_end(context) # called after gradient step was done, good place to update LR (for step-based schedulers)
on_train_batch_end(context)
on_train_loader_end(context)
on_validation_loader_start(context)
for batch in validation_loader:
on_validation_batch_start(context)
on_validation_batch_end(context)
on_validation_loader_end(context)
on_validation_end_best_epoch(context)
on_test_start(context)
for batch in test_loader:
on_test_batch_start(context)
on_test_batch_end(context)
on_test_end(context)
on_training_end(context) # called once after training ends.
Correspondence mapping from the old callback API:
on_training_start(context) <-> Phase.PRE_TRAINING for epoch in range(epochs): on_train_loader_start(context) <-> Phase.TRAIN_EPOCH_START for batch in train_loader: on_train_batch_start(context) on_train_batch_loss_end(context) on_train_batch_backward_end(context) <-> Phase.TRAIN_BATCH_END on_train_batch_gradient_step_start(context) on_train_batch_gradient_step_end(context) <-> Phase.TRAIN_BATCH_STEP on_train_batch_end(context) on_train_loader_end(context) <-> Phase.TRAIN_EPOCH_END
on_validation_loader_start(context)
for batch in validation_loader:
on_validation_batch_start(context)
on_validation_batch_end(context) <-> Phase.VALIDATION_BATCH_END
on_validation_loader_end(context) <-> Phase.VALIDATION_EPOCH_END
on_validation_end_best_epoch(context) <-> Phase.VALIDATION_END_BEST_EPOCH
on_test_start(context) for batch in test_loader: on_test_batch_start(context) on_test_batch_end(context) <-> Phase.TEST_BATCH_END on_test_end(context) <-> Phase.TEST_END
on_training_end(context) <-> Phase.POST_TRAINING
Source code in V3_2/src/super_gradients/training/utils/callbacks/base_callbacks.py
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 |
|
on_test_batch_end(context)
Called after all forward step have been performed for a given batch and there is nothing left to do. The corresponding Phase enum value for this event is Phase.TEST_BATCH_END.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
context |
PhaseContext
|
required |
Returns:
Type | Description |
---|---|
None
|
Source code in V3_2/src/super_gradients/training/utils/callbacks/base_callbacks.py
330 331 332 333 334 335 336 337 |
|
on_test_batch_start(context)
Called at each batch after getting batch of data from test loader and moving it to target device.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
context |
PhaseContext
|
required |
Returns:
Type | Description |
---|---|
None
|
Source code in V3_2/src/super_gradients/training/utils/callbacks/base_callbacks.py
322 323 324 325 326 327 328 |
|
on_test_loader_end(context)
Called once at the end of test data loader (after processing the last batch). The corresponding Phase enum value for this event is Phase.TEST_END.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
context |
PhaseContext
|
required |
Returns:
Type | Description |
---|---|
None
|
Source code in V3_2/src/super_gradients/training/utils/callbacks/base_callbacks.py
339 340 341 342 343 344 345 346 |
|
on_test_loader_start(context)
Called once at the start of test data loader (before getting the first batch).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
context |
PhaseContext
|
required |
Returns:
Type | Description |
---|---|
None
|
Source code in V3_2/src/super_gradients/training/utils/callbacks/base_callbacks.py
313 314 315 316 317 318 319 320 |
|
on_train_batch_backward_end(context)
Called after loss.backward() method was called for a given batch
Parameters:
Name | Type | Description | Default |
---|---|---|---|
context |
PhaseContext
|
required |
Returns:
Type | Description |
---|---|
None
|
Source code in V3_2/src/super_gradients/training/utils/callbacks/base_callbacks.py
222 223 224 225 226 227 228 229 |
|
on_train_batch_end(context)
Called after all forward/backward/optimizer steps have been performed for a given batch and there is nothing left to do.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
context |
PhaseContext
|
required |
Returns:
Type | Description |
---|---|
None
|
Source code in V3_2/src/super_gradients/training/utils/callbacks/base_callbacks.py
249 250 251 252 253 254 255 256 257 |
|
on_train_batch_gradient_step_end(context)
Called after gradient step has been performed. Good place to update LR (for step-based schedulers) The corresponding Phase enum value for this event is Phase.TRAIN_BATCH_STEP.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
context |
PhaseContext
|
required |
Returns:
Type | Description |
---|---|
None
|
Source code in V3_2/src/super_gradients/training/utils/callbacks/base_callbacks.py
240 241 242 243 244 245 246 247 |
|
on_train_batch_gradient_step_start(context)
Called before the graadient step is about to happen. Good place to clip gradients (with respect to scaler), log gradients to data ratio, etc.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
context |
PhaseContext
|
required |
Returns:
Type | Description |
---|---|
None
|
Source code in V3_2/src/super_gradients/training/utils/callbacks/base_callbacks.py
231 232 233 234 235 236 237 238 |
|
on_train_batch_loss_end(context)
Called after model forward and loss computation has been done. At this point the context argument is guaranteed to have the following attributes: - preds - loss_log_items The corresponding Phase enum value for this event is Phase.TRAIN_BATCH_END.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
context |
PhaseContext
|
required |
Returns:
Type | Description |
---|---|
None
|
Source code in V3_2/src/super_gradients/training/utils/callbacks/base_callbacks.py
208 209 210 211 212 213 214 215 216 217 218 219 220 |
|
on_train_batch_start(context)
Called at each batch after getting batch of data from data loader and moving it to target device. This event triggered AFTER Trainer.pre_prediction_callback call (If it was defined).
At this point the context argument is guaranteed to have the following attributes: - batch_idx - inputs - targets - **additional_batch_items
Parameters:
Name | Type | Description | Default |
---|---|---|---|
context |
PhaseContext
|
required |
Returns:
Type | Description |
---|---|
None
|
Source code in V3_2/src/super_gradients/training/utils/callbacks/base_callbacks.py
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 |
|
on_train_loader_end(context)
Called each epoch at the end of train data loader (after processing the last batch). The corresponding Phase enum value for this event is Phase.TRAIN_EPOCH_END.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
context |
PhaseContext
|
required |
Returns:
Type | Description |
---|---|
None
|
Source code in V3_2/src/super_gradients/training/utils/callbacks/base_callbacks.py
259 260 261 262 263 264 265 266 267 |
|
on_train_loader_start(context)
Called each epoch at the start of train data loader (before getting the first batch). At this point, the context argument is guaranteed to have the following attributes: - epoch The corresponding Phase enum value for this event is Phase.TRAIN_EPOCH_START.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
context |
PhaseContext
|
required |
Returns:
Type | Description |
---|---|
None
|
Source code in V3_2/src/super_gradients/training/utils/callbacks/base_callbacks.py
181 182 183 184 185 186 187 188 189 190 |
|
on_training_end(context)
Called once after the training loop has finished (Due to reaching optimization criterion or because of an error.) The corresponding Phase enum value for this event is Phase.POST_TRAINING.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
context |
PhaseContext
|
required |
Returns:
Type | Description |
---|---|
None
|
Source code in V3_2/src/super_gradients/training/utils/callbacks/base_callbacks.py
348 349 350 351 352 353 354 355 |
|
on_training_start(context)
Called once before start of the first epoch At this point, the context argument is guaranteed to have the following attributes: - optimizer - net - checkpoints_dir_path - criterion - sg_logger - train_loader - valid_loader - training_params - checkpoint_params - architecture - arch_params - metric_to_watch - device - ema_model
The corresponding Phase enum value for this event is Phase.PRE_TRAINING.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
context |
PhaseContext
|
required |
Returns:
Type | Description |
---|---|
None
|
Source code in V3_2/src/super_gradients/training/utils/callbacks/base_callbacks.py
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 |
|
on_validation_batch_end(context)
Called after all forward step / loss / metric computation have been performed for a given batch and there is nothing left to do. The corresponding Phase enum value for this event is Phase.VALIDATION_BATCH_END.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
context |
PhaseContext
|
required |
Returns:
Type | Description |
---|---|
None
|
Source code in V3_2/src/super_gradients/training/utils/callbacks/base_callbacks.py
286 287 288 289 290 291 292 293 |
|
on_validation_batch_start(context)
Called at each batch after getting batch of data from validation loader and moving it to target device.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
context |
PhaseContext
|
required |
Returns:
Type | Description |
---|---|
None
|
Source code in V3_2/src/super_gradients/training/utils/callbacks/base_callbacks.py
278 279 280 281 282 283 284 |
|
on_validation_end_best_epoch(context)
Called each epoch after validation has been performed and the best metric has been achieved. The corresponding Phase enum value for this event is Phase.VALIDATION_END_BEST_EPOCH.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
context |
PhaseContext
|
required |
Returns:
Type | Description |
---|---|
None
|
Source code in V3_2/src/super_gradients/training/utils/callbacks/base_callbacks.py
304 305 306 307 308 309 310 311 |
|
on_validation_loader_end(context)
Called each epoch at the end of validation data loader (after processing the last batch). The corresponding Phase enum value for this event is Phase.VALIDATION_EPOCH_END.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
context |
PhaseContext
|
required |
Returns:
Type | Description |
---|---|
None
|
Source code in V3_2/src/super_gradients/training/utils/callbacks/base_callbacks.py
295 296 297 298 299 300 301 302 |
|
on_validation_loader_start(context)
Called each epoch at the start of validation data loader (before getting the first batch).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
context |
PhaseContext
|
required |
Returns:
Type | Description |
---|---|
None
|
Source code in V3_2/src/super_gradients/training/utils/callbacks/base_callbacks.py
269 270 271 272 273 274 275 276 |
|
CallbackHandler
Bases: Callback
Runs all callbacks
Parameters:
Name | Type | Description | Default |
---|---|---|---|
callbacks |
List[Callback]
|
Callbacks to be run. |
required |
Source code in V3_2/src/super_gradients/training/utils/callbacks/base_callbacks.py
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 |
|
PhaseCallback
Bases: Callback
Kept here to keep backward compatibility with old code. New callbacks should use Callback class instead. This callback supports receiving only a subset of events defined in Phase enum:
PRE_TRAINING = "PRE_TRAINING" TRAIN_EPOCH_START = "TRAIN_EPOCH_START" TRAIN_BATCH_END = "TRAIN_BATCH_END" TRAIN_BATCH_STEP = "TRAIN_BATCH_STEP" TRAIN_EPOCH_END = "TRAIN_EPOCH_END"
VALIDATION_BATCH_END = "VALIDATION_BATCH_END" VALIDATION_EPOCH_END = "VALIDATION_EPOCH_END" VALIDATION_END_BEST_EPOCH = "VALIDATION_END_BEST_EPOCH"
TEST_BATCH_END = "TEST_BATCH_END" TEST_END = "TEST_END" POST_TRAINING = "POST_TRAINING"
Source code in V3_2/src/super_gradients/training/utils/callbacks/base_callbacks.py
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 |
|
PhaseContext
Represents the input for phase callbacks, and is constantly updated after callback calls.
Source code in V3_2/src/super_gradients/training/utils/callbacks/base_callbacks.py
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 |
|
BatchStepLinearWarmupLRCallback
Bases: Callback
LR scheduling callback for linear step warmup on each batch step. LR climbs from warmup_initial_lr with to initial lr.
Source code in V3_2/src/super_gradients/training/utils/callbacks/callbacks.py
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 |
|
__init__(warmup_initial_lr, initial_lr, train_loader_len, update_param_groups, lr_warmup_steps, training_params, net, **kwargs)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
warmup_initial_lr |
float
|
Starting learning rate |
required |
initial_lr |
float
|
Target learning rate after warmup |
required |
train_loader_len |
int
|
Length of train data loader |
required |
lr_warmup_steps |
int
|
Optional. If passed, will use fixed number of warmup steps to warmup LR. Default is None. |
required |
kwargs |
{}
|
Source code in V3_2/src/super_gradients/training/utils/callbacks/callbacks.py
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 |
|
update_lr(optimizer, epoch, batch_idx=None)
Same as in LRCallbackBase
Parameters:
Name | Type | Description | Default |
---|---|---|---|
optimizer |
required | ||
epoch |
required | ||
batch_idx |
None
|
Returns:
Type | Description |
---|---|
Source code in V3_2/src/super_gradients/training/utils/callbacks/callbacks.py
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 |
|
BinarySegmentationVisualizationCallback
Bases: PhaseCallback
A callback that adds a visualization of a batch of segmentation predictions to context.sg_logger
Parameters:
Name | Type | Description | Default |
---|---|---|---|
phase |
Phase
|
When to trigger the callback. |
required |
freq |
int
|
Frequency (in epochs) to perform this callback. |
required |
batch_idx |
int
|
Batch index to perform visualization for. |
0
|
last_img_idx_in_batch |
int
|
Last image index to add to log. (default=-1, will take entire batch). |
-1
|
Source code in V3_2/src/super_gradients/training/utils/callbacks/callbacks.py
641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 |
|
CosineLRCallback
Bases: LRCallbackBase
Hard coded step Cosine anealing learning rate scheduling.
Source code in V3_2/src/super_gradients/training/utils/callbacks/callbacks.py
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 |
|
DeciLabUploadCallback
Bases: PhaseCallback
Post-training callback for uploading and optimizing a model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model_meta_data |
Model's meta-data object. Type: ModelMetadata |
required | |
optimization_request_form |
Optimization request form object. Type: OptimizationRequestForm |
required | |
ckpt_name |
str
|
Checkpoint filename, inside the checkpoint directory. |
'ckpt_best.pth'
|
Source code in V3_2/src/super_gradients/training/utils/callbacks/callbacks.py
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 |
|
__call__(context)
This function will attempt to upload the trained model and schedule an optimization for it.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
context |
PhaseContext
|
Training phase context |
required |
Source code in V3_2/src/super_gradients/training/utils/callbacks/callbacks.py
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 |
|
get_optimization_status(optimized_model_name)
This function will do fetch the optimized version of the trained model and check on its benchmark status. The status will be checked against the server every 30 seconds and the process will timeout after 30 minutes or log about the successful optimization - whichever happens first.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
optimized_model_name |
str
|
Optimized model name |
required |
Returns:
Type | Description |
---|---|
Whether or not the optimized model has been benchmarked |
Source code in V3_2/src/super_gradients/training/utils/callbacks/callbacks.py
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 |
|
upload_model(model)
This function will upload the trained model to the Deci Lab
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model |
The resulting model from the training process |
required |
Source code in V3_2/src/super_gradients/training/utils/callbacks/callbacks.py
149 150 151 152 153 154 155 156 157 158 159 160 161 162 |
|
DetectionVisualizationCallback
Bases: PhaseCallback
A callback that adds a visualization of a batch of detection predictions to context.sg_logger
Parameters:
Name | Type | Description | Default |
---|---|---|---|
phase |
Phase
|
When to trigger the callback. |
required |
freq |
int
|
Frequency (in epochs) to perform this callback. |
required |
batch_idx |
int
|
Batch index to perform visualization for. |
0
|
classes |
list
|
Class list of the dataset. |
required |
last_img_idx_in_batch |
int
|
Last image index to add to log. (default=-1, will take entire batch). |
-1
|
Source code in V3_2/src/super_gradients/training/utils/callbacks/callbacks.py
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 |
|
EpochStepWarmupLRCallback
Bases: LRCallbackBase
LR scheduling callback for linear step warmup. This scheduler uses a whole epoch as single step. LR climbs from warmup_initial_lr with even steps to initial lr. When warmup_initial_lr is None - LR climb starts from initial_lr/(1+warmup_epochs).
Source code in V3_2/src/super_gradients/training/utils/callbacks/callbacks.py
272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 |
|
ExponentialLRCallback
Bases: LRCallbackBase
Exponential decay learning rate scheduling. Decays the learning rate by lr_decay_factor
every epoch.
Source code in V3_2/src/super_gradients/training/utils/callbacks/callbacks.py
411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 |
|
FunctionLRCallback
Bases: LRCallbackBase
Hard coded rate scheduling for user defined lr scheduling function.
Source code in V3_2/src/super_gradients/training/utils/callbacks/callbacks.py
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 |
|
IllegalLRSchedulerMetric
Bases: Exception
Exception raised illegal combination of training parameters.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
metric_name |
str
|
Name of the metric that is not supported. |
required |
metrics_dict |
dict
|
Dictionary of metrics that are supported. |
required |
Source code in V3_2/src/super_gradients/training/utils/callbacks/callbacks.py
523 524 525 526 527 528 529 530 531 532 |
|
LRCallbackBase
Bases: PhaseCallback
Base class for hard coded learning rate scheduling regimes, implemented as callbacks.
Source code in V3_2/src/super_gradients/training/utils/callbacks/callbacks.py
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 |
|
is_lr_scheduling_enabled(context)
Predicate that controls whether to perform lr scheduling based on values in context.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
context |
PhaseContext
|
PhaseContext: current phase's context. |
required |
Returns:
Type | Description |
---|---|
bool, whether to apply lr scheduling or not. |
Source code in V3_2/src/super_gradients/training/utils/callbacks/callbacks.py
243 244 245 246 247 248 249 250 |
|
perform_scheduling(context)
Performs lr scheduling based on values in context.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
context |
PhaseContext
|
PhaseContext: current phase's context. |
required |
Source code in V3_2/src/super_gradients/training/utils/callbacks/callbacks.py
252 253 254 255 256 257 258 |
|
LRSchedulerCallback
Bases: PhaseCallback
Learning rate scheduler callback.
When passing call a metrics_dict, with a key=self.metric_name, the value of that metric will monitored for ReduceLROnPlateau (i.e step(metrics_dict[self.metric_name]).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
scheduler |
torch.optim.lr_scheduler._LRScheduler
|
Learning rate scheduler to be called step() with. |
required |
metric_name |
str
|
Metric name for ReduceLROnPlateau learning rate scheduler. |
None
|
phase |
Phase
|
Phase of when to trigger it. |
required |
Source code in V3_2/src/super_gradients/training/utils/callbacks/callbacks.py
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 |
|
LinearStepWarmupLRCallback
Bases: EpochStepWarmupLRCallback
Deprecated, use EpochStepWarmupLRCallback instead
Source code in V3_2/src/super_gradients/training/utils/callbacks/callbacks.py
296 297 298 299 300 301 302 303 304 305 |
|
ModelConversionCheckCallback
Bases: PhaseCallback
Pre-training callback that verifies model conversion to onnx given specified conversion parameters.
The model is converted, then inference is applied with onnx runtime.
Use this callback with the same args as DeciPlatformCallback to prevent conversion fails at the end of training.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model_name |
str
|
Model's name |
required |
input_dimensions |
Sequence[int]
|
Model's input dimensions |
required |
primary_batch_size |
int
|
Model's primary batch size |
required |
opset_version |
(default=11) |
required | |
do_constant_folding |
(default=True) |
required | |
dynamic_axes |
(default={'input': {0: 'batch_size'}, 'output': {0: 'batch_size'}}) |
required | |
input_names |
(default=["input"]) |
required | |
output_names |
(default=["output"]) |
required | |
rtol |
(default=1e-03) |
required | |
atol |
(default=1e-05) |
required |
Source code in V3_2/src/super_gradients/training/utils/callbacks/callbacks.py
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 109 110 111 112 113 |
|
PhaseContextTestCallback
Bases: PhaseCallback
A callback that saves the phase context the for testing.
Source code in V3_2/src/super_gradients/training/utils/callbacks/callbacks.py
588 589 590 591 592 593 594 595 596 597 598 |
|
PolyLRCallback
Bases: LRCallbackBase
Hard coded polynomial decay learning rate scheduling (i.e at specific milestones).
Source code in V3_2/src/super_gradients/training/utils/callbacks/callbacks.py
432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 |
|
RoboflowResultCallback
Bases: Callback
Append the training results to a csv file. Be aware that this does not fully overwrite the existing file, just appends.
Source code in V3_2/src/super_gradients/training/utils/callbacks/callbacks.py
719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 |
|
__init__(dataset_name, output_path=None)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dataset_name |
str
|
Name of the dataset that was used to train the model. |
required |
output_path |
Optional[str]
|
Full path to the output csv file. By default, save at 'checkpoint_dir/results.csv' |
None
|
Source code in V3_2/src/super_gradients/training/utils/callbacks/callbacks.py
723 724 725 726 727 728 729 730 731 732 733 734 |
|
StepLRCallback
Bases: LRCallbackBase
Hard coded step learning rate scheduling (i.e at specific milestones).
Source code in V3_2/src/super_gradients/training/utils/callbacks/callbacks.py
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 |
|
TestLRCallback
Bases: PhaseCallback
Phase callback that collects the learning rates in lr_placeholder at the end of each epoch (used for testing). In the case of multiple parameter groups (i.e multiple learning rates) the learning rate is collected from the first one. The phase is VALIDATION_EPOCH_END to ensure all lr updates have been performed before calling this callback.
Source code in V3_2/src/super_gradients/training/utils/callbacks/callbacks.py
745 746 747 748 749 750 751 752 753 754 755 756 757 |
|
TrainingStageSwitchCallbackBase
Bases: PhaseCallback
TrainingStageSwitchCallback
A phase callback that is called at a specific epoch (epoch start) to support multi-stage training. It does so by manipulating the objects inside the context.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
next_stage_start_epoch |
int
|
Epoch idx to apply the stage change. |
required |
Source code in V3_2/src/super_gradients/training/utils/callbacks/callbacks.py
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 |
|
apply_stage_change(context)
This method is called when the callback is fired on the next_stage_start_epoch, and holds the stage change logic that should be applied to the context's objects.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
context |
PhaseContext
|
PhaseContext, context of current phase |
required |
Source code in V3_2/src/super_gradients/training/utils/callbacks/callbacks.py
688 689 690 691 692 693 694 695 |
|
YoloXTrainingStageSwitchCallback
Bases: TrainingStageSwitchCallbackBase
YoloXTrainingStageSwitchCallback
Training stage switch for YoloX training. Disables mosaic, and manipulates YoloX loss to use L1.
Source code in V3_2/src/super_gradients/training/utils/callbacks/callbacks.py
698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 |
|
create_lr_scheduler_callback(lr_mode, train_loader, net, training_params, update_param_groups, optimizer)
Creates the phase callback in charge of LR scheduling, to be used by Trainer.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
lr_mode |
Union[str, Mapping]
|
Union[str, Mapping], When str: Learning rate scheduling policy, one of ['step','poly','cosine','function']. 'step' refers to constant updates at epoch numbers passed through |
required |
train_loader |
DataLoader
|
DataLoader, the Trainer.train_loader used for training. |
required |
net |
torch.nn.Module
|
torch.nn.Module, the Trainer.net used for training. |
required |
training_params |
Mapping
|
Mapping, Trainer.training_params. |
required |
update_param_groups |
bool
|
bool, Whether the Trainer.net has a specific way of updaitng its parameter group. |
required |
optimizer |
torch.optim.Optimizer
|
The optimizer used for training. Will be passed to the LR callback's init (or the torch scheduler's init, depending on the lr_mode value as described above). |
required |
Returns:
Type | Description |
---|---|
PhaseCallback
|
a PhaseCallback instance to be used by Trainer for LR scheduling. |
Source code in V3_2/src/super_gradients/training/utils/callbacks/callbacks.py
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 |
|
PPYoloETrainingStageSwitchCallback
Bases: TrainingStageSwitchCallbackBase
PPYoloETrainingStageSwitchCallback
Training stage switch for PPYolo training. It changes static bbox assigner to a task aligned assigned after certain number of epochs passed
Source code in V3_2/src/super_gradients/training/utils/callbacks/ppyoloe_switch_callback.py
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
|
MissingPretrainedWeightsException
Bases: Exception
Exception raised by unsupported pretrianed model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
desc |
explanation of the error |
required |
Source code in V3_2/src/super_gradients/training/utils/checkpoint_utils.py
270 271 272 273 274 275 276 277 278 |
|
adapt_state_dict_to_fit_model_layer_names(model_state_dict, source_ckpt, exclude=[], solver=None)
Given a model state dict and source checkpoints, the method tries to correct the keys in the model_state_dict to fit the ckpt in order to properly load the weights into the model. If unsuccessful - returns None :param model_state_dict: the model state_dict :param source_ckpt: checkpoint dict :param exclude optional list for excluded layers :param solver: callable with signature (ckpt_key, ckpt_val, model_key, model_val) that returns a desired weight for ckpt_val. :return: renamed checkpoint dict (if possible)
Source code in V3_2/src/super_gradients/training/utils/checkpoint_utils.py
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 |
|
adaptive_load_state_dict(net, state_dict, strict, solver=None)
Adaptively loads state_dict to net, by adapting the state_dict to net's layer names first.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
net |
torch.nn.Module
|
(nn.Module) to load state_dict to |
required |
state_dict |
dict
|
(dict) Checkpoint state_dict |
required |
strict |
Union[bool, StrictLoad]
|
(StrictLoad) key matching strictness |
required |
solver |
callable with signature (ckpt_key, ckpt_val, model_key, model_val) that returns a desired weight for ckpt_val. |
None
|
Returns:
Type | Description |
---|---|
Source code in V3_2/src/super_gradients/training/utils/checkpoint_utils.py
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 |
|
copy_ckpt_to_local_folder(local_ckpt_destination_dir, ckpt_filename, remote_ckpt_source_dir=None, path_src='local', overwrite_local_ckpt=False, load_weights_only=False)
Copy the checkpoint from any supported source to a local destination path :param local_ckpt_destination_dir: destination where the checkpoint will be saved to :param ckpt_filename: ckpt_best.pth Or ckpt_latest.pth :param remote_ckpt_source_dir: Name of the source checkpoint to be loaded (S3 Modelull URL) :param path_src: S3 / url :param overwrite_local_ckpt: determines if checkpoint will be saved in destination dir or in a temp folder
:return: Path to checkpoint
Source code in V3_2/src/super_gradients/training/utils/checkpoint_utils.py
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 |
|
load_checkpoint_to_model(net, ckpt_local_path, load_backbone=False, strict=StrictLoad.NO_KEY_MATCHING, load_weights_only=False, load_ema_as_net=False, load_processing_params=False)
Loads the state dict in ckpt_local_path to net and returns the checkpoint's state dict.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
load_ema_as_net |
bool
|
Will load the EMA inside the checkpoint file to the network when set |
False
|
ckpt_local_path |
str
|
local path to the checkpoint file |
required |
load_backbone |
bool
|
whether to load the checkpoint as a backbone |
False
|
net |
torch.nn.Module
|
network to load the checkpoint to |
required |
strict |
Union[str, StrictLoad]
|
StrictLoad.NO_KEY_MATCHING
|
|
load_weights_only |
bool
|
Whether to ignore all other entries other then "net". |
False
|
load_processing_params |
bool
|
Whether to call set_dataset_processing_params on "processing_params" entry inside the checkpoint file (default=False). |
False
|
Returns:
Type | Description |
---|---|
Source code in V3_2/src/super_gradients/training/utils/checkpoint_utils.py
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 |
|
load_pretrained_weights(model, architecture, pretrained_weights)
Loads pretrained weights from the MODEL_URLS dictionary to model
Parameters:
Name | Type | Description | Default |
---|---|---|---|
architecture |
str
|
name of the model's architecture |
required |
model |
torch.nn.Module
|
model to load pretrinaed weights for |
required |
pretrained_weights |
str
|
name for the pretrianed weights (i.e imagenet) |
required |
Returns:
Type | Description |
---|---|
None |
Source code in V3_2/src/super_gradients/training/utils/checkpoint_utils.py
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 |
|
load_pretrained_weights_local(model, architecture, pretrained_weights)
Loads pretrained weights from the MODEL_URLS dictionary to model
Parameters:
Name | Type | Description | Default |
---|---|---|---|
architecture |
str
|
name of the model's architecture |
required |
model |
torch.nn.Module
|
model to load pretrinaed weights for |
required |
pretrained_weights |
str
|
path tp pretrained weights |
required |
Returns:
Type | Description |
---|---|
None |
Source code in V3_2/src/super_gradients/training/utils/checkpoint_utils.py
340 341 342 343 344 345 346 347 348 349 350 351 352 353 |
|
raise_informative_runtime_error(state_dict, checkpoint, exception_msg)
Given a model state dict and source checkpoints, the method calls "adapt_state_dict_to_fit_model_layer_names" and enhances the exception_msg if loading the checkpoint_dict via the conversion method is possible
Source code in V3_2/src/super_gradients/training/utils/checkpoint_utils.py
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 |
|
read_ckpt_state_dict(ckpt_path, device='cpu')
Reads a checkpoint state dict from a given path or url
Parameters:
Name | Type | Description | Default |
---|---|---|---|
ckpt_path |
str
|
Checkpoint path or url |
required |
device |
Target device where tensors should be loaded |
'cpu'
|
Returns:
Type | Description |
---|---|
Mapping[str, torch.Tensor]
|
Checkpoint state dict object |
Source code in V3_2/src/super_gradients/training/utils/checkpoint_utils.py
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 |
|
transfer_weights(model, model_state_dict)
Copy weights from model_state_dict
to model
, skipping layers that are incompatible (Having different shape).
This method is helpful if you are doing some model surgery and want to load
part of the model weights into different model.
This function will go over all the layers in model_state_dict
and will try to find a matching layer in model
and
copy the weights into it. If shape will not match, the layer will be skipped.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model |
nn.Module
|
Model to load weights into |
required |
model_state_dict |
Mapping[str, Tensor]
|
Model state dict to load weights from |
required |
Returns:
Type | Description |
---|---|
None
|
None |
Source code in V3_2/src/super_gradients/training/utils/checkpoint_utils.py
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
|
AccessCounterMixin
Implements access counting mechanism for configuration settings (dicts/lists). It is achieved by wrapping underlying config and override getitem, getattr methods to catch read operations and increments access counter for each property.
Source code in V3_2/src/super_gradients/training/utils/config_utils.py
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 |
|
maybe_wrap_as_counter(value, key, count_usage=True)
Return an attribute value optionally wrapped as access counter adapter to trace read counts.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
value |
Attribute value |
required | |
key |
Attribute name |
required | |
count_usage |
bool
|
Whether increment usage count for given attribute. Default is True. |
True
|
Returns:
Type | Description |
---|---|
wrapped value |
Source code in V3_2/src/super_gradients/training/utils/config_utils.py
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
|
raise_if_unused_params(config)
A helper function to check whether all confuration parameters were used on given block of code. Motivation to have this check is to ensure there were no typo or outdated configuration parameters. It at least one of config parameters was not used, this function will raise an UnusedConfigParamException exception. Example usage:
from super_gradients.training.utils import raise_if_unused_params
with raise_if_unused_params(some_config) as some_config: do_something_with_config(some_config)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
config |
Union[HpmStruct, DictConfig, ListConfig, Mapping, list, tuple]
|
A config to check |
required |
Returns:
Type | Description |
---|---|
ConfigInspector
|
An instance of ConfigInspector |
Source code in V3_2/src/super_gradients/training/utils/config_utils.py
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 |
|
warn_if_unused_params(config)
A helper function to check whether all confuration parameters were used on given block of code. Motivation to have this check is to ensure there were no typo or outdated configuration parameters. It at least one of config parameters was not used, this function will emit warning. Example usage:
from super_gradients.training.utils import warn_if_unused_params
with warn_if_unused_params(some_config) as some_config: do_something_with_config(some_config)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
config |
A config to check |
required |
Returns:
Type | Description |
---|---|
An instance of ConfigInspector |
Source code in V3_2/src/super_gradients/training/utils/config_utils.py
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 |
|
wrap_with_warning(cls, message)
Emits a warning when target class of function is called.
from super_gradients.training.utils.deprecated_utils import wrap_with_warning from super_gradients.training.utils.callbacks import EpochStepWarmupLRCallback, BatchStepLinearWarmupLRCallback
LR_WARMUP_CLS_DICT = { "linear": wrap_with_warning( EpochStepWarmupLRCallback, message=f"Parameter
linear
has been made deprecated and will be removed in the next SG release. Please uselinear_epoch
instead", ), 'linear_epoch`': EpochStepWarmupLRCallback, }
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cls |
Callable
|
A class or function to wrap |
required |
message |
str
|
A message to emit when this class is called |
required |
Returns:
Type | Description |
---|---|
Any
|
A factory method that returns wrapped class |
Source code in V3_2/src/super_gradients/training/utils/deprecated_utils.py
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
|
Anchors
Bases: nn.Module
A wrapper function to hold the anchors used by detection models such as Yolo
Source code in V3_2/src/super_gradients/training/utils/detection_utils.py
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 |
|
__init__(anchors_list, strides)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
anchors_list |
List[List]
|
of the shape [[w1,h1,w2,h2,w3,h3], [w4,h4,w5,h5,w6,h6] .... where each sublist holds the width and height of the anchors of a specific detection layer. i.e. for a model with 3 detection layers, each containing 5 anchors the format will be a of 3 sublists of 10 numbers each The width and height are in pixels (not relative to image size) |
required |
strides |
List[int]
|
a list containing the stride of the layers from which the detection heads are fed. i.e. if the firs detection head is connected to the backbone after the input dimensions were reduces by 8, the first number will be 8 |
required |
Source code in V3_2/src/super_gradients/training/utils/detection_utils.py
542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 |
|
CrowdDetectionCollateFN
Bases: DetectionCollateFN
Collate function for Yolox training with additional_batch_items that includes crowd targets
Source code in V3_2/src/super_gradients/training/utils/detection_utils.py
810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 |
|
CrowdDetectionPPYoloECollateFN
Bases: PPYoloECollateFN
Collate function for Yolox training with additional_batch_items that includes crowd targets
Source code in V3_2/src/super_gradients/training/utils/detection_utils.py
788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 |
|
DatasetItemsException
Bases: Exception
Source code in V3_2/src/super_gradients/training/utils/detection_utils.py
677 678 679 680 681 682 683 684 685 686 687 |
|
__init__(data_sample, collate_type, expected_item_names)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
data_sample |
Tuple
|
item(s) returned by a dataset |
required |
collate_type |
Type
|
type of the collate that caused the exception |
required |
expected_item_names |
Tuple
|
tuple of names of items that are expected by the collate to be returned from the dataset |
required |
Source code in V3_2/src/super_gradients/training/utils/detection_utils.py
678 679 680 681 682 683 684 685 686 687 |
|
DetectionCollateFN
Collate function for Yolox training
Source code in V3_2/src/super_gradients/training/utils/detection_utils.py
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 |
|
DetectionPostPredictionCallback
Bases: ABC
, nn.Module
Source code in V3_2/src/super_gradients/training/utils/detection_utils.py
181 182 183 184 185 186 187 188 189 190 191 192 193 194 |
|
forward(x, device)
abstractmethod
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x |
the output of your model |
required | |
device |
str
|
the device to move all output tensors into |
required |
Returns:
Type | Description |
---|---|
a list with length batch_size, each item in the list is a detections with shape: nx6 (x1, y1, x2, y2, confidence, class) where x and y are in range [0,1] |
Source code in V3_2/src/super_gradients/training/utils/detection_utils.py
185 186 187 188 189 190 191 192 193 194 |
|
DetectionTargetsFormat
Bases: Enum
Enum class for the different detection output formats
When NORMALIZED is not specified- the type refers to unnormalized image coordinates (of the bboxes).
For example: LABEL_NORMALIZED_XYXY means [class_idx,x1,y1,x2,y2]
Source code in V3_2/src/super_gradients/training/utils/detection_utils.py
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
|
DetectionVisualization
Source code in V3_2/src/super_gradients/training/utils/detection_utils.py
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 |
|
visualize_batch(image_tensor, pred_boxes, target_boxes, batch_name, class_names, checkpoint_dir=None, undo_preprocessing_func=undo_image_preprocessing, box_thickness=2, image_scale=1.0, gt_alpha=0.4)
staticmethod
A helper function to visualize detections predicted by a network: saves images into a given path with a name that is {batch_name}_{imade_idx_in_the_batch}.jpg, one batch per call. Colors are generated on the fly: uniformly sampled from color wheel to support all given classes.
Adjustable: * Ground truth box transparency; * Box width; * Image size (larger or smaller than what's provided)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
image_tensor |
torch.Tensor
|
rgb images, (B, H, W, 3) |
required |
pred_boxes |
List[torch.Tensor]
|
boxes after NMS for each image in a batch, each (Num_boxes, 6), values on dim 1 are: x1, y1, x2, y2, confidence, class |
required |
target_boxes |
torch.Tensor
|
(Num_targets, 6), values on dim 1 are: image id in a batch, class, x y w h (coordinates scaled to [0, 1]) |
required |
batch_name |
Union[int, str]
|
id of the current batch to use for image naming |
required |
class_names |
List[str]
|
names of all classes, each on its own index |
required |
checkpoint_dir |
str
|
a path where images with boxes will be saved. if None, the result images will be returns as a list of numpy image arrays |
None
|
undo_preprocessing_func |
Callable[[torch.Tensor], np.ndarray]
|
a function to convert preprocessed images tensor into a batch of cv2-like images |
undo_image_preprocessing
|
box_thickness |
int
|
box line thickness in px |
2
|
image_scale |
float
|
scale of an image w.r.t. given image size, e.g. incoming images are (320x320), use scale = 2. to preview in (640x640) |
1.0
|
gt_alpha |
float
|
a value in [0., 1.] transparency on ground truth boxes, 0 for invisible, 1 for fully opaque |
0.4
|
Source code in V3_2/src/super_gradients/training/utils/detection_utils.py
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 |
|
IouThreshold
Bases: tuple
, Enum
Source code in V3_2/src/super_gradients/training/utils/detection_utils.py
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 |
|
from_bounds(low, high, step=0.05)
classmethod
Create a tensor with values from low (including) to high (including) with a given step size.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
low |
float
|
Lower bound |
required |
high |
float
|
Upper bound |
required |
step |
float
|
Step size |
0.05
|
Returns:
Type | Description |
---|---|
torch.Tensor
|
Tensor of [low, low + step, low + 2 * step, ..., high] |
Source code in V3_2/src/super_gradients/training/utils/detection_utils.py
210 211 212 213 214 215 216 217 218 219 220 |
|
NMS_Type
Bases: str
, Enum
Type of non max suppression algorithm that can be used for post processing detection
Source code in V3_2/src/super_gradients/training/utils/detection_utils.py
360 361 362 363 364 365 366 |
|
PPYoloECollateFN
Bases: DetectionCollateFN
Collate function for PPYoloE training
Source code in V3_2/src/super_gradients/training/utils/detection_utils.py
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 |
|
__init__(random_resize_sizes=None, random_resize_modes=None)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
random_resize_sizes |
Union[List[int], None]
|
(rows, cols) |
None
|
Source code in V3_2/src/super_gradients/training/utils/detection_utils.py
735 736 737 738 739 740 741 |
|
adjust_box_anns(bbox, scale_ratio, padw, padh, w_max, h_max)
Adjusts the bbox annotations of rescaled, padded image.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
bbox |
(np.array) bbox to modify. |
required | |
scale_ratio |
(float) scale ratio between rescale output image and original one. |
required | |
padw |
(int) width padding size. |
required | |
padh |
(int) height padding size. |
required | |
w_max |
(int) width border. |
required | |
h_max |
(int) height border |
required |
Returns:
Type | Description |
---|---|
modified bbox (np.array) |
Source code in V3_2/src/super_gradients/training/utils/detection_utils.py
660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 |
|
box_iou(box1, box2)
Return intersection-over-union (Jaccard index) of boxes. Both sets of boxes are expected to be in (x1, y1, x2, y2) format.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
box1 |
torch.Tensor
|
Tensor of shape [N, 4] |
required |
box2 |
torch.Tensor
|
Tensor of shape [M, 4] |
required |
Returns:
Type | Description |
---|---|
torch.Tensor
|
iou, Tensor of shape [N, M]: the NxM matrix containing the pairwise IoU values for every element in boxes1 and boxes2 |
Source code in V3_2/src/super_gradients/training/utils/detection_utils.py
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 |
|
calc_bbox_iou_matrix(pred)
calculate iou for every pair of boxes in the boxes vector
Parameters:
Name | Type | Description | Default |
---|---|---|---|
pred |
torch.Tensor
|
a 3-dimensional tensor containing all boxes for a batch of images [N, num_boxes, 4], where each box format is [x1,y1,x2,y2] |
required |
Returns:
Type | Description |
---|---|
a 3-dimensional matrix where M_i_j_k is the iou of box j and box k of the i'th image in the batch |
Source code in V3_2/src/super_gradients/training/utils/detection_utils.py
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 |
|
calculate_bbox_iou_matrix(box1, box2, x1y1x2y2=True, GIoU=False, DIoU=False, CIoU=False, eps=1e-09)
calculate iou matrix containing the iou of every couple iuo(i,j) where i is in box1 and j is in box2
Parameters:
Name | Type | Description | Default |
---|---|---|---|
box1 |
a 2D tensor of boxes (shape N x 4) |
required | |
box2 |
a 2D tensor of boxes (shape M x 4) |
required | |
x1y1x2y2 |
boxes format is x1y1x2y2 (True) or xywh where xy is the center (False) |
True
|
Returns:
Type | Description |
---|---|
a 2D iou matrix (shape NxM) |
Source code in V3_2/src/super_gradients/training/utils/detection_utils.py
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 |
|
compute_box_area(box)
Compute the area of one or many boxes.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
box |
torch.Tensor
|
One or many boxes, shape = (4, ?), each box in format (x1, y1, x2, y2) |
required |
Returns:
Type | Description |
---|---|
torch.Tensor
|
Area of every box, shape = (1, ?) |
Source code in V3_2/src/super_gradients/training/utils/detection_utils.py
829 830 831 832 833 834 835 836 |
|
compute_detection_matching(output, targets, height, width, iou_thresholds, denormalize_targets, device, crowd_targets=None, top_k=100, return_on_cpu=True)
Match predictions (NMS output) and the targets (ground truth) with respect to IoU and confidence score.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
output |
List[torch.Tensor]
|
list (of length batch_size) of Tensors of shape (num_predictions, 6) format: (x1, y1, x2, y2, confidence, class_label) where x1,y1,x2,y2 are according to image size |
required |
targets |
torch.Tensor
|
targets for all images of shape (total_num_targets, 6) format: (index, x, y, w, h, label) where x,y,w,h are in range [0,1] |
required |
height |
int
|
dimensions of the image |
required |
width |
int
|
dimensions of the image |
required |
iou_thresholds |
torch.Tensor
|
Threshold to compute the mAP |
required |
device |
str
|
Device |
required |
crowd_targets |
Optional[torch.Tensor]
|
crowd targets for all images of shape (total_num_crowd_targets, 6) format: (index, x, y, w, h, label) where x,y,w,h are in range [0,1] |
None
|
top_k |
int
|
Number of predictions to keep per class, ordered by confidence score |
100
|
denormalize_targets |
bool
|
If True, denormalize the targets and crowd_targets |
required |
return_on_cpu |
bool
|
If True, the output will be returned on "CPU", otherwise it will be returned on "device" |
True
|
Returns:
Type | Description |
---|---|
List[Tuple]
|
list of the following tensors, for every image: :preds_matched: Tensor of shape (num_img_predictions, n_iou_thresholds) True when prediction (i) is matched with a target with respect to the (j)th IoU threshold :preds_to_ignore: Tensor of shape (num_img_predictions, n_iou_thresholds) True when prediction (i) is matched with a crowd target with respect to the (j)th IoU threshold :preds_scores: Tensor of shape (num_img_predictions), confidence score for every prediction :preds_cls: Tensor of shape (num_img_predictions), predicted class for every prediction :targets_cls: Tensor of shape (num_img_targets), ground truth class for every target |
Source code in V3_2/src/super_gradients/training/utils/detection_utils.py
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 |
|
compute_detection_metrics(preds_matched, preds_to_ignore, preds_scores, preds_cls, targets_cls, device, recall_thresholds=None, score_threshold=0.1, calc_best_score_thresholds=False)
Compute the list of precision, recall, MaP and f1 for every recall IoU threshold and for every class.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
preds_matched |
torch.Tensor
|
Tensor of shape (num_predictions, n_iou_thresholds) True when prediction (i) is matched with a target with respect to the (j)th IoU threshold |
required |
preds_scores |
torch.Tensor
|
Tensor of shape (num_predictions), confidence score for every prediction |
required |
preds_cls |
torch.Tensor
|
Tensor of shape (num_predictions), predicted class for every prediction |
required |
targets_cls |
torch.Tensor
|
Tensor of shape (num_targets), ground truth class for every target box to be detected |
required |
recall_thresholds |
Optional[torch.Tensor]
|
Recall thresholds used to compute MaP. |
None
|
score_threshold |
Optional[float]
|
Minimum confidence score to consider a prediction for the computation of precision, recall and f1 (not MaP) |
0.1
|
device |
str
|
Device |
required |
calc_best_score_thresholds |
bool
|
If True, the best confidence score threshold is computed for each class |
False
|
Returns:
Type | Description |
---|---|
Tuple
|
:ap, precision, recall, f1: Tensors of shape (n_class, nb_iou_thrs) :unique_classes: Vector with all unique target classes :best_score_threshold: torch.float with the best overall score threshold if calc_best_score_thresholds is True else None :best_score_threshold_per_cls: dict that stores the best score threshold for each class , if calc_best_score_thresholds is True else None |
Source code in V3_2/src/super_gradients/training/utils/detection_utils.py
1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 |
|
compute_detection_metrics_per_cls(preds_matched, preds_to_ignore, preds_scores, n_targets, recall_thresholds, score_threshold, device, calc_best_score_thresholds=False, nb_score_thrs=101)
Compute the list of precision, recall and MaP of a given class for every recall IoU threshold.
:param preds_matched: Tensor of shape (num_predictions, n_iou_thresholds)
True when prediction (i) is matched with a target
with respect to the(j)th IoU threshold
:param preds_to_ignore Tensor of shape (num_predictions, n_iou_thresholds)
True when prediction (i) is matched with a crowd target
with respect to the (j)th IoU threshold
:param preds_scores: Tensor of shape (num_predictions), confidence score for every prediction
:param n_targets: Number of target boxes of this class
:param recall_thresholds: Tensor of shape (max_n_rec_thresh) list of recall thresholds used to compute MaP
:param score_threshold: Minimum confidence score to consider a prediction for the computation of
precision and recall (not MaP)
:param device: Device
:param calc_best_score_thresholds: If True, the best confidence score threshold is computed for this class
:param nb_score_thrs: Number of score thresholds to consider when calc_best_score_thresholds is True
:return:
:ap, precision, recall: Tensors of shape (nb_iou_thrs)
:mean_f1_per_threshold: Tensor of shape (nb_score_thresholds) if calc_best_score_thresholds is True else None
:best_score_threshold: torch.float if calc_best_score_thresholds is True else None
Source code in V3_2/src/super_gradients/training/utils/detection_utils.py
1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 |
|
compute_img_detection_matching(preds, targets, crowd_targets, height, width, iou_thresholds, device, denormalize_targets, top_k=100, return_on_cpu=True)
Match predictions (NMS output) and the targets (ground truth) with respect to IoU and confidence score for a given image.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
preds |
torch.Tensor
|
Tensor of shape (num_img_predictions, 6) format: (x1, y1, x2, y2, confidence, class_label) where x1,y1,x2,y2 are according to image size |
required |
targets |
torch.Tensor
|
targets for this image of shape (num_img_targets, 6) format: (label, cx, cy, w, h, label) where cx,cy,w,h |
required |
height |
int
|
dimensions of the image |
required |
width |
int
|
dimensions of the image |
required |
iou_thresholds |
torch.Tensor
|
Threshold to compute the mAP |
required |
device |
str
|
required | |
crowd_targets |
torch.Tensor
|
crowd targets for all images of shape (total_num_crowd_targets, 6) format: (index, x, y, w, h, label) where x,y,w,h are in range [0,1] |
required |
top_k |
int
|
Number of predictions to keep per class, ordered by confidence score |
100
|
denormalize_targets |
bool
|
If True, denormalize the targets and crowd_targets |
required |
return_on_cpu |
bool
|
If True, the output will be returned on "CPU", otherwise it will be returned on "device" |
True
|
Returns:
Type | Description |
---|---|
Tuple
|
:preds_matched: Tensor of shape (num_img_predictions, n_iou_thresholds) True when prediction (i) is matched with a target with respect to the (j)th IoU threshold :preds_to_ignore: Tensor of shape (num_img_predictions, n_iou_thresholds) True when prediction (i) is matched with a crowd target with respect to the (j)th IoU threshold :preds_scores: Tensor of shape (num_img_predictions), confidence score for every prediction :preds_cls: Tensor of shape (num_img_predictions), predicted class for every prediction :targets_cls: Tensor of shape (num_img_targets), ground truth class for every target |
Source code in V3_2/src/super_gradients/training/utils/detection_utils.py
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 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 |
|
convert_cxcywh_bbox_to_xyxy(input_bbox)
Converts bounding box format from [cx, cy, w, h] to [x1, y1, x2, y2] :param input_bbox: input bbox either 2-dimensional (for all boxes of a single image) or 3-dimensional (for boxes of a batch of images) :return: Converted bbox in same dimensions as the original
Source code in V3_2/src/super_gradients/training/utils/detection_utils.py
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 |
|
crowd_ioa(det_box, crowd_box)
Return intersection-over-detection_area of boxes, used for crowd ground truths. Both sets of boxes are expected to be in (x1, y1, x2, y2) format.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
det_box |
torch.Tensor
|
Tensor of shape [N, 4] |
required |
crowd_box |
torch.Tensor
|
Tensor of shape [M, 4] |
required |
Returns:
Type | Description |
---|---|
torch.Tensor
|
crowd_ioa, Tensor of shape [N, M]: the NxM matrix containing the pairwise IoA values for every element in det_box and crowd_box |
Source code in V3_2/src/super_gradients/training/utils/detection_utils.py
839 840 841 842 843 844 845 846 847 848 849 850 851 852 |
|
cxcywh2xyxy(bboxes)
Transforms bboxes from centerized xy wh format to xyxy format
Parameters:
Name | Type | Description | Default |
---|---|---|---|
bboxes |
array, shaped (nboxes, 4) |
required |
Returns:
Type | Description |
---|---|
modified bboxes |
Source code in V3_2/src/super_gradients/training/utils/detection_utils.py
614 615 616 617 618 619 620 621 622 623 624 |
|
get_cls_posx_in_target(target_format)
Get the label of a given target
Parameters:
Name | Type | Description | Default |
---|---|---|---|
target_format |
DetectionTargetsFormat
|
Representation of the target (ex: LABEL_XYXY) |
required |
Returns:
Type | Description |
---|---|
int
|
Position of the class id in a bbox ex: 0 if bbox of format label_xyxy | -1 if bbox of format xyxy_label |
Source code in V3_2/src/super_gradients/training/utils/detection_utils.py
42 43 44 45 46 47 48 49 50 51 52 53 54 |
|
get_mosaic_coordinate(mosaic_index, xc, yc, w, h, input_h, input_w)
Returns the mosaic coordinates of final mosaic image according to mosaic image index.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
mosaic_index |
(int) mosaic image index |
required | |
xc |
(int) center x coordinate of the entire mosaic grid. |
required | |
yc |
(int) center y coordinate of the entire mosaic grid. |
required | |
w |
(int) width of bbox |
required | |
h |
(int) height of bbox |
required | |
input_h |
(int) image input height (should be 1/2 of the final mosaic output image height). |
required | |
input_w |
(int) image input width (should be 1/2 of the final mosaic output image width). |
required |
Returns:
Type | Description |
---|---|
(x1, y1, x2, y2), (x1s, y1s, x2s, y2s) where (x1, y1, x2, y2) are the coordinates in the final mosaic output image, and (x1s, y1s, x2s, y2s) are the coordinates in the placed image. |
Source code in V3_2/src/super_gradients/training/utils/detection_utils.py
627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 |
|
get_top_k_idx_per_cls(preds_scores, preds_cls, top_k)
Get the indexes of all the top k predictions for every class
Parameters:
Name | Type | Description | Default |
---|---|---|---|
preds_scores |
torch.Tensor
|
The confidence scores, vector of shape (n_pred) |
required |
preds_cls |
torch.Tensor
|
The predicted class, vector of shape (n_pred) |
required |
top_k |
int
|
Number of predictions to keep per class, ordered by confidence score |
required |
Returns:
Type | Description |
---|---|
Indexes of the top k predictions. length <= (k * n_unique_class) |
Source code in V3_2/src/super_gradients/training/utils/detection_utils.py
1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 |
|
matrix_non_max_suppression(pred, conf_thres=0.1, kernel='gaussian', sigma=3.0, max_num_of_detections=500, class_agnostic_nms=False)
Performs Matrix Non-Maximum Suppression (NMS) on inference results https://arxiv.org/pdf/1912.04488.pdf
Parameters:
Name | Type | Description | Default |
---|---|---|---|
pred |
Raw model prediction (in test mode) - a Tensor of shape [batch, num_predictions, 85] where each item format is (x, y, w, h, object_conf, class_conf, ... 80 classes score ...) |
required | |
conf_thres |
float
|
Threshold under which prediction are discarded |
0.1
|
kernel |
str
|
Type of kernel to use ['gaussian', 'linear'] |
'gaussian'
|
sigma |
float
|
Sigma for the gaussian kernel |
3.0
|
max_num_of_detections |
int
|
Maximum number of boxes to output |
500
|
Returns:
Type | Description |
---|---|
List[torch.Tensor]
|
Detections list with shape (x1, y1, x2, y2, object_conf, class_conf, class) |
Source code in V3_2/src/super_gradients/training/utils/detection_utils.py
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 |