Reference for ultralytics/utils/torch_utils.py
Note
This file is available at https://github.com/ultralytics/ultralytics/blob/main/ultralytics/utils/torch_utils.py. If you spot a problem please help fix it by contributing a Pull Request 🛠️. Thank you 🙏!
ultralytics.utils.torch_utils.ModelEMA
ModelEMA(model, decay=0.9999, tau=2000, updates=0)
Updated Exponential Moving Average (EMA) implementation.
Keeps a moving average of everything in the model state_dict (parameters and buffers). For EMA details see References.
To disable EMA set the enabled
attribute to False
.
Attributes:
Name | Type | Description |
---|---|---|
ema |
Module
|
Copy of the model in evaluation mode. |
updates |
int
|
Number of EMA updates. |
decay |
function
|
Decay function that determines the EMA weight. |
enabled |
bool
|
Whether EMA is enabled. |
References
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model
|
Module
|
Model to create EMA for. |
required |
decay
|
float
|
Maximum EMA decay rate. Defaults to 0.9999. |
0.9999
|
tau
|
int
|
EMA decay time constant. Defaults to 2000. |
2000
|
updates
|
int
|
Initial number of updates. Defaults to 0. |
0
|
Source code in ultralytics/utils/torch_utils.py
654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 |
|
update
update(model)
Update EMA parameters.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model
|
Module
|
Model to update EMA from. |
required |
Source code in ultralytics/utils/torch_utils.py
671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 |
|
update_attr
update_attr(model, include=(), exclude=('process_group', 'reducer'))
Updates attributes and saves stripped model with optimizer removed.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model
|
Module
|
Model to update attributes from. |
required |
include
|
tuple
|
Attributes to include. Defaults to (). |
()
|
exclude
|
tuple
|
Attributes to exclude. Defaults to ("process_group", "reducer"). |
('process_group', 'reducer')
|
Source code in ultralytics/utils/torch_utils.py
689 690 691 692 693 694 695 696 697 698 699 |
|
ultralytics.utils.torch_utils.EarlyStopping
EarlyStopping(patience=50)
Early stopping class that stops training when a specified number of epochs have passed without improvement.
Attributes:
Name | Type | Description |
---|---|---|
best_fitness |
float
|
Best fitness value observed. |
best_epoch |
int
|
Epoch where best fitness was observed. |
patience |
int
|
Number of epochs to wait after fitness stops improving before stopping. |
possible_stop |
bool
|
Flag indicating if stopping may occur next epoch. |
Parameters:
Name | Type | Description | Default |
---|---|---|---|
patience
|
int
|
Number of epochs to wait after fitness stops improving before stopping. |
50
|
Source code in ultralytics/utils/torch_utils.py
903 904 905 906 907 908 909 910 911 912 913 |
|
__call__
__call__(epoch, fitness)
Check whether to stop training.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
epoch
|
int
|
Current epoch of training |
required |
fitness
|
float
|
Fitness value of current epoch |
required |
Returns:
Type | Description |
---|---|
bool
|
True if training should stop, False otherwise |
Source code in ultralytics/utils/torch_utils.py
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 |
|
ultralytics.utils.torch_utils.FXModel
FXModel(model)
Bases: Module
A custom model class for torch.fx compatibility.
This class extends torch.nn.Module
and is designed to ensure compatibility with torch.fx for tracing and graph
manipulation. It copies attributes from an existing model and explicitly sets the model attribute to ensure proper
copying.
Attributes:
Name | Type | Description |
---|---|---|
model |
Module
|
The original model's layers. |
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model
|
Module
|
The original model to wrap for torch.fx compatibility. |
required |
Source code in ultralytics/utils/torch_utils.py
958 959 960 961 962 963 964 965 966 967 968 |
|
forward
forward(x)
Forward pass through the model.
This method performs the forward pass through the model, handling the dependencies between layers and saving intermediate outputs.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x
|
Tensor
|
The input tensor to the model. |
required |
Returns:
Type | Description |
---|---|
Tensor
|
The output tensor from the model. |
Source code in ultralytics/utils/torch_utils.py
970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 |
|
ultralytics.utils.torch_utils.torch_distributed_zero_first
torch_distributed_zero_first(local_rank: int)
Ensures all processes in distributed training wait for the local master (rank 0) to complete a task first.
Source code in ultralytics/utils/torch_utils.py
49 50 51 52 53 54 55 56 57 58 59 |
|
ultralytics.utils.torch_utils.smart_inference_mode
smart_inference_mode()
Applies torch.inference_mode() decorator if torch>=1.9.0 else torch.no_grad() decorator.
Source code in ultralytics/utils/torch_utils.py
62 63 64 65 66 67 68 69 70 71 72 |
|
ultralytics.utils.torch_utils.autocast
autocast(enabled: bool, device: str = 'cuda')
Get the appropriate autocast context manager based on PyTorch version and AMP setting.
This function returns a context manager for automatic mixed precision (AMP) training that is compatible with both older and newer versions of PyTorch. It handles the differences in the autocast API between PyTorch versions.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
enabled
|
bool
|
Whether to enable automatic mixed precision. |
required |
device
|
str
|
The device to use for autocast. Defaults to 'cuda'. |
'cuda'
|
Returns:
Type | Description |
---|---|
autocast
|
The appropriate autocast context manager. |
Notes
- For PyTorch versions 1.13 and newer, it uses
torch.amp.autocast
. - For older versions, it uses
torch.cuda.autocast
.
Examples:
>>> with autocast(enabled=True):
... # Your mixed precision operations here
... pass
Source code in ultralytics/utils/torch_utils.py
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 |
|
ultralytics.utils.torch_utils.get_cpu_info
get_cpu_info()
Return a string with system CPU information, i.e. 'Apple M2'.
Source code in ultralytics/utils/torch_utils.py
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 |
|
ultralytics.utils.torch_utils.get_gpu_info
get_gpu_info(index)
Return a string with system GPU information, i.e. 'Tesla T4, 15102MiB'.
Source code in ultralytics/utils/torch_utils.py
121 122 123 124 |
|
ultralytics.utils.torch_utils.select_device
select_device(device='', batch=0, newline=False, verbose=True)
Select the appropriate PyTorch device based on the provided arguments.
The function takes a string specifying the device or a torch.device object and returns a torch.device object representing the selected device. The function also validates the number of available devices and raises an exception if the requested device(s) are not available.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
device
|
str | device
|
Device string or torch.device object. Options are 'None', 'cpu', or 'cuda', or '0' or '0,1,2,3'. Defaults to an empty string, which auto-selects the first available GPU, or CPU if no GPU is available. |
''
|
batch
|
int
|
Batch size being used in your model. |
0
|
newline
|
bool
|
If True, adds a newline at the end of the log string. |
False
|
verbose
|
bool
|
If True, logs the device information. |
True
|
Returns:
Type | Description |
---|---|
device
|
Selected device. |
Raises:
Type | Description |
---|---|
ValueError
|
If the specified device is not available or if the batch size is not a multiple of the number of devices when using multiple GPUs. |
Examples:
>>> select_device("cuda:0")
device(type='cuda', index=0)
>>> select_device("cpu")
device(type='cpu')
Note
Sets the 'CUDA_VISIBLE_DEVICES' environment variable for specifying which GPUs to use.
Source code in ultralytics/utils/torch_utils.py
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 |
|
ultralytics.utils.torch_utils.time_sync
time_sync()
PyTorch-accurate time.
Source code in ultralytics/utils/torch_utils.py
242 243 244 245 246 |
|
ultralytics.utils.torch_utils.fuse_conv_and_bn
fuse_conv_and_bn(conv, bn)
Fuse Conv2d() and BatchNorm2d() layers.
Source code in ultralytics/utils/torch_utils.py
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 |
|
ultralytics.utils.torch_utils.fuse_deconv_and_bn
fuse_deconv_and_bn(deconv, bn)
Fuse ConvTranspose2d() and BatchNorm2d() layers.
Source code in ultralytics/utils/torch_utils.py
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 |
|
ultralytics.utils.torch_utils.model_info
model_info(model, detailed=False, verbose=True, imgsz=640)
Print and return detailed model information layer by layer.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model
|
Module
|
Model to analyze. |
required |
detailed
|
bool
|
Whether to print detailed layer information. Defaults to False. |
False
|
verbose
|
bool
|
Whether to print model information. Defaults to True. |
True
|
imgsz
|
int | List
|
Input image size. Defaults to 640. |
640
|
Returns:
Type | Description |
---|---|
Tuple[int, int, int, float]
|
Number of layers, parameters, gradients, and GFLOPs. |
Source code in ultralytics/utils/torch_utils.py
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 |
|
ultralytics.utils.torch_utils.get_num_params
get_num_params(model)
Return the total number of parameters in a YOLO model.
Source code in ultralytics/utils/torch_utils.py
356 357 358 |
|
ultralytics.utils.torch_utils.get_num_gradients
get_num_gradients(model)
Return the total number of parameters with gradients in a YOLO model.
Source code in ultralytics/utils/torch_utils.py
361 362 363 |
|
ultralytics.utils.torch_utils.model_info_for_loggers
model_info_for_loggers(trainer)
Return model info dict with useful model information.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
trainer
|
BaseTrainer
|
The trainer object containing model and validation data. |
required |
Returns:
Type | Description |
---|---|
dict
|
Dictionary containing model parameters, GFLOPs, and inference speeds. |
Examples:
YOLOv8n info for loggers
>>> results = {
... "model/parameters": 3151904,
... "model/GFLOPs": 8.746,
... "model/speed_ONNX(ms)": 41.244,
... "model/speed_TensorRT(ms)": 3.211,
... "model/speed_PyTorch(ms)": 18.755,
...}
Source code in ultralytics/utils/torch_utils.py
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 |
|
ultralytics.utils.torch_utils.get_flops
get_flops(model, imgsz=640)
Calculate FLOPs (floating point operations) for a model in billions.
Attempts two calculation methods: first with a stride-based tensor for efficiency, then falls back to full image size if needed (e.g., for RTDETR models). Returns 0.0 if thop library is unavailable or calculation fails.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model
|
Module
|
The model to calculate FLOPs for. |
required |
imgsz
|
int | List[int]
|
Input image size. Defaults to 640. |
640
|
Returns:
Type | Description |
---|---|
float
|
The model FLOPs in billions. |
Source code in ultralytics/utils/torch_utils.py
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 |
|
ultralytics.utils.torch_utils.get_flops_with_torch_profiler
get_flops_with_torch_profiler(model, imgsz=640)
Compute model FLOPs using torch profiler (alternative to thop package, but 2-10x slower).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model
|
Module
|
The model to calculate FLOPs for. |
required |
imgsz
|
int | List[int]
|
Input image size. Defaults to 640. |
640
|
Returns:
Type | Description |
---|---|
float
|
The model's FLOPs in billions. |
Source code in ultralytics/utils/torch_utils.py
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 |
|
ultralytics.utils.torch_utils.initialize_weights
initialize_weights(model)
Initialize model weights to random values.
Source code in ultralytics/utils/torch_utils.py
476 477 478 479 480 481 482 483 484 485 486 |
|
ultralytics.utils.torch_utils.scale_img
scale_img(img, ratio=1.0, same_shape=False, gs=32)
Scales and pads an image tensor, optionally maintaining aspect ratio and padding to gs multiple.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
img
|
Tensor
|
Input image tensor. |
required |
ratio
|
float
|
Scaling ratio. Defaults to 1.0. |
1.0
|
same_shape
|
bool
|
Whether to maintain the same shape. Defaults to False. |
False
|
gs
|
int
|
Grid size for padding. Defaults to 32. |
32
|
Returns:
Type | Description |
---|---|
Tensor
|
Scaled and padded image tensor. |
Source code in ultralytics/utils/torch_utils.py
489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 |
|
ultralytics.utils.torch_utils.copy_attr
copy_attr(a, b, include=(), exclude=())
Copies attributes from object 'b' to object 'a', with options to include/exclude certain attributes.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
a
|
object
|
Destination object to copy attributes to. |
required |
b
|
object
|
Source object to copy attributes from. |
required |
include
|
tuple
|
Attributes to include. If empty, all attributes are included. Defaults to (). |
()
|
exclude
|
tuple
|
Attributes to exclude. Defaults to (). |
()
|
Source code in ultralytics/utils/torch_utils.py
512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 |
|
ultralytics.utils.torch_utils.get_latest_opset
get_latest_opset()
Return the second-most recent ONNX opset version supported by this version of PyTorch, adjusted for maturity.
Returns:
Type | Description |
---|---|
int
|
The ONNX opset version. |
Source code in ultralytics/utils/torch_utils.py
529 530 531 532 533 534 535 536 537 538 539 540 541 |
|
ultralytics.utils.torch_utils.intersect_dicts
intersect_dicts(da, db, exclude=())
Returns a dictionary of intersecting keys with matching shapes, excluding 'exclude' keys, using da values.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
da
|
dict
|
First dictionary. |
required |
db
|
dict
|
Second dictionary. |
required |
exclude
|
tuple
|
Keys to exclude. Defaults to (). |
()
|
Returns:
Type | Description |
---|---|
dict
|
Dictionary of intersecting keys with matching shapes. |
Source code in ultralytics/utils/torch_utils.py
544 545 546 547 548 549 550 551 552 553 554 555 556 |
|
ultralytics.utils.torch_utils.is_parallel
is_parallel(model)
Returns True if model is of type DP or DDP.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model
|
Module
|
Model to check. |
required |
Returns:
Type | Description |
---|---|
bool
|
True if model is DataParallel or DistributedDataParallel. |
Source code in ultralytics/utils/torch_utils.py
559 560 561 562 563 564 565 566 567 568 569 |
|
ultralytics.utils.torch_utils.de_parallel
de_parallel(model)
De-parallelize a model: returns single-GPU model if model is of type DP or DDP.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model
|
Module
|
Model to de-parallelize. |
required |
Returns:
Type | Description |
---|---|
Module
|
De-parallelized model. |
Source code in ultralytics/utils/torch_utils.py
572 573 574 575 576 577 578 579 580 581 582 |
|
ultralytics.utils.torch_utils.one_cycle
one_cycle(y1=0.0, y2=1.0, steps=100)
Returns a lambda function for sinusoidal ramp from y1 to y2 https://arxiv.org/pdf/1812.01187.pdf.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
y1
|
float
|
Initial value. Defaults to 0.0. |
0.0
|
y2
|
float
|
Final value. Defaults to 1.0. |
1.0
|
steps
|
int
|
Number of steps. Defaults to 100. |
100
|
Returns:
Type | Description |
---|---|
function
|
Lambda function for computing the sinusoidal ramp. |
Source code in ultralytics/utils/torch_utils.py
585 586 587 588 589 590 591 592 593 594 595 596 597 |
|
ultralytics.utils.torch_utils.init_seeds
init_seeds(seed=0, deterministic=False)
Initialize random number generator (RNG) seeds https://pytorch.org/docs/stable/notes/randomness.html.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
seed
|
int
|
Random seed. Defaults to 0. |
0
|
deterministic
|
bool
|
Whether to set deterministic algorithms. Defaults to False. |
False
|
Source code in ultralytics/utils/torch_utils.py
600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 |
|
ultralytics.utils.torch_utils.unset_deterministic
unset_deterministic()
Unsets all the configurations applied for deterministic training.
Source code in ultralytics/utils/torch_utils.py
626 627 628 629 630 631 |
|
ultralytics.utils.torch_utils.strip_optimizer
strip_optimizer(
f: Union[str, Path] = "best.pt", s: str = "", updates: dict = None
) -> dict
Strip optimizer from 'f' to finalize training, optionally save as 's'.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
f
|
str | Path
|
File path to model to strip the optimizer from. Defaults to 'best.pt'. |
'best.pt'
|
s
|
str
|
File path to save the model with stripped optimizer to. If not provided, 'f' will be overwritten. |
''
|
updates
|
dict
|
A dictionary of updates to overlay onto the checkpoint before saving. |
None
|
Returns:
Type | Description |
---|---|
dict
|
The combined checkpoint dictionary. |
Examples:
>>> from pathlib import Path
>>> from ultralytics.utils.torch_utils import strip_optimizer
>>> for f in Path("path/to/model/checkpoints").rglob("*.pt"):
>>> strip_optimizer(f)
Source code in ultralytics/utils/torch_utils.py
702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 |
|
ultralytics.utils.torch_utils.convert_optimizer_state_dict_to_fp16
convert_optimizer_state_dict_to_fp16(state_dict)
Converts the state_dict of a given optimizer to FP16, focusing on the 'state' key for tensor conversions.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
state_dict
|
dict
|
Optimizer state dictionary. |
required |
Returns:
Type | Description |
---|---|
dict
|
Converted optimizer state dictionary with FP16 tensors. |
Source code in ultralytics/utils/torch_utils.py
762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 |
|
ultralytics.utils.torch_utils.cuda_memory_usage
cuda_memory_usage(device=None)
Monitor and manage CUDA memory usage.
This function checks if CUDA is available and, if so, empties the CUDA cache to free up unused memory. It then yields a dictionary containing memory usage information, which can be updated by the caller. Finally, it updates the dictionary with the amount of memory reserved by CUDA on the specified device.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
device
|
device
|
The CUDA device to query memory usage for. Defaults to None. |
None
|
Yields:
Type | Description |
---|---|
dict
|
A dictionary with a key 'memory' initialized to 0, which will be updated with the reserved memory. |
Source code in ultralytics/utils/torch_utils.py
780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 |
|
ultralytics.utils.torch_utils.profile_ops
profile_ops(input, ops, n=10, device=None, max_num_obj=0)
Ultralytics speed, memory and FLOPs profiler.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
input
|
Tensor | List[Tensor]
|
Input tensor(s) to profile. |
required |
ops
|
Module | List[Module]
|
Model or list of operations to profile. |
required |
n
|
int
|
Number of iterations to average. Defaults to 10. |
10
|
device
|
str | device
|
Device to profile on. Defaults to None. |
None
|
max_num_obj
|
int
|
Maximum number of objects for simulation. Defaults to 0. |
0
|
Returns:
Type | Description |
---|---|
list
|
Profile results for each operation. |
Examples:
>>> from ultralytics.utils.torch_utils import profile_ops
>>> input = torch.randn(16, 3, 640, 640)
>>> m1 = lambda x: x * torch.sigmoid(x)
>>> m2 = nn.SiLU()
>>> profile_ops(input, [m1, m2], n=100) # profile over 100 iterations
Source code in ultralytics/utils/torch_utils.py
806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 |
|