DanLing¶
danling
¶
AverageMeter
¶
Computes and stores the average and current value.
Attributes:
Name | Type | Description |
---|---|---|
val |
Results of current batch on current device. |
|
bat |
Results of current batch on all devices. |
|
avg |
Results of all results on all devices. |
|
sum |
float
|
Sum of values. |
count |
float
|
Number of values. |
See Also
[MetricMeter
]: Average Meter with metric function built-in.
[AverageMeters
]: Manage multiple average meters in one object.
[MultiTaskAverageMeters
]: Manage multiple average meters in one object with multi-task support.
Examples:
Python Console Session | |
---|---|
Source code in danling/metric/average_meter.py
Python | |
---|---|
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 |
|
AverageMeters
¶
Bases: MetricsDict
Manages multiple average meters in one object.
See Also
[AverageMeter
]: Computes and stores the average and current value.
[MultiTaskAverageMeters
]: Manage multiple average meters in one object with multi-task support.
[MetricMeters
]: Manage multiple metric meters in one object.
Examples:
Source code in danling/metric/average_meter.py
update
¶
Updates the average and current value in all meters.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
int | float
|
Dict of values to be added to the average. |
{}
|
|
Number of values to be added. |
required |
Raises:
Type | Description |
---|---|
ValueError
|
If the value is not an instance of (int, float). |
Source code in danling/metric/average_meter.py
MetricMeter
¶
Bases: AverageMeter
Computes metrics and averages them over time.
Attributes:
Name | Type | Description |
---|---|---|
metric |
Callable
|
Metric function for computing the value. |
ignore_index |
int
|
Index to be ignored in the computation. |
ignore_nan |
bool
|
Whether to ignore NaN values in the computation. |
val |
Results of current batch on current device. |
|
bat |
Results of current batch on all devices. |
|
avg |
Results of all results on all devices. |
|
sum |
float
|
Sum of values. |
count |
float
|
Number of values. |
See Also
[AverageMeter
]: Average meter for computed values.
[MetricMeters
]: Manage multiple metric meters in one object.
Examples:
Source code in danling/metric/metric_meter.py
update
¶
update(
input: Tensor | NestedTensor | Sequence,
target: Tensor | NestedTensor | Sequence,
preprocessed: bool = False,
) -> None
Updates the average and current value in the meter.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
Value to be added to the average. |
required | |
|
Number of values to be added. |
required |
Source code in danling/metric/metric_meter.py
MetricMeters
¶
Bases: AverageMeters
Manages multiple metric meters in one object.
Attributes:
Name | Type | Description |
---|---|---|
ignore_index |
Index to be ignored in the computation. Defaults to None. |
|
ignore_nan |
Whether to ignore NaN values in the computation. Defaults to False. |
See Also
[MetricMeter
]: Computes metrics and averages them over time.
[AverageMeters
]: Average meters for computed values.
from danling.metric.functional import accuracy, auroc, auprc meters = MetricMeters(acc=accuracy, auroc=auroc, auprc=auprc) meters.update([0.1, 0.8, 0.6, 0.2], [0, 1, 0, 0]) meters.sum.dict() {‘acc’: 3.0, ‘auroc’: 4.0, ‘auprc’: 4.0} meters.count.dict() {‘acc’: 4, ‘auroc’: 4, ‘auprc’: 4} meters[‘auroc’].update([0.2, 0.8], [0, 1]) meters.sum.dict() {‘acc’: 3.0, ‘auroc’: 6.0, ‘auprc’: 4.0} meters.count.dict() {‘acc’: 4, ‘auroc’: 6, ‘auprc’: 4} meters.update([[0.1, 0.7, 0.3, 0.2], [0.8, 0.4]], [[0, 0, 1, 0], [0, 0]]) meters.sum.dict() {‘acc’: 6.0, ‘auroc’: 8.4, ‘auprc’: 5.5} meters.count.dict() {‘acc’: 10, ‘auroc’: 12, ‘auprc’: 10} meters[‘auroc’].update([0.4, 0.8, 0.6, 0.2], [0, 1, 1, 0]) meters.avg.dict() {‘acc’: 0.6, ‘auroc’: 0.775, ‘auprc’: 0.55} meters.update(dict(loss=”“)) # doctest: +ELLIPSIS Traceback (most recent call last): TypeError: …update() missing 1 required positional argument: ‘target’
Source code in danling/metric/metric_meter.py
Python | |
---|---|
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 |
|
update
¶
update(
input: Tensor | NestedTensor | Sequence,
target: Tensor | NestedTensor | Sequence,
) -> None
Updates the average and current value in all meters.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
Tensor | NestedTensor | Sequence
|
Input values to compute the metrics. |
required |
|
Tensor | NestedTensor | Sequence
|
Target values to compute the metrics. |
required |
Source code in danling/metric/metric_meter.py
MultiTaskAverageMeters
¶
Bases: MultiTaskDict
Manages multiple average meters in one object with multi-task support.
See Also
[AverageMeter
]: Computes and stores the average and current value.
[AverageMeters
]: Manage multiple average meters in one object.
[MetricMeters
]: Manage multiple metric meters in one object.
Examples:
Source code in danling/metric/average_meter.py
Python | |
---|---|
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 |
|
update
¶
Updates the average and current value in all meters.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
float
|
Dict of values to be added to the average. |
{}
|
|
Number of values to be added. |
required |
Raises:
Type | Description |
---|---|
ValueError
|
If the value is not an instance of (int, float, Mapping). |
Source code in danling/metric/average_meter.py
MultiTaskMetricMeters
¶
Bases: MultiTaskAverageMeters
Examples:
Source code in danling/metric/metric_meter.py
Python | |
---|---|
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 |
|
update
¶
update(
values: Mapping[
str,
Tuple[
Tensor | NestedTensor | Sequence,
Tensor | NestedTensor | Sequence,
],
]
) -> None
Updates the average and current value in all meters.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
Input values to compute the metrics. |
required | |
|
Target values to compute the metrics. |
required |
Source code in danling/metric/metric_meter.py
LRScheduler
¶
Bases: _LRScheduler
General learning rate scheduler.
PyTorch LRScheduler is hard to extend. This class is a wrapper of PyTorch LRScheduler, which provides a more general interface. You only needs to add a new method which calculates a learning rate ratio (range from 0 to 1) with total progress (range from 0 to 1), and everything else will be done automatically.
Moreover, this class has warmup and cooldown built-in.
By default, the first 5% and last 20% of training steps will be warmup and cooldown respectively.
You can alternate by passing warmup_steps
and cooldown_steps
, or disable them by setting them to 0.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
Optimizer
|
Wrapped optimizer. |
required |
|
int
|
Total number of trainable steps. |
required |
|
Optional[float]
|
Final learning rate ratio to initial learning rate. Defaults to 1e-3. |
None
|
|
Optional[float]
|
Final learning rate. |
None
|
|
float
|
Minimal learning rate. Defaults to 1e-9. |
1e-09
|
|
str
|
Scaling strategy. Defaults to “cosine”. |
'cosine'
|
|
Optional[int]
|
Number of warmup steps.
Defaults to |
None
|
|
Optional[int]
|
Number of cooldown steps.
Defaults to |
None
|
|
int
|
The index of last epoch. Defaults to -1. |
-1
|
|
Optional[str]
|
Method to calculate learning rate given ratio, should be one of “percentile” or “numerical”.
Defaults to “percentile” if |
None
|
Examples:
Source code in danling/optim/lr_scheduler/lr_scheduler.py
Python | |
---|---|
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 202 203 |
|
AccelerateRunner
¶
Bases: TorchRunner
, Accelerator
Set up everything for running a job with 🤗 accelerate
.
AccelerateRunner
extends the Accelerator
class to provide a more user-friendly
and consistent interface.
AccelerateRunner
provides the most easy-to-use interface for distributed training, but it can be slow, and not
very flexible.
Read the documentation of Accelerator
for more details.
Source code in danling/runner/accelerate_runner.py
Python | |
---|---|
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 |
|
advance
¶
advance(loss) -> None
Backward loss and step optimizer & scheduler.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
The loss tensor from which to backpropagate. |
required |
Source code in danling/runner/accelerate_runner.py
BaseRunner
¶
Base class for DanLing runners.
The BaseRunner
class provides a complete infrastructure for managing:
-
Experiment Environment: Sets up reproducible training environment with:
- Random seed management
- Deterministic execution options
- Configurable logging systems
-
Experiment Lifecycle: Handles the complete experiment workflow:
- Model, optimizer, and scheduler setup
- Dataset and dataloader management
- Training, evaluation, and inference loops
- Checkpointing and restoration
-
Experiment Tracking: Provides comprehensive experiment monitoring:
- Progress tracking
- Metrics computation and logging
- Results collection and comparison
- Best model selection
-
Distributed Training: Supports various parallel training configurations:
- Multi-process distributed training
- Gradient accumulation
- Mixed precision training
This class defines standard attributes and methods that can be extended by more specialized runners. It is designed to be modular and configurable to support various experiment requirements.
ID:
Name | Type | Description |
---|---|---|
timestamp |
str
|
Time string of when the runner was created.
Format: |
name |
str
|
Human-readable name combining experiment and run names ( |
id |
str
|
Unique identifier generated from experiment and run IDs. |
uuid |
UUID
|
UUID5 generated from the run ID and combined ID. |
Model:
Name | Type | Description |
---|---|---|
model |
Callable | None
|
The model being trained/evaluated. |
criterion |
Callable | None
|
Loss function used for optimization. |
optimizer |
Any | None
|
Optimizer used for parameter updates. |
scheduler |
Any | None
|
Learning rate scheduler for adaptive learning rates. |
Data:
Name | Type | Description |
---|---|---|
datasets |
FlatDict
|
Dictionary mapping split names to dataset objects. |
datasamplers |
FlatDict
|
Dictionary mapping split names to data samplers. |
dataloaders |
FlatDict
|
Dictionary mapping split names to dataloader objects. |
split |
str | None
|
Current active data split. |
batch_size |
int
|
Number of samples per batch for current split. |
batch_size_equivalent |
int
|
Total effective batch size accounting for distribution. |
Progress:
Name | Type | Description |
---|---|---|
progress |
float
|
Running progress as a value between 0 and 1. |
steps |
int
|
Current step count. |
epochs |
int
|
Current epoch count. |
total_steps |
int
|
Total steps to be performed. |
total_epochs |
int
|
Total epochs to be performed. |
Results:
Name | Type | Description |
---|---|---|
results |
NestedDict
|
Hierarchical results organized by epoch, split, and metric. |
latest_result |
NestedDict | None
|
Most recent evaluation results. |
best_result |
NestedDict | None
|
Best evaluation results achieved. |
scores |
FlatDict | None
|
Main metric values used for model comparison. |
latest_score |
float | None
|
Most recent score. |
best_score |
float | None
|
Best score achieved. |
is_best |
bool
|
Whether the latest result is the best so far. |
I/O:
Name | Type | Description |
---|---|---|
dir |
str
|
Root directory for all experiment outputs. |
checkpoint_dir |
str
|
Directory for saving model checkpoints. |
log_file |
str
|
Path to the log file. |
Distributed Training:
Name | Type | Description |
---|---|---|
world_size |
int
|
Number of processes in distributed training. |
rank |
int
|
Global process rank. |
local_rank |
int
|
Local process rank on current node. |
distributed |
bool
|
Whether running in distributed mode. |
is_main_process |
bool
|
Whether current process is the main process. |
Logging and Visualization:
Name | Type | Description |
---|---|---|
meters |
AverageMeters
|
Meters for tracking running averages of metrics. |
metrics |
Metrics | MetricMeters | None
|
Metric computation objects. |
logger |
Logger | None
|
Logger for capturing runtime information. |
writer |
Any | None
|
Writer for visualizing metrics (e.g., TensorBoard). |
Source code in danling/runner/base_runner.py
Python | |
---|---|
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 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 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 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 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 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 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 1171 1172 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 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 |
|
batch_size
property
¶
batch_size: int
Batch size.
Note
If self.dataloaders
is specified:
- If self.split
is specified, batch_size
is the batch size of self.split
.
- If self.train_splits
is specified, batch_size
is the batch size of the first split.
- If self.evaluate_splits
is specified, batch_size
is the batch size of the first split.
- Otherwise, batch_size
is the batch size of the first dataloader.
Otherwise, batch_size
is the batch size specified in self.config.dataloader.batch_size
.
batch_size_equivalent
property
¶
batch_size_equivalent: int
The effective total batch size across all processes and gradient accumulation steps.
This property calculates the total number of examples processed in a single optimization step by accounting for: - The base batch size per device - The number of processes (world_size for distributed training) - The number of gradient accumulation steps
This is particularly useful for: - Learning rate scaling using the linear scaling rule - Calculating the total steps in an epoch - Estimating memory requirements across all devices
Returns:
Type | Description |
---|---|
int
|
Effective batch size calculated as |
is_main_process
property
¶
is_main_process: bool
If current process is the main process of all processes.
is_local_main_process
property
¶
is_local_main_process: bool
If current process is the main process of local processes.
best_fn
property
¶
best_fn: Callable
Function to determine the best score from a list of scores.
By default, the best_fn
returns min
if self.config.score_name
is loss
,
otherwise, returns max
.
Subclass can override this method to accommodate needs, such as min
.
scores
property
¶
scores: FlatDict | None
All scores.
Scores are extracted from results by score_split
and runner.config.score_name
,
following [r[score_split][self.config.score_name] for r in self.results]
.
Scores are considered as the index of the performance of the model. It is useful to determine the best model and the best hyper-parameters.
score_split
is defined in self.config.score_split
.
If it is not set, DanLing
will use val
or validate
if they appear in the latest_result
.
If DanLing
still could not find, it will fall back to the second key in the latest_result
if it contains more that one element, or the first key.
Note that certain keys are ignored when falling back, they are defined in {defaults.IGNORED_NAMES_IN_METRICS}.
is_best
property
¶
is_best: bool
Determines whether the latest model checkpoint is the best performing one.
This property compares the latest_score
with the best_score
to determine
if the most recent model evaluation represents the best performance achieved
so far. The comparison uses a small epsilon (1e-7) to handle floating point
comparison issues.
The property is used by:
- save_checkpoint
method to determine whether to save a “best.pth” checkpoint
- Result logging and reporting mechanisms
- Early stopping implementations
Returns:
Type | Description |
---|---|
bool
|
True if the latest evaluation results represent the best performance or if no results exist yet, False otherwise. |
Note
- Returns True if no results exist (first evaluation)
- Uses numerical comparison with tolerance to avoid floating point issues
- The definition of “best” depends on the metric (maximization for accuracy,
minimization for loss, etc.) and is handled by the
best_fn
property
See Also
best_score
: The best score achieved so far.
latest_score
: The most recent score.
best_fn
: Function defining “best” (min/max).
init_distributed
¶
init_logging
¶
Set up logging.
Source code in danling/runner/base_runner.py
init_print
¶
Set up print
.
Only print on a specific process
or when force = True
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
int
|
The process to |
0
|
Note
If self.config.log = True
, the default print
function will be override by logging.info
.
Source code in danling/runner/base_runner.py
init_tensorboard
¶
set_seed
¶
Set random seeds for reproducibility across the application.
This method configures the random number generators for various libraries
to ensure reproducible behavior in experiments. In the base implementation,
it sets seeds for Python’s built-in random
module and NumPy’s random
generators if available.
Derived runners typically extend this method to set seeds for additional libraries (e.g., PyTorch, TensorFlow).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
int
|
The base random seed to use.
If None, uses the value from |
None
|
|
int
|
An offset to add to the seed for process-specific randomness.
- If specified, adds this value to the seed
- If None, uses Using a per-process bias is important in distributed training to avoid all processes applying identical data augmentation. |
None
|
Returns:
Name | Type | Description |
---|---|---|
int |
int
|
The actual seed that was set (after applying bias) |
Examples:
Set seed from config¶
runner.set_seed()
Set specific seed¶
runner.set_seed(42)
Set seed with explicit bias¶
runner.set_seed(42, bias=10)
Set same seed for all processes (not recommended for data augmentation)¶
runner.set_seed(42, bias=False)
Note
- Setting seeds is essential for reproducible experiments
- Different biases across processes ensure diverse data augmentation
- Subclasses should call
super().set_seed()
if overriding
Source code in danling/runner/base_runner.py
set_deterministic
¶
scale_lr
¶
scale_lr(
lr: float,
lr_scale_factor: float | None = None,
batch_size_base: int | None = None,
) -> float
Scale learning rate according to linear scaling rule.
Source code in danling/runner/base_runner.py
advance
¶
advance(loss, *args, **kwargs) -> None
Backward loss and step optimizer & scheduler.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
loss. |
required |
state_dict
¶
dict
¶
save
¶
Save any file with supported extensions.
Runner.save
internally calls dl.save
,
but with additional arguments to allow it save only on the main process.
Moreover, any error raised by Runner.save
will be caught and logged.
Source code in danling/runner/base_runner.py
load
staticmethod
¶
load(file: PathStr, *args, **kwargs) -> Any
Load any file with supported extensions.
Runner.load
is identical to dl.load
.
json
¶
json(
file: File,
main_process_only: bool = True,
*args,
**kwargs
) -> None
Dump Runner config to json file.
Source code in danling/runner/base_runner.py
Python | |
---|---|
from_json
classmethod
¶
from_json(file: File, *args, **kwargs) -> BaseRunner
Construct Runner from json file.
This function calls self.from_jsons()
to construct object from json string.
You may overwrite from_jsons
in case something is not json serializable.
Source code in danling/runner/base_runner.py
from_jsons
classmethod
¶
from_jsons(string: str, *args, **kwargs) -> BaseRunner
yaml
¶
yaml(
file: File,
main_process_only: bool = True,
*args,
**kwargs
) -> None
Dump Runner config to yaml file.
Source code in danling/runner/base_runner.py
Python | |
---|---|
from_yaml
classmethod
¶
from_yaml(file: File, *args, **kwargs) -> BaseRunner
Construct Runner from yaml file.
This function calls self.from_yamls()
to construct object from yaml string.
You may overwrite from_yamls
in case something is not yaml serializable.
Source code in danling/runner/base_runner.py
from_yamls
classmethod
¶
from_yamls(string: str, *args, **kwargs) -> BaseRunner
check_dir
¶
Check if self.dir
is not empty.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
str
|
The action to perform if |
'warn'
|
Source code in danling/runner/base_runner.py
save_checkpoint
¶
save_checkpoint(
name: str = "latest",
epochs: int | None = None,
save_best: bool = True,
) -> None
Save the current model state and runner configuration to a checkpoint file.
This method saves the complete state of the runner, including model weights, optimizer state, scheduler state, and configuration to the checkpoint directory. The method handles various checkpoint naming strategies based on parameters.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
str
|
Base name of the checkpoint file (without extension).
Defaults to |
'latest'
|
|
int | None
|
Epoch number to record in the checkpoint.
If None, uses |
None
|
|
bool
|
Whether to also save a copy of the checkpoint as |
True
|
Note
- Checkpoints are saved only on the main process in distributed training.
- The format is determined by the extension, defaulting to
.pth
. - The checkpoint includes the complete runner state from
self.state_dict()
. - Periodic checkpoints are saved based on
save_interval
configuration: Ifself.config.save_interval > 0
and(epochs + 1) % save_interval == 0
, the checkpoint will be copied to{checkpoint_dir}/epoch-{epochs}.pth
.
See Also
load_checkpoint
: Load a saved checkpoint.
state_dict
: Get the state dictionary to save.
Source code in danling/runner/base_runner.py
load_config
¶
load_config(
checkpoint: Mapping | bytes | str | PathLike,
overwrite: bool = False,
*args,
**kwargs
) -> None
Load config from checkpoint.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
Mapping | bytes | str | PathLike
|
Checkpoint (or its path) to load. |
required |
|
bool
|
If |
False
|
|
Additional arguments to pass to |
()
|
|
|
Additional keyword arguments to pass to |
{}
|
Raises:
Type | Description |
---|---|
FileNotFoundError
|
If |
Source code in danling/runner/base_runner.py
load_checkpoint
¶
Restore model, optimizer, and scheduler states from a saved checkpoint.
This method loads the complete training state from a checkpoint, including: - Model weights and parameters - Optimizer state (learning rates, momentum buffers, etc.) - Learning rate scheduler state
The method supports loading from either: - A file path (str, bytes, PathLike) - An already loaded checkpoint dictionary (Mapping)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
Mapping | bytes | str | PathLike
|
The checkpoint to load from, which can be: - A path to the checkpoint file - A pre-loaded checkpoint dictionary |
required |
|
Additional arguments passed to the underlying |
()
|
|
|
Additional keyword arguments passed to the underlying |
{}
|
Raises:
Type | Description |
---|---|
ValueError
|
If |
ValueError
|
If |
FileNotFoundError
|
If the checkpoint file specified does not exist. |
Note
- This method attempts to unwrap the model before loading (useful for distributed training wrappers)
- Unlike
load_config
, this method loads both model parameters and optimizer/scheduler states - Missing optimizer or scheduler states in the checkpoint will produce warnings but not errors
- The checkpoint is stored in
self.config.checkpoint
for reference
Example
See Also
from_checkpoint
: Build a new runner instance from checkpoint.
load_pretrained
: Load only model parameters from a checkpoint.
save_checkpoint
: Save current state to a checkpoint.
Source code in danling/runner/base_runner.py
from_checkpoint
classmethod
¶
from_checkpoint(
checkpoint: Mapping | bytes | str | PathLike,
*args,
**kwargs
) -> BaseRunner
Build BaseRunner from checkpoint.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
Mapping | bytes | str | PathLike
|
Checkpoint (or its path) to load. |
required |
|
Additional arguments to pass to |
()
|
|
|
Additional keyword arguments to pass to |
{}
|
Returns:
Type | Description |
---|---|
BaseRunner
|
|
Source code in danling/runner/base_runner.py
load_pretrained
¶
Load model from pretrained checkpoint.
This method only loads the model weights.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
Mapping | bytes | str | PathLike
|
Pretrained checkpoint (or its path) to load. |
required |
|
Additional arguments to pass to |
()
|
|
|
Additional keyword arguments to pass to |
{}
|
Raises:
Type | Description |
---|---|
ValueError
|
If |
ValueError
|
If |
FileNotFoundError
|
If |
See Also
load_checkpoint
: Load model, optimizer, and scheduler from
checkpoint.
Source code in danling/runner/base_runner.py
append_result
¶
append_result(
result: NestedDict, index: int | None = None
) -> None
Append result to self.results
.
Source code in danling/runner/base_runner.py
print_result
¶
save_result
¶
Save result to self.dir
.
This method will save latest and best result to
self.dir/latest.json
and self.dir/best.json
respectively.
Source code in danling/runner/base_runner.py
Config
¶
Bases: Config
Config
is a Config
that contains all states of a Runner
.
Config
is designed to store all critical information of a Run so that you can resume a run
from a state and corresponding weights or even restart a run from a state.
Config
is also designed to be serialisable and hashable, so that you can save it to a file.
Config
is saved in checkpoint together with weights by default.
Since Config
is a Config
, you can access its attributes by
state["key"]
or state.key
.
General:
Name | Type | Description |
---|---|---|
run_name |
str
|
Defaults to |
run_id |
str
|
hex of |
run_uuid |
(UUID, property)
|
|
experiment_name |
str
|
Defaults to |
experiment_id |
str
|
git hash of the current HEAD.
Defaults to |
experiment_uuid |
(UUID, property)
|
UUID of |
Reproducibility:
Name | Type | Description |
---|---|---|
seed |
int
|
Defaults to |
deterministic |
bool
|
Ensure deterministic operations.
Defaults to |
Progress:
Name | Type | Description |
---|---|---|
steps |
int
|
The number of |
epochs |
int
|
The number of complete passes over the datasets. |
step_end |
int
|
End running step.
Note that |
epoch_end |
int
|
End running epoch.
Note that |
In general you should use either step_end
or epoch_end
to indicate the length of running.
IO:
Name | Type | Description |
---|---|---|
project_root |
str
|
The root directory for all experiments.
Defaults to |
project_root
is the root directory of all Experiments, and should be consistent across the Project.
dir
is the directory of a certain Run.
There is no attributes/properties for Group and Experiment.
checkpoint_dir_name
is relative to dir
, and is passed to generate checkpoint_dir
(checkpoint_dir = os.path.join(dir, checkpoint_dir_name)
).
In practice, checkpoint_dir_name
is rarely called.
logging:
Name | Type | Description |
---|---|---|
log |
bool
|
Whether to log the outputs.
Defaults to |
tensorboard |
bool
|
Whether to use |
log_interval |
int
|
Interval of printing logs.
Defaults to |
save_interval |
int
|
Interval of saving intermediate checkpoints.
Defaults to |
Note
Config
is a Config
, so you can access its attributes by state["name"]
or state.name
.
See Also
BaseRunner
: The base runner class.
Source code in danling/runner/config.py
Python | |
---|---|
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 |
|
DeepSpeedRunner
¶
Bases: TorchRunner
Set up everything for running a job with DeepSpeed.
DeepSpeed is a distributed training framework that provides a more efficient way to run large-scale models.
Configure DeepSpeedRunner is tough, but once you get the hang of it, it’s a powerful tool. Read more about DeepSpeed at DeepSpeed’s official website.
Source code in danling/runner/deepspeed_runner.py
Python | |
---|---|
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 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 |
|
init_distributed
¶
Set up distributed training.
Initialise process group and set up DDP variables.
Source code in danling/runner/deepspeed_runner.py
save_checkpoint
¶
save_checkpoint(
name: str = "latest",
epoch: int | None = None,
save_best: bool = True,
) -> None
Save checkpoint to self.checkpoint_dir
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
str
|
Name of the checkpoint. Defaults to |
'latest'
|
|
int | None
|
Epoch to save. Defaults to |
None
|
|
bool
|
If |
True
|
If self.config.save_interval
is positive and epochs + 1
is a multiple of save_interval
,
the checkpoint will also be copied to self.checkpoint_dir/epoch-{epochs}
.
Source code in danling/runner/deepspeed_runner.py
load_checkpoint
¶
Load model, optimizer, and scheduler from checkpoint.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
bytes | str | PathLike
|
Checkpoint (or its path) to load. |
required |
|
Additional arguments to pass to |
()
|
|
|
Additional keyword arguments to pass to |
{}
|
Raises:
Type | Description |
---|---|
ValueError
|
If |
ValueError
|
If |
See Also
from_checkpoint
: Build runner from checkpoint.
load_pretrained
: Load model parameters from pretrained checkpoint.
Source code in danling/runner/deepspeed_runner.py
load_pretrained
¶
Load model from pretrained checkpoint.
This method only loads the model weights.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
bytes | str | PathLike
|
Pretrained checkpoint directory. |
required |
|
Additional arguments to pass to |
()
|
|
|
Additional keyword arguments to pass to |
{}
|
Raises:
Type | Description |
---|---|
ValueError
|
If |
See Also
load_checkpoint
: Load model, optimizer, and scheduler from
checkpoint.
Source code in danling/runner/deepspeed_runner.py
load_config
¶
load_config(
checkpoint: bytes | str | PathLike,
overwrite: bool = False,
*args,
**kwargs
) -> None
Load config from checkpoint.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
bytes | str | PathLike
|
Checkpoint (or its path) to load. |
required |
|
bool
|
If |
False
|
|
Additional arguments to pass to |
()
|
|
|
Additional keyword arguments to pass to |
{}
|
Raises:
Type | Description |
---|---|
FileNotFoundError
|
If |
Source code in danling/runner/deepspeed_runner.py
Runner
¶
Bases: BaseRunner
Dynamic runner class that selects the appropriate platform based on configuration.
This runner dynamically changes its class to combine with the appropriate platform (torch, accelerate, or deepspeed) based on the ‘platform’ configuration option.
It’s safe (and recommended) to inherit from this class to extend the Runner.
Valid platform options are:
- “auto” (default)
- “torch”
- “accelerate”
- “deepspeed”
Examples:
Python Console Session | |
---|---|
See Also
BaseRunner
: Base class for all runners.TorchRunner
: Runner for PyTorch.AccelerateRunner
: Runner for Accelerate.DeepSpeedRunner
: Runner for DeepSpeed.
Source code in danling/runner/runner.py
TorchRunner
¶
Bases: BaseRunner
Set up everything for running a job with PyTorch.
PyTorch backend is the most basic and flexible distributed backend. If you wish to extend the Runner, this is the best choice.
Source code in danling/runner/torch_runner.py
Python | |
---|---|
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 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 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 |
|
train
¶
train(
train_splits: list[str] | None = None,
evaluate_splits: list[str] | None = None,
) -> NestedDict
Perform training on split
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
list[str] | None
|
list of split to run train.
Defaults to |
None
|
|
list[str] | None
|
list of split to run evaluate.
Defaults to |
None
|
Return
Source code in danling/runner/torch_runner.py
train_epoch
¶
train_epoch(split: str = 'train') -> NestedDict
Train one epoch on split
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
str
|
split to run train |
'train'
|
Return
Source code in danling/runner/torch_runner.py
advance
¶
advance(loss) -> None
Backward loss and step optimizer & scheduler.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
The loss tensor from which to backpropagate. |
required |
Source code in danling/runner/torch_runner.py
evaluate
¶
evaluate(
evaluate_splits: list[str] | None = None,
) -> NestedDict
Perform evaluation on evaluate_splits
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
list[str] | None
|
list of split to run evaluate.
Defaults to |
None
|
Return
Source code in danling/runner/torch_runner.py
evaluate_epoch
¶
evaluate_epoch(split: str = 'val') -> NestedDict
Evaluate one epoch on split
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
str
|
split to run evaluate |
'val'
|
Return
Source code in danling/runner/torch_runner.py
infer
¶
Perform inference on split
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
str
|
split to run inference |
'infer'
|
Return
Source code in danling/runner/torch_runner.py
backward
¶
has_nan_inf_grad
¶
Check if model has NaN or Inf gradients.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
Module | None
|
Model to check.
Defaults to |
None
|
Return
Source code in danling/runner/torch_runner.py
init_distributed
¶
Set up distributed training.
Initialise process group and set up DDP variables.
Source code in danling/runner/torch_runner.py
init_tensorboard
¶
Set up Tensoraoard SummaryWriter.
Source code in danling/runner/torch_runner.py
set_seed
¶
Set up random seed.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
int
|
Random seed to set.
Defaults to |
None
|
|
int
|
Make the seed different for each processes.
This is used to ensure the data augmentation are applied differently on every processes.
Defaults to |
None
|
Source code in danling/runner/torch_runner.py
get_deepspeed_config
¶
get_deepspeed_config(
config: NestedDict | str = None,
) -> NestedDict
Preprocess DeepSpeed config.
Source code in danling/runner/torch_runner.py
Python | |
---|---|
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 |
|
NestedTensor
¶
Wrap an iterable of tensors into a single tensor with a mask.
In sequence to sequence tasks, elements of a batch are usually not of the same length. This made it tricky to use a single tensor to represent a batch of sequences.
NestedTensor
allows to store a sequence of tensors of different lengths in a single object.
It also provides a mask that can be used to retrieve the original sequence of tensors.
When calling __getitem__(arg)
on a NestedTensor
, it has two return type:
1. if arg is int
or slice
, returns a tuple of two tensor
s, representing data and padding mask.
2. if arg is a tuple
, return a new NestedTensor
with specified shape.
Attributes:
Name | Type | Description |
---|---|---|
_storage |
The sequence of tensors. |
|
tensor |
Tensor
|
padded tensor. |
mask |
Tensor
|
mask tensor. |
concat |
Tensor
|
concatenated tensor. |
batch_first |
bool
|
Whether the first dimension of the tensors is the batch dimension. If If |
padding_value |
SupportsFloat
|
The padding value used to in padded tensor. |
mask_value |
bool
|
The mask value used in mask tensor. |
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
Iterable[Tensor]
|
|
()
|
|
bool
|
|
True
|
|
SupportsFloat
|
|
0.0
|
|
bool
|
|
False
|
Raises:
Type | Description |
---|---|
ValueError
|
If |
ValueError
|
If |
Note
We have rewritten the __getattr__
function to support as much native tensor operations as possible.
However, not all operations are tested.
Please file an issue if you find any bugs.
Examples:
Source code in danling/tensor/nested_tensor.py
Python | |
---|---|
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 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 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 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 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 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 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 |
|
tensor_mask
property
¶
concat
property
¶
concat: Tensor
Concat tensor
in padding dim.
This is particularly useful when calculating loss or passing Linear
to avoid unnecessary computation.
Returns:
Type | Description |
---|---|
Tensor
|
|
Examples:
from_tensor_mask
classmethod
¶
Build a NestedTensor
object from a padded Tensor
and corresponding mask Tensor
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
Tensor
|
Padded Tensor. |
required |
|
Tensor
|
Tensor Mask. |
required |
Returns:
Type | Description |
---|---|
Tensor
|
|
Examples:
Source code in danling/tensor/nested_tensor.py
nested_like
¶
nested_like(
tensor: Tensor, strict: bool = True
) -> NestedTensor
Create a new NestedTensor
from a Tensor
.
The newly created NestedTensor
will have the same shape as current NestedTensor
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
Tensor
|
The tensor to be converted to |
required |
|
bool
|
Check if the shape of |
True
|
Returns:
Type | Description |
---|---|
NestedTensor
|
|
Examples:
Source code in danling/tensor/nested_tensor.py
size
¶
Returns the size of the self NestedTensor
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
int | None
|
If not specified, the returned value is a |
None
|
Returns:
Type | Description |
---|---|
Size | int
|
|
Examples:
Python Console Session | |
---|---|
Source code in danling/tensor/nested_tensor.py
dim
¶
dim() -> int
Number of dimension of the NestedTensor.
Returns:
Type | Description |
---|---|
int
|
|
Examples:
Python Console Session | |
---|---|
Source code in danling/tensor/nested_tensor.py
tolist
¶
tolist() -> list
Convert a NestedTensor to a list of lists of values.
Returns:
Type | Description |
---|---|
list
|
|
Examples:
Python Console Session | |
---|---|
Source code in danling/tensor/nested_tensor.py
Python | |
---|---|
all
¶
all(
dim: int | None = None, keepdim: bool = False
) -> bool | Tensor | NestedTensor
Tests if all elements in NestedTensor evaluate to True.
Returns:
Type | Description |
---|---|
bool | Tensor
|
|
Examples:
Source code in danling/tensor/nested_tensor.py
where
¶
where(
condition: Tensor | NestedTensor,
other: Tensor | NestedTensor | SupportsFloat,
) -> NestedTensor
Return a NestedTensor of elements selected from either self or other, depending on condition.
Returns:
Type | Description |
---|---|
NestedTensor
|
|
Examples:
Source code in danling/tensor/nested_tensor.py
view
¶
view(*shape) -> Tensor
Returns a torch tensor with a different shape.
Note
since NestedTensor is a collection of tensors, the view operation is ambiguous.
Therefore, it is converted to a tensor and then reshaped.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
The desired size of each dimension. |
()
|
Returns:
Type | Description |
---|---|
Tensor
|
|
Examples:
Python Console Session | |
---|---|
Source code in danling/tensor/nested_tensor.py
reshape
¶
reshape(*shape) -> Tensor
Returns a torch tensor with a different shape.
Note
since NestedTensor is a collection of tensors, the reshape operation is ambiguous.
Therefore, it is converted to a tensor and then reshaped.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
The desired size of each dimension. |
()
|
Returns:
Type | Description |
---|---|
Tensor
|
|
Examples:
Python Console Session | |
---|---|
Source code in danling/tensor/nested_tensor.py
PNTensor
¶
Bases: Tensor
Wrapper for tensors to be converted to NestedTensor
.
PNTensor
is a subclass of torch.Tensor
.
It implements three additional property as NestedTensor
: tensor
, mask
, and concat
.
Although it is possible to directly construct NestedTensor
in dataset,
the best practice is to do so is in collate_fn
.
PNTensor
is introduced to smoothen the process.
Convert tensors that will be converted to NestedTensor
to a PNTensor
,
and PyTorch Dataloader will automatically collate PNTensor
to NestedTensor
.
Source code in danling/tensor/nested_tensor.py
ensure_dir
¶
Bases: property
Ensure a directory property exists.
Examples:
Python Console Session | |
---|---|
Source code in danling/utils/descriptors.py
Python | |
---|---|
Metrics
¶
Bases: Metric
Metric class wraps around multiple metrics that share the same states.
Typically, there are many metrics that we want to compute for a single task.
For example, we usually needs to compute pearson
and spearman
for a regression task.
Unlike accuracy
, which can uses an average meter to compute the average accuracy,
pearson
and spearman
cannot be computed by averaging the results of multiple batches.
They need access to all the data to compute the correct results.
And saving all intermediate results for each tasks is quite inefficient.
Metrics
solves this problem by maintaining a shared state for multiple metric functions.
Attributes:
Name | Type | Description |
---|---|---|
metrics |
FlatDict[str, Callable]
|
A dictionary of metrics to be computed.A |
ignore_index |
int
|
Index to be ignored in the computation. |
ignore_nan |
bool
|
Whether to ignore NaN values in the computation. |
val |
NestedDict[str, float | flist]
|
Metric results of current batch on current device. |
avg |
NestedDict[str, float | flist]
|
Metric results of all results on all devices. |
input |
The input tensor of latest batch. |
|
target |
The target tensor of latest batch. |
|
inputs |
All input tensors. |
|
targets |
All target tensors. |
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
A single mapping of metrics. |
()
|
|
|
int | None
|
Index to be ignored in the computation, for classification tasks. |
None
|
|
bool | None
|
Whether to ignore NaN values in the computation, for regression tasks. |
None
|
|
Callable
|
Metrics. |
{}
|
Examples:
Source code in danling/metric/metrics.py
Python | |
---|---|
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 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 |
|
reset
¶
Reset the metric state variables to their default value.
The tensors in the default values are also moved to the device of
the last self.to(device)
call.
Source code in danling/metric/metrics.py
MultiTaskMetrics
¶
Bases: MultiTaskDict
Examples:
Source code in danling/metric/metrics.py
Python | |
---|---|
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 |
|
update
¶
Updates the average and current value in all metrics.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
Mapping[str, Mapping[str, Tensor | NestedTensor | Sequence]]
|
Dict of values to be added to the average. |
required |
Raises:
Type | Description |
---|---|
ValueError
|
If the value is not an instance of (Mapping). |
Source code in danling/metric/metrics.py
catch
¶
catch(
error: Exceptions = Exception,
exclude: Exceptions | None = None,
callback: Callable = print_exc,
*callback_args,
**callback_kwargs
)
Decorator to catch error
except for exclude
.
Detailed traceback will be printed to stderr
.
catch
is extremely useful for unfatal errors.
For example, Runner
saves checkpoint regularly, however, this might break running if the space is full.
Decorating save
method with catch
will allow you to catch these errors and continue your running.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
Exceptions
|
Exceptions to be caught. |
Exception
|
|
Exceptions | None
|
Exceptions to be excluded. |
None
|
|
Callable
|
Callback to be called when an error occurs.
The first four arguments to |
print_exc
|
|
Arguments to be passed to |
()
|
|
|
Keyword arguments to be passed to |
{}
|
Examples:
Source code in danling/utils/decorators.py
debug
¶
debug(
enable: bool = True,
error: Exceptions = Exception,
exclude: Optional[Exceptions] = None,
)
Contextmanager to enter debug mode on error
except for exclude
.
debug
is intended to be used to catch the error and enter debug mode.
Since it is mainly for development purposed, we include an enable
args so that it can be deactivated.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
bool
|
Whether to enable the contextmanager.
Defaults to |
True
|
|
Exceptions
|
The error to catch.
Defaults to |
Exception
|
|
Optional[Exceptions]
|
The error to exclude.
Defaults to |
None
|
Source code in danling/utils/contextmanagers.py
flexible_decorator
¶
Meta decorator to allow bracket-less decorator when no arguments are passed.
Examples:
For decorator defined as follows:
Python Console Session | |
---|---|
The following two are equivalent:
Source code in danling/utils/decorators.py
is_json_serializable
¶
load
¶
Load any file with supported extensions.
Source code in danling/utils/io.py
load_pandas
¶
Load any pandas data file with supported extensions.
Source code in danling/utils/io.py
method_cache
¶
Decorator to cache the result of an instance method.
functools.lru_cache
uses a strong reference to the instance,
which will make the instance immortal and break the garbage collection.
method_cache
uses a weak reference to the instance to resolve this issue.
See Also
Source code in danling/utils/decorators.py
save
¶
Save any file with supported extensions.