Training API¶
Training runs on PyTorch Lightning. run_training is the entry
point the yolonas train CLI calls; the pieces below are what it wires together, and each
can be used on its own if you would rather drive Lightning yourself.
Entry point¶
modern_yolonas.training.run.run_training(model_name, recipe, train_dataset, val_dataset, val_ann_file=None, output_dir='runs/train', num_classes=80, pretrained=True, devices='auto', logger='csv', resume_path=None, epochs=None, batch_size=None)
¶
Run a full training session, returning path to the best checkpoint.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_name
|
str
|
One of 'yolo_nas_s', 'yolo_nas_m', 'yolo_nas_l'. |
required |
recipe
|
dict
|
Recipe dict (from recipes.py). |
required |
train_dataset
|
Dataset
|
Training dataset. |
required |
val_dataset
|
Dataset | None
|
Validation dataset. |
required |
val_ann_file
|
str | Path | None
|
COCO annotation file for mAP evaluation. |
None
|
output_dir
|
str | Path
|
Directory for checkpoints and logs. |
'runs/train'
|
num_classes
|
int
|
Number of object classes. |
80
|
pretrained
|
bool
|
Whether to start from pretrained COCO weights. |
True
|
devices
|
str | int | list[int]
|
Lightning devices spec. |
'auto'
|
logger
|
str
|
Logger backend ('csv', 'tensorboard', 'wandb'). |
'csv'
|
resume_path
|
str | Path | None
|
Optional checkpoint to resume from. |
None
|
epochs
|
int | None
|
Override recipe epochs. |
None
|
batch_size
|
int | None
|
Override recipe batch_size. |
None
|
Returns:
| Type | Description |
|---|---|
Path
|
Path to the best checkpoint file. |
Source code in src/modern_yolonas/training/run.py
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 | |
Lightning module and data¶
modern_yolonas.training.lightning_module.YoloNASLightningModule
¶
Bases: LightningModule
Lightning module wrapping a YOLO-NAS model for training.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Module
|
YoloNAS or QuantizedYoloNAS model. |
required |
num_classes
|
int
|
Number of object classes. |
80
|
lr
|
float
|
Learning rate. |
0.0002
|
optimizer_name
|
str
|
Optimizer name ('adamw' or 'sgd'). |
'adamw'
|
weight_decay
|
float
|
Weight decay. |
1e-05
|
warmup_steps
|
int
|
LR warmup steps. |
1000
|
cosine_final_lr_ratio
|
float
|
Final LR as fraction of initial LR. |
0.1
|
val_ann_file
|
str | Path | None
|
Path to COCO annotation JSON for mAP evaluation. When set, validation computes mAP instead of loss. |
None
|
val_dataset_ids
|
list[int] | None
|
List of COCO image IDs matching validation dataset order. If None, extracted from the val dataloader's dataset. |
None
|
conf_threshold
|
float
|
Confidence threshold for mAP evaluation. |
0.001
|
iou_threshold
|
float
|
NMS IoU threshold for mAP evaluation. |
0.65
|
input_size
|
int
|
Square size the images are letterboxed to. The evaluator needs it to map predictions back to original image coordinates before comparing them with the ground truth. |
640
|
channels_last
|
bool
|
Hold activations in NHWC. Ampere and newer run convolutions under AMP faster in that layout — measured +15% on a 3060 Laptop, 2026-09-19 — and it changes memory layout only, not results. |
False
|
Source code in src/modern_yolonas/training/lightning_module.py
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 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 | |
on_after_batch_transfer(batch, dataloader_idx)
¶
Finish preprocessing on the device, after the batch has crossed the bus.
Normalize(dtype="uint8") leaves the divide-by-255 to this hook so that a
quarter as many bytes cross pin_memory and PCIe. The check is on the dtype
rather than on a flag, so a float32 pipeline passes through untouched and
either kind of dataloader works against either kind of module.
Source code in src/modern_yolonas/training/lightning_module.py
modern_yolonas.training.data_module.DetectionDataModule
¶
Bases: LightningDataModule
DataModule wrapping training and validation detection datasets.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
train_dataset
|
Dataset
|
Training dataset. |
required |
val_dataset
|
Dataset | None
|
Optional validation dataset. |
None
|
batch_size
|
int
|
Batch size per device. |
32
|
num_workers
|
int
|
DataLoader workers. |
8
|
Source code in src/modern_yolonas/training/data_module.py
Loss and metrics¶
modern_yolonas.training.loss.PPYoloELoss
¶
Bases: Module
Combined loss for YOLO-NAS training.
Components: - VarifocalLoss (classification) - GIoULoss (box regression, weighted by assigned scores) - DFLLoss (distribution focal loss, weighted by assigned scores)
Weighted sum: cls_weight * vfl + iou_weight * giou + dfl_weight * dfl
All terms normalized by assigned_scores_sum (matching super-gradients).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
num_classes
|
int
|
Number of object classes. |
80
|
reg_max
|
int
|
Distribution regression maximum. |
16
|
cls_weight
|
float
|
Classification loss weight. |
1.0
|
iou_weight
|
float
|
Box regression loss weight. |
2.5
|
dfl_weight
|
float
|
Distribution focal loss weight. |
0.5
|
static_assigner_epochs
|
int
|
Use ATSS for the first N epochs (0 to disable). |
4
|
Source code in src/modern_yolonas/training/loss.py
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 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 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 | |
forward(predictions, targets, input_size=None, epoch=None)
¶
Compute loss.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
predictions
|
tuple
|
|
required |
targets
|
Tensor
|
|
required |
input_size
|
tuple[int, int] | None
|
|
None
|
epoch
|
int | None
|
Current training epoch (used for ATSS warmup). |
None
|
Returns:
| Type | Description |
|---|---|
tuple[Tensor, dict[str, float]]
|
(total_loss, loss_dict) |
Source code in src/modern_yolonas/training/loss.py
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 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 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 | |
modern_yolonas.training.metrics.DetectionMetrics
¶
COCO-style object-detection metrics backed by :class:torchmetrics.detection.MeanAveragePrecision.
Computes mAP @IoU[0.50:0.95], mAP@0.50, mAP@0.75, per-size mAP, and maximum average recall (mAR) for one, ten, and one-hundred max-detections per image — i.e. the same set reported by the COCO benchmark.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
class_metrics
|
bool
|
When |
False
|
extended_summary
|
bool
|
Forward the |
False
|
device
|
str | device
|
Device on which internal accumulation tensors are kept. Use the training device to avoid cross-device copies during validation. |
'cpu'
|
Example::
metrics = DetectionMetrics(device="cuda")
for images, targets in val_loader:
preds = decode_predictions(model(images)) # list of dicts
gts = convert_targets(targets) # list of dicts
metrics.update(preds, gts)
scores = metrics.compute()
# {"mAP": 0.423, "mAP_50": 0.612, "mAP_75": 0.448, ...}
metrics.reset()
Source code in src/modern_yolonas/training/metrics.py
update(preds, targets)
¶
Accumulate predictions and ground-truth for one batch.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
preds
|
list[dict]
|
One dict per image, each containing:
|
required |
targets
|
list[dict]
|
One dict per image, each containing:
|
required |
Source code in src/modern_yolonas/training/metrics.py
compute()
¶
Compute metrics over all accumulated predictions and return a flat dict.
Returns:
| Type | Description |
|---|---|
dict[str, float]
|
A |
dict[str, float]
|
|
dict[str, float]
|
|
dict[str, float]
|
|
Source code in src/modern_yolonas/training/metrics.py
Callbacks¶
modern_yolonas.training.callbacks.EMACallback
¶
Bases: Callback
Exponential Moving Average of model weights.
Maintains a shadow copy of model parameters updated with an exponential moving average. During validation and checkpointing, EMA weights are swapped in.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
decay
|
float
|
EMA decay factor. |
0.9997
|
warmup_steps
|
int
|
Steps before reaching full decay. |
2000
|
Source code in src/modern_yolonas/training/callbacks.py
modern_yolonas.training.callbacks.CloseMosaicCallback
¶
Bases: Callback
Disable Mosaic and Mixup augmentations in the final N epochs.
Accesses the train dataset's transforms pipeline and calls
disable_mosaic_mixup(). Idempotent — safe to call every epoch.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
close_mosaic_epochs
|
int
|
Number of final epochs without Mosaic/Mixup. |
15
|
Source code in src/modern_yolonas/training/callbacks.py
modern_yolonas.training.callbacks.QATCallback
¶
Bases: Callback
Freeze BatchNorm and observers during Quantization-Aware Training.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
freeze_bn_after_epoch
|
int
|
Freeze BN running stats after this epoch. |
3
|
freeze_observer_after_epoch
|
int
|
Stop updating fake-quant ranges after this epoch. |
5
|
Source code in src/modern_yolonas/training/callbacks.py
Checkpoints¶
modern_yolonas.weights.extract_model_state_dict(checkpoint_path, map_location='cpu')
¶
Load model weights from either a Lightning .ckpt or legacy .pt checkpoint.
Handles:
- Lightning format: state_dict keys prefixed with model.
- Legacy format: model_state_dict key or EMA ema.ema_state_dict
- Plain state_dict (e.g. from super-gradients pretrained weights)