DanLing¶
danling
¶
AverageMeter
¶
Computes and stores the average and current value.
Attributes:
Name | Type | Description |
---|---|---|
val |
Results of current batch on current device. |
|
bat |
Results of current batch on all devices. |
|
avg |
Results of all results on all devices. |
|
sum |
float
|
Sum of values. |
count |
float
|
Number of values. |
See Also
[MetricMeter
]: Average Meter with metric function built-in.
[AverageMeters
]: Manage multiple average meters in one object.
[MultiTaskAverageMeters
]: Manage multiple average meters in one object with multi-task support.
Examples:
>>> meter = AverageMeter()
>>> meter.update(0.7)
>>> meter.val
0.7
>>> meter.avg
0.7
>>> meter.update(0.9)
>>> meter.val
0.9
>>> meter.avg
0.8
>>> meter.sum
1.6
>>> meter.count
2
>>> meter.reset()
>>> meter.val
0.0
>>> meter.avg
nan
Source code in danling/metrics/average_meter.py
Python | |
---|---|
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 |
|
AverageMeters
¶
Bases: MetricsDict
Manages multiple average meters in one object.
See Also
[AverageMeter
]: Computes and stores the average and current value.
[MultiTaskAverageMeters
]: Manage multiple average meters in one object with multi-task support.
[MetricMeters
]: Manage multiple metric meters in one object.
Examples:
>>> meters = AverageMeters()
>>> meters.update({"loss": 0.6, "auroc": 0.7, "r2": 0.8})
>>> f"{meters:.4f}"
'loss: 0.6000 (0.6000)\tauroc: 0.7000 (0.7000)\tr2: 0.8000 (0.8000)'
>>> meters['loss'].update(value=0.9, n=1)
>>> f"{meters:.4f}"
'loss: 0.9000 (0.7500)\tauroc: 0.7000 (0.7000)\tr2: 0.8000 (0.8000)'
>>> meters.sum.dict()
{'loss': 1.5, 'auroc': 0.7, 'r2': 0.8}
>>> meters.count.dict()
{'loss': 2, 'auroc': 1, 'r2': 1}
>>> meters.reset()
>>> f"{meters:.4f}"
'loss: 0.0000 (nan)\tauroc: 0.0000 (nan)\tr2: 0.0000 (nan)'
Source code in danling/metrics/average_meter.py
update
¶
Updates the average and current value in all meters.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
int | float
|
Dict of values to be added to the average. |
{}
|
|
Number of values to be added. |
required |
Raises:
Type | Description |
---|---|
ValueError
|
If the value is not an instance of (int, float). |
Source code in danling/metrics/average_meter.py
MetricMeter
¶
Bases: AverageMeter
Computes metrics and averages them over time.
Attributes:
Name | Type | Description |
---|---|---|
metric |
Callable
|
Metric function for computing the value. |
ignored_index |
Optional[int]
|
Index to be ignored in the computation. |
val |
Optional[int]
|
Results of current batch on current device. |
bat |
Optional[int]
|
Results of current batch on all devices. |
avg |
Optional[int]
|
Results of all results on all devices. |
sum |
Optional[int]
|
Sum of values. |
count |
Optional[int]
|
Number of values. |
See Also
[AverageMeter
]: Average meter for computed values.
[MetricMeters
]: Manage multiple metric meters in one object.
Examples:
>>> from danling.metrics.functional import accuracy
>>> meter = MetricMeter(accuracy)
>>> meter.update([0.1, 0.8, 0.6, 0.2], [0, 1, 0, 0])
>>> meter.val
0.75
>>> meter.avg
0.75
>>> meter.update([0.1, 0.7, 0.3, 0.2, 0.8, 0.4], [0, 1, 1, 0, 0, 1])
>>> meter.val
0.5
>>> meter.avg
0.6
>>> meter.sum
6.0
>>> meter.count
10
>>> meter.reset()
>>> meter.val
0.0
>>> meter.avg
nan
Source code in danling/metrics/metric_meter.py
update
¶
Python | |
---|---|
|
Updates the average and current value in the meter.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
Value to be added to the average. |
required | |
|
Number of values to be added. |
required |
Source code in danling/metrics/metric_meter.py
MetricMeters
¶
Bases: AverageMeters
Manages multiple metric meters in one object.
Attributes:
Name | Type | Description |
---|---|---|
ignored_index |
Index to be ignored in the computation. Defaults to None. |
See Also
[MetricMeter
]: Computes metrics and averages them over time.
[AverageMeters
]: Average meters for computed values.
from danling.metrics.functional import accuracy, auroc, auprc meters = MetricMeters(acc=accuracy, auroc=auroc, auprc=auprc) meters.update([0.1, 0.8, 0.6, 0.2], [0, 1, 0, 0]) meters.sum.dict() {‘acc’: 3.0, ‘auroc’: 4.0, ‘auprc’: 4.0} meters.count.dict() {‘acc’: 4, ‘auroc’: 4, ‘auprc’: 4} meters[‘auroc’].update([0.2, 0.8], [0, 1]) meters.sum.dict() {‘acc’: 3.0, ‘auroc’: 6.0, ‘auprc’: 4.0} meters.count.dict() {‘acc’: 4, ‘auroc’: 6, ‘auprc’: 4} meters.update([[0.1, 0.7, 0.3, 0.2], [0.8, 0.4]], [[0, 0, 1, 0], [0, 0]]) meters.sum.dict() {‘acc’: 6.0, ‘auroc’: 8.4, ‘auprc’: 5.5} meters.count.dict() {‘acc’: 10, ‘auroc’: 12, ‘auprc’: 10} meters[‘auroc’].update([0.4, 0.8, 0.6, 0.2], [0, 1, 1, 0]) meters.avg.dict() {‘acc’: 0.6, ‘auroc’: 0.775, ‘auprc’: 0.55} meters.update(dict(loss=”“)) # doctest: +ELLIPSIS Traceback (most recent call last): TypeError: …update() missing 1 required positional argument: ‘target’
Source code in danling/metrics/metric_meter.py
Python | |
---|---|
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 |
|
update
¶
Python | |
---|---|
|
Updates the average and current value in all meters.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
Tensor | NestedTensor | Sequence
|
Input values to compute the metrics. |
required |
|
Tensor | NestedTensor | Sequence
|
Target values to compute the metrics. |
required |
Source code in danling/metrics/metric_meter.py
MultiTaskAverageMeters
¶
Bases: MultiTaskDict
Manages multiple average meters in one object with multi-task support.
See Also
[AverageMeter
]: Computes and stores the average and current value.
[AverageMeters
]: Manage multiple average meters in one object.
[MetricMeters
]: Manage multiple metric meters in one object.
Examples:
>>> meters = MultiTaskAverageMeters()
>>> meters.update({"loss": 0.6, "dataset1.cls.auroc": 0.7, "dataset1.reg.r2": 0.8, "dataset2.r2": 0.9})
>>> f"{meters:.4f}"
'loss: 0.6000 (0.6000)\ndataset1.cls.auroc: 0.7000 (0.7000)\ndataset1.reg.r2: 0.8000 (0.8000)\ndataset2.r2: 0.9000 (0.9000)'
>>> meters['loss'].update(0.9, n=1)
>>> f"{meters:.4f}"
'loss: 0.9000 (0.7500)\ndataset1.cls.auroc: 0.7000 (0.7000)\ndataset1.reg.r2: 0.8000 (0.8000)\ndataset2.r2: 0.9000 (0.9000)'
>>> meters.sum.dict()
{'loss': 1.5, 'dataset1': {'cls': {'auroc': 0.7}, 'reg': {'r2': 0.8}}, 'dataset2': {'r2': 0.9}}
>>> meters.count.dict()
{'loss': 2, 'dataset1': {'cls': {'auroc': 1}, 'reg': {'r2': 1}}, 'dataset2': {'r2': 1}}
>>> meters.reset()
>>> f"{meters:.4f}"
'loss: 0.0000 (nan)\ndataset1.cls.auroc: 0.0000 (nan)\ndataset1.reg.r2: 0.0000 (nan)\ndataset2.r2: 0.0000 (nan)'
>>> meters = MultiTaskAverageMeters(return_average=True)
>>> meters.update({"loss": 0.6, "dataset1.a.auroc": 0.7, "dataset1.b.auroc": 0.8, "dataset2.auroc": 0.9})
>>> f"{meters:.4f}"
'loss: 0.6000 (0.6000)\ndataset1.a.auroc: 0.7000 (0.7000)\ndataset1.b.auroc: 0.8000 (0.8000)\ndataset2.auroc: 0.9000 (0.9000)'
>>> meters.update({"loss": 0.9, "dataset1.a.auroc": 0.8, "dataset1.b.auroc": 0.9, "dataset2.auroc": 1.0})
>>> f"{meters:.4f}"
'loss: 0.9000 (0.7500)\ndataset1.a.auroc: 0.8000 (0.7500)\ndataset1.b.auroc: 0.9000 (0.8500)\ndataset2.auroc: 1.0000 (0.9500)'
Source code in danling/metrics/average_meter.py
Python | |
---|---|
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 |
|
update
¶
Updates the average and current value in all meters.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
float
|
Dict of values to be added to the average. |
{}
|
|
Number of values to be added. |
required |
Raises:
Type | Description |
---|---|
ValueError
|
If the value is not an instance of (int, float, Mapping). |
Source code in danling/metrics/average_meter.py
MultiTaskMetricMeters
¶
Bases: MultiTaskAverageMeters
Examples:
>>> from danling.metrics.functional import accuracy
>>> metrics = MultiTaskMetricMeters()
>>> metrics.dataset1.cls = MetricMeters(acc=accuracy)
>>> metrics.dataset2 = MetricMeters(acc=accuracy)
>>> metrics
MultiTaskMetricMeters(<class 'danling.metrics.metric_meter.MultiTaskMetricMeters'>,
('dataset1'): MultiTaskMetricMeters(<class 'danling.metrics.metric_meter.MultiTaskMetricMeters'>,
('cls'): MetricMeters('acc',)
)
('dataset2'): MetricMeters('acc',)
)
>>> metrics.update({"dataset1.cls": {"input": [0.2, 0.4, 0.5, 0.7], "target": [0, 1, 0, 1]}, "dataset2": ([0.1, 0.4, 0.6, 0.8], [1, 0, 0, 0])})
>>> f"{metrics:.4f}"
'dataset1.cls: acc: 0.5000 (0.5000)\ndataset2: acc: 0.2500 (0.2500)'
>>> metrics.setattr("return_average", True)
>>> metrics.update({"dataset1.cls": [[0.1, 0.4, 0.6, 0.8], [0, 0, 1, 0]], "dataset2": {"input": [0.2, 0.3, 0.5, 0.7], "target": [0, 0, 0, 1]}})
>>> f"{metrics:.4f}"
'dataset1.cls: acc: 0.7500 (0.6250)\ndataset2: acc: 0.7500 (0.5000)'
>>> metrics.update(dict(loss=""))
Traceback (most recent call last):
ValueError: Metric loss not found in ...
Source code in danling/metrics/metric_meter.py
Python | |
---|---|
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 |
|
update
¶
Python | |
---|---|
|
Updates the average and current value in all meters.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
Input values to compute the metrics. |
required | |
|
Target values to compute the metrics. |
required |
Source code in danling/metrics/metric_meter.py
LRScheduler
¶
Bases: _LRScheduler
General learning rate scheduler.
PyTorch LRScheduler is hard to extend. This class is a wrapper of PyTorch LRScheduler, which provides a more general interface. You only needs to add a new method which calculates a learning rate ratio (range from 0 to 1) with total progress (range from 0 to 1), and everything else will be done automatically.
Moreover, this class has warmup and cooldown built-in.
By default, the first 5% and last 20% of training steps will be warmup and cooldown respectively.
You can alternate by passing warmup_steps
and cooldown_steps
, or disable them by setting them to 0.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
Optimizer
|
Wrapped optimizer. |
required |
|
int
|
Total number of trainable steps. |
required |
|
Optional[float]
|
Final learning rate ratio to initial learning rate. Defaults to 1e-3. |
None
|
|
Optional[float]
|
Final learning rate. |
None
|
|
float
|
Minimal learning rate. Defaults to 1e-9. |
1e-09
|
|
str
|
Scaling strategy. Defaults to “cosine”. |
'cosine'
|
|
Optional[int]
|
Number of warmup steps.
Defaults to |
None
|
|
Optional[int]
|
Number of cooldown steps.
Defaults to |
None
|
|
int
|
The index of last epoch. Defaults to -1. |
-1
|
|
Optional[str]
|
Method to calculate learning rate given ratio, should be one of “percentile” or “numerical”.
Defaults to “percentile” if |
None
|
Examples:
>>> from danling.optim import LRScheduler
>>> import torch
>>> from torch import optim
>>> optimizer = optim.SGD([{'params': torch.tensor([0])}], lr=1, momentum=0.9)
>>> scheduler = LRScheduler(optimizer, total_steps=5, final_lr_ratio=1e-5, strategy='linear')
>>> lrs = []
>>> for epoch in range(5):
... lrs.append(scheduler.get_lr()[0])
... scheduler.step()
>>> [round(lr, 10) for lr in lrs]
[0.1, 0.01, 0.001, 0.0001, 1e-09]
>>> scheduler = LRScheduler(optimizer, total_steps=5, final_lr_ratio=1e-5, strategy='cosine')
>>> lrs = []
>>> for epoch in range(5):
... lrs.append(scheduler.get_lr()[0])
... scheduler.step()
>>> [round(lr, 10) for lr in lrs]
[0.3330753446, 0.0187302031, 0.000533897, 3.00232e-05, 1e-09]
>>> scheduler = LRScheduler(optimizer, total_steps=5, final_lr_ratio=1e-5, strategy='linear', method='numerical')
>>> lrs = []
>>> for epoch in range(5):
... lrs.append(scheduler.get_lr()[0])
... scheduler.step()
>>> [round(lr, 2) for lr in lrs]
[0.8, 0.6, 0.4, 0.2, 0.0]
Source code in danling/optim/lr_scheduler/lr_scheduler.py
Python | |
---|---|
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 |
|
AccelerateRunner
¶
Bases: TorchRunner
, Accelerator
Set up everything for running a job.
AccelerateRunner
uses [accelerate
][accelerate] as distributed backend to
provide seamless distributed training experience.
AccelerateRunner
will automatically prepare
everything,
including model
, criterion
, optimizer
, scheduler
, and dataloaders
for distribute training,
mixed precision, and deepspeed (optional).
In fact, you don’t even need to create dataloaders
, just define
datasets
and AccelerateRunner
will create dataloaders
for you.
AccelerateRunner
will inspect the train
flag in corresponding dataset to
set shuffle
and drop_last
automatically.
Source code in danling/runner/accelerate_runner.py
Python | |
---|---|
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 |
|
advance
¶
Python | |
---|---|
Backward loss and step optimizer & scheduler.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
Whether to zero the gradients. |
required |
Source code in danling/runner/accelerate_runner.py
BaseRunner
¶
Base class for all runners.
BaseRunner
sets up basic running environment, including seed
, deterministic
, and logging
.
BaseRunner
also provides some basic methods, such as, step
, state_dict
, save_checkpoint
, load_checkpoint
.
BaseRunner
defines all basic attributes and relevant properties such as scores
, progress
, etc.
ID:
Name | Type | Description |
---|---|---|
timestamp |
str
|
A time string representing the creation time of run. |
name |
str
|
|
id |
str
|
|
uuid |
(UUID, property)
|
|
Core:
Name | Type | Description |
---|---|---|
mode |
(RunnerMode, property)
|
Running mode. |
config |
Config
|
Running config. See [ |
Model:
Name | Type | Description |
---|---|---|
model |
Callable
|
|
criterion |
Callable
|
|
optimizer |
Any | None
|
|
scheduler |
Any | None
|
|
Data:
Name | Type | Description |
---|---|---|
datasets |
FlatDict
|
All datasets, should be in the form of |
datasamplers |
FlatDict
|
All datasamplers, should be in the form of |
dataloaders |
FlatDict
|
All dataloaders, should be in the form of |
split |
str
|
Current running split. |
batch_size |
(int, property)
|
Number of samples per batch in current running split. |
batch_size_equivalent |
(int, property)
|
Total batch_size ( |
datasets
, datasamplers
, dataloaders
should be a dict with the same keys.
Their keys should be split
(e.g. train
, val
, test
).
Progress:
Name | Type | Description |
---|---|---|
progress |
(float, property)
|
Running Progress, in |
Results:
Name | Type | Description |
---|---|---|
results |
NestedDict
|
Results include all metric information of the model.
Results should be in the form of |
latest_result |
(NestedDict, property)
|
Most recent result, should be in the form of |
best_result |
(NestedDict, property)
|
Best result, should be in the form of |
scores |
(List[float], property)
|
Score is the core metric that is used to evaluate the performance of the model.
Scores should be in the form of |
latest_score |
(float, property)
|
Most recent score, should be in the form of |
best_score |
(float, property)
|
Best score, should be in the form of |
score_split |
Optional[str]
|
The subset to calculate the score.
If is |
score_name |
str
|
The metric name of score.
Defaults to |
is_best |
(bool, property)
|
If |
A result
is a dict with the same split
as keys, like dataloaders
.
A typical result
shall look like this:
Python | |
---|---|
scores
are dynamically extracted from results
by score_split
and score_name
.
They represent the core metric that is used in comparing the performance against different models and settings.
For the above results
, If score_split = "val"
, score_name = "accuracy"
, then scores = 0.9
.
IO:
Name | Type | Description |
---|---|---|
dir |
(str, property)
|
Directory of the run.
Defaults to |
checkpoint_dir |
(str, property)
|
Directory of checkpoints. |
log_path |
(str, property)
|
Path of log file. |
checkpoint_dir_name |
str
|
The name of the directory under |
Parallel Training:
Name | Type | Description |
---|---|---|
world_size |
(int, property)
|
Number of processes. |
rank |
(int, property)
|
Process index of all processes. |
local_rank |
(int, property)
|
Process index of local processes. |
distributed |
(bool, property)
|
If runner is running in distributed mode. |
is_main_process |
(bool, property)
|
If current process is the main process of all processes. |
is_local_main_process |
(bool, property)
|
If current process is the main process of local processes. |
logging:
Name | Type | Description |
---|---|---|
meters |
AverageMeters | MultiTaskAverageMeters
|
Average meters.
Initialised to |
metrics |
Metrics | MultiTaskMetrics | MetricMeters | None
|
Metrics for evaluating. |
logger |
Logger | None
|
|
writer |
Any | None
|
|
See Also
Config
: The runeer base that stores runtime information.
BaseRunner
: The base runner class.
Source code in danling/runner/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 |
|
batch_size
property
¶
Batch size.
Notes
If train
is in dataloaders
, then batch_size
is the batch size of train
.
Otherwise, batch_size
is the batch size of the first dataloader.
Returns:
Type | Description |
---|---|
int
|
|
batch_size_equivalent
property
¶
accum_steps
cached
property
¶
progress
property
¶
Training Progress.
Returns:
Type | Description |
---|---|
float
|
|
Raises:
Type | Description |
---|---|
RuntimeError
|
If no terminal is defined. |
is_main_process
property
¶
If current process is the main process of all processes.
is_local_main_process
property
¶
If current process is the main process of local processes.
best_fn
property
¶
Function to determine the best score from a list of scores.
By default, the best_fn
returns min
if self.config.score_name
is loss
,
otherwise, returns max
.
Subclass can override this method to accommodate needs, such as min
.
Returns:
Type | Description |
---|---|
callable
|
|
best_index
property
¶
scores
property
¶
All scores.
Scores are extracted from results by score_split
and runner.config.score_name
,
following [r[score_split][self.config.score_name] for r in self.results]
.
Scores are considered as the index of the performance of the model. It is useful to determine the best model and the best hyper-parameters.
score_split
is defined in self.config.score_split
.
If it is not set, DanLing
will use val
or validate
if they appear in the latest_result
.
If DanLing
still could not find, it will fall back to the second key in the latest_result
if it contains more that one element, or the first key.
Note that certain keys are ignored when falling back, they are defined in {IGNORED_SET_NAMES}.
init_distributed
¶
Python | |
---|---|
init_logging
¶
Python | |
---|---|
Set up logging.
Source code in danling/runner/base_runner.py
init_print
¶
Set up print
.
Only print on a specific process
or when force = True
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
int
|
The process to |
0
|
Notes¶
If self.config.log = True
, the default print
function will be override by logging.info
.
Source code in danling/runner/base_runner.py
init_tensorboard
¶
Python | |
---|---|
set_seed
¶
Set up random seed.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
int
|
Random seed to set.
Defaults to |
None
|
|
int
|
Make the seed different for each processes. This avoids same data augmentation are applied on every processes. Defaults to Set to |
None
|
Source code in danling/runner/base_runner.py
set_deterministic
¶
Python | |
---|---|
scale_lr
¶
Python | |
---|---|
Scale learning rate according to linear scaling rule.
Source code in danling/runner/base_runner.py
update
¶
Backward loss and step optimizer & scheduler.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
loss. |
required |
state_dict
¶
dict
¶
save
¶
Save any file with supported extensions.
Runner.save
internally calls dl.save
,
but with additional arguments to allow it save only on the main process.
Moreover, any error raised by Runner.save
will be caught and logged.
Source code in danling/runner/base_runner.py
load
staticmethod
¶
Load any file with supported extensions.
Runner.load
is identical to dl.load
.
json
¶
Dump Runner config to json file.
Source code in danling/runner/base_runner.py
Python | |
---|---|
from_json
classmethod
¶
Python | |
---|---|
|
Construct Runner from json file.
This function calls self.from_jsons()
to construct object from json string.
You may overwrite from_jsons
in case something is not json serializable.
Source code in danling/runner/base_runner.py
jsons
¶
from_jsons
classmethod
¶
Python | |
---|---|
|
yaml
¶
Dump Runner config to yaml file.
Source code in danling/runner/base_runner.py
Python | |
---|---|
from_yaml
classmethod
¶
Python | |
---|---|
|
Construct Runner from yaml file.
This function calls self.from_yamls()
to construct object from yaml string.
You may overwrite from_yamls
in case something is not yaml serializable.
Source code in danling/runner/base_runner.py
yamls
¶
from_yamls
classmethod
¶
Python | |
---|---|
|
check_dir
¶
Check if self.dir
is not empty.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
str
|
The action to perform if |
'warn'
|
Source code in danling/runner/base_runner.py
save_checkpoint
¶
Save checkpoint to self.checkpoint_dir
.
The checkpoint will be saved to self.checkpoint_dir/latest.pth
.
If self.config.save_interval
is positive and self.config.epoch + 1
is a multiple of save_interval
,
the checkpoint will also be copied to self.checkpoint_dir/epoch-{self.config.epoch}.pth
.
If self.is_best
is True
, the checkpoint will also be copied to self.checkpoint_dir/best.pth
.
Source code in danling/runner/base_runner.py
load_checkpoint
¶
Python | |
---|---|
|
Load info from checkpoint.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
Mapping | bytes | str | PathLike | None
|
Checkpoint (or its path) to load.
Defaults to |
None
|
|
bool | None
|
Automatically resume from latest checkpoint if exists.
Defaults to |
None
|
|
bool
|
If True, override runner config with checkpoint config.
Defaults to |
False
|
|
Additional arguments to pass to |
()
|
|
|
Additional keyword arguments to pass to |
{}
|
Raises:
Type | Description |
---|---|
FileNotFoundError
|
If |
See Also
from_checkpoint
: Build runner from checkpoint.
load_pretrained
: Load parameters from pretrained checkpoint.
Source code in danling/runner/base_runner.py
from_checkpoint
classmethod
¶
Python | |
---|---|
|
Build BaseRunner from checkpoint.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
Mapping | bytes | str | PathLike
|
Checkpoint (or its path) to load. |
required |
|
Additional arguments to pass to |
()
|
|
|
Additional keyword arguments to pass to |
{}
|
Returns:
Type | Description |
---|---|
BaseRunner
|
|
Source code in danling/runner/base_runner.py
load_pretrained
¶
Python | |
---|---|
Load parameters from pretrained checkpoint.
This method only loads the model weights.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
Mapping | bytes | str | PathLike | None
|
Pretrained checkpoint (or its path) to load.
Defaults to |
None
|
|
Additional arguments to pass to |
()
|
|
|
Additional keyword arguments to pass to |
{}
|
Raises:
Type | Description |
---|---|
FileNotFoundError
|
If |
See Also
load_checkpoint
: Load info from checkpoint.
Source code in danling/runner/base_runner.py
Python | |
---|---|