DanLing¶
danling
¶
AverageMeter
¶
A lightweight utility to compute and store running averages of values.
AverageMeter provides an efficient way to track running statistics (current value, sum, count, average) with minimal memory overhead and optional distributed averaging. Scalar values stay scalar. Tensor values are preserved end to end as long as each update for the meter has the same shape.
Attributes:
| Name | Type | Description |
|---|---|---|
val |
float | Tensor
|
Most recent local value added to the meter |
bat |
float | Tensor
|
Synchronized metric value for the current step |
avg |
float | Tensor
|
Running average of all values, weighted by counts |
sum |
float | Tensor
|
Sum of all values added to the meter |
count |
int
|
Total count of values added (considering weights) |
device |
Device used when synchronising running averages across processes |
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
device | str | None
|
Optional device used for distributed reductions. When not provided, the device is detected automatically when synchronisation happens. |
None
|
Examples:
See Also
MetricMeter: Memory-efficient metric tracker that averages metrics batch-by-batch.
Source code in danling/metrics/average_meter.py
| Python | |
|---|---|
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 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 | |
reset
¶
Resets the meter.
Source code in danling/metrics/average_meter.py
| Python | |
|---|---|
update
¶
Updates the average and current value in the meter.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
float | int | Tensor
|
Value to be added to the average. |
required |
|
int
|
Number of values to be added. |
1
|
Source code in danling/metrics/average_meter.py
AverageMeters
¶
Bases: MetersBase
Manages multiple average meters in one object.
Examples:
See Also
StreamMetrics: Memory-efficient metric tracker that averages multiple metrics batch-by-batch.
Source code in danling/metrics/average_meter.py
| Python | |
|---|---|
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 | |
update
¶
Updates the average and current value in all meters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
int | float | Tensor
|
Mapping or keyword values to be added to the corresponding meters. |
{}
|
Source code in danling/metrics/average_meter.py
MetricMeter
¶
Bases: AverageMeter
A memory-efficient metric tracker that computes and averages metrics across batches.
MetricMeter applies a metric function to each batch and maintains running averages without storing the complete history of predictions and labels. This makes it ideal for metrics that can be meaningfully averaged across batches (like accuracy or loss).
Attributes:
| Name | Type | Description |
|---|---|---|
metric |
Callable | MetricFunc
|
The metric function to compute on each batch |
preprocess |
Optional preprocessing function applied before the metric |
|
val |
float | Tensor
|
Result from the most recent batch on the current rank |
bat |
float | Tensor
|
Synchronized metric result for the current step |
avg |
float | Tensor
|
Weighted average of all results so far |
sum |
float | Tensor
|
Running sum of (metric × batch_size) values |
count |
int
|
Running sum of batch sizes |
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Callable | MetricFunc
|
Function that computes a metric given input and target tensors |
required |
|
Callable | None
|
Optional preprocessing function to apply before computing the metric |
None
|
Examples:
Notes
- MetricMeter is more memory-efficient than
GlobalMetricsbecause it only stores running statistics - Only suitable for metrics that can be meaningfully averaged batch-by-batch
- Not suitable for metrics like AUROC that need the entire dataset
- Metrics are evaluated once per update; batch-vs-sample semantics are determined by the metric itself
- Stream metrics may return tensors; tensor outputs are averaged elementwise across batches
MetricFuncdescriptors receive [MetricState][danling.metrics.MetricState]- Plain callables receive preprocessed
input/targettensors - For multiple metrics, use
StreamMetrics
See Also
AverageMeter: A lightweight utility to compute and store running averages of values.
Source code in danling/metrics/stream_metrics.py
| Python | |
|---|---|
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 | |
update
¶
update(
input: Tensor | NestedTensor,
target: Tensor | NestedTensor,
*,
n: int | None = None
) -> None
Updates the average and current value in the meter.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Tensor | NestedTensor
|
Prediction tensor or nested tensor. |
required |
|
Tensor | NestedTensor
|
Ground-truth tensor or nested tensor. |
required |
|
int | None
|
Optional number of samples represented by this update. When omitted, the batch size is inferred from the inputs. |
None
|
Source code in danling/metrics/stream_metrics.py
StreamMetrics
¶
Bases: AverageMeters
A container for managing multiple MetricMeter instances with shared preprocessing.
StreamMetrics allows you to organize and track multiple metrics in a unified interface, with consistent preprocessing applied to all inputs before computing each metric. This is particularly useful when you want to track several metrics that can be meaningfully averaged across batches.
Attributes:
| Name | Type | Description |
|---|---|---|
preprocess |
Shared preprocessing function for all meters |
|
val |
RoundDict[str, float | Tensor]
|
Dictionary of current local values from all meters |
bat |
RoundDict[str, float | Tensor]
|
Dictionary of synchronized current-step values from all meters |
avg |
RoundDict[str, float | Tensor]
|
Dictionary of running averages from all meters |
sum |
RoundDict[str, float | Tensor]
|
Dictionary of sums from all meters |
count |
RoundDict[str, int]
|
Dictionary of counts from all meters |
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Metric functions to register as meters |
required | |
|
Callable
|
Preprocessing function to apply to inputs before computing metrics |
base_preprocess
|
|
Named MetricMeter instances or metric functions |
{}
|
Examples:
Notes
StreamMetricsmanages multipleMetricMeterinstances with shared preprocessing- Each metric is computed independently but uses the same inputs
- All meters are updated simultaneously when you call
update() - Individual meters can be accessed like dictionary items or attributes
- Metrics are evaluated once per update; batch-vs-sample semantics are determined by the metric itself
- Tensor-valued metrics are preserved and averaged elementwise across batches
- Built-in
MetricFuncstream values may be approximate rather than exact dataset-level metrics
See Also
AverageMeters: A container for managing multiple average meters in one object.GlobalMetrics: Metric tracker that stores the complete prediction and target history.
Source code in danling/metrics/stream_metrics.py
| Python | |
|---|---|
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 | |
update
¶
update(
input: Tensor | NestedTensor | Sequence,
target: Tensor | NestedTensor | Sequence,
*,
n: int | None = None
) -> 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 |
|
int | None
|
Optional number of samples represented by this update. Defaults to the inferred batch size. |
None
|
Source code in danling/metrics/stream_metrics.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 scaling 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 method. 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 204 205 206 207 208 | |
BaseRunner
¶
Backend-agnostic runner state and orchestration utilities.
BaseRunner intentionally keeps only the shared runtime contract used by
concrete runners such as TorchRunner:
- configuration and process lifecycle bootstrap
- datasets/dataloaders/result containers
- checkpoint/result persistence helpers
- progress and score bookkeeping
Concrete runners are expected to customize runtime behavior through the explicit training/checkpoint hooks below, not by overriding bootstrap internals.
Construction lifecycle:
- Normalize config and create
RunnerState. - Bind workspace, containers, default
FileCheckpointManager, and supervisor. - Call early service hooks in order:
init_distributed,init_checkpoint_manager,init_fault_tolerance,init_garbage_collection. - Apply seed/determinism policy.
- Initialize logging, TensorBoard/W&B, print routing, signal handlers, and heartbeat.
MetaRunnercalls__post_init__. Concrete runners such asTorchRunnermaterialize models, optimizers, schedulers, and resume checkpoints there before delegating back toBaseRunner.__post_init__for metadata persistence.
Override rule: early hooks run while the runner is only partially
constructed; model/runtime hooks run in concrete __post_init__; loop
hooks (train_step, evaluate_step, infer_step) run after all runtime
components are bound.
Attributes:
| Name | Type | Description |
|---|---|---|
state |
RunnerState
|
Checkpointable aggregate state object. |
config |
RunnerConfig
|
Runner configuration. |
train_state |
RunnerTrainState
|
Training progress counters. |
elastic_state |
RunnerElasticState
|
Torchelastic restart metadata. |
rng_state |
RunnerRNGState
|
Python/NumPy/Torch RNG snapshots. |
datasets |
FlatDict
|
Dataset mapping keyed by split. |
dataloaders |
FlatDict
|
Dataloader mapping keyed by split. |
checkpoint_manager |
CheckpointManager
|
Active checkpoint backend manager. |
workspace |
RunnerWorkspace
|
Workspace, logging, metadata, and print-routing helper. |
supervisor |
RunnerSupervisor
|
Signal, heartbeat, and garbage-collection helper. |
ft |
FaultTolerance | None
|
Optional fault-tolerance runtime handle. |
Source code in danling/runners/base_runner.py
| Python | |
|---|---|
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 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 | |
is_local_main_process
property
¶
is_local_main_process: bool
Whether current rank is local main process.
scores
property
¶
scores: FlatDict | None
Index-to-score mapping extracted from score_split/score_name.
best_result
property
¶
Best result row according to configured score metric.
is_best
property
¶
is_best: bool
Whether latest score matches current best score.
Returns True only when comparable scalar scores are available and
agree within tolerance. Returns True on the first iteration (no
prior results), and False when scores cannot be resolved (e.g.,
no score_split/score_name configured) — silently reporting best
in that case would trigger phantom “best” checkpoint copies.
max_grad_value
cached
property
¶
max_grad_value: float | None
Gradient value clipping threshold.
skip_nonfinite_grad
cached
property
¶
skip_nonfinite_grad: bool
Whether to skip optimizer updates when gradients are non-finite.
evaluate_splits
property
¶
Configured or inferred evaluation split names.
checkpoint_interval
property
¶
checkpoint_interval: int
Checkpoint cadence in optimizer steps (step mode) or epochs (epoch mode).
__post_init__
¶
auto_restore
¶
Auto-load resume/pretrained sources declared in config.
Precedence
config.resume > config.auto_resume > config.pretrained.
Source code in danling/runners/base_runner.py
init_distributed
¶
Initialize the distributed environment.
The default is a no-op (single-process). Concrete runners override
this hook to initialize the torch.distributed process group; see
TorchRunner.init_distributed
for the canonical specification.
Source code in danling/runners/base_runner.py
init_checkpoint_manager
¶
Bind the runner’s checkpoint manager.
The default is a no-op — BaseRunner.__init__ already binds the
FileCheckpointManager. Concrete runners override this hook to swap
in the backend-appropriate manager via set_checkpoint_manager(...);
see
TorchRunner.init_checkpoint_manager
for the canonical specification.
Source code in danling/runners/base_runner.py
init_fault_tolerance
¶
init_heartbeat
¶
init_garbage_collection
¶
init_signal_handlers
¶
prepare_for_shutdown_checkpoint
¶
init_tensorboard
¶
Initialize tensorboard writer.
Source code in danling/runners/base_runner.py
init_wandb
¶
Initialize Weights & Biases run for scalar logging.
Source code in danling/runners/base_runner.py
set_seed
¶
Set python/numpy RNG seeds and snapshot RNG state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
int | None
|
Base seed. Defaults to |
None
|
|
int | bool | None
|
Optional per-process bias. |
None
|
Returns:
| Type | Description |
|---|---|
int
|
The process-local seed after applying bias. |
Source code in danling/runners/base_runner.py
set_deterministic
¶
train
¶
train_epochs
¶
train_epoch
¶
train_steps
¶
train_step
¶
Run one training micro-step.
Concrete runners define the override contract; see
TorchRunner.train_step for
the canonical specification.
Source code in danling/runners/base_runner.py
backward
¶
step
¶
evaluate
¶
evaluate_epoch
¶
evaluate_steps
¶
evaluate_step
¶
Run one evaluation step.
Concrete runners define the override contract; see
TorchRunner.evaluate_step
for the canonical specification.
Source code in danling/runners/base_runner.py
| Python | |
|---|---|
infer
¶
infer_step
¶
Run one inference step.
Concrete runners define the override contract; see
TorchRunner.infer_step for
the canonical specification.
Source code in danling/runners/base_runner.py
unwrap
¶
state_dict
¶
Build the backend-neutral runner checkpoint payload.
The base payload contains semantic runner config, mutable runner state, RNG snapshots, and dataloader resume state. Backend runners extend this payload with model/optimizer/scheduler state.
Called when: checkpoint managers build a payload for
save_checkpoint, and fault-tolerance callbacks need a runner state
snapshot.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
type
|
Mapping factory used for nested payloads. Backends may pass
|
dict
|
Returns:
| Type | Description |
|---|---|
Mapping
|
Mapping with |
Side effects: snapshots Python and NumPy RNG state into
self.rng_state before exporting.
Do not
- Mutate model or optimizer state here.
- Drop the
runnerconfig payload; resume validation depends on it. - Override without calling
super()unless you fully replace the checkpoint format.
Source code in danling/runners/base_runner.py
load_state_dict
¶
load_state_dict(checkpoint: Mapping[str, Any]) -> None
Restore backend-neutral runner state from a checkpoint payload.
This restores semantic runner state and Python/NumPy RNG state. Model,
EMA, optimizer, scheduler, and dataloader component loading is owned by
load_checkpoint.
Called when: load_checkpoint restores a full checkpoint, and
fault-tolerance callbacks receive a runner state payload.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Mapping[str, Any]
|
Mapping produced by |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
checkpoint runner config differs semantically from the current runner config. |
Side effects: updates self.state, self.train_state,
self.elastic_state, self.rng_state, and process RNG state.
Do not
- Load model/optimizer/scheduler state here; use component loaders
through
load_checkpoint. - Suppress semantic config diffs unless you also update the resume policy deliberately.
Source code in danling/runners/base_runner.py
save_checkpoint
¶
save_checkpoint(
name: str = "latest",
epochs: int | None = None,
save_best: bool = True,
last_step: bool = False,
force: bool = False,
) -> None
Persist runner state through the active checkpoint manager.
Backend collective semantics are owned by
checkpoint_manager.is_collective. File-style managers save on the
main process only; collective managers require every rank to enter this
method together.
Called when: training loops hit checkpoint cadence, final
last_step saves run, or the supervisor handles a shutdown signal.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
str
|
Logical checkpoint alias, usually |
'latest'
|
|
int | None
|
Epoch index used for history checkpoint naming. Defaults
to |
None
|
|
bool
|
Whether to publish/update the best-checkpoint alias
when |
True
|
|
bool
|
Whether this save is the final save for the run. |
False
|
|
bool
|
Bypass cadence checks inside the manager. |
False
|
Side effects: delegates to
self.checkpoint_manager.save_checkpoint(...).
Do not
- Add a main-process guard around calls to this method; DCP-style managers need all ranks to participate.
- Bypass the checkpoint manager for normal runner checkpoints.
Source code in danling/runners/base_runner.py
save_seed_checkpoint
¶
save_seed_checkpoint(name: str = 'seed') -> None
Persist an initialization checkpoint for cross-topology experiments.
Seed checkpoints are intended to be created before training advances,
then loaded with checkpoint.load_only=True or resume/pretrained
when comparing different parallel layouts from the same initial model
state. They are saved through the final-checkpoint path, so
checkpoint.last_save_model_only=True intentionally applies.
Source code in danling/runners/base_runner.py
load_checkpoint
¶
load_checkpoint(
checkpoint: Mapping | bytes | str | PathLike,
*args: Any,
**kwargs: Any
) -> None
Restore a full runner checkpoint.
This is the full-state restore path: runtime state, model/EMA, optimizer, scheduler, and dataloader progress are restored when present and applicable to the current runner.
Called when: users resume a run explicitly, auto_restore selects
a resume source, from_checkpoint constructs a runner, or
fault-tolerance callbacks restore a full runner payload.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Mapping | bytes | str | PathLike
|
In-memory checkpoint mapping or backend-specific path. |
required |
|
Any
|
Forwarded to |
()
|
|
Any
|
Forwarded to |
{}
|
Raises:
| Type | Description |
|---|---|
ValueError
|
checkpoint is missing required component state for an initialized component, or config validation fails. |
Side effects: updates runner state, model/EMA weights, optimizer,
scheduler, dataloader progress, and config.resume for path inputs.
Do not
- Use this for model-only finetuning payloads; use
load_pretrainedinstead. - Override just to support a new path type; prefer overriding
read_checkpoint.
Source code in danling/runners/base_runner.py
| Python | |
|---|---|
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 | |
load_model
¶
Load model state.
Source code in danling/runners/base_runner.py
load_ema
¶
Load EMA state.
Source code in danling/runners/base_runner.py
load_optimizer
¶
Load optimizer state.
Source code in danling/runners/base_runner.py
| Python | |
|---|---|
load_scheduler
¶
Load scheduler state.
Source code in danling/runners/base_runner.py
| Python | |
|---|---|
load_dataloaders
¶
Load dataloader progress state when the current runner has matching loaders.
Source code in danling/runners/base_runner.py
load_pretrained
¶
load_pretrained(
checkpoint: Mapping | bytes | str | PathLike,
*args: Any,
**kwargs: Any
) -> None
Load model weights only from a checkpoint payload or path.
When checkpoint payload provides EMA weights (ema), EMA is preferred as
the pretrained source. Otherwise model is used.
Called when: users initialize from pretrained weights, or
auto_restore selects config.pretrained.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Mapping | bytes | str | PathLike
|
In-memory payload or backend-specific path containing
|
required |
|
Any
|
Forwarded to |
()
|
|
Any
|
Forwarded to |
{}
|
Raises:
| Type | Description |
|---|---|
ValueError
|
model is not initialized, or the payload has no usable model/EMA state. |
Side effects: loads model weights and updates config.pretrained
for path inputs. Optimizer, scheduler, runner state, and dataloaders
are intentionally untouched.
Do not
- Use this to resume training state; use
load_checkpointfor full-state restore. - Load optimizer/scheduler state in this path.
Source code in danling/runners/base_runner.py
from_checkpoint
classmethod
¶
from_checkpoint(
checkpoint: Mapping | bytes | str | PathLike,
*args,
**kwargs
) -> BaseRunner
Instantiate runner from checkpoint config and restore full state.
Source code in danling/runners/base_runner.py
read_config
classmethod
¶
read_config(
checkpoint: Mapping | bytes | str | PathLike,
*args,
**kwargs
) -> RunnerConfig
Read runner config from checkpoint mapping or file path.
Note
BaseRunner only accepts file checkpoints for path input. Backend-specific directory checkpoints must be handled in subclasses.
Source code in danling/runners/base_runner.py
from_pretrained
classmethod
¶
from_pretrained(
config: RunnerConfig | Mapping[str, Any],
checkpoint: Mapping | bytes | str | PathLike,
*args,
**kwargs
) -> BaseRunner
Build a runner from config and load model weights only.
Source code in danling/runners/base_runner.py
read_checkpoint
¶
read_checkpoint(
checkpoint: Mapping | bytes | str | PathLike,
*args,
**kwargs
) -> Mapping[str, Any]
Normalize checkpoint input into an in-memory mapping payload.
Source code in danling/runners/base_runner.py
save
¶
Save an object with optional main-process guard.
Source code in danling/runners/base_runner.py
| Python | |
|---|---|
close
¶
Finalize checkpoint/log/writer resources before shutdown.
Source code in danling/runners/base_runner.py
DeepSpeedRunner
¶
Bases: TorchRunner
DeepSpeed-backed runner focused on ZeRO-½ training flows.
Use this runner when DeepSpeed should own the training engine and optimizer update while DanLing still owns the outer lifecycle: dataloaders, metrics, accumulation normalization, result writing, and checkpoint alias policy.
DeepSpeed checkpoints are directory/tag based. DanLing writes lightweight
pointer files (latest.pointer, best.pointer, and named aliases) so the
public checkpoint API can keep using logical names.
Attributes:
| Name | Type | Description |
|---|---|---|
model |
DeepSpeedEngine
|
DeepSpeed engine after |
deepspeed_config |
dict[str, Any]
|
Effective DeepSpeed config passed to
|
Source code in danling/runners/deepspeed_runner.py
| Python | |
|---|---|
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 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 | |
materialize_model
¶
Move and compile the local model before DeepSpeed engine creation.
Called when: TorchRunner.__post_init__ reaches
materialize_model, before build_optimizer, build_scheduler, and
_finalize_runtime_components.
Precondition: self.model is the user-provided nn.Module, not
yet a DeepSpeed engine.
Raises:
| Type | Description |
|---|---|
ValueError
|
|
Side effects: moves the model and optional EMA module to
self.device, applies FP8 policy when enabled, and compiles the model.
DeepSpeed wrapping happens later in the engine-finalization step.
Do not
- Call
deepspeed.initializehere; optimizer and scheduler build happen after this hook. - DDP-wrap the model; DeepSpeed owns distributed wrapping.
Source code in danling/runners/deepspeed_runner.py
get_deepspeed_config
¶
Build the effective DeepSpeed config.
Called when: _finalize_runtime_components initializes the
DeepSpeed engine.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
A mutable config dict suitable for |
Raises:
| Type | Description |
|---|---|
ValueError
|
|
Side effects: none. The returned config forces
gradient_accumulation_steps=1 because DanLing owns accumulation
boundaries, fills train_micro_batch_size_per_gpu from the dataloader
batch size when absent, and mirrors runner precision into DeepSpeed
precision sections when possible.
Source code in danling/runners/deepspeed_runner.py
backward
¶
Route one micro-step backward pass through the DeepSpeed engine.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Tensor
|
Raw micro-step loss from |
required |
Side effects: accumulates gradients inside the DeepSpeed engine after DanLing’s loss-scaling/normalization policy is applied.
Source code in danling/runners/deepspeed_runner.py
optimizer_step
¶
optimizer_step() -> bool
Perform one DeepSpeed engine optimizer update.
DeepSpeed owns the concrete optimizer step; DanLing keeps accumulation normalization, runner state, profiler, timeout, and supervisor state in sync.
Source code in danling/runners/deepspeed_runner.py
save_checkpoint
¶
save_checkpoint(
name: str = "latest",
epochs: int | None = None,
save_best: bool = True,
last_step: bool = False,
force: bool = False,
) -> None
Save a DeepSpeed checkpoint and publish DanLing pointer aliases.
Called when: the training loop or shutdown supervisor requests a checkpoint save.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
str
|
Logical alias to publish in addition to |
'latest'
|
|
int | None
|
Epoch index used for retention/history naming. |
None
|
|
bool
|
Whether to publish |
True
|
|
bool
|
Whether this is the final checkpoint save. |
False
|
|
bool
|
Bypass checkpoint manager cadence checks. |
False
|
Side effects: all ranks enter DeepSpeedEngine.save_checkpoint.
The main process writes runner.yaml and pointer files for logical
aliases. Success/failure is reported through the checkpoint manager.
Do not
- Guard the whole method with
is_main_process; DeepSpeed saves are collective. - Write aliases before
save_checkpointsucceeds. - Use the generic file checkpoint payload here; DeepSpeed owns the physical checkpoint layout.
Source code in danling/runners/deepspeed_runner.py
| Python | |
|---|---|
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 | |
load_checkpoint
¶
load_checkpoint(
checkpoint: Mapping | bytes | str | PathLike,
*args: Any,
**kwargs: Any
) -> None
Restore a full DeepSpeed checkpoint.
Mapping checkpoints delegate to TorchRunner.load_checkpoint. Path
checkpoints resolve pointer files/directories to a DeepSpeed
(checkpoint_dir, tag) pair, then load engine state and DanLing client
state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Mapping | bytes | str | PathLike
|
In-memory payload, pointer file, checkpoint directory, or tagged checkpoint directory. |
required |
|
Any
|
Forwarded to component loaders for client state. |
()
|
|
Any
|
Forwarded to component loaders for client state. |
{}
|
Side effects: restores DeepSpeed engine state, runner state,
optional EMA, runner-owned scheduler state, dataloader state, and
config.resume.
Do not
- Treat DeepSpeed pointer files as torch
loadpayloads; resolve them to a tag first. - Rebind an
OptimizerContainer; DeepSpeed owns optimizer stepping.
Source code in danling/runners/deepspeed_runner.py
load_pretrained
¶
load_pretrained(
checkpoint: Mapping | bytes | str | PathLike,
*args: Any,
**kwargs: Any
) -> None
Load DeepSpeed model weights without restoring training state.
Mapping checkpoints delegate to the generic pretrained path. Path
checkpoints use DeepSpeedEngine.load_checkpoint(..., load_module_only=True).
If DanLing client state contains EMA weights, EMA is used as the
pretrained source.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Mapping | bytes | str | PathLike
|
In-memory payload, pointer file, checkpoint directory, or tagged checkpoint directory. |
required |
|
Any
|
Forwarded to model loading for client-state EMA payloads. |
()
|
|
Any
|
Forwarded to model loading for client-state EMA payloads. |
{}
|
Side effects: loads model weights through the DeepSpeed engine and
updates config.pretrained. Optimizer, scheduler, dataloaders, and
runner progress are untouched.
Source code in danling/runners/deepspeed_runner.py
ParallelRunner
¶
Bases: TorchRunner
Torch runner for data, FSDP, pipeline, and model-parallel stacks.
Use this runner when training spans explicit parallel axes (replicate,
shard, pipeline, tensor, context, expert, expert_tensor) rather
than plain DDP. It keeps the TorchRunner outer lifecycle and replaces the
distributed topology, sampler, model materialization, collective reduction,
pipeline step, and checkpoint semantics.
Checkpoint invariants
- Distributed parallel runs use
checkpoint.backend="dcp"only. - Single-local-part checkpoints use torch.distributed.checkpoint state-dict APIs when available.
- Restore order is model first, then optimizer, then scheduler.
Attributes:
| Name | Type | Description |
|---|---|---|
topology |
ParallelTopology
|
Rank/axis layout for the current world. |
parallel |
ParallelContext
|
Process-group/device-mesh context built from |
model_parts |
list[Module]
|
Local pipeline/FSDP model parts. |
pipeline_schedule |
Any | None
|
Optional PyTorch pipeline schedule. |
pipeline_has_first_stage |
bool
|
Whether this rank owns pipeline input. |
pipeline_has_last_stage |
bool
|
Whether this rank owns pipeline target/loss. |
Source code in danling/runners/parallel_runner.py
| Python | |
|---|---|
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 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 | |
init_distributed
¶
Initialize default distributed state and parallel process groups.
Called when: BaseRunner.__init__ invokes init_distributed,
before checkpoint manager/fault-tolerance setup and before model
materialization.
Precondition: WORLD_SIZE > 1 and the configured parallel axis
product equals WORLD_SIZE.
Raises:
| Type | Description |
|---|---|
RuntimeError
|
distributed mode is not active, or device-mesh process groups cannot be initialized. |
ValueError
|
|
Side effects: calls TorchRunner.init_distributed, builds
self.topology, initializes the device mesh, binds per-axis process
groups, and stores self.parallel.
Do not
- Initialize model/pipeline/FSDP objects here; materialization
happens in
materialize_model. - Override this just to change axis degrees; set
config.parallel.axesor overridebuild_topology.
Source code in danling/runners/parallel_runner.py
build_topology
¶
Build the rank-to-axis topology for this parallel run.
Called when: init_distributed has initialized the default process
group and needs per-axis domains.
Returns:
| Type | Description |
|---|---|
ParallelTopology
|
|
ParallelTopology
|
named reduction domains. |
Raises:
| Type | Description |
|---|---|
ValueError
|
any axis degree is less than one, or the product of axis
degrees does not equal |
Side effects: none. Override this only for non-standard axis/domain
layouts; normal users should configure config.parallel.axes.
Source code in danling/runners/parallel_runner.py
materialize_model
¶
Materialize local model parts for FSDP/pipeline/model-parallel training.
Called when: TorchRunner.__post_init__ reaches
materialize_model, after FP8 setup and before optimizer build.
Precondition: either self.model or self.model_parts is bound.
Pipeline runs may also provide self.pipeline_schedule; otherwise a
single local model is converted to a pipeline stage when
pipeline_degree > 1.
Raises:
| Type | Description |
|---|---|
RuntimeError
|
FSDP prerequisites are unavailable. |
ValueError
|
model/model_parts are missing or an unsupported auto-pipeline shape is requested. |
Side effects: moves local parts to self.device, calls
parallelize_model, applies FP8 policy, compiles each part, optionally
wraps parts with FSDP2 after apply_activation_checkpointing, binds
pipeline schedule modules, installs TorchFT all-reduce hooks for FSDP,
and moves EMA to device.
Do not
- Build the optimizer before this hook; optimizer parameters must come from materialized/wrapped parts.
- FSDP-wrap before
apply_activation_checkpointing. - Replace
self.model_partswithout keepingself.modelaligned to the first local part.
Source code in danling/runners/parallel_runner.py
pipeline_stage_indices
¶
Return the pipeline stage indices owned by this rank.
The default supports the common looped virtual-stage mapping used by
interleaved schedules: rank r owns r, r + pp_degree, …
Override this method for mirrored, zero-bubble, or other custom local
stage placement.
Source code in danling/runners/parallel_runner.py
build_pipeline_model_part
¶
Return the local pipeline model part for this pipeline rank.
The default supports two user-facing contracts:
- If the model defines
build_pipeline_model_part(...), delegate to it. - If
parallel.module_fqns_per_model_partis configured, extract those named modules for the current pipeline rank. Multiple FQNs become a simplenn.Sequentialin the provided order.
Complex graph partitioning should be implemented in the model hook or by overriding this method.
Source code in danling/runners/parallel_runner.py
build_pipeline_model_parts
¶
Return all local pipeline model parts for this pipeline rank.
Override this when a schedule maps multiple stages to each local rank and the default FQN/model-owned partitioning is not expressive enough.
Source code in danling/runners/parallel_runner.py
parallelize_model
¶
Apply model-specific tensor/context/expert parallel transforms.
Called when: _prepare_local_model_parts materializes each local
part, before compile and FSDP wrapping.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Module
|
Local model part to transform. |
required |
Returns:
| Type | Description |
|---|---|
Module
|
The transformed model. If the model defines |
Module
|
|
Module
|
return |
Raises:
| Type | Description |
|---|---|
TypeError
|
|
NotImplementedError
|
model-parallel axes are enabled but no transform hook is available. |
Do not
- Move the model to device here; the surrounding
materialize_modelflow handles device placement before this hook runs. - Compile or FSDP-wrap here; those happen after this hook.
Source code in danling/runners/parallel_runner.py
apply_activation_checkpointing
¶
Apply activation checkpointing to one local model part.
Called when: materialize_model wraps FSDP-enabled parts, before
compile/FSDP wrapping.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Module
|
Local model part. |
required |
Returns:
| Type | Description |
|---|---|
Module
|
Model part with activation checkpointing wrappers applied. |
Side effects: default is a no-op. Overrides may mutate the module in place or return a wrapped module.
Do not
- Change parameter ownership or shard layout here; FSDP has not wrapped the model yet.
- Return a non-module value.
Source code in danling/runners/parallel_runner.py
build_pipeline_schedule
¶
build_pipeline_schedule(
stage_model: Module | Sequence[Module],
) -> Any
Build the PyTorch pipeline schedule for this rank.
Called when: materialize_model sees pipeline_degree > 1 and no
explicit pipeline_schedule is already bound.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Module | Sequence[Module]
|
Local stage module for this pipeline rank, or all local stage modules for an interleaved/multi-stage schedule. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
A PyTorch pipeline schedule instance. |
Raises:
| Type | Description |
|---|---|
ValueError
|
pipeline microbatch count cannot be inferred or is inconsistent with batch size. |
Side effects: none beyond schedule construction. The caller binds the schedule modules after compile/FSDP wrapping.
Do not
- Set
scale_grads=True; DanLing owns gradient/loss scaling. - Build the optimizer here.
Source code in danling/runners/parallel_runner.py
build_datasampler
¶
Build a data-parallel sampler for one split.
Called when: inherited build_dataloaders materializes a dataset
split.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Any
|
Dataset object for the split. |
required |
|
str
|
Split name being materialized. |
required |
|
bool
|
Whether to shuffle the split. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
|
Any
|
adjusted by TorchFT when active. |
Source code in danling/runners/parallel_runner.py
train_step
¶
Run one training micro-step for plain or pipeline-parallel execution.
Non-pipeline configurations delegate to TorchRunner.train_step.
Pipeline configurations call the schedule, compute loss only on last
stages, synchronize accumulation normalization across the pipeline, and
then delegate optimizer-boundary handling to step().
Called when: train_epoch/train_steps consume one micro-batch.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Any
|
Micro-batch from the local loader. Non-first/non-last
pipeline stages may receive |
required |
Returns:
| Type | Description |
|---|---|
Any
|
|
Tensor | None
|
ranks that can report last-stage loss. Non-pipeline mode returns |
tuple[Any, Tensor | None]
|
the TorchRunner result. |
Do not
- Call the optimizer directly; use
step(). - Update metrics from pipeline mode here; pipeline schedule outputs are not a normal full-batch prediction.
- Manually divide gradients by pipeline microbatch count.
Source code in danling/runners/parallel_runner.py
evaluate_step
¶
Run one evaluation micro-step for plain or pipeline execution.
Non-pipeline configurations delegate to TorchRunner.evaluate_step.
Pipeline configurations call the schedule in eval mode and report
normalized loss from last-stage ranks.
Called when: evaluate_epoch/evaluate_steps consume one
micro-batch under inference mode.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Any
|
Micro-batch from the local loader. Non-first/non-last
pipeline stages may receive |
required |
Returns:
| Type | Description |
|---|---|
Any
|
|
Tensor | None
|
TorchRunner result. |
Do not
- Call backward or step.
- Assume every rank has targets; only last-stage ranks need them.
Source code in danling/runners/parallel_runner.py
infer_step
¶
Run one inference micro-step for plain or pipeline execution.
Non-pipeline configurations delegate to TorchRunner.infer_step.
Pipeline configurations call the schedule in eval mode and normalize
whatever the schedule returns into a flat list of floats.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Any
|
Micro-batch on first-stage ranks; |
required |
Returns:
| Type | Description |
|---|---|
list[float]
|
Flat list of numeric predictions. Non-output ranks may return an |
list[float]
|
empty list. |
Raises:
| Type | Description |
|---|---|
ValueError
|
pipeline output cannot be normalized into floats. |
Source code in danling/runners/parallel_runner.py
infer
¶
infer(
split: str = "infer",
*,
steps: int | None = None,
stream: bool | None = None
) -> list[float] | Iterator[list[float]]
Run inference across a pipeline-aware loader.
Non-pipeline configurations delegate to TorchRunner.infer. Pipeline
configurations consume real dataloader batches only on first-stage
ranks; other stages run infer_step(None) for the same number of
steps.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
str
|
Inference split name. |
'infer'
|
|
int | None
|
Optional maximum number of batches/stage ticks. |
None
|
|
bool | None
|
Whether to return a per-batch iterator instead of a flattened list. |
None
|
Returns:
| Type | Description |
|---|---|
list[float] | Iterator[list[float]]
|
Flattened predictions or a streaming iterator. |
Raises:
| Type | Description |
|---|---|
ValueError
|
|
Source code in danling/runners/parallel_runner.py
| Python | |
|---|---|
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 | |
load_checkpoint
¶
load_checkpoint(
checkpoint: Mapping | bytes | str | PathLike,
*args: Any,
**kwargs: Any
) -> None
Restore a parallel checkpoint with topology validation.
The checkpoint is read through the active DCP manager, validated against current parallel axes, optionally remapped for allowed non-FSDP degree changes, and then restored through the TorchRunner component loaders.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Mapping | bytes | str | PathLike
|
In-memory checkpoint mapping or DCP checkpoint path. |
required |
|
Any
|
Forwarded to checkpoint reading and component loaders. |
()
|
|
Any
|
Forwarded to checkpoint reading and component loaders. |
{}
|
Raises:
| Type | Description |
|---|---|
ValueError
|
saved topology is incompatible with the current run, or FSDP topology metadata is missing/changed. |
Side effects: restores model/optimizer/scheduler/runner state and
updates config.resume for path inputs.
Do not
- Suppress topology validation for FSDP restores; shard metadata is part of the checkpoint contract.
- Attempt degree-change restore with multiple local model parts.
Source code in danling/runners/parallel_runner.py
Runner
¶
Bases: BaseRunner
Dynamic runner entrypoint that selects stack-specific runner classes.
Source code in danling/runners/runner.py
RunnerConfig
¶
Bases: Config
Configuration class for managing and persisting all states of a DanLing Runner.
The RunnerConfig class provides a hierarchical configuration system that handles:
- Parameter management: Hyperparameters, model settings, training options
- Experiment tracking: IDs, names, and other metadata for runs and experiments
- Serialization: Save/load configurations from files or command line
- Reproducibility: Tracking seeds and settings for reproducible runs
RunnerConfig inherits from Config and provides attribute-style access to nested values:
| Python | |
|---|---|
RunnerConfig objects support three types of hierarchical attribute access patterns:
-
Direct assignment for simple values:
Python -
Auto-created nested objects for hierarchical settings:
-
Class-level annotations for typed properties with defaults:
Command-line integration is built-in. You can define a configuration and then override values via command line arguments:
General:
| Name | Type | Description |
|---|---|---|
stack |
str
|
Runner stack selector used by |
Reproducibility:
| Name | Type | Description |
|---|---|---|
seed |
int
|
Random seed for reproducibility. If not set, a random value is generated. |
deterministic |
bool
|
Whether to enforce deterministic operations in PyTorch.
Defaults to |
Progress:
| Name | Type | Description |
|---|---|---|
steps |
int | None
|
Final global step target for training.
In step mode, training stops when |
epochs |
int | None
|
Final epoch index boundary for training.
In epoch mode, training iterates epochs until |
Model Evaluation:
| Name | Type | Description |
|---|---|---|
score_split |
str
|
Dataset split to use for model selection. Defaults to None.
If unset, runner infers once ( |
score_name |
str
|
Metric name to use for model selection. Defaults to “loss”. |
scheduler.interval |
str
|
Scheduler advancement policy.
Supported values: |
scheduler.monitor |
str
|
Optional metric selector for metric schedulers.
Supports dotted paths such as |
Optimization:
| Name | Type | Description |
|---|---|---|
optim.param_groups |
list[dict] | None
|
Optional regex-based optimizer
parameter groups. Each entry requires |
I/O:
| Name | Type | Description |
|---|---|---|
workspace_root |
str
|
Root directory for experiments. Defaults to |
auto_resume |
bool
|
Auto-resume from backend latest checkpoint alias/path.
When |
resume |
str | None
|
Optional full-state checkpoint source for resume workflows.
This is a path-like identifier consumed by runner |
pretrained |
str | None
|
Optional model-only checkpoint source for finetune workflows.
This is a path-like identifier consumed by runner |
lineage |
str
|
Top-level lineage namespace.
Defaults to |
experiment |
str
|
Experiment namespace. Defaults to |
checkpoint.dir_name |
str
|
Subdirectory name for checkpoints. Defaults to |
checkpoint.async_enabled |
bool
|
Whether to persist checkpoints asynchronously.
Defaults to |
checkpoint.async_mode |
str | None
|
Checkpoint async behavior.
Supported values: |
checkpoint.dedicated_async_process_group |
bool
|
Use a dedicated process group for async DCP
checkpoint I/O to reduce interference with training collectives. Defaults to |
checkpoint.async_process_group_backend |
str
|
Backend for the dedicated async checkpoint process
group. Defaults to |
checkpoint.backend |
str
|
Checkpoint backend selected at runtime by the runner
( |
checkpoint.wait_timeout |
float
|
Timeout in seconds when draining async checkpoint writes
during runner shutdown ( |
parallel.axes.replicate |
int
|
Data-replication degree for DDP/HSDP-style replication.
Defaults to |
parallel.axes.shard |
int
|
Data-sharding degree for FSDP-style sharding.
Defaults to |
parallel.axes.context |
int
|
Context/sequence parallel degree. Defaults to |
parallel.axes.pipeline |
int
|
Pipeline-parallel degree. Defaults to |
parallel.axes.tensor |
int
|
Tensor-parallel degree. Defaults to |
parallel.axes.expert |
int
|
Expert-parallel degree for MoE models. Defaults to |
parallel.axes.expert_tensor |
int
|
Expert tensor-parallel degree for MoE models. Defaults to |
parallel.pipeline_schedule |
str
|
Pipeline schedule class name resolved by
|
parallel.pipeline_microbatch_size |
int
|
Local microbatch size used to infer
schedule microbatch count as |
parallel.pipeline_n_microbatches |
int
|
Explicit schedule microbatch count.
When set, overrides |
parallel.module_fqns_per_model_part |
list[list[str]] | None
|
Optional
module FQNs for simple pipeline stage extraction. The outer list
length is the total pipeline stage count and must be divisible by
|
log |
bool
|
Whether to enable file logging. Defaults to |
tensorboard |
bool
|
Whether to use TensorBoard for visualization. Defaults to |
wandb.enabled |
bool
|
Whether to enable Weights & Biases scalar logging. Defaults to |
wandb.project |
str | None
|
Optional W&B project name. Defaults to |
wandb.entity |
str | None
|
Optional W&B entity/team override. |
wandb.group |
str | None
|
Optional W&B group name. Defaults to |
wandb.name |
str | None
|
Optional W&B display name. Defaults to stable runner |
wandb.job_type |
str | None
|
Optional W&B job type. |
wandb.tags |
list[str] | str | None
|
Optional W&B run tags. |
wandb.dir |
str | None
|
Optional local W&B run directory. Defaults to run dir. |
wandb.mode |
str | None
|
Optional W&B mode such as |
ft.enabled |
bool
|
Enable TorchFT-managed fault tolerance. Defaults to |
ft.process_group |
str
|
TorchFT coordination backend. Supported values: |
ft.process_group_timeout_ms |
int
|
TorchFT process-group timeout in milliseconds.
Defaults to |
ft.replica_id |
int
|
Replica-group identifier for this run. Defaults to |
ft.group_size |
int
|
Number of replica groups participating in TorchFT. Defaults to |
ft.min_replica_size |
int
|
Minimum healthy replicas required by TorchFT per step.
Defaults to |
log_interval |
int
|
Iterations between log outputs. If None, auto-calculated. |
checkpoint.interval |
int
|
Interval between checkpoint save attempts for |
checkpoint.keep_latest_k |
int
|
Number of framework-generated history checkpoints to retain.
|
checkpoint.load_only |
bool
|
Disable checkpoint persistence entirely while still allowing checkpoint loading. |
checkpoint.enable_ft_dataloader_checkpoints |
bool
|
Enable per-replica dataloader checkpoints for FT recovery.
Uses DCP and stores checkpoints under
|
checkpoint.ft_replica_id |
str | None
|
Replica identifier used for FT dataloader checkpoint directory naming.
Defaults to |
checkpoint.ft_dataloader_checkpoint_prefix |
str
|
Prefix used for FT per-replica checkpoint directories.
Defaults to |
checkpoint.exclude_from_loading |
list[str] | str | None
|
Checkpoint keys to skip during
|
checkpoint.last_save_model_only |
bool
|
Save model-only payload on final |
checkpoint.export_dtype |
str
|
Optional dtype cast for final model-only export
( |
dataloader.batch_size |
int | None
|
Local dataloader batch size passed to
|
dataloader.shuffle |
bool | None
|
Optional shuffle override. When unset, train splits shuffle and non-train splits do not. |
dataloader.drop_last |
bool | None
|
Optional drop-last override. When unset, train splits drop incomplete batches and non-train splits keep them. |
dataloader.num_workers |
/ persistent_workers / prefetch_factor / pin_memory
|
Standard PyTorch DataLoader kwargs forwarded to |
dataloader.in_order |
bool
|
PyTorch DataLoader ordering flag. |
dataloader.snapshot_every_n_steps |
int | None
|
StatefulDataLoader snapshot cadence. |
dataloader.<split> |
dict
|
Split-specific overrides merged on top of default
dataloader kwargs, for example |
fsdp.enabled |
bool
|
Enable FSDP2 wrapping in |
fsdp.reshard_after_forward |
bool | int | None
|
Optional FSDP2 reshard policy. |
fsdp.mp_policy |
bool | int | None
|
Optional FSDP2 mixed precision policy. |
fsdp.offload_policy |
bool | int | None
|
Optional FSDP2 CPU offload policy. |
compile.enable |
bool
|
Whether to enable |
compile.backend |
str
|
Optional backend passed to |
compile.fullgraph |
bool
|
Optional |
compile.dynamic |
bool
|
Optional |
compile.mode |
str
|
Optional mode passed to |
compile.options |
dict
|
Optional options passed to |
compile.optimize_ddp |
str | None
|
Optional |
compile.precompile_artifact_dir |
str | None
|
Optional directory for GraphRunner torch compiler cache artifacts. Current eager runners ignore this setting. |
compile.memory_policy |
str | None
|
Optional graph-memory policy label for experimental graph paths.
GraphRunner currently accepts |
comm.init_timeout_seconds |
int | None
|
Optional distributed process-group timeout used during initialization and early startup. |
comm.train_timeout_seconds |
int | None
|
Optional tighter distributed process-group timeout applied once after the first successful optimizer step. |
gc.interval |
int | None
|
Optional periodic Python GC cadence. When unset, runner-managed GC pacing is disabled. |
gc.generation |
int
|
Python GC generation passed to |
gc.disable_automatic |
bool
|
Disable CPython automatic GC while runner-managed pacing is enabled.
Defaults to |
profiling.enabled |
bool
|
Enable bounded-step |
profiling.wait |
int
|
Profiler schedule wait steps before warmup. Defaults to |
profiling.warmup |
int
|
Profiler schedule warmup steps. Defaults to |
profiling.active |
int
|
Profiler schedule active trace steps. Defaults to |
profiling.repeat |
int | None
|
Optional profiler schedule repeat count. |
profiling.record_shapes |
bool
|
Enable shape recording in traces. Defaults to |
profiling.profile_memory |
bool
|
Enable profiler-side memory recording. Defaults to |
profiling.with_stack |
bool
|
Include Python stack traces in profiler output. Defaults to |
profiling.with_flops |
bool
|
Enable profiler FLOPs estimation when available. Defaults to |
profiling.trace_dir |
str
|
Relative or absolute trace output directory. Defaults to |
heartbeat.enabled |
bool
|
Enable a machine-readable per-rank heartbeat/progress file. Defaults to |
heartbeat.interval_seconds |
float
|
Heartbeat write interval in seconds. Defaults to |
heartbeat.dir_name |
str
|
Subdirectory under the run dir for heartbeat files. Defaults to |
| Text Only | |
|---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | |
Note
Always store all parameters needed to reproduce a run in the RunnerConfig. The RunnerConfig is automatically saved with checkpoints, enabling exact resumption.
See Also
Runner: Main runner class that uses this config.chanfig.Config: Base config implementation.
Source code in danling/runners/config.py
| Python | |
|---|---|
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 | |
RunnerState
dataclass
¶
Bases: _StatefulBase
Checkpointable state container for a runner instance.
Attributes:
| Name | Type | Description |
|---|---|---|
config |
RunnerConfig
|
Runner configuration associated with this state object. |
train |
RunnerTrainState
|
Training progress counters. |
elastic |
RunnerElasticState
|
Torchelastic restart metadata. |
rng |
RunnerRNGState
|
Python/NumPy/Torch RNG snapshots. |
Source code in danling/runners/state.py
TorchRunner
¶
Bases: Fp8Mixin, BaseRunner
PyTorch-native runner for training, evaluation, and inference.
Use this runner for single-model PyTorch training with optional DDP,
autocast/FP8, torch.compile, stateful dataloaders, metric logging, and
file or torch.distributed.checkpoint persistence.
Users must provide self.model before construction completes. Most
training tasks also provide self.criterion, and either self.optimizer
or config.optim. Datasets may be supplied through self.datasets and
will be materialized into StatefulDataLoader instances during
__post_init__.
The default batch contract is intentionally simple:
mappings use input/target, sequences use index 0/1, and any other value
is treated as model input with no target. Override train_step,
evaluate_step, or infer_step when a task needs a different contract.
Attributes:
| Name | Type | Description |
|---|---|---|
model |
Module
|
Local model module after materialization (possibly DDP-wrapped). |
ema |
Module | None
|
Optional EMA/evaluation model. |
criterion |
Callable | None
|
Loss callable used by default train/evaluate steps. |
optimizer |
Optimizer | None
|
Optimizer used by the runner or backend engine. |
scheduler |
Any | None
|
Optional LR scheduler. |
optimizer_container |
OptimizerContainer | None
|
Helper that owns optimizer step, clipping, non-finite checks, and step-scheduler dispatch. |
compiler |
Compiler
|
|
scheduler_interval |
str
|
Effective scheduler interval ( |
scheduler_monitor |
str | None
|
Optional metric path used for metric schedulers. |
Source code in danling/runners/torch_runner.py
| Python | |
|---|---|
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 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 | |
init_distributed
¶
Initialize the distributed environment.
The default implementation initializes the default torch.distributed
process group from WORLD_SIZE/RANK/LOCAL_RANK environment
variables when WORLD_SIZE > 1, sets the active CUDA device,
broadcasts self.timestamp from rank 0, and seeds
elastic_state.restart_count from TORCHELASTIC_RESTART_COUNT.
Called when: once during BaseRunner.__init__, before
init_checkpoint_manager, init_fault_tolerance, and
init_garbage_collection. The runner is partially constructed at
this point — self.config, self.workspace, self.timestamp, the
dataloader container, and the default FileCheckpointManager are
bound, but the model is not materialized and optimizers/dataloaders
are not built.
Precondition: environment variables WORLD_SIZE, RANK,
LOCAL_RANK are set when running distributed. The default
torch.distributed process group is not already initialized when
WORLD_SIZE > 1 — the runner owns process-group lifecycle.
Raises:
| Type | Description |
|---|---|
RuntimeError
|
the default process group is already initialized
when |
ValueError
|
|
Side effects: when WORLD_SIZE > 1, calls
dist.init_process_group(...), sets the active CUDA device when
CUDA is available, and broadcasts self.timestamp from rank 0.
Reads TORCHELASTIC_RESTART_COUNT into elastic_state.restart_count.
Do not
- Initialize a process group via
dist.init_process_group(...)outside the runner; the runner owns its lifecycle. - Build the model or dataloaders here; those happen in
__post_init__. - Bind the checkpoint manager here;
init_checkpoint_managerruns next.
Backend notes:
ParallelRunnerextends this hook: after callingsuper(), it builds the parallel topology (build_topology) and initializes per-axis process groups viainit_device_mesh.DeepSpeedRunnerinherits the default; DeepSpeed reuses the default process group initialized here.
Source code in danling/runners/torch_runner.py
| Python | |
|---|---|
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 | |
init_checkpoint_manager
¶
Bind the checkpoint manager corresponding to config.checkpoint.backend.
The default dispatches by backend: when the backend is "dcp", it
binds a TorchDistributedCheckpointManager (or
TorchFTCheckpointManager when FT dataloader checkpoints are
enabled). For "file" it leaves the FileCheckpointManager already
bound by BaseRunner.__init__ in place.
Called when: once during BaseRunner.__init__, after
init_distributed and before init_fault_tolerance. The default
FileCheckpointManager is already bound at this point — overrides
should swap it via set_checkpoint_manager(...), not by direct
attribute assignment.
Precondition: config.checkpoint.backend is normalized to one
of {"file", "dcp"} (TorchRunner does this in __init__). When
the backend is "dcp", the default process group is initialized
for distributed runs.
Side effects: swaps self.checkpoint_manager via
set_checkpoint_manager(...) when the backend differs from
"file". The prior manager is closed with a zero timeout.
Do not
- Set
self.checkpoint_managerdirectly; useset_checkpoint_managerso the prior manager is closed cleanly. - Initialize fault tolerance here;
init_fault_toleranceruns next. - Bind the model or dataloaders here.
Backend notes:
DeepSpeedRunnercoercesconfig.checkpoint.backendto"file"in__init__, so this hook is a no-op for that backend.ParallelRunnercoerces the backend to"dcp", so this hook always bindsTorchDistributedCheckpointManagerorTorchFTCheckpointManager.
Source code in danling/runners/torch_runner.py
init_tensorboard
¶
Set up TensorBoard SummaryWriter.
Source code in danling/runners/torch_runner.py
set_seed
¶
Set up random seed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
int | None
|
Random seed to set.
Defaults to |
None
|
|
int | bool | None
|
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/runners/torch_runner.py
materialize_model
¶
Move the model to the runtime device, optionally compile, and wrap with DDP when distributed.
The default is a single-module DDP-style materialization: it moves
self.model to self.device, applies any FP8 module policy when
FP8 is enabled, runs torch.compile via self.compiler (under the
DDP-optimizer context when wrapping is needed), and wraps the result
with nn.parallel.DistributedDataParallel when world size > 1.
Called when: once during __post_init__, after setup_fp8()
and before build_optimizer(). The order matters — the optimizer
must see post-wrap parameters.
Precondition: self.model is set (typically by the user before
constructing the runner). self.device resolves to the runtime
device.
Raises:
| Type | Description |
|---|---|
ValueError
|
|
Side effects: moves self.model to self.device; applies FP8
module policy when self.fp8_enabled; compiles via
self.compiler.compile(...) under the DDP-optimizer context when
wrapping is needed; wraps with DistributedDataParallel for world
size > 1. Moves self.ema to device when EMA is bound.
Do not
- Build the optimizer or scheduler here; they run after this hook.
- Skip the device move when overriding (tensors must live on
self.devicebefore the forward pass). - Re-wrap an already-wrapped model (e.g., DDP-wrap a DDP module).
Backend notes:
DeepSpeedRunneroverrides this hook to move the model to device and compile only; the DeepSpeed engine wraps the model later in_finalize_runtime_components.ParallelRunneroverrides this hook for FSDP2, pipeline-parallel schedules, and tensor/expert/context parallelism (via theparallelize_modelandapply_activation_checkpointinghooks).
Source code in danling/runners/torch_runner.py
build_optimizer
¶
Auto-build the optimizer from config.optim (or config.optimizer)
when self.optimizer is absent.
The default iterates parameters via iter_optimizer_parameters and
dispatches to the OPTIMIZERS registry with the merged config. If
optim.param_groups is configured, entries are matched by regex
search against iter_optimizer_named_parameters; unmatched
parameters keep the optimizer-level defaults.
Called when: once during TorchRunner.__post_init__, after
materialize_model (so parameters reflect DDP/FSDP wrapping) and
before build_scheduler.
Precondition: self.model is materialized and on self.device.
self.optimizer is None (the auto-build is skipped when the user
has already bound an optimizer).
Side effects: sets self.optimizer to the registry-built
instance.
Do not
- Run before
materialize_model; parameters won’t reflect DDP/FSDP wrapping. - Build a scheduler here.
- Override parameter enumeration here; override
iter_optimizer_parameters/iter_optimizer_named_parametersinstead so subclass topology (e.g.,ParallelRunner.model_parts) is preserved.
Backend notes:
DeepSpeedRunnerinherits this hook; DeepSpeed may replace the optimizer with a DeepSpeed-managed instance during_finalize_runtime_components.ParallelRunnerinherits this hook but overridesiter_optimizer_parametersto enumerateself.model_parts.
Source code in danling/runners/torch_runner.py
build_scheduler
¶
Auto-build the LR scheduler from config.sched (or
config.scheduler) when self.scheduler is absent.
The default pops interval and monitor from the config (those
drive runner-level dispatch, not scheduler construction), defaults
total_steps to self.steps when computable, and dispatches to
the SCHEDULERS registry with self.optimizer and the merged
config.
Called when: once during TorchRunner.__post_init__, after
build_optimizer.
Precondition: self.optimizer is bound. self.scheduler is
None (the auto-build is skipped when the user has already bound a
scheduler).
Side effects: sets self.scheduler to the registry-built
instance.
Do not
- Run before
build_optimizer; the scheduler must wrap an optimizer. - Set scheduler interval or monitor here; configure them via
config.sched.interval/config.sched.monitor.
Backend notes:
DeepSpeedRunnerinherits this hook; the scheduler may be handed to the DeepSpeed engine in_finalize_runtime_componentswhen its effective interval is"step". Otherwise the runner retains it.
Source code in danling/runners/torch_runner.py
build_dataloaders
¶
Build dataloaders for dataset splits not already materialized.
The default iterates self.datasets, merges config.dataloader
defaults with split-specific overrides (config.dataloader.<split>),
constructs a sampler via build_datasampler, and wraps each dataset
in a StatefulDataLoader using self.collate_fn. Train splits
default to shuffle=True and drop_last=True; non-train splits
default to the opposite.
Called when: once during TorchRunner.__post_init__ when
self.datasets is non-empty.
Precondition: self.datasets is populated (typically by the
user before constructing the runner). self.dataloaders is bound
to a default-constructed DataLoaderDict.
Side effects: populates self.dataloaders[split] for each
split in self.datasets not already materialized. Existing entries
in self.dataloaders are left untouched.
Do not
- Override sampler logic here; override
build_datasamplerinstead. - Override collation; set
self.collate_fnor overridecollate_fn(classmethod) instead. - Bind the optimizer or scheduler here.
Backend notes:
ParallelRunnersubstitutesself.dataloaderswith a proxying dict in__init__so non-first/last pipeline stages receive aStepProxyLoaderview. The build logic itself is inherited.
Source code in danling/runners/torch_runner.py
build_datasampler
¶
Build the sampler for one dataset split.
Called when: build_dataloaders materializes a split from
self.datasets.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Any
|
Dataset object for the split. |
required |
|
str
|
Split name being materialized. |
required |
|
bool
|
Whether this split should be sampled in shuffled order. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
A local random/sequential sampler in single-process mode, or a |
Any
|
|
Backend notes:
ParallelRunneroverrides replica/rank selection so data-parallel sampling follows its topology instead of raw global rank.
Source code in danling/runners/torch_runner.py
all_reduce
¶
Reduce tensor over the runner’s replica/data-parallel collective domain.
Source code in danling/runners/torch_runner.py
| Python | |
|---|---|
reduce
¶
Average-reduce tensor over the runner’s collective domain.
Source code in danling/runners/torch_runner.py
reduce_loss_for_logging
¶
Detach and all-reduce weighted loss tensor for logging.
Source code in danling/runners/torch_runner.py
train_context
¶
Context for one training micro-step (autocast + optional DDP no_sync).
forward_context
¶
Precision context used by train/eval/infer forward passes.
Source code in danling/runners/torch_runner.py
| Python | |
|---|---|
train_step
¶
Run one training micro-step.
The default implementation runs forward → loss → metric update → backward → step for one micro-batch.
Called when: once per micro-batch by train_epoch/train_steps. The
caller seeds the loop’s accumulation state before each invocation; this
method consumes that state through backward() and step().
Precondition: self.model, self.optimizer, and self.criterion
are bound; self.mode == RunnerMode.train.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Any
|
One micro-batch. The default unpacks |
required |
Returns:
| Type | Description |
|---|---|
Any
|
|
Tensor | None
|
|
tuple[Any, Tensor | None]
|
The default raises when |
tuple[Any, Tensor | None]
|
overrides may return |
tuple[Any, Tensor | None]
|
which case the caller skips loss bookkeeping. |
Raises:
| Type | Description |
|---|---|
ValueError
|
|
Side effects: moves data to self.device, runs forward under
train_context() (autocast + optional DDP no-sync), updates
self.metrics when bound, then calls self.backward(loss) and
self.step() to scale gradients, advance accumulation state, and flush
the optimizer on accumulation boundaries.
Do not
- Zero gradients (
optimizer_stepdoes this on flush). - Call
self.optimizer.step()directly (useself.step()). - Mutate
train_state.global_steportrain_state.micro_step. - Implement gradient scaling here (override
backward()instead). - Call
save_checkpoint()(cadence is owned by the loop method).
Backend notes:
DeepSpeedRunnerinherits the default;backward/steproute through the DeepSpeed engine.ParallelRunneroverrides this method when a pipeline schedule is set; the schedule owns micro-batching and loss reduction.
Source code in danling/runners/torch_runner.py
| Python | |
|---|---|
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 | |
backward
¶
Run backward pass on one micro-step loss.
Called when: the default train_step has produced a loss tensor.
The method receives the raw micro-step loss; accumulation scaling and
loss-normalizer weighting are applied before Tensor.backward().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Tensor
|
The loss tensor for this micro-step. |
required |
Side effects: accumulates gradients on model parameters.
Do not
- Advance the optimizer here; optimizer stepping belongs to
step()/optimizer_step(). - Mutate
train_statecounters.
Backend notes:
DeepSpeedRunneroverrides this hook to call the DeepSpeed engine’s backward method.
Source code in danling/runners/torch_runner.py
step
¶
Advance the accumulation state machine after one training micro-step.
Called when: train_step finishes backward for a micro-batch.
Side effects: increments train_state.micro_step and calls
optimizer_step() only when the accumulation boundary is reached or
the surrounding loop marks the current batch as the final flush in a
partial window.
Do not
- Call this from evaluation/inference paths.
- Call
optimizer_step()in addition to this method from the same micro-step. - Adjust
train_state.micro_stepintrain_stepoverrides.
Source code in danling/runners/torch_runner.py
optimizer_step
¶
optimizer_step() -> bool
Perform one backend optimizer update.
The default Torch implementation waits for checkpoint staging, applies
accumulated-loss gradient scaling, optional grad clipping, non-finite
grad skip logic, optimizer/scheduler stepping through
OptimizerContainer, gradient zeroing, profiler advancement, and
garbage-collection cadence.
Called when: step() reaches an accumulation boundary, or
_flush_pending_optimizer_step() flushes a partial boundary before
shutdown.
Returns:
| Type | Description |
|---|---|
bool
|
|
Side effects: may update optimizer/scheduler state; increments
train_state.global_step only when an update is actually applied.
Do not
- Increment
global_stepon skipped updates. - Forget to zero gradients after a successful update or skipped non-finite update.
- Bypass
checkpoint_manager.maybe_wait_for_staging().
Backend notes:
DeepSpeedRunneroverrides this hook because the DeepSpeed engine owns the concrete optimizer update.
Source code in danling/runners/torch_runner.py
| Python | |
|---|---|
1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 | |
train
¶
train(
train_splits: list[str] | None = None,
evaluate_splits: list[str] | None = None,
) -> RoundDict
Run the full training workflow.
Selects epoch mode or step mode from self.is_step_mode, validates
explicit split lists against the runner’s configured/inferred splits,
and delegates to train_epochs or train_steps.
Called when: user code starts training.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
list[str] | None
|
Optional training splits. When |
None
|
|
list[str] | None
|
Optional evaluation splits. When |
None
|
Returns:
| Type | Description |
|---|---|
RoundDict
|
Aggregated runner results ( |
Raises:
| Type | Description |
|---|---|
ValueError
|
no valid training split can be resolved. |
Side effects: prints selected splits and runs the selected training loop. Checkpointing, result writing, scheduler stepping, and early stop are owned by the delegated loop method.
Source code in danling/runners/torch_runner.py
train_epochs
¶
train_epochs(
train_splits: list[str] | None = None,
evaluate_splits: list[str] | None = None,
) -> RoundDict
Run epoch-mode training until self.epochs is reached.
Each epoch runs all train splits, then all evaluation splits, advances epoch/metric schedulers, appends and writes results, and saves periodic checkpoints.
Called when: train dispatches while config.epochs is set, or
user code explicitly wants epoch-mode semantics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
list[str] | None
|
Training splits for each epoch. |
None
|
|
list[str] | None
|
Evaluation splits after each epoch. |
None
|
Returns:
| Type | Description |
|---|---|
RoundDict
|
Aggregated runner results ( |
Raises:
| Type | Description |
|---|---|
ValueError
|
|
Source code in danling/runners/torch_runner.py
train_epoch
¶
Run one full dataloader pass for a training split.
This is the per-split epoch loop. It sets train mode, resets meters and
train metrics, manages accumulation-window normalization, invokes
train_step for each micro-batch, emits step logs, and records
interval/epoch telemetry.
Called when: train_epochs processes one train split.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
str
|
Training split name. |
'train'
|
Returns:
| Type | Description |
|---|---|
RoundDict
|
Epoch-level metric mapping for this split. |
Side effects: updates optimizer state through train_step,
advances train_state.global_step on optimizer flushes, writes step
logs, and may save step-cadence checkpoints.
Do not
- Call this for evaluation data; use
evaluate_epoch. - Override this just to change one batch’s forward/loss logic;
override
train_step. - Manually manage gradient zeroing inside
train_step; this loop andoptimizer_stepown accumulation boundaries. - Increment
train_state.epoch; the surroundingtrain_epochsloop owns epoch progress. - Save result or checkpoint aliases here;
train_epochsowns epoch-level persistence.
See Also
train_steps:
Step-mode counterpart that consumes splits against a global
step budget instead of one epoch per split.
Source code in danling/runners/torch_runner.py
| Python | |
|---|---|
1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 | |
train_steps
¶
train_steps(
train_splits: list[str] | None = None,
evaluate_splits: list[str] | None = None,
) -> RoundDict
Run step-mode training for the configured global step budget.
Step mode consumes train splits in sorted split order until
train_state.global_step >= self.steps, then optionally evaluates
configured evaluation splits with evaluate_steps.
Called when: train dispatches while config.epochs is unset, or
user code explicitly wants a global-step budget.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
list[str] | None
|
Training splits to consume in order. |
None
|
|
list[str] | None
|
Evaluation splits to run after training steps finish. |
None
|
Returns:
| Type | Description |
|---|---|
RoundDict
|
Aggregated runner results ( |
Raises:
| Type | Description |
|---|---|
ValueError
|
total step budget cannot be resolved. |
Side effects: updates epoch as an outer split-round counter,
appends one result row indexed by global_step, writes result files,
and saves the final checkpoint.
Do not
- Assume a split is consumed exactly once; step mode can resume a split iterator across outer rounds.
- Mutate
train_state.global_stepoutside optimizer stepping.
See Also
train_epoch:
Per-split epoch loop used by epoch-mode training.
Source code in danling/runners/torch_runner.py
| Python | |
|---|---|
1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 | |
evaluate_step
¶
Run one evaluation micro-step.
The default implementation runs forward → optional loss → optional
metric update under forward_context(). No backward pass and no
optimizer step.
Called when: once per micro-batch by evaluate_epoch/evaluate_steps,
which run under torch.inference_mode().
Precondition: at least one of self.model or self.ema is bound.
self.mode == RunnerMode.evaluate. The default prefers self.ema over
self.model when both are available.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Any
|
One micro-batch. The default unpacks |
required |
Returns:
| Type | Description |
|---|---|
Any
|
|
Tensor | None
|
|
tuple[Any, Tensor | None]
|
logging, or |
Raises:
| Type | Description |
|---|---|
ValueError
|
neither |
Side effects: moves data to self.device, runs forward through
self.ema or self.model under forward_context(), computes loss when
criterion is set, and updates self.metrics when bound.
Do not
- Call
self.backward(...)orself.step()(no optimizer here). - Mutate
train_state.global_steportrain_state.micro_step. - Switch the runner mode (the loop owns
self.mode). - Call
save_checkpoint()(cadence is owned by training loops only).
Backend notes:
ParallelRunneroverrides this method when a pipeline schedule is set; the schedule owns micro-batching and pipeline-stage loss reduction.
Source code in danling/runners/torch_runner.py
| Python | |
|---|---|
2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 | |
evaluate
¶
evaluate(
evaluate_splits: list[str] | None = None,
) -> RoundDict
Run evaluation across splits with epoch-mode semantics.
Called when: user code explicitly evaluates a runner, or training code delegates to evaluation helpers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
list[str] | None
|
Optional evaluation splits. When |
None
|
Returns:
| Type | Description |
|---|---|
RoundDict
|
Mapping of split -> evaluation result for this call. |
Raises:
| Type | Description |
|---|---|
ValueError
|
no valid evaluation split can be resolved. |
Side effects: sets evaluation mode per split, prints a formatted
aggregate result, and writes scalar outputs through evaluate_epoch.
Source code in danling/runners/torch_runner.py
evaluate_epoch
¶
Run one full dataloader pass for an evaluation split.
Sets evaluation mode, resets meters/evaluation metrics, runs
evaluate_step for every batch under inference mode, emits step logs,
and writes the split result at the current epoch index.
Called when: evaluate or train_epochs evaluates a split.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
str
|
Evaluation split name. |
'val'
|
Returns:
| Type | Description |
|---|---|
RoundDict
|
Epoch-level metric mapping for this split. |
Side effects: updates evaluation meters/metrics, emits logs, writes scalar results, and records telemetry. It does not update optimizer or training progress counters.
Source code in danling/runners/torch_runner.py
| Python | |
|---|---|
2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 | |
evaluate_steps
¶
Run bounded evaluation steps on one split.
Used by step-mode training to evaluate a small fixed number of batches without requiring a full evaluation pass.
Called when: train_steps evaluates configured splits after the
step budget finishes, or user code requests bounded evaluation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
str
|
Evaluation split name. |
'val'
|
|
int | None
|
Number of batches to evaluate. When |
None
|
Returns:
| Type | Description |
|---|---|
RoundDict
|
Step-bounded evaluation metrics. |
Raises:
| Type | Description |
|---|---|
ValueError
|
step budget cannot be inferred, |
Side effects: writes scalar results at train_state.global_step.
Source code in danling/runners/torch_runner.py
| Python | |
|---|---|
2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 | |
infer_step
¶
Run one inference micro-step.
The default implementation runs forward through self.ema or self.model,
detaches scalar-per-example predictions, squeezes the trailing
dimension, moves them to CPU, and returns them as a Python list.
Called when: once per micro-batch by infer/_iter_infer_batches.
The method is decorated with torch.inference_mode().
Precondition: at least one of self.model or self.ema is bound.
self.mode == RunnerMode.infer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Any
|
One micro-batch. The default unpacks |
required |
Returns:
| Type | Description |
|---|---|
list[float]
|
List of CPU floats for scalar-per-example predictions. The |
list[float]
|
default converts with |
list[float]
|
Override if your model emits multi-dim tensors, mappings, or |
list[float]
|
non-numeric outputs. |
Raises:
| Type | Description |
|---|---|
ValueError
|
neither |
Side effects: moves data to self.device, runs forward through
self.ema or self.model under forward_context(), then converts the
output to a CPU list.
Do not
- Compute or accumulate metrics (inference is metric-free).
- Mutate runner state counters.
- Return a
torch.Tensor(callers expectlist[float]for batched aggregation and streaming). - Call
self.backward(...)orself.step().
Backend notes:
ParallelRunneroverrides this method when a pipeline schedule is set; non-first-stage ranks passdata=Noneand the schedule routes activations through pipeline communication.
Source code in danling/runners/torch_runner.py
| Python | |
|---|---|
2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 | |
infer
¶
infer(
split: str = "infer",
*,
steps: int | None = None,
stream: bool | None = None
) -> list[float] | Iterator[list[float]]
Run inference on one split.
In non-stream mode this consumes all requested batches and returns a flattened Python list. In stream mode it returns an iterator of per-batch outputs and leaves consumption to the caller.
Called when: user code requests prediction-only execution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
str
|
Inference split name. |
'infer'
|
|
int | None
|
Optional max number of batches to consume. |
None
|
|
bool | None
|
|
None
|
Returns:
| Type | Description |
|---|---|
list[float] | Iterator[list[float]]
|
Flattened predictions or a streaming iterator of batch predictions. |
Raises:
| Type | Description |
|---|---|
ValueError
|
|
Side effects: sets inference mode/split. It does not update metrics or optimizer state.
Source code in danling/runners/torch_runner.py
state_dict
¶
Return the TorchRunner checkpoint payload.
Extends BaseRunner.state_dict with backend metadata plus EMA,
optimizer, scheduler, and unwrapped model state.
Called when: checkpoint managers persist a TorchRunner checkpoint.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
type
|
Mapping factory used for nested payloads. |
dict
|
Returns:
| Type | Description |
|---|---|
Mapping
|
Mapping containing base runner state and torch component state. |
Side effects: snapshots Python/NumPy/Torch RNG state before exporting.
Source code in danling/runners/torch_runner.py
load_state_dict
¶
Restore base runner state plus Torch RNG state.
Model, optimizer, scheduler, and dataloader components are restored by
load_checkpoint; this method owns only runner/RNG state.
Source code in danling/runners/torch_runner.py
load_checkpoint
¶
Load a full checkpoint and rebind optimizer/scheduler helpers.
This delegates component restore to BaseRunner.load_checkpoint, then
rebuilds the OptimizerContainer so scheduler and optimizer state stay
bound after restore.
Source code in danling/runners/torch_runner.py
read_checkpoint
¶
read_checkpoint(
checkpoint: Mapping | bytes | str | PathLike,
*args,
**kwargs
) -> Mapping[str, Any]
Read checkpoint payload from mapping/file/DCP directory input.
Source code in danling/runners/torch_runner.py
read_config
classmethod
¶
read_config(
checkpoint: Mapping | bytes | str | PathLike,
*args,
**kwargs
) -> RunnerConfig
Read runner config from checkpoint payload, including DCP directory inputs.
Source code in danling/runners/torch_runner.py
close
¶
Close runner resources.
Source code in danling/runners/torch_runner.py
NestedTensor
¶
Bases: Tensor
A container for variable-length tensors that enables efficient batch operations.
NestedTensor solves a fundamental problem in deep learning: handling sequences of different lengths
in batch operations. Instead of excessive padding or complex bucketing, NestedTensor provides an
elegant solution that maintains both efficiency and usability.
The class provides three main views of the data:
- .tensor: A padded tensor with zeros (or other value) in place of missing elements
- .mask: A boolean mask indicating which elements are real vs padding
- .concat: The packed tensor containing all elements concatenated without padding
When indexing a NestedTensor, the behavior depends on the index type:
1. Integer index (nt[0]): Returns a single tensor without padding
2. Slice index (nt[:]): Returns a new NestedTensor containing the selected batch elements
3. Tuple index (nt[:, 1:]): Returns a new NestedTensor with the specified sliced shape
Attributes:
| Name | Type | Description |
|---|---|---|
_values |
Tensor
|
Packed tensor data |
_offsets |
Tensor
|
Top-level cumulative element counts, shape (B+1,) |
_permutation |
tuple[int, ...]
|
Canonical logical-to-packed dimension permutation |
_physical_shape |
Tensor
|
Per-element physical shapes, shape (B, max_ndim) |
batch_first |
bool
|
Whether the first dimension is the batch dimension (B, N, *)
If |
padding_value |
float
|
Value used for padding in the padded tensor |
mask_value |
bool
|
Boolean fill value for padding positions in generated masks.
- |
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Variable-length tensors or sequences to store |
required | |
|
Whether to use batch-first representation. |
required | |
|
Value to use for padding. |
required | |
|
Boolean fill value used for padding positions in masks. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
Basic usage:
| Python Console Session | |
|---|---|
Type conversion:
| Python Console Session | |
|---|---|
Conversion to Python types:
Creating from Python lists:
| Python Console Session | |
|---|---|
Source code in danling/tensors/nested_tensor.py
| Python | |
|---|---|
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 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 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 | |
tensor_mask
property
¶
mask
property
¶
mask: Tensor
Padding mask of tensor.
mask_value controls which boolean value denotes padding in this mask.
With the default mask_value=False, True means valid data.
Examples:
concat
property
¶
concat: Tensor
Flatten elements and concatenate along the ragged dimension (no padding).
This is particularly useful when calculating loss or passing Linear to avoid unnecessary computation.
Examples:
batch_first
property
writable
¶
batch_first: bool
Whether the logical outer shape uses (B, ...) instead of (..., B, ...).
padding_value
property
writable
¶
padding_value: float
Padding fill value used when materializing dense views.
mask_value
property
writable
¶
mask_value: bool
Boolean value used to denote padding positions in generated masks.
requires_grad
property
writable
¶
requires_grad: bool
Whether gradient computation is enabled for this tensor.
concatenate
¶
Concatenate tensors in padding dimension and return structural information for reconstruction.
Returns:
| Type | Description |
|---|---|
Tensor
|
A tuple containing: |
tuple[Size, ...]
|
|
tuple[Tensor, tuple[Size, ...]]
|
|
Examples:
Source code in danling/tensors/nested_tensor.py
__len__
¶
__len__() -> int
Return the number of tensors in the batch.
Source code in danling/tensors/nested_tensor.py
__repr__
¶
Return a human-readable string representation of the NestedTensor.
Source code in danling/tensors/nested_tensor.py
| Python | |
|---|---|
1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 | |
__bool__
¶
__bool__() -> bool
NestedTensor follows tensor-style truthiness and never acts like a Python container.
Source code in danling/tensors/nested_tensor.py
__iter__
¶
__eq__
¶
__ne__
¶
from_concatenated
classmethod
¶
Reconstruct a NestedTensor from a concatenated tensor and shape information.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Tensor
|
The concatenated tensor returned by concatenate() |
required |
|
tuple[Size, ...]
|
Tuple of original tensor shapes returned by concatenate() |
required |
|
Additional arguments to pass to NestedTensor constructor |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
Reconstructed NestedTensor |
Examples:
Source code in danling/tensors/nested_tensor.py
| Python | |
|---|---|
1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 | |
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.
The mask uses the same convention as |
required |
|
bool
|
When |
False
|
Examples:
Source code in danling/tensors/nested_tensor.py
| Python | |
|---|---|
1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 | |
nested_like
¶
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
|
Examples:
Source code in danling/tensors/nested_tensor.py
| Python | |
|---|---|
2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 | |
to_torch_nested
¶
to_torch_nested() -> Tensor
Create a torch.nested.nested_tensor object from self.
Examples:
| Python Console Session | |
|---|---|
Source code in danling/tensors/nested_tensor.py
unbind
¶
__getitem__
¶
__getitem__(
index: (
int | slice | list | tuple | Tensor | NestedTensor
),
) -> Tensor | NestedTensor
Retrieve element(s) by index, slice, list, tuple, or tensor mask.
Source code in danling/tensors/nested_tensor.py
| Python | |
|---|---|
2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 | |
__setitem__
¶
Set values in the NestedTensor at the specified index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
int | slice | list | tuple
|
The index to modify. Can be an integer, slice, list, or tuple. |
required |
|
Tensor | NestedTensor
|
The new value to set. Can be a Tensor or NestedTensor. |
required |
Examples:
| Python Console Session | |
|---|---|
Source code in danling/tensors/nested_tensor.py
| Python | |
|---|---|
2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 | |
__copy__
¶
Shallow copy: new NestedTensor sharing underlying tensor data.
Source code in danling/tensors/nested_tensor.py
__deepcopy__
¶
Deep copy: clones all tensor data.
Source code in danling/tensors/nested_tensor.py
all
¶
all(
dim: int | None = None, keepdim: bool = False
) -> bool | Tensor | NestedTensor
Tests if all elements in NestedTensor evaluate to True.
Examples:
Source code in danling/tensors/nested_tensor.py
any
¶
any(
dim: int | None = None, keepdim: bool = False
) -> bool | Tensor | NestedTensor
Tests if any elements in NestedTensor evaluate to True.
Examples:
| Python Console Session | |
|---|---|
Source code in danling/tensors/nested_tensor.py
dim
¶
dim() -> int
Number of dimension of the NestedTensor.
Examples:
| Python Console Session | |
|---|---|
Source code in danling/tensors/nested_tensor.py
max
¶
max(
dim: int | None = None, keepdim: bool = False
) -> Tensor | NestedTensor
Return the maximum value, optionally along a given dimension.
Source code in danling/tensors/nested_tensor.py
mean
¶
mean(
dim: int | None = None,
keepdim: bool = False,
*,
dtype: dtype | None = None
) -> Tensor | NestedTensor
Return the mean value, optionally along a given dimension.
Source code in danling/tensors/nested_tensor.py
| Python | |
|---|---|
min
¶
min(
dim: int | None = None, keepdim: bool = False
) -> Tensor | NestedTensor
Return the minimum value, optionally along a given dimension.
Source code in danling/tensors/nested_tensor.py
numel
¶
numel() -> int
Number of elements in the NestedTensor.
Examples:
| Python Console Session | |
|---|---|
Source code in danling/tensors/nested_tensor.py
permute
¶
permute(*dims) -> Self
Apply permutation to each tensor in the NestedTensor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
The desired ordering of dimensions for the NestedTensor (including batch dimension). |
()
|
Returns:
| Name | Type | Description |
|---|---|---|
NestedTensor |
Self
|
A new NestedTensor with each tensor permuted. |
Examples:
| Python Console Session | |
|---|---|
Source code in danling/tensors/nested_tensor.py
moveaxis
¶
movedim
¶
pin_memory
¶
Pin the underlying tensor memory for faster host-to-device transfer.
Source code in danling/tensors/nested_tensor.py
prod
¶
prod(
dim: int | None = None,
keepdim: bool = False,
*,
dtype: dtype | None = None
) -> Tensor | NestedTensor
Return the product of elements, optionally along a given dimension.
Source code in danling/tensors/nested_tensor.py
| Python | |
|---|---|
reshape
¶
reshape(*shape) -> Self
Reshape each tensor in the NestedTensor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
The desired size of each dimension for the underlying tensors. |
()
|
Returns:
| Name | Type | Description |
|---|---|---|
NestedTensor |
Self
|
A new NestedTensor with each tensor reshaped. |
Examples:
| Python Console Session | |
|---|---|
Source code in danling/tensors/nested_tensor.py
flatten
¶
flip
¶
size
¶
Returns the size of the self NestedTensor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
int | None
|
If not specified, the returned value is a |
None
|
Examples:
| Python Console Session | |
|---|---|
Source code in danling/tensors/nested_tensor.py
sum
¶
sum(
dim: int | Sequence[int] | None = None,
keepdim: bool = False,
*,
dtype: dtype | None = None
) -> Tensor | NestedTensor
Returns the sum of each tensor over the given dimension(s).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
int | Sequence[int] | None
|
The dimension or dimensions to reduce. If None, sum over all dimensions. Supports int, Sequence[int], or None. Negative dimensions are supported. |
None
|
|
bool
|
Whether to retain reduced dimensions with size 1. |
False
|
|
dtype | None
|
The desired data type of returned tensor. |
None
|
Returns:
| Type | Description |
|---|---|
Tensor | NestedTensor
|
Tensor or NestedTensor depending on the dimensions being reduced. |
Examples:
Source code in danling/tensors/nested_tensor.py
tolist
¶
tolist() -> list
Convert a NestedTensor to a list of lists of values.
Examples:
| Python Console Session | |
|---|---|
Source code in danling/tensors/nested_tensor.py
| Python | |
|---|---|
transpose
¶
Transpose dimensions dim0 and dim1 for each tensor in the NestedTensor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
int
|
First dimension to transpose (in NestedTensor coordinate system). |
required |
|
int
|
Second dimension to transpose (in NestedTensor coordinate system). |
required |
Returns:
| Name | Type | Description |
|---|---|---|
NestedTensor |
Self
|
A new NestedTensor with each tensor transposed. |
Examples:
Source code in danling/tensors/nested_tensor.py
swapaxes
¶
swapdims
¶
squeeze
¶
squeeze(dim: int | None = None) -> Self
Squeeze singleton dimensions from each tensor in the NestedTensor.
unsqueeze
¶
Unsqueeze each tensor in the NestedTensor by adding a singleton dimension at the specified position.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
int
|
The dimension at which to add the singleton dimension. This is in the NestedTensor’s coordinate system (where dim 0 is the batch dimension). |
required |
Returns:
| Name | Type | Description |
|---|---|---|
NestedTensor |
Self
|
A new NestedTensor with each tensor unsqueezed at the specified dimension. |
Examples:
Source code in danling/tensors/nested_tensor.py
unflatten
¶
unflatten(dim: int, sizes) -> Self
Unflatten one dimension of each tensor in the NestedTensor.
roll
¶
rot90
¶
Rotate each tensor in the NestedTensor by 90 degrees in the given plane.
view
¶
view(*shape) -> Self
View each tensor in the NestedTensor with a different shape.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
The desired size of each dimension for the underlying tensors. |
()
|
Returns:
| Name | Type | Description |
|---|---|---|
NestedTensor |
Self
|
A new NestedTensor with each tensor viewed with the new shape. |
Examples:
| Python Console Session | |
|---|---|
Source code in danling/tensors/nested_tensor.py
where
¶
where(
condition: Tensor | NestedTensor,
other: Tensor | NestedTensor | SupportsFloat,
) -> Self
Return a NestedTensor of elements selected from either self or other, depending on condition.
Examples:
Source code in danling/tensors/nested_tensor.py
PNTensor
¶
Bases: Tensor
A tensor wrapper that can be collated into NestedTensor with PyTorch DataLoader.
PNTensor (Potential Nested Tensor) seamlessly bridges the gap between individual tensors
and batched NestedTensor objects in PyTorch workflows. It’s designed specifically to work
with PyTorch’s DataLoader collation mechanism, allowing datasets to return variable-length
tensors that can be combined into a NestedTensor when batched.
The class provides three properties that mirror those of NestedTensor:
- .tensor: The tensor itself (self)
- .mask: A tensor of ones with the same shape as self
- .concat: The tensor itself (self)
Examples:
Basic usage with PyTorch DataLoader:
Using PNTensor directly:
| Python Console Session | |
|---|---|
Source code in danling/tensors/pn_tensor.py
| Python | |
|---|---|
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 | |
ensure_dir
¶
Bases: property
Ensure a directory property exists.
Examples:
| Python Console Session | |
|---|---|
Source code in danling/utils/descriptors.py
| Python | |
|---|---|
GlobalMetrics
¶
Data container for metrics descriptors.
The container aggregates required artifacts (preds/targets, confusion matrix, running stats) only once, synchronises them across processes, and lets descriptors compute metric values without duplicating work.
Source code in danling/metrics/global_metrics.py
| Python | |
|---|---|
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 | |
MultiTaskMetrics
¶
Bases: MultiTaskBase
Examples:
Notes
MultiTaskMetricsmanages a flat collection of task-level metric containers- All task containers are updated simultaneously with a single
update()call - Aggregation mode is configured at construction time via
aggregate=... aggregate="macro"gives equal task weight,aggregate="micro"weights by sample count, andaggregate="weighted"uses explicitaggregate_weights- Aggregate outputs are matched by exact relative metric path across tasks
- Provides a structured way to track metrics across different tasks or model components
See Also
GlobalMetrics: Exact metrics container that stores prediction and target history.StreamMetrics: Streaming metrics container for hot-path metric tracking.
Source code in danling/metrics/multitask.py
| Python | |
|---|---|
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 | |
update
¶
update(
values: Mapping[
str,
Mapping[str, Tensor | NestedTensor | Sequence]
| Sequence,
],
) -> None
Updates all task metric containers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Mapping[str, Mapping[str, Tensor | NestedTensor | Sequence] | Sequence]
|
Mapping from task names to update payloads.
Mapping payloads are forwarded as keyword arguments to the
child container’s |
required |
Source code in danling/metrics/multitask.py
to_device
¶
Move data to device.
Source code in danling/data/utils.py
tensor
¶
tensor(
data: Any,
dtype=None,
device=None,
requires_grad: bool = False,
pin_memory: bool = False,
) -> PNTensor
Create a PNTensor from data, similar to torch.tensor() but returning a PNTensor.
This function is a convenient way to create PNTensor objects that can be
collated into NestedTensor when used with PyTorch DataLoader after importing
danling.tensors. The interface mirrors torch.tensor() to make it easy to
switch between regular tensors and PNTensors.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Any
|
Initial data for the tensor. Can be a list, tuple, NumPy ndarray, scalar, etc. |
required |
|
Desired data type of the returned tensor. |
None
|
|
|
Device on which to place the tensor. |
None
|
|
|
bool
|
If autograd should record operations on the returned tensor. |
False
|
|
bool
|
If True, the tensor will be allocated in pinned memory. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
PNTensor |
PNTensor
|
A tensor wrapper for NestedTensor-oriented collation |
Examples:
| Python Console Session | |
|---|---|
Source code in danling/tensors/pn_tensor.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/context_managers.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.