Tuning¶
Search strategies for choosing hyperparameters, from random sampling through model-based search to the multi-fidelity methods that spend their budget unevenly on purpose.
One entry point per method, plus a dispatcher that takes a method name. The
per-method functions take that method's own search-space format and return its
own result type; the dispatcher takes the framework's and returns an
ExperimentResult.
dlhub.tuning ¶
Hyperparameter Tuning¶
Search strategies for choosing hyperparameters, from random sampling through model-based search to the multi-fidelity methods that spend their budget unevenly on purpose.
License
MIT
BayesianOptimizationResult
dataclass
¶
Container for Bayesian optimization results.
Attributes:
| Name | Type | Description |
|---|---|---|
best_params |
dict
|
Best hyperparameter configuration found |
best_score |
float
|
Best objective function value achieved |
history |
list
|
History of all evaluations |
convergence_data |
dict
|
Convergence statistics and diagnostics |
Source code in src/dlhub/tuning/bayesian.py
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | |
BayesianOptimizer ¶
Bayesian Optimization using Gaussian Process surrogate models.
This implementation uses Expected Improvement as the acquisition function to balance exploration and exploitation in hyperparameter search.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
objective_function
|
callable
|
Function to optimize. Should take hyperparameter dict and return float |
required |
search_space
|
dict
|
Dictionary defining search space for each hyperparameter. Format: {'param_name': (min_val, max_val)} for continuous parameters |
required |
acquisition
|
str
|
Acquisition function ('ei' for Expected Improvement, 'ucb' for UCB) |
'ei'
|
kappa
|
float
|
Exploration parameter for UCB (ignored if acquisition='ei') |
2.576
|
xi
|
float
|
Exploration parameter for Expected Improvement |
0.01
|
n_initial
|
int
|
Number of random initial evaluations |
5
|
random_state
|
int
|
Random seed for reproducibility |
None
|
Source code in src/dlhub/tuning/bayesian.py
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 | |
optimize ¶
optimize(n_iterations: int = 20, verbose: int = 1) -> BayesianOptimizationResult
Run Bayesian optimization.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_iterations
|
int
|
Maximum number of optimization iterations |
20
|
verbose
|
int
|
Reporting level: 0 is silent, 1 prints phases and new bests, 2 adds every evaluation and the final configuration. |
1
|
Returns:
| Type | Description |
|---|---|
BayesianOptimizationResult
|
Optimization results including best parameters and history |
Source code in src/dlhub/tuning/bayesian.py
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 | |
GaussianProcess ¶
Simplified Gaussian Process for Bayesian Optimization.
Implements a GP with RBF kernel for modeling the objective function. This is a educational implementation - production code should use more robust libraries like GPy or scikit-learn.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
kernel_lengthscale
|
float
|
Length scale parameter for RBF kernel |
1.0
|
kernel_variance
|
float
|
Variance parameter for RBF kernel |
1.0
|
noise_variance
|
float
|
Noise variance for numerical stability |
1e-6
|
Source code in src/dlhub/tuning/bayesian.py
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 | |
rbf_kernel ¶
rbf_kernel(X1: ndarray, X2: ndarray) -> np.ndarray
Compute RBF (Radial Basis Function) kernel matrix.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X1
|
(ndarray, shape(n1, d))
|
First set of input points |
required |
X2
|
(ndarray, shape(n2, d))
|
Second set of input points |
required |
Returns:
| Type | Description |
|---|---|
(ndarray, shape(n1, n2))
|
Kernel matrix K(X1, X2) |
Source code in src/dlhub/tuning/bayesian.py
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 | |
fit ¶
fit(X: ndarray, y: ndarray) -> None
Fit the Gaussian Process to training data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
(ndarray, shape(n_samples, n_features))
|
Training input points |
required |
y
|
(ndarray, shape(n_samples))
|
Training target values |
required |
Source code in src/dlhub/tuning/bayesian.py
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 | |
predict ¶
predict(X: ndarray) -> tuple[np.ndarray, np.ndarray]
Make predictions with uncertainty estimates.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
(ndarray, shape(n_test, n_features))
|
Test input points |
required |
Returns:
| Name | Type | Description |
|---|---|---|
mean |
(ndarray, shape(n_test))
|
Predicted mean values |
std |
(ndarray, shape(n_test))
|
Predicted standard deviations |
Source code in src/dlhub/tuning/bayesian.py
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 | |
ExperimentConfig
dataclass
¶
Configuration for hyperparameter optimization experiment.
Attributes:
| Name | Type | Description |
|---|---|---|
experiment_name |
str
|
Name of the experiment |
optimization_method |
OptimizationMethod
|
Optimization strategy to use |
hyperparameters |
list
|
List of HyperparameterConfig objects |
objective_metric |
str
|
Name of metric to optimize |
maximize |
bool, default=True
|
Whether to maximize the objective metric |
n_trials |
int, default=100
|
Number of trials to run |
random_seed |
int(optional)
|
Random seed for reproducibility |
save_dir |
str(optional)
|
Directory to save results |
additional_config |
dict(optional)
|
Additional method-specific configuration |
Source code in src/dlhub/tuning/framework.py
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 | |
ExperimentLogger ¶
Logger for experiment results and metadata.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
save_dir
|
str(optional)
|
Directory to save logs |
required |
experiment_name
|
str
|
Name of the experiment |
required |
Source code in src/dlhub/tuning/framework.py
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 | |
log_trial ¶
log_trial(trial_result: TrialResult) -> None
Log a trial result.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
trial_result
|
TrialResult
|
Trial result to log |
required |
Source code in src/dlhub/tuning/framework.py
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 | |
save_results ¶
save_results(result: ExperimentResult) -> None
Save complete optimization results.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
result
|
ExperimentResult
|
Optimization results to save |
required |
Source code in src/dlhub/tuning/framework.py
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 | |
load_results ¶
load_results() -> list[TrialResult] | None
Load trial results from log file.
Returns:
| Type | Description |
|---|---|
list or None
|
List of TrialResult objects, or None if no log exists |
Source code in src/dlhub/tuning/framework.py
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 | |
ExperimentResult
dataclass
¶
The outcome of one hyperparameter search: every trial, and the best of them.
Named for the :class:ExperimentConfig it answers. Not to be confused with
:class:dlhub.optimizers.OptimizationRun, which traces a single descent.
Attributes:
| Name | Type | Description |
|---|---|---|
experiment_config |
ExperimentConfig
|
Configuration used for the experiment |
best_trial |
TrialResult
|
Best performing trial |
all_trials |
list
|
All trial results |
total_time |
float
|
Total optimization time |
summary_statistics |
dict
|
Summary statistics and analysis |
Source code in src/dlhub/tuning/framework.py
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 | |
FunctionObjective ¶
Bases: ObjectiveFunction
Wrapper for function-based objectives.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
eval_function
|
callable
|
Function that takes hyperparams and returns metrics dict |
required |
metric_names
|
list
|
Names of metrics returned by eval_function |
required |
Source code in src/dlhub/tuning/framework.py
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 | |
evaluate ¶
evaluate(hyperparams: dict[str, Any]) -> dict[str, float]
Evaluate using wrapped function.
Source code in src/dlhub/tuning/framework.py
234 235 236 | |
get_metric_names ¶
get_metric_names() -> list[str]
Get metric names.
Source code in src/dlhub/tuning/framework.py
238 239 240 | |
HyperparameterConfig
dataclass
¶
Configuration for a single hyperparameter.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
Parameter name |
type |
str
|
Parameter type ('continuous', 'integer', 'categorical') |
range |
tuple or list
|
Valid range or choices for the parameter |
scale |
str, default='linear'
|
Scale for sampling ('linear', 'log') |
default |
Any(optional)
|
Default value for said parameter |
Source code in src/dlhub/tuning/framework.py
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 | |
HyperparameterOptimizer ¶
Main hyperparameter optimization framework.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
ExperimentConfig
|
Experiment configuration |
required |
objective
|
ObjectiveFunction
|
Objective function to optimize |
required |
Source code in src/dlhub/tuning/framework.py
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 | |
optimize ¶
optimize(verbose: bool = True) -> ExperimentResult
Run hyperparameter optimization.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
verbose
|
bool
|
Whether to print progress |
True
|
Returns:
| Type | Description |
|---|---|
ExperimentResult
|
Optimization results |
Source code in src/dlhub/tuning/framework.py
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 | |
HyperparameterSampler ¶
Utility class for sampling hyperparameters from configurations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hyperparameter_configs
|
list
|
List of HyperparameterConfig objects |
required |
random_state
|
int
|
Random seed for reproducibility |
None
|
Source code in src/dlhub/tuning/framework.py
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 | |
sample ¶
sample() -> dict[str, Any]
Sample a hyperparameter configuration.
Returns:
| Type | Description |
|---|---|
dict
|
Sampled hyperparameter configuration |
Source code in src/dlhub/tuning/framework.py
264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 | |
validate ¶
validate(hyperparams: dict[str, Any]) -> bool
Validate a hyperparameter configuration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hyperparams
|
dict
|
Hyperparameter configuration to validate |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if configuration is valid |
Source code in src/dlhub/tuning/framework.py
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 | |
ObjectiveFunction ¶
Bases: ABC
Abstract base class for objective functions.
Defines the interface that objective functions must implement.
Source code in src/dlhub/tuning/framework.py
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 | |
evaluate
abstractmethod
¶
evaluate(hyperparams: dict[str, Any]) -> dict[str, float]
Evaluate hyperparameters and return metrics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hyperparams
|
dict
|
Hyperparameter configuration |
required |
Returns:
| Type | Description |
|---|---|
dict
|
Dictionary of metric names to values |
Source code in src/dlhub/tuning/framework.py
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 | |
get_metric_names
abstractmethod
¶
get_metric_names() -> list[str]
Get names of all metrics returned by evaluate.
Returns:
| Type | Description |
|---|---|
list
|
List of metric names |
Source code in src/dlhub/tuning/framework.py
203 204 205 206 207 208 209 210 211 212 213 | |
OptimizationMethod ¶
Bases: Enum
Enumeration of available optimization methods.
Source code in src/dlhub/tuning/framework.py
47 48 49 50 51 52 53 54 | |
TrialResult
dataclass
¶
Result from a single trial.
Attributes:
| Name | Type | Description |
|---|---|---|
trial_id |
int
|
Unique trial identifier |
hyperparams |
dict
|
Hyperparameter configuration used |
metrics |
dict
|
All metrics recorded |
training_time |
float
|
Time taken for training |
status |
str
|
Trial status ('success', 'failed', 'cancelled') |
metadata |
dict
|
Additional trial information |
Source code in src/dlhub/tuning/framework.py
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 | |
BaseTrainer ¶
Bases: ABC
Abstract base class for training interface.
Defines the interface that training functions must implement to work with the learning rate finder.
Source code in src/dlhub/tuning/learning_rate_finder.py
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 | |
train_batch
abstractmethod
¶
train_batch(learning_rate: float) -> float
Train one batch with given learning rate and return loss.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
learning_rate
|
float
|
Learning rate to use for this batch |
required |
Returns:
| Type | Description |
|---|---|
float
|
Loss value after training step |
Source code in src/dlhub/tuning/learning_rate_finder.py
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 | |
reset_model
abstractmethod
¶
reset_model() -> None
Reset model to initial state.
Source code in src/dlhub/tuning/learning_rate_finder.py
97 98 99 100 | |
FunctionTrainer ¶
Bases: BaseTrainer
Trainer wrapper for function-based training.
Wraps user-provided training and reset functions to conform to the BaseTrainer interface.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
train_function
|
callable
|
Function that takes learning_rate and returns loss |
required |
reset_function
|
callable
|
Function to reset model state |
required |
Source code in src/dlhub/tuning/learning_rate_finder.py
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 | |
train_batch ¶
train_batch(learning_rate: float) -> float
Train one batch with given learning rate.
Source code in src/dlhub/tuning/learning_rate_finder.py
126 127 128 | |
reset_model ¶
reset_model() -> None
Reset model to initial state.
Source code in src/dlhub/tuning/learning_rate_finder.py
130 131 132 | |
LearningRateFinder ¶
Learning Rate Finder for optimal learning rate discovery.
Implements the learning rate range test by training with exponentially increasing learning rates and analyzing the loss curve to suggest optimal learning rate ranges.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
trainer
|
BaseTrainer
|
Training interface object |
required |
min_lr
|
float
|
Minimum learning rate to test |
1e-7
|
max_lr
|
float
|
Maximum learning rate to test |
10.0
|
num_iterations
|
int
|
Number of iterations to run the test |
100
|
step_mode
|
str
|
How to step learning rate ('exp' for exponential, 'linear' for linear) |
'exp'
|
smooth_beta
|
float
|
Smoothing factor for loss smoothing (exponential moving average) |
0.98
|
divergence_threshold
|
float
|
Stop if loss > divergence_threshold * min_loss |
4.0
|
Source code in src/dlhub/tuning/learning_rate_finder.py
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 | |
find ¶
find(verbose: bool = True) -> LearningRateFinderResult
Run learning rate finder.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
verbose
|
bool
|
Whether to print progress information |
True
|
Returns:
| Type | Description |
|---|---|
LearningRateFinderResult
|
Results of the learning rate finder |
Source code in src/dlhub/tuning/learning_rate_finder.py
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 | |
plot_results ¶
plot_results(result: LearningRateFinderResult, figsize: tuple[int, int] = (12, 8), save_path: str | None = None) -> None
Plot learning rate finder results.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
result
|
LearningRateFinderResult
|
Results from learning rate finder |
required |
figsize
|
tuple
|
Figure size for the plot |
(12, 8)
|
save_path
|
str
|
Path to save the plot |
None
|
Source code in src/dlhub/tuning/learning_rate_finder.py
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 | |
LearningRateFinderResult
dataclass
¶
Container for learning rate finder results.
Attributes:
| Name | Type | Description |
|---|---|---|
learning_rates |
ndarray
|
Array of learning rates tested |
losses |
ndarray
|
Corresponding loss values |
smoothed_losses |
ndarray
|
Smoothed loss values for trend analysis |
suggested_lr |
float
|
Suggested learning rate based on analysis |
min_gradient_lr |
float
|
Learning rate with steepest loss decrease |
analysis |
dict
|
Additional analysis metrics and diagnostics |
Source code in src/dlhub/tuning/learning_rate_finder.py
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 | |
ASHAOptimizer ¶
Asynchronous Successive Halving Algorithm (ASHA) for multi-fidelity optimization.
ASHA efficiently allocates computational resources by starting many configurations at low fidelity and promoting the most promising ones to higher fidelities.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
evaluator
|
FidelityEvaluator
|
Evaluator for hyperparameter configurations |
required |
reduction_factor
|
int
|
Factor by which to reduce number of configurations at each rung |
3
|
min_budget
|
int
|
Minimum budget (fidelity) to start configurations |
1
|
max_budget
|
int
|
Maximum budget (fidelity) for full evaluation |
81
|
grace_period
|
int
|
Minimum budget before first promotion opportunity |
1
|
max_concurrent
|
int
|
Maximum number of concurrent evaluations |
4
|
random_state
|
int
|
Random seed for reproducibility |
None
|
Source code in src/dlhub/tuning/multifidelity.py
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 | |
suggest_initial_configurations ¶
suggest_initial_configurations(configurations: list[dict[str, Any]]) -> None
Add initial configurations to start evaluation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
configurations
|
list
|
List of hyperparameter configurations to evaluate |
required |
Source code in src/dlhub/tuning/multifidelity.py
419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 | |
optimize ¶
optimize(initial_configurations: list[dict[str, Any]], max_iterations: int = 100, timeout: float | None = None, verbose: bool = True) -> MultiFidelityResult
Run ASHA optimization.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
initial_configurations
|
list
|
Initial hyperparameter configurations to evaluate. Must be non-empty. |
required |
max_iterations
|
int
|
Maximum number of evaluations to perform. Counted at submission, and
every submitted evaluation is recorded, so this bounds the results as
well as the work -- at any |
100
|
timeout
|
float
|
Maximum time in seconds (None for no timeout). Evaluations already running when the clock runs out are still awaited and recorded; the timeout stops new submissions, it does not cancel paid-for work. |
None
|
verbose
|
bool
|
Whether to print progress information |
True
|
Returns:
| Type | Description |
|---|---|
MultiFidelityResult
|
Optimization results. A run granted no budget -- |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in src/dlhub/tuning/multifidelity.py
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 | |
CandidateResult
dataclass
¶
Result from evaluating a hyperparameter candidate.
Attributes:
| Name | Type | Description |
|---|---|---|
config_id |
int
|
Unique identifier for the configuration |
hyperparams |
dict
|
Hyperparameter configuration |
fidelity |
int
|
Fidelity level used for evaluation |
score |
float
|
Performance score achieved |
training_time |
float
|
Time taken for training |
metadata |
dict
|
Additional metadata from training |
Source code in src/dlhub/tuning/multifidelity.py
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 | |
FidelityConfig
dataclass
¶
Configuration for a fidelity level.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
Name of the fidelity level |
budget |
int
|
Budget/resource allocation for this fidelity |
min_budget |
int
|
Minimum budget required for this fidelity |
max_budget |
int
|
Maximum budget for this fidelity |
Source code in src/dlhub/tuning/multifidelity.py
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | |
FidelityEvaluator ¶
Bases: ABC
Abstract base class for fidelity-aware evaluation.
Defines the interface for evaluating hyperparameter configurations at different fidelity levels.
Source code in src/dlhub/tuning/multifidelity.py
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 | |
evaluate
abstractmethod
¶
evaluate(hyperparams: dict[str, Any], fidelity: int) -> tuple[float, dict[str, Any]]
Evaluate hyperparameters at given fidelity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hyperparams
|
dict
|
Hyperparameter configuration |
required |
fidelity
|
int
|
Fidelity level (e.g., training epochs, data size) |
required |
Returns:
| Type | Description |
|---|---|
tuple
|
(score, metadata) where score is performance and metadata contains additional information from training |
Source code in src/dlhub/tuning/multifidelity.py
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 | |
get_fidelity_range
abstractmethod
¶
get_fidelity_range() -> tuple[int, int]
Get the valid fidelity range.
Returns:
| Type | Description |
|---|---|
tuple
|
(min_fidelity, max_fidelity) |
Source code in src/dlhub/tuning/multifidelity.py
176 177 178 179 180 181 182 183 184 185 186 | |
FunctionEvaluator ¶
Bases: FidelityEvaluator
Function-based evaluator wrapper.
Wraps a user-provided evaluation function to conform to the FidelityEvaluator interface.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
eval_function
|
callable
|
Function that takes (hyperparams, fidelity) and returns (score, metadata) |
required |
min_fidelity
|
int
|
Minimum fidelity level |
1
|
max_fidelity
|
int
|
Maximum fidelity level |
100
|
Source code in src/dlhub/tuning/multifidelity.py
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 | |
evaluate ¶
evaluate(hyperparams: dict[str, Any], fidelity: int) -> tuple[float, dict[str, Any]]
Evaluate using wrapped function.
Source code in src/dlhub/tuning/multifidelity.py
213 214 215 216 217 | |
get_fidelity_range ¶
get_fidelity_range() -> tuple[int, int]
Get fidelity range.
Source code in src/dlhub/tuning/multifidelity.py
219 220 221 | |
MultiFidelityResult
dataclass
¶
Results from multi-fidelity optimization.
Attributes:
| Name | Type | Description |
|---|---|---|
best_config |
dict or None
|
Best hyperparameter configuration found, or None if the run recorded no results at all (see Notes) |
best_score |
float or None
|
Best score achieved, or None for a run with no results |
best_fidelity |
int or None
|
Fidelity level of best result, or None for a run with no results |
all_results |
list
|
All evaluation results |
total_time |
float
|
Total optimization time |
total_budget_used |
int
|
Total computational budget consumed |
statistics |
dict
|
Optimization statistics and analysis, empty for a run with no results |
Notes
A run can legitimately record nothing: max_iterations=0 grants no budget,
and a timeout that has already elapsed stops the first submission. Both
return this dataclass with the three best_* fields set to None rather than
raising, so the three are optional together -- either all are None or none
are. all_results is empty and statistics is {} in exactly those runs,
so if result.best_config is None and if not result.all_results are
equivalent tests.
An empty initial_configurations is caller error rather than an empty run,
and ASHAOptimizer.optimize rejects it with a ValueError.
Source code in src/dlhub/tuning/multifidelity.py
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 | |
ChoicePerturbation ¶
Bases: HyperparameterDistribution
Perturbation for categorical hyperparameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
choices
|
list
|
List of possible values |
required |
change_probability
|
float
|
Probability of changing to a different value |
0.3
|
Source code in src/dlhub/tuning/population_based.py
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 | |
perturb ¶
perturb(value: Any) -> Any
Perturb categorical value.
Source code in src/dlhub/tuning/population_based.py
224 225 226 227 228 229 230 231 | |
resample ¶
resample() -> Any
Resample from choices.
Source code in src/dlhub/tuning/population_based.py
233 234 235 | |
FunctionWorker ¶
Bases: WorkerInterface
Function-based worker implementation.
Wraps user-provided training functions to conform to WorkerInterface.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
train_function
|
callable
|
Function that takes (hyperparams, steps) and returns (score, state) |
required |
save_function
|
callable
|
Function that returns current state |
required |
load_function
|
callable
|
Function that loads given state |
required |
reset_function
|
callable
|
Function that resets to initial state |
required |
Source code in src/dlhub/tuning/population_based.py
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 | |
train_step ¶
train_step(hyperparams: dict[str, Any], steps: int = 1) -> tuple[float, Any]
Train using wrapped function.
Source code in src/dlhub/tuning/population_based.py
327 328 329 330 331 | |
save_state ¶
save_state() -> Any
Save state using wrapped function.
Source code in src/dlhub/tuning/population_based.py
333 334 335 | |
load_state ¶
load_state(state: Any) -> None
Load state using wrapped function.
Source code in src/dlhub/tuning/population_based.py
337 338 339 | |
reset ¶
reset() -> None
Reset using wrapped function.
Source code in src/dlhub/tuning/population_based.py
341 342 343 | |
HyperparameterDistribution ¶
Bases: ABC
Abstract class for hyperparameter distributions used in exploration.
Source code in src/dlhub/tuning/population_based.py
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 | |
perturb
abstractmethod
¶
perturb(value: Any) -> Any
Perturb a hyperparameter value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
any
|
Current hyperparameter value |
required |
Returns:
| Type | Description |
|---|---|
any
|
Perturbed hyperparameter value |
Source code in src/dlhub/tuning/population_based.py
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 | |
resample
abstractmethod
¶
resample() -> Any
Resample a hyperparameter value from the distribution.
Returns:
| Type | Description |
|---|---|
any
|
New hyperparameter value |
Source code in src/dlhub/tuning/population_based.py
124 125 126 127 128 129 130 131 132 133 134 | |
LogUniformPerturbation ¶
Bases: HyperparameterDistribution
Log-uniform perturbation for hyperparameters that vary over orders of magnitude.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
factor_range
|
tuple
|
Range of multiplicative factors for perturbation |
(0.8, 1.2)
|
bounds
|
tuple
|
(min, max) bounds for the hyperparameter |
None
|
Source code in src/dlhub/tuning/population_based.py
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 | |
perturb ¶
perturb(value: float) -> float
Perturb value by random multiplicative factor.
Source code in src/dlhub/tuning/population_based.py
157 158 159 160 161 162 163 164 165 | |
resample ¶
resample() -> float
Resample from log-uniform distribution.
Source code in src/dlhub/tuning/population_based.py
167 168 169 170 171 | |
PBTResult
dataclass
¶
Results from Population-Based Training.
Attributes:
| Name | Type | Description |
|---|---|---|
best_worker |
WorkerState
|
Best performing worker at the end |
final_population |
list
|
Final state of all workers |
population_history |
list
|
History of population states over time |
total_training_time |
float
|
Total time spent training |
total_steps |
int
|
Total training steps across all workers |
statistics |
dict
|
Training statistics and analysis |
Source code in src/dlhub/tuning/population_based.py
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 | |
PopulationBasedTrainer ¶
Population-Based Training optimizer.
Manages a population of workers, periodically evaluating performance and updating hyperparameters through exploitation and exploration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
worker_factory
|
callable
|
Factory function that creates new WorkerInterface instances |
required |
initial_hyperparams
|
list
|
Initial hyperparameter configurations for population |
required |
hyperparam_distributions
|
dict
|
Mapping from hyperparameter names to HyperparameterDistribution objects |
required |
population_size
|
int
|
Size of the population |
10
|
eval_interval
|
int
|
Training steps between population evaluations |
100
|
exploit_fraction
|
float
|
Fraction of worst performers to replace |
0.2
|
explore_fraction
|
float
|
Fraction of hyperparameters to perturb during exploration |
0.2
|
truncation_selection
|
bool
|
Whether to use truncation selection (replace worst with best) |
True
|
random_state
|
int
|
Random seed for reproducibility |
None
|
Source code in src/dlhub/tuning/population_based.py
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 | |
train ¶
train(max_steps: int = 10000, max_generations: int = 100, timeout: float | None = None, verbose: bool = True) -> PBTResult
Run Population-Based Training.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_steps
|
int
|
Maximum total training steps |
10000
|
max_generations
|
int
|
Maximum number of generations |
100
|
timeout
|
float
|
Maximum training time in seconds |
None
|
verbose
|
bool
|
Whether to print progress information |
True
|
Returns:
| Type | Description |
|---|---|
PBTResult
|
Training results including best worker and population history |
Source code in src/dlhub/tuning/population_based.py
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 | |
UniformPerturbation ¶
Bases: HyperparameterDistribution
Uniform perturbation for continuous hyperparameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
noise_std
|
float
|
Standard deviation of Gaussian noise to add |
0.1
|
bounds
|
tuple
|
(min, max) bounds for the hyperparameter |
None
|
Source code in src/dlhub/tuning/population_based.py
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 | |
perturb ¶
perturb(value: float) -> float
Perturb value by adding Gaussian noise.
Source code in src/dlhub/tuning/population_based.py
192 193 194 195 196 197 198 199 | |
resample ¶
resample() -> float
Resample from uniform distribution.
Source code in src/dlhub/tuning/population_based.py
201 202 203 204 205 | |
WorkerInterface ¶
Bases: ABC
Abstract interface for training workers in PBT.
Defines the methods that workers must implement to participate in population-based training.
Source code in src/dlhub/tuning/population_based.py
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 | |
train_step
abstractmethod
¶
train_step(hyperparams: dict[str, Any], steps: int = 1) -> tuple[float, Any]
Train for specified number of steps.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hyperparams
|
dict
|
Current hyperparameter configuration |
required |
steps
|
int
|
Number of training steps to perform |
1
|
Returns:
| Type | Description |
|---|---|
tuple
|
(performance_score, model_state) |
Source code in src/dlhub/tuning/population_based.py
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 | |
save_state
abstractmethod
¶
save_state() -> Any
Save current model state.
Returns:
| Type | Description |
|---|---|
any
|
Serializable model state |
Source code in src/dlhub/tuning/population_based.py
267 268 269 270 271 272 273 274 275 276 277 | |
load_state
abstractmethod
¶
load_state(state: Any) -> None
Load model state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
any
|
Model state to load |
required |
Source code in src/dlhub/tuning/population_based.py
279 280 281 282 283 284 285 286 287 288 289 | |
reset
abstractmethod
¶
reset() -> None
Reset worker to initial state.
Source code in src/dlhub/tuning/population_based.py
291 292 293 294 | |
WorkerState
dataclass
¶
State of a single worker in the population.
Attributes:
| Name | Type | Description |
|---|---|---|
worker_id |
int
|
Unique identifier for the worker |
hyperparams |
dict
|
Current hyperparameter configuration |
performance_history |
list
|
History of performance scores |
training_step |
int
|
Current training step |
model_state |
any
|
Current model state (implementation dependent) |
metadata |
dict
|
Additional worker metadata |
Source code in src/dlhub/tuning/population_based.py
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 | |
ChoiceDistribution ¶
Bases: ParameterDistribution
Categorical distribution for discrete choices.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
choices
|
list
|
List of possible values to choose from |
required |
probabilities
|
list
|
Probability weights for each choice (uniform if None) |
None
|
Source code in src/dlhub/tuning/random_search.py
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 | |
sample ¶
sample() -> Any
Sample from categorical distribution.
Source code in src/dlhub/tuning/random_search.py
190 191 192 | |
IntegerDistribution ¶
Bases: ParameterDistribution
Discrete uniform distribution for integer parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
low
|
int
|
Lower bound (inclusive) |
required |
high
|
int
|
Upper bound (exclusive) |
required |
Source code in src/dlhub/tuning/random_search.py
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 | |
sample ¶
sample() -> int
Sample from discrete uniform distribution.
Source code in src/dlhub/tuning/random_search.py
159 160 161 | |
LogUniformDistribution ¶
Bases: ParameterDistribution
Log-uniform distribution for parameters that vary over orders of magnitude.
Particularly useful for learning rates, regularization parameters, etc.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
low
|
float
|
Lower bound (must be positive) |
required |
high
|
float
|
Upper bound (must be positive) |
required |
Source code in src/dlhub/tuning/random_search.py
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 | |
sample ¶
sample() -> float
Sample from log-uniform distribution.
Source code in src/dlhub/tuning/random_search.py
134 135 136 | |
ParameterDistribution ¶
Base class for hyperparameter distributions.
Defines the interface for sampling hyperparameters from different probability distributions.
Source code in src/dlhub/tuning/random_search.py
72 73 74 75 76 77 78 79 80 81 82 83 84 85 | |
sample ¶
sample() -> Any
Sample a value from the distribution.
Source code in src/dlhub/tuning/random_search.py
80 81 82 | |
PowerDistribution ¶
Bases: ParameterDistribution
Power law distribution for parameters with non-uniform preferences.
Useful when smaller values are preferred (common in regularization).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
low
|
float
|
Lower bound |
required |
high
|
float
|
Upper bound |
required |
power
|
float
|
Power parameter. Above 1 the mass concentrates near |
2.0
|
Source code in src/dlhub/tuning/random_search.py
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 | |
sample ¶
sample() -> float
Sample from power distribution.
Source code in src/dlhub/tuning/random_search.py
220 221 222 223 224 225 226 227 228 | |
RandomSearchOptimizer ¶
Random Search optimizer for hyperparameter tuning.
Implements efficient random sampling of hyperparameters with support for different probability distributions, parallel evaluation, and early stopping.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
objective_function
|
callable
|
Function to optimize. Should take hyperparameter dict and return float |
required |
search_space
|
dict
|
Dictionary mapping parameter names to ParameterDistribution objects |
required |
n_iter
|
int
|
Number of parameter configurations to sample and evaluate |
100
|
random_state
|
int(optional)
|
Random seed for reproducibility |
None
|
n_jobs
|
int
|
Number of parallel jobs (-1 for all available cores) |
1
|
early_stopping
|
bool
|
Whether to use early stopping based on improvement |
False
|
patience
|
int
|
Number of iterations without improvement before stopping |
10
|
Source code in src/dlhub/tuning/random_search.py
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 | |
sample_parameters ¶
sample_parameters() -> dict[str, Any]
Sample a single parameter configuration from the search space.
Returns:
| Type | Description |
|---|---|
dict
|
Sampled hyperparameter configuration |
Source code in src/dlhub/tuning/random_search.py
288 289 290 291 292 293 294 295 296 297 298 299 300 | |
sample_multiple_parameters ¶
sample_multiple_parameters(n_samples: int) -> list[dict[str, Any]]
Sample multiple parameter configurations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_samples
|
int
|
Number of configurations to sample |
required |
Returns:
| Type | Description |
|---|---|
list
|
List of parameter configurations |
Source code in src/dlhub/tuning/random_search.py
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 | |
optimize ¶
optimize(verbose: bool = True) -> RandomSearchResult
Run random search optimization.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
verbose
|
bool
|
Whether to print progress information |
True
|
Returns:
| Type | Description |
|---|---|
RandomSearchResult
|
Optimization results |
Source code in src/dlhub/tuning/random_search.py
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 | |
RandomSearchResult
dataclass
¶
Container for random search optimization results.
Attributes:
| Name | Type | Description |
|---|---|---|
best_params |
dict
|
Best hyperparameter configuration found |
best_score |
float
|
Best objective function value achieved |
all_params |
list
|
All parameter configurations evaluated |
all_scores |
list
|
All scores corresponding to parameter configurations |
search_time |
float
|
Total search time in seconds |
statistics |
dict
|
Search statistics and analysis |
Source code in src/dlhub/tuning/random_search.py
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 | |
UniformDistribution ¶
Bases: ParameterDistribution
Uniform distribution for continuous parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
low
|
float
|
Lower bound of the distribution |
required |
high
|
float
|
Upper bound of the distribution |
required |
Source code in src/dlhub/tuning/random_search.py
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 | |
sample ¶
sample() -> float
Sample from uniform distribution.
Source code in src/dlhub/tuning/random_search.py
105 106 107 | |
bayesian_optimize ¶
bayesian_optimize(objective_function: Callable[[dict], float], search_space: dict[str, tuple[float, float]], n_iterations: int = 20, n_initial: int = 5, acquisition: str = 'ei', random_state: int | None = None, verbose: int = 1) -> BayesianOptimizationResult
Run a Bayesian search over continuous bounds, returning its own result type.
The method-specific entry point, alongside :func:~dlhub.tuning.random_search
and :func:~dlhub.tuning.asha_optimize. To choose a method by name instead,
call :func:~dlhub.tuning.optimize_hyperparameters, which takes the
framework's richer search-space format and returns an ExperimentResult.
Takes a scalar objective and a {name: (low, high)} search space; every
dimension is continuous, since the Gaussian process interpolates over them.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
objective_function
|
callable
|
Function to optimize. Should accept hyperparameter dict and return float |
required |
search_space
|
dict
|
Search space definition: {'param_name': (min_val, max_val)} |
required |
n_iterations
|
int
|
Number of optimization iterations after initial random sampling |
20
|
n_initial
|
int
|
Number of random initial points |
5
|
acquisition
|
str
|
Acquisition function ('ei' or 'ucb') |
'ei'
|
random_state
|
int
|
Random seed for reproducibility |
None
|
verbose
|
int
|
Reporting level, as in :meth: |
1
|
Returns:
| Type | Description |
|---|---|
BayesianOptimizationResult
|
Optimization results |
Examples:
>>> def objective(params):
... # Simulate training a model and return validation accuracy
... lr, wd = params["learning_rate"], params["weight_decay"]
... # Dummy objective (replace with actual model training)
... return -((lr - 0.001) ** 2) - (wd - 0.0001) ** 2 + np.random.normal(0, 0.01)
>>>
>>> search_space = {"learning_rate": (1e-5, 1e-1), "weight_decay": (1e-6, 1e-2)}
>>>
>>> result = bayesian_optimize(
... objective, search_space, n_iterations=30, random_state=42
... )
>>> print(f"Best parameters: {result.best_params}")
Source code in src/dlhub/tuning/bayesian.py
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 | |
optimize_hyperparameters ¶
optimize_hyperparameters(objective_function: Callable[[dict], dict[str, float]], hyperparameters: list[dict[str, Any]], objective_metric: str, experiment_name: str = 'hyperparameter_optimization', optimization_method: str = 'random_search', n_trials: int = 100, maximize: bool = True, random_seed: int | None = None, save_dir: str | None = None, verbose: bool = True) -> ExperimentResult
Run a hyperparameter search by method name, returning an ExperimentResult.
The general dispatcher: optimization_method selects the strategy. It takes
the framework's search-space format, which carries a type per hyperparameter
and so covers categorical and integer dimensions as well as continuous ones.
The method-specific entry points -- :func:~dlhub.tuning.bayesian_optimize,
:func:~dlhub.tuning.random_search -- take their own formats and return their
own result types.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
objective_function
|
callable
|
Function that takes hyperparams dict and returns metrics dict |
required |
hyperparameters
|
list
|
List of hyperparameter definitions (dicts with 'name', 'type', 'range') |
required |
objective_metric
|
str
|
Name of metric to optimize |
required |
experiment_name
|
str
|
Name of the experiment |
"hyperparameter_optimization"
|
optimization_method
|
str
|
Optimization method ('random_search' or 'grid_search') |
"random_search"
|
n_trials
|
int
|
Number of trials |
100
|
maximize
|
bool
|
Whether to maximize objective |
True
|
random_seed
|
int(optional)
|
Random seed |
None
|
save_dir
|
str(optional)
|
Directory to save results |
None
|
verbose
|
bool
|
Whether to print progress |
True
|
Returns:
| Type | Description |
|---|---|
ExperimentResult
|
Optimization results |
Examples:
>>> def objective(hyperparams):
... lr = hyperparams["learning_rate"]
... wd = hyperparams["weight_decay"]
... accuracy = 0.9 - (lr - 0.001) ** 2 - (wd - 0.0001) ** 2
... return {"accuracy": accuracy, "loss": 1 - accuracy}
>>> hyperparams = [
... {
... "name": "learning_rate",
... "type": "continuous",
... "range": (1e-5, 1e-1),
... "scale": "log",
... },
... {
... "name": "weight_decay",
... "type": "continuous",
... "range": (1e-6, 1e-2),
... "scale": "log",
... },
... ]
>>> result = optimize_hyperparameters(
... objective, hyperparams, "accuracy", n_trials=50, random_seed=42
... )
Source code in src/dlhub/tuning/framework.py
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 | |
find_learning_rate ¶
find_learning_rate(train_function: Callable[[float], float], reset_function: Callable[[], None], min_lr: float = 1e-07, max_lr: float = 10.0, num_iterations: int = 100, step_mode: str = 'exp', smooth_beta: float = 0.98, verbose: bool = True, plot: bool = True) -> LearningRateFinderResult
Convenience function to find optimal learning rate.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
train_function
|
callable
|
Function that takes learning_rate (float) and returns loss (float) |
required |
reset_function
|
callable
|
Function to reset model to initial state |
required |
min_lr
|
float
|
Minimum learning rate to test |
1e-7
|
max_lr
|
float
|
Maximum learning rate to test |
10.0
|
num_iterations
|
int
|
Number of iterations for the test |
100
|
step_mode
|
str
|
Learning rate stepping mode ('exp' or 'linear') |
'exp'
|
smooth_beta
|
float
|
Smoothing factor for loss curves |
0.98
|
verbose
|
bool
|
Whether to print progress |
True
|
plot
|
bool
|
Whether to plot results |
True
|
Returns:
| Type | Description |
|---|---|
LearningRateFinderResult
|
Results including suggested learning rate |
Examples:
>>> # Example with simple quadratic loss
>>> def train_step(lr):
... # Simulate one training step
... current_w = getattr(train_step, "w", 1.0) # Get current weight
... target_w = 0.5 # Target weight
... loss = (current_w - target_w) ** 2
...
... # Gradient descent update
... gradient = 2 * (current_w - target_w)
... train_step.w = current_w - lr * gradient
...
... return loss + np.random.normal(0, 0.01) # Add noise
>>> def reset_model():
... train_step.w = 1.0 # Reset to initial weight
>>> result = find_learning_rate(
... train_step, reset_model, min_lr=1e-4, max_lr=1.0, num_iterations=50
... )
>>> print(f"Suggested learning rate: {result.suggested_lr}")
Source code in src/dlhub/tuning/learning_rate_finder.py
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 | |
suggest_learning_rate_schedule ¶
suggest_learning_rate_schedule(result: LearningRateFinderResult, schedule_type: str = 'onecycle') -> dict[str, Any]
Suggest learning rate schedule based on finder results.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
result
|
LearningRateFinderResult
|
Results from learning rate finder |
required |
schedule_type
|
str
|
Type of schedule to suggest ('onecycle', 'cyclic', 'cosine', 'step') |
'onecycle'
|
Returns:
| Type | Description |
|---|---|
dict
|
Suggested schedule parameters |
Source code in src/dlhub/tuning/learning_rate_finder.py
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 | |
analyze_fidelity_correlation ¶
analyze_fidelity_correlation(result: MultiFidelityResult) -> dict[str, float]
Analyze correlation between different fidelity levels.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
result
|
MultiFidelityResult
|
Results from multi-fidelity optimization |
required |
Returns:
| Type | Description |
|---|---|
dict
|
Correlation analysis between fidelity levels |
Source code in src/dlhub/tuning/multifidelity.py
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 | |
asha_optimize ¶
asha_optimize(eval_function: Callable[[dict, int], tuple[float, dict]], initial_configurations: list[dict[str, Any]], min_fidelity: int = 1, max_fidelity: int = 81, reduction_factor: int = 3, max_iterations: int = 100, max_concurrent: int = 4, timeout: float | None = None, random_state: int | None = None, verbose: bool = True) -> MultiFidelityResult
Convenience function for ASHA optimization.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
eval_function
|
callable
|
Function that takes (hyperparams, fidelity) and returns (score, metadata) |
required |
initial_configurations
|
list
|
Initial hyperparameter configurations to evaluate; must be non-empty |
required |
min_fidelity
|
int
|
Minimum fidelity level |
1
|
max_fidelity
|
int
|
Maximum fidelity level |
81
|
reduction_factor
|
int
|
ASHA reduction factor |
3
|
max_iterations
|
int
|
Maximum number of evaluations, performed and recorded alike |
100
|
max_concurrent
|
int
|
Maximum concurrent evaluations |
4
|
timeout
|
float
|
Timeout in seconds; evaluations already running are still awaited |
None
|
random_state
|
int
|
Random seed |
None
|
verbose
|
bool
|
Whether to print progress |
True
|
Returns:
| Type | Description |
|---|---|
MultiFidelityResult
|
Optimization results. The three |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
>>> def evaluate_model(hyperparams, fidelity):
... # Simulate training with given hyperparameters and fidelity
... lr = hyperparams["learning_rate"]
... wd = hyperparams["weight_decay"]
...
... # Simulate performance improving with fidelity
... base_score = 0.7 - (lr - 0.001) ** 2 - (wd - 0.0001) ** 2
... fidelity_bonus = 0.2 * (1 - np.exp(-fidelity / 20))
... noise = np.random.normal(0, 0.01)
...
... score = base_score + fidelity_bonus + noise
... metadata = {"fidelity_used": fidelity}
...
... return score, metadata
>>>
>>> configs = [
... {"learning_rate": 0.001, "weight_decay": 0.0001},
... {"learning_rate": 0.01, "weight_decay": 0.001},
... {"learning_rate": 0.0001, "weight_decay": 0.00001},
... ]
>>>
>>> result = asha_optimize(
... evaluate_model, configs, min_fidelity=1, max_fidelity=27, max_iterations=20
... )
Source code in src/dlhub/tuning/multifidelity.py
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 | |
pbt_optimize ¶
pbt_optimize(train_function: Callable[[dict, int], tuple[float, Any]], save_function: Callable[[], Any], load_function: Callable[[Any], None], reset_function: Callable[[], None], initial_hyperparams: list[dict[str, Any]], hyperparam_distributions: dict[str, HyperparameterDistribution], population_size: int = 10, max_steps: int = 10000, eval_interval: int = 100, exploit_fraction: float = 0.2, explore_fraction: float = 0.2, random_state: int | None = None, verbose: bool = True) -> PBTResult
Convenience function for Population-Based Training.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
train_function
|
callable
|
Function that takes (hyperparams, steps) and returns (score, state) |
required |
save_function
|
callable
|
Function that returns current model state |
required |
load_function
|
callable
|
Function that loads given model state |
required |
reset_function
|
callable
|
Function that resets model to initial state |
required |
initial_hyperparams
|
list
|
Initial hyperparameter configurations |
required |
hyperparam_distributions
|
dict
|
Hyperparameter perturbation distributions |
required |
population_size
|
int
|
Size of population |
10
|
max_steps
|
int
|
Maximum training steps |
10000
|
eval_interval
|
int
|
Steps between evaluations |
100
|
exploit_fraction
|
float
|
Fraction to exploit |
0.2
|
explore_fraction
|
float
|
Fraction to explore |
0.2
|
random_state
|
int
|
Random seed |
None
|
verbose
|
bool
|
Whether to print progress |
True
|
Returns:
| Type | Description |
|---|---|
PBTResult
|
Training results |
Examples:
>>> # Define training functions
>>> def train_step(hyperparams, steps):
... # Simulate training
... lr = hyperparams["learning_rate"]
... # Performance improves with more steps but depends on lr
... performance = 0.8 - (lr - 0.001) ** 2 + steps * 0.001
... return performance, {"step": steps}
>>>
>>> def save_state():
... return getattr(save_state, "state", {})
>>>
>>> def load_state(state):
... save_state.state = state
>>>
>>> def reset():
... save_state.state = {}
>>>
>>> # Define hyperparameters
>>> initial_configs = [
... {"learning_rate": 0.001},
... {"learning_rate": 0.01},
... {"learning_rate": 0.0001},
... ]
>>>
>>> distributions = {
... "learning_rate": LogUniformPerturbation((0.8, 1.2), (1e-5, 1e-1))
... }
>>>
>>> result = pbt_optimize(
... train_step,
... save_state,
... load_state,
... reset,
... initial_configs,
... distributions,
... population_size=5,
... )
Source code in src/dlhub/tuning/population_based.py
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 | |
analyze_parameter_importance ¶
analyze_parameter_importance(result: RandomSearchResult, top_n: int = 10) -> dict[str, float]
Analyze parameter importance using correlation with objective values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
result
|
RandomSearchResult
|
Results from random search optimization |
required |
top_n
|
int
|
Number of top configurations to analyze |
10
|
Returns:
| Type | Description |
|---|---|
dict
|
Parameter importance scores (correlation coefficients) |
Source code in src/dlhub/tuning/random_search.py
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 | |
bayesian ¶
Bayesian Optimization for Hyperparameter Tuning¶
Implements Bayesian optimization using Gaussian Process surrogate models with Expected Improvement acquisition function for efficient hyperparameter search. This approach is particularly effective for expensive black-box optimization problems like neural network hyperparameter tuning.
References
- Snoek, J., Larochelle, H., & Adams, R. P. (2012). "Practical Bayesian Optimization of Machine Learning Algorithms." NIPS.
- Mockus, J. (1994). "Application of Bayesian approach to numerical methods of global and stochastic optimization." Journal of Global Optimization.
License
MIT License
Notes
This implementation uses a simplified Gaussian Process with RBF kernel. For production use, consider libraries like Optuna, GPyOpt, or scikit-optimize which provide more robust implementations with additional features.
BayesianOptimizationResult
dataclass
¶
Container for Bayesian optimization results.
Attributes:
| Name | Type | Description |
|---|---|---|
best_params |
dict
|
Best hyperparameter configuration found |
best_score |
float
|
Best objective function value achieved |
history |
list
|
History of all evaluations |
convergence_data |
dict
|
Convergence statistics and diagnostics |
Source code in src/dlhub/tuning/bayesian.py
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | |
GaussianProcess ¶
Simplified Gaussian Process for Bayesian Optimization.
Implements a GP with RBF kernel for modeling the objective function. This is a educational implementation - production code should use more robust libraries like GPy or scikit-learn.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
kernel_lengthscale
|
float
|
Length scale parameter for RBF kernel |
1.0
|
kernel_variance
|
float
|
Variance parameter for RBF kernel |
1.0
|
noise_variance
|
float
|
Noise variance for numerical stability |
1e-6
|
Source code in src/dlhub/tuning/bayesian.py
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 | |
rbf_kernel ¶
rbf_kernel(X1: ndarray, X2: ndarray) -> np.ndarray
Compute RBF (Radial Basis Function) kernel matrix.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X1
|
(ndarray, shape(n1, d))
|
First set of input points |
required |
X2
|
(ndarray, shape(n2, d))
|
Second set of input points |
required |
Returns:
| Type | Description |
|---|---|
(ndarray, shape(n1, n2))
|
Kernel matrix K(X1, X2) |
Source code in src/dlhub/tuning/bayesian.py
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 | |
fit ¶
fit(X: ndarray, y: ndarray) -> None
Fit the Gaussian Process to training data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
(ndarray, shape(n_samples, n_features))
|
Training input points |
required |
y
|
(ndarray, shape(n_samples))
|
Training target values |
required |
Source code in src/dlhub/tuning/bayesian.py
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 | |
predict ¶
predict(X: ndarray) -> tuple[np.ndarray, np.ndarray]
Make predictions with uncertainty estimates.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
(ndarray, shape(n_test, n_features))
|
Test input points |
required |
Returns:
| Name | Type | Description |
|---|---|---|
mean |
(ndarray, shape(n_test))
|
Predicted mean values |
std |
(ndarray, shape(n_test))
|
Predicted standard deviations |
Source code in src/dlhub/tuning/bayesian.py
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 | |
BayesianOptimizer ¶
Bayesian Optimization using Gaussian Process surrogate models.
This implementation uses Expected Improvement as the acquisition function to balance exploration and exploitation in hyperparameter search.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
objective_function
|
callable
|
Function to optimize. Should take hyperparameter dict and return float |
required |
search_space
|
dict
|
Dictionary defining search space for each hyperparameter. Format: {'param_name': (min_val, max_val)} for continuous parameters |
required |
acquisition
|
str
|
Acquisition function ('ei' for Expected Improvement, 'ucb' for UCB) |
'ei'
|
kappa
|
float
|
Exploration parameter for UCB (ignored if acquisition='ei') |
2.576
|
xi
|
float
|
Exploration parameter for Expected Improvement |
0.01
|
n_initial
|
int
|
Number of random initial evaluations |
5
|
random_state
|
int
|
Random seed for reproducibility |
None
|
Source code in src/dlhub/tuning/bayesian.py
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 | |
optimize ¶
optimize(n_iterations: int = 20, verbose: int = 1) -> BayesianOptimizationResult
Run Bayesian optimization.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_iterations
|
int
|
Maximum number of optimization iterations |
20
|
verbose
|
int
|
Reporting level: 0 is silent, 1 prints phases and new bests, 2 adds every evaluation and the final configuration. |
1
|
Returns:
| Type | Description |
|---|---|
BayesianOptimizationResult
|
Optimization results including best parameters and history |
Source code in src/dlhub/tuning/bayesian.py
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 | |
bayesian_optimize ¶
bayesian_optimize(objective_function: Callable[[dict], float], search_space: dict[str, tuple[float, float]], n_iterations: int = 20, n_initial: int = 5, acquisition: str = 'ei', random_state: int | None = None, verbose: int = 1) -> BayesianOptimizationResult
Run a Bayesian search over continuous bounds, returning its own result type.
The method-specific entry point, alongside :func:~dlhub.tuning.random_search
and :func:~dlhub.tuning.asha_optimize. To choose a method by name instead,
call :func:~dlhub.tuning.optimize_hyperparameters, which takes the
framework's richer search-space format and returns an ExperimentResult.
Takes a scalar objective and a {name: (low, high)} search space; every
dimension is continuous, since the Gaussian process interpolates over them.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
objective_function
|
callable
|
Function to optimize. Should accept hyperparameter dict and return float |
required |
search_space
|
dict
|
Search space definition: {'param_name': (min_val, max_val)} |
required |
n_iterations
|
int
|
Number of optimization iterations after initial random sampling |
20
|
n_initial
|
int
|
Number of random initial points |
5
|
acquisition
|
str
|
Acquisition function ('ei' or 'ucb') |
'ei'
|
random_state
|
int
|
Random seed for reproducibility |
None
|
verbose
|
int
|
Reporting level, as in :meth: |
1
|
Returns:
| Type | Description |
|---|---|
BayesianOptimizationResult
|
Optimization results |
Examples:
>>> def objective(params):
... # Simulate training a model and return validation accuracy
... lr, wd = params["learning_rate"], params["weight_decay"]
... # Dummy objective (replace with actual model training)
... return -((lr - 0.001) ** 2) - (wd - 0.0001) ** 2 + np.random.normal(0, 0.01)
>>>
>>> search_space = {"learning_rate": (1e-5, 1e-1), "weight_decay": (1e-6, 1e-2)}
>>>
>>> result = bayesian_optimize(
... objective, search_space, n_iterations=30, random_state=42
... )
>>> print(f"Best parameters: {result.best_params}")
Source code in src/dlhub/tuning/bayesian.py
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 | |
quadratic_objective ¶
quadratic_objective(params)
Example objective function - quadratic with noise.
Source code in src/dlhub/tuning/bayesian.py
558 559 560 561 562 | |
nn_objective ¶
nn_objective(params)
Dummy neural network training objective.
Source code in src/dlhub/tuning/bayesian.py
581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 | |
framework ¶
Modern Hyperparameter Tuning Framework¶
Production-ready framework integrating multiple optimization strategies with experiment tracking and statistical analysis. This framework provides a unified interface for various hyperparameter optimization methods and includes tools for result comparison, visualization, and reproducibility.
References
- Feurer, M., & Hutter, F. (2019). "Hyperparameter Optimization." Automated Machine Learning: Methods, Systems, Challenges.
- Liaw, R., et al. (2018). "Tune: A Research Platform for Distributed Model Selection and Training." arXiv preprint arXiv:1807.05118.
License
MIT License
Notes
This framework is designed to be: 1. Flexible - supports multiple optimization strategies 2. Extensible - easy to add new optimizers 3. Reproducible - proper random seeding and logging 4. Production-ready - includes error handling and checkpointing
OptimizationMethod ¶
Bases: Enum
Enumeration of available optimization methods.
Source code in src/dlhub/tuning/framework.py
47 48 49 50 51 52 53 54 | |
HyperparameterConfig
dataclass
¶
Configuration for a single hyperparameter.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
Parameter name |
type |
str
|
Parameter type ('continuous', 'integer', 'categorical') |
range |
tuple or list
|
Valid range or choices for the parameter |
scale |
str, default='linear'
|
Scale for sampling ('linear', 'log') |
default |
Any(optional)
|
Default value for said parameter |
Source code in src/dlhub/tuning/framework.py
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 | |
ExperimentConfig
dataclass
¶
Configuration for hyperparameter optimization experiment.
Attributes:
| Name | Type | Description |
|---|---|---|
experiment_name |
str
|
Name of the experiment |
optimization_method |
OptimizationMethod
|
Optimization strategy to use |
hyperparameters |
list
|
List of HyperparameterConfig objects |
objective_metric |
str
|
Name of metric to optimize |
maximize |
bool, default=True
|
Whether to maximize the objective metric |
n_trials |
int, default=100
|
Number of trials to run |
random_seed |
int(optional)
|
Random seed for reproducibility |
save_dir |
str(optional)
|
Directory to save results |
additional_config |
dict(optional)
|
Additional method-specific configuration |
Source code in src/dlhub/tuning/framework.py
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 | |
TrialResult
dataclass
¶
Result from a single trial.
Attributes:
| Name | Type | Description |
|---|---|---|
trial_id |
int
|
Unique trial identifier |
hyperparams |
dict
|
Hyperparameter configuration used |
metrics |
dict
|
All metrics recorded |
training_time |
float
|
Time taken for training |
status |
str
|
Trial status ('success', 'failed', 'cancelled') |
metadata |
dict
|
Additional trial information |
Source code in src/dlhub/tuning/framework.py
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 | |
ExperimentResult
dataclass
¶
The outcome of one hyperparameter search: every trial, and the best of them.
Named for the :class:ExperimentConfig it answers. Not to be confused with
:class:dlhub.optimizers.OptimizationRun, which traces a single descent.
Attributes:
| Name | Type | Description |
|---|---|---|
experiment_config |
ExperimentConfig
|
Configuration used for the experiment |
best_trial |
TrialResult
|
Best performing trial |
all_trials |
list
|
All trial results |
total_time |
float
|
Total optimization time |
summary_statistics |
dict
|
Summary statistics and analysis |
Source code in src/dlhub/tuning/framework.py
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 | |
ObjectiveFunction ¶
Bases: ABC
Abstract base class for objective functions.
Defines the interface that objective functions must implement.
Source code in src/dlhub/tuning/framework.py
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 | |
evaluate
abstractmethod
¶
evaluate(hyperparams: dict[str, Any]) -> dict[str, float]
Evaluate hyperparameters and return metrics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hyperparams
|
dict
|
Hyperparameter configuration |
required |
Returns:
| Type | Description |
|---|---|
dict
|
Dictionary of metric names to values |
Source code in src/dlhub/tuning/framework.py
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 | |
get_metric_names
abstractmethod
¶
get_metric_names() -> list[str]
Get names of all metrics returned by evaluate.
Returns:
| Type | Description |
|---|---|
list
|
List of metric names |
Source code in src/dlhub/tuning/framework.py
203 204 205 206 207 208 209 210 211 212 213 | |
FunctionObjective ¶
Bases: ObjectiveFunction
Wrapper for function-based objectives.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
eval_function
|
callable
|
Function that takes hyperparams and returns metrics dict |
required |
metric_names
|
list
|
Names of metrics returned by eval_function |
required |
Source code in src/dlhub/tuning/framework.py
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 | |
evaluate ¶
evaluate(hyperparams: dict[str, Any]) -> dict[str, float]
Evaluate using wrapped function.
Source code in src/dlhub/tuning/framework.py
234 235 236 | |
get_metric_names ¶
get_metric_names() -> list[str]
Get metric names.
Source code in src/dlhub/tuning/framework.py
238 239 240 | |
HyperparameterSampler ¶
Utility class for sampling hyperparameters from configurations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hyperparameter_configs
|
list
|
List of HyperparameterConfig objects |
required |
random_state
|
int
|
Random seed for reproducibility |
None
|
Source code in src/dlhub/tuning/framework.py
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 | |
sample ¶
sample() -> dict[str, Any]
Sample a hyperparameter configuration.
Returns:
| Type | Description |
|---|---|
dict
|
Sampled hyperparameter configuration |
Source code in src/dlhub/tuning/framework.py
264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 | |
validate ¶
validate(hyperparams: dict[str, Any]) -> bool
Validate a hyperparameter configuration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hyperparams
|
dict
|
Hyperparameter configuration to validate |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if configuration is valid |
Source code in src/dlhub/tuning/framework.py
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 | |
ExperimentLogger ¶
Logger for experiment results and metadata.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
save_dir
|
str(optional)
|
Directory to save logs |
required |
experiment_name
|
str
|
Name of the experiment |
required |
Source code in src/dlhub/tuning/framework.py
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 | |
log_trial ¶
log_trial(trial_result: TrialResult) -> None
Log a trial result.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
trial_result
|
TrialResult
|
Trial result to log |
required |
Source code in src/dlhub/tuning/framework.py
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 | |
save_results ¶
save_results(result: ExperimentResult) -> None
Save complete optimization results.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
result
|
ExperimentResult
|
Optimization results to save |
required |
Source code in src/dlhub/tuning/framework.py
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 | |
load_results ¶
load_results() -> list[TrialResult] | None
Load trial results from log file.
Returns:
| Type | Description |
|---|---|
list or None
|
List of TrialResult objects, or None if no log exists |
Source code in src/dlhub/tuning/framework.py
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 | |
HyperparameterOptimizer ¶
Main hyperparameter optimization framework.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
ExperimentConfig
|
Experiment configuration |
required |
objective
|
ObjectiveFunction
|
Objective function to optimize |
required |
Source code in src/dlhub/tuning/framework.py
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 | |
optimize ¶
optimize(verbose: bool = True) -> ExperimentResult
Run hyperparameter optimization.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
verbose
|
bool
|
Whether to print progress |
True
|
Returns:
| Type | Description |
|---|---|
ExperimentResult
|
Optimization results |
Source code in src/dlhub/tuning/framework.py
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 | |
optimize_hyperparameters ¶
optimize_hyperparameters(objective_function: Callable[[dict], dict[str, float]], hyperparameters: list[dict[str, Any]], objective_metric: str, experiment_name: str = 'hyperparameter_optimization', optimization_method: str = 'random_search', n_trials: int = 100, maximize: bool = True, random_seed: int | None = None, save_dir: str | None = None, verbose: bool = True) -> ExperimentResult
Run a hyperparameter search by method name, returning an ExperimentResult.
The general dispatcher: optimization_method selects the strategy. It takes
the framework's search-space format, which carries a type per hyperparameter
and so covers categorical and integer dimensions as well as continuous ones.
The method-specific entry points -- :func:~dlhub.tuning.bayesian_optimize,
:func:~dlhub.tuning.random_search -- take their own formats and return their
own result types.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
objective_function
|
callable
|
Function that takes hyperparams dict and returns metrics dict |
required |
hyperparameters
|
list
|
List of hyperparameter definitions (dicts with 'name', 'type', 'range') |
required |
objective_metric
|
str
|
Name of metric to optimize |
required |
experiment_name
|
str
|
Name of the experiment |
"hyperparameter_optimization"
|
optimization_method
|
str
|
Optimization method ('random_search' or 'grid_search') |
"random_search"
|
n_trials
|
int
|
Number of trials |
100
|
maximize
|
bool
|
Whether to maximize objective |
True
|
random_seed
|
int(optional)
|
Random seed |
None
|
save_dir
|
str(optional)
|
Directory to save results |
None
|
verbose
|
bool
|
Whether to print progress |
True
|
Returns:
| Type | Description |
|---|---|
ExperimentResult
|
Optimization results |
Examples:
>>> def objective(hyperparams):
... lr = hyperparams["learning_rate"]
... wd = hyperparams["weight_decay"]
... accuracy = 0.9 - (lr - 0.001) ** 2 - (wd - 0.0001) ** 2
... return {"accuracy": accuracy, "loss": 1 - accuracy}
>>> hyperparams = [
... {
... "name": "learning_rate",
... "type": "continuous",
... "range": (1e-5, 1e-1),
... "scale": "log",
... },
... {
... "name": "weight_decay",
... "type": "continuous",
... "range": (1e-6, 1e-2),
... "scale": "log",
... },
... ]
>>> result = optimize_hyperparameters(
... objective, hyperparams, "accuracy", n_trials=50, random_seed=42
... )
Source code in src/dlhub/tuning/framework.py
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 | |
nn_objective ¶
nn_objective(hyperparams: dict[str, Any]) -> dict[str, float]
Simulate neural network training objective.
Returns multiple metrics for comprehensive evaluation.
Source code in src/dlhub/tuning/framework.py
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 | |
is_dominated ¶
is_dominated(trial1, trial2)
Check if trial1 is dominated by trial2.
Source code in src/dlhub/tuning/framework.py
1098 1099 1100 1101 1102 1103 1104 1105 1106 | |
learning_rate_finder ¶
Learning Rate Finder for Hyperparameter Tuning¶
Automated learning rate range testing to find optimal learning rate ranges before full training. This technique helps identify good learning rate ranges by monitoring loss behavior during short training runs with exponentially increasing learning rates.
References
- Smith, L. N. (2017). "Cyclical Learning Rates for Training Neural Networks." IEEE Winter Conference on Applications of Computer Vision (WACV).
- Smith, L. N. (2018). "A disciplined approach to neural network hyper-parameters: Part 1 -- learning rate, batch size, momentum, and weight decay." arXiv preprint.
License
MIT License
Notes
The learning rate finder is particularly useful for: 1. Finding the maximum usable learning rate 2. Identifying learning rate ranges for cyclical learning rate schedules 3. Detecting when the learning rate is too high (loss divergence) 4. Setting appropriate learning rates for different optimizers
LearningRateFinderResult
dataclass
¶
Container for learning rate finder results.
Attributes:
| Name | Type | Description |
|---|---|---|
learning_rates |
ndarray
|
Array of learning rates tested |
losses |
ndarray
|
Corresponding loss values |
smoothed_losses |
ndarray
|
Smoothed loss values for trend analysis |
suggested_lr |
float
|
Suggested learning rate based on analysis |
min_gradient_lr |
float
|
Learning rate with steepest loss decrease |
analysis |
dict
|
Additional analysis metrics and diagnostics |
Source code in src/dlhub/tuning/learning_rate_finder.py
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 | |
BaseTrainer ¶
Bases: ABC
Abstract base class for training interface.
Defines the interface that training functions must implement to work with the learning rate finder.
Source code in src/dlhub/tuning/learning_rate_finder.py
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 | |
train_batch
abstractmethod
¶
train_batch(learning_rate: float) -> float
Train one batch with given learning rate and return loss.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
learning_rate
|
float
|
Learning rate to use for this batch |
required |
Returns:
| Type | Description |
|---|---|
float
|
Loss value after training step |
Source code in src/dlhub/tuning/learning_rate_finder.py
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 | |
reset_model
abstractmethod
¶
reset_model() -> None
Reset model to initial state.
Source code in src/dlhub/tuning/learning_rate_finder.py
97 98 99 100 | |
FunctionTrainer ¶
Bases: BaseTrainer
Trainer wrapper for function-based training.
Wraps user-provided training and reset functions to conform to the BaseTrainer interface.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
train_function
|
callable
|
Function that takes learning_rate and returns loss |
required |
reset_function
|
callable
|
Function to reset model state |
required |
Source code in src/dlhub/tuning/learning_rate_finder.py
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 | |
train_batch ¶
train_batch(learning_rate: float) -> float
Train one batch with given learning rate.
Source code in src/dlhub/tuning/learning_rate_finder.py
126 127 128 | |
reset_model ¶
reset_model() -> None
Reset model to initial state.
Source code in src/dlhub/tuning/learning_rate_finder.py
130 131 132 | |
LearningRateFinder ¶
Learning Rate Finder for optimal learning rate discovery.
Implements the learning rate range test by training with exponentially increasing learning rates and analyzing the loss curve to suggest optimal learning rate ranges.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
trainer
|
BaseTrainer
|
Training interface object |
required |
min_lr
|
float
|
Minimum learning rate to test |
1e-7
|
max_lr
|
float
|
Maximum learning rate to test |
10.0
|
num_iterations
|
int
|
Number of iterations to run the test |
100
|
step_mode
|
str
|
How to step learning rate ('exp' for exponential, 'linear' for linear) |
'exp'
|
smooth_beta
|
float
|
Smoothing factor for loss smoothing (exponential moving average) |
0.98
|
divergence_threshold
|
float
|
Stop if loss > divergence_threshold * min_loss |
4.0
|
Source code in src/dlhub/tuning/learning_rate_finder.py
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 | |
find ¶
find(verbose: bool = True) -> LearningRateFinderResult
Run learning rate finder.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
verbose
|
bool
|
Whether to print progress information |
True
|
Returns:
| Type | Description |
|---|---|
LearningRateFinderResult
|
Results of the learning rate finder |
Source code in src/dlhub/tuning/learning_rate_finder.py
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 | |
plot_results ¶
plot_results(result: LearningRateFinderResult, figsize: tuple[int, int] = (12, 8), save_path: str | None = None) -> None
Plot learning rate finder results.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
result
|
LearningRateFinderResult
|
Results from learning rate finder |
required |
figsize
|
tuple
|
Figure size for the plot |
(12, 8)
|
save_path
|
str
|
Path to save the plot |
None
|
Source code in src/dlhub/tuning/learning_rate_finder.py
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 | |
SimulatedNN ¶
Simulated neural network for demonstration.
Source code in src/dlhub/tuning/learning_rate_finder.py
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 | |
reset ¶
reset()
Reset network to initial state.
Source code in src/dlhub/tuning/learning_rate_finder.py
712 713 714 715 716 | |
train_step ¶
train_step(learning_rate)
Simulate one training step.
Source code in src/dlhub/tuning/learning_rate_finder.py
718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 | |
find_learning_rate ¶
find_learning_rate(train_function: Callable[[float], float], reset_function: Callable[[], None], min_lr: float = 1e-07, max_lr: float = 10.0, num_iterations: int = 100, step_mode: str = 'exp', smooth_beta: float = 0.98, verbose: bool = True, plot: bool = True) -> LearningRateFinderResult
Convenience function to find optimal learning rate.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
train_function
|
callable
|
Function that takes learning_rate (float) and returns loss (float) |
required |
reset_function
|
callable
|
Function to reset model to initial state |
required |
min_lr
|
float
|
Minimum learning rate to test |
1e-7
|
max_lr
|
float
|
Maximum learning rate to test |
10.0
|
num_iterations
|
int
|
Number of iterations for the test |
100
|
step_mode
|
str
|
Learning rate stepping mode ('exp' or 'linear') |
'exp'
|
smooth_beta
|
float
|
Smoothing factor for loss curves |
0.98
|
verbose
|
bool
|
Whether to print progress |
True
|
plot
|
bool
|
Whether to plot results |
True
|
Returns:
| Type | Description |
|---|---|
LearningRateFinderResult
|
Results including suggested learning rate |
Examples:
>>> # Example with simple quadratic loss
>>> def train_step(lr):
... # Simulate one training step
... current_w = getattr(train_step, "w", 1.0) # Get current weight
... target_w = 0.5 # Target weight
... loss = (current_w - target_w) ** 2
...
... # Gradient descent update
... gradient = 2 * (current_w - target_w)
... train_step.w = current_w - lr * gradient
...
... return loss + np.random.normal(0, 0.01) # Add noise
>>> def reset_model():
... train_step.w = 1.0 # Reset to initial weight
>>> result = find_learning_rate(
... train_step, reset_model, min_lr=1e-4, max_lr=1.0, num_iterations=50
... )
>>> print(f"Suggested learning rate: {result.suggested_lr}")
Source code in src/dlhub/tuning/learning_rate_finder.py
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 | |
suggest_learning_rate_schedule ¶
suggest_learning_rate_schedule(result: LearningRateFinderResult, schedule_type: str = 'onecycle') -> dict[str, Any]
Suggest learning rate schedule based on finder results.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
result
|
LearningRateFinderResult
|
Results from learning rate finder |
required |
schedule_type
|
str
|
Type of schedule to suggest ('onecycle', 'cyclic', 'cosine', 'step') |
'onecycle'
|
Returns:
| Type | Description |
|---|---|
dict
|
Suggested schedule parameters |
Source code in src/dlhub/tuning/learning_rate_finder.py
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 | |
quadratic_train_step ¶
quadratic_train_step(lr)
Simulate one training step on quadratic function.
Source code in src/dlhub/tuning/learning_rate_finder.py
672 673 674 675 676 677 678 679 680 681 682 683 | |
reset_quadratic ¶
reset_quadratic()
Reset model to initial state.
Source code in src/dlhub/tuning/learning_rate_finder.py
685 686 687 | |
multifidelity ¶
Multi-Fidelity Optimization for Hyperparameter Tuning¶
ASHA (Asynchronous Successive Halving) implementation for efficient resource allocation across hyperparameter candidates. This approach uses cheaper approximations (lower fidelity) to guide the search, then evaluates promising candidates at full fidelity.
References
- Li, L., et al. (2018). "Massively Parallel Hyperparameter Tuning." arXiv preprint arXiv:1810.05934.
- Jamieson, K., & Talwalkar, A. (2016). "Non-stochastic best arm identification and hyperparameter optimization." Artificial Intelligence and Statistics.
License
MIT License
Notes
Multi-fidelity optimization is particularly effective when: 1. Training time is expensive 2. Early performance correlates with final performance 3. You have many hyperparameter configurations to evaluate 4. Computational resources can be allocated dynamically
FidelityConfig
dataclass
¶
Configuration for a fidelity level.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
Name of the fidelity level |
budget |
int
|
Budget/resource allocation for this fidelity |
min_budget |
int
|
Minimum budget required for this fidelity |
max_budget |
int
|
Maximum budget for this fidelity |
Source code in src/dlhub/tuning/multifidelity.py
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | |
CandidateResult
dataclass
¶
Result from evaluating a hyperparameter candidate.
Attributes:
| Name | Type | Description |
|---|---|---|
config_id |
int
|
Unique identifier for the configuration |
hyperparams |
dict
|
Hyperparameter configuration |
fidelity |
int
|
Fidelity level used for evaluation |
score |
float
|
Performance score achieved |
training_time |
float
|
Time taken for training |
metadata |
dict
|
Additional metadata from training |
Source code in src/dlhub/tuning/multifidelity.py
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 | |
MultiFidelityResult
dataclass
¶
Results from multi-fidelity optimization.
Attributes:
| Name | Type | Description |
|---|---|---|
best_config |
dict or None
|
Best hyperparameter configuration found, or None if the run recorded no results at all (see Notes) |
best_score |
float or None
|
Best score achieved, or None for a run with no results |
best_fidelity |
int or None
|
Fidelity level of best result, or None for a run with no results |
all_results |
list
|
All evaluation results |
total_time |
float
|
Total optimization time |
total_budget_used |
int
|
Total computational budget consumed |
statistics |
dict
|
Optimization statistics and analysis, empty for a run with no results |
Notes
A run can legitimately record nothing: max_iterations=0 grants no budget,
and a timeout that has already elapsed stops the first submission. Both
return this dataclass with the three best_* fields set to None rather than
raising, so the three are optional together -- either all are None or none
are. all_results is empty and statistics is {} in exactly those runs,
so if result.best_config is None and if not result.all_results are
equivalent tests.
An empty initial_configurations is caller error rather than an empty run,
and ASHAOptimizer.optimize rejects it with a ValueError.
Source code in src/dlhub/tuning/multifidelity.py
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 | |
FidelityEvaluator ¶
Bases: ABC
Abstract base class for fidelity-aware evaluation.
Defines the interface for evaluating hyperparameter configurations at different fidelity levels.
Source code in src/dlhub/tuning/multifidelity.py
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 | |
evaluate
abstractmethod
¶
evaluate(hyperparams: dict[str, Any], fidelity: int) -> tuple[float, dict[str, Any]]
Evaluate hyperparameters at given fidelity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hyperparams
|
dict
|
Hyperparameter configuration |
required |
fidelity
|
int
|
Fidelity level (e.g., training epochs, data size) |
required |
Returns:
| Type | Description |
|---|---|
tuple
|
(score, metadata) where score is performance and metadata contains additional information from training |
Source code in src/dlhub/tuning/multifidelity.py
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 | |
get_fidelity_range
abstractmethod
¶
get_fidelity_range() -> tuple[int, int]
Get the valid fidelity range.
Returns:
| Type | Description |
|---|---|
tuple
|
(min_fidelity, max_fidelity) |
Source code in src/dlhub/tuning/multifidelity.py
176 177 178 179 180 181 182 183 184 185 186 | |
FunctionEvaluator ¶
Bases: FidelityEvaluator
Function-based evaluator wrapper.
Wraps a user-provided evaluation function to conform to the FidelityEvaluator interface.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
eval_function
|
callable
|
Function that takes (hyperparams, fidelity) and returns (score, metadata) |
required |
min_fidelity
|
int
|
Minimum fidelity level |
1
|
max_fidelity
|
int
|
Maximum fidelity level |
100
|
Source code in src/dlhub/tuning/multifidelity.py
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 | |
evaluate ¶
evaluate(hyperparams: dict[str, Any], fidelity: int) -> tuple[float, dict[str, Any]]
Evaluate using wrapped function.
Source code in src/dlhub/tuning/multifidelity.py
213 214 215 216 217 | |
get_fidelity_range ¶
get_fidelity_range() -> tuple[int, int]
Get fidelity range.
Source code in src/dlhub/tuning/multifidelity.py
219 220 221 | |
ASHAOptimizer ¶
Asynchronous Successive Halving Algorithm (ASHA) for multi-fidelity optimization.
ASHA efficiently allocates computational resources by starting many configurations at low fidelity and promoting the most promising ones to higher fidelities.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
evaluator
|
FidelityEvaluator
|
Evaluator for hyperparameter configurations |
required |
reduction_factor
|
int
|
Factor by which to reduce number of configurations at each rung |
3
|
min_budget
|
int
|
Minimum budget (fidelity) to start configurations |
1
|
max_budget
|
int
|
Maximum budget (fidelity) for full evaluation |
81
|
grace_period
|
int
|
Minimum budget before first promotion opportunity |
1
|
max_concurrent
|
int
|
Maximum number of concurrent evaluations |
4
|
random_state
|
int
|
Random seed for reproducibility |
None
|
Source code in src/dlhub/tuning/multifidelity.py
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 | |
suggest_initial_configurations ¶
suggest_initial_configurations(configurations: list[dict[str, Any]]) -> None
Add initial configurations to start evaluation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
configurations
|
list
|
List of hyperparameter configurations to evaluate |
required |
Source code in src/dlhub/tuning/multifidelity.py
419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 | |
optimize ¶
optimize(initial_configurations: list[dict[str, Any]], max_iterations: int = 100, timeout: float | None = None, verbose: bool = True) -> MultiFidelityResult
Run ASHA optimization.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
initial_configurations
|
list
|
Initial hyperparameter configurations to evaluate. Must be non-empty. |
required |
max_iterations
|
int
|
Maximum number of evaluations to perform. Counted at submission, and
every submitted evaluation is recorded, so this bounds the results as
well as the work -- at any |
100
|
timeout
|
float
|
Maximum time in seconds (None for no timeout). Evaluations already running when the clock runs out are still awaited and recorded; the timeout stops new submissions, it does not cancel paid-for work. |
None
|
verbose
|
bool
|
Whether to print progress information |
True
|
Returns:
| Type | Description |
|---|---|
MultiFidelityResult
|
Optimization results. A run granted no budget -- |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in src/dlhub/tuning/multifidelity.py
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 | |
asha_optimize ¶
asha_optimize(eval_function: Callable[[dict, int], tuple[float, dict]], initial_configurations: list[dict[str, Any]], min_fidelity: int = 1, max_fidelity: int = 81, reduction_factor: int = 3, max_iterations: int = 100, max_concurrent: int = 4, timeout: float | None = None, random_state: int | None = None, verbose: bool = True) -> MultiFidelityResult
Convenience function for ASHA optimization.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
eval_function
|
callable
|
Function that takes (hyperparams, fidelity) and returns (score, metadata) |
required |
initial_configurations
|
list
|
Initial hyperparameter configurations to evaluate; must be non-empty |
required |
min_fidelity
|
int
|
Minimum fidelity level |
1
|
max_fidelity
|
int
|
Maximum fidelity level |
81
|
reduction_factor
|
int
|
ASHA reduction factor |
3
|
max_iterations
|
int
|
Maximum number of evaluations, performed and recorded alike |
100
|
max_concurrent
|
int
|
Maximum concurrent evaluations |
4
|
timeout
|
float
|
Timeout in seconds; evaluations already running are still awaited |
None
|
random_state
|
int
|
Random seed |
None
|
verbose
|
bool
|
Whether to print progress |
True
|
Returns:
| Type | Description |
|---|---|
MultiFidelityResult
|
Optimization results. The three |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
>>> def evaluate_model(hyperparams, fidelity):
... # Simulate training with given hyperparameters and fidelity
... lr = hyperparams["learning_rate"]
... wd = hyperparams["weight_decay"]
...
... # Simulate performance improving with fidelity
... base_score = 0.7 - (lr - 0.001) ** 2 - (wd - 0.0001) ** 2
... fidelity_bonus = 0.2 * (1 - np.exp(-fidelity / 20))
... noise = np.random.normal(0, 0.01)
...
... score = base_score + fidelity_bonus + noise
... metadata = {"fidelity_used": fidelity}
...
... return score, metadata
>>>
>>> configs = [
... {"learning_rate": 0.001, "weight_decay": 0.0001},
... {"learning_rate": 0.01, "weight_decay": 0.001},
... {"learning_rate": 0.0001, "weight_decay": 0.00001},
... ]
>>>
>>> result = asha_optimize(
... evaluate_model, configs, min_fidelity=1, max_fidelity=27, max_iterations=20
... )
Source code in src/dlhub/tuning/multifidelity.py
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 | |
analyze_fidelity_correlation ¶
analyze_fidelity_correlation(result: MultiFidelityResult) -> dict[str, float]
Analyze correlation between different fidelity levels.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
result
|
MultiFidelityResult
|
Results from multi-fidelity optimization |
required |
Returns:
| Type | Description |
|---|---|
dict
|
Correlation analysis between fidelity levels |
Source code in src/dlhub/tuning/multifidelity.py
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 | |
quadratic_eval ¶
quadratic_eval(hyperparams: dict[str, Any], fidelity: int) -> tuple[float, dict[str, Any]]
Simulate model evaluation with fidelity-dependent performance.
Source code in src/dlhub/tuning/multifidelity.py
822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 | |
nn_eval ¶
nn_eval(hyperparams: dict[str, Any], fidelity: int) -> tuple[float, dict[str, Any]]
Simulate neural network training with different fidelities.
Source code in src/dlhub/tuning/multifidelity.py
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 | |
random_search_baseline ¶
random_search_baseline(eval_func, configs, max_budget, n_evals)
Simple random search baseline at maximum fidelity.
Source code in src/dlhub/tuning/multifidelity.py
959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 | |
population_based ¶
Population-Based Training (PBT) for Hyperparameter Optimization¶
Complete PBT implementation with online hyperparameter adaptation during training. PBT simultaneously trains multiple models with different hyperparameters and periodically updates hyperparameters based on population performance, enabling discovery of time-varying optimal hyperparameters.
References
- Jaderberg, M., et al. (2017). "Population Based Training of Neural Networks." arXiv preprint arXiv:1711.09846.
- Parker-Holder, J., et al. (2020). "Effective Diversity in Population Based Reinforcement Learning." NeurIPS.
License
MIT License
Notes
PBT is particularly effective for: 1. Long training runs where optimal hyperparameters may change over time 2. Scenarios where early performance may not predict final performance 3. Reinforcement learning where environment complexity increases 4. Large-scale distributed training with multiple workers
WorkerState
dataclass
¶
State of a single worker in the population.
Attributes:
| Name | Type | Description |
|---|---|---|
worker_id |
int
|
Unique identifier for the worker |
hyperparams |
dict
|
Current hyperparameter configuration |
performance_history |
list
|
History of performance scores |
training_step |
int
|
Current training step |
model_state |
any
|
Current model state (implementation dependent) |
metadata |
dict
|
Additional worker metadata |
Source code in src/dlhub/tuning/population_based.py
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 | |
PBTResult
dataclass
¶
Results from Population-Based Training.
Attributes:
| Name | Type | Description |
|---|---|---|
best_worker |
WorkerState
|
Best performing worker at the end |
final_population |
list
|
Final state of all workers |
population_history |
list
|
History of population states over time |
total_training_time |
float
|
Total time spent training |
total_steps |
int
|
Total training steps across all workers |
statistics |
dict
|
Training statistics and analysis |
Source code in src/dlhub/tuning/population_based.py
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 | |
HyperparameterDistribution ¶
Bases: ABC
Abstract class for hyperparameter distributions used in exploration.
Source code in src/dlhub/tuning/population_based.py
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 | |
perturb
abstractmethod
¶
perturb(value: Any) -> Any
Perturb a hyperparameter value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
any
|
Current hyperparameter value |
required |
Returns:
| Type | Description |
|---|---|
any
|
Perturbed hyperparameter value |
Source code in src/dlhub/tuning/population_based.py
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 | |
resample
abstractmethod
¶
resample() -> Any
Resample a hyperparameter value from the distribution.
Returns:
| Type | Description |
|---|---|
any
|
New hyperparameter value |
Source code in src/dlhub/tuning/population_based.py
124 125 126 127 128 129 130 131 132 133 134 | |
LogUniformPerturbation ¶
Bases: HyperparameterDistribution
Log-uniform perturbation for hyperparameters that vary over orders of magnitude.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
factor_range
|
tuple
|
Range of multiplicative factors for perturbation |
(0.8, 1.2)
|
bounds
|
tuple
|
(min, max) bounds for the hyperparameter |
None
|
Source code in src/dlhub/tuning/population_based.py
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 | |
perturb ¶
perturb(value: float) -> float
Perturb value by random multiplicative factor.
Source code in src/dlhub/tuning/population_based.py
157 158 159 160 161 162 163 164 165 | |
resample ¶
resample() -> float
Resample from log-uniform distribution.
Source code in src/dlhub/tuning/population_based.py
167 168 169 170 171 | |
UniformPerturbation ¶
Bases: HyperparameterDistribution
Uniform perturbation for continuous hyperparameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
noise_std
|
float
|
Standard deviation of Gaussian noise to add |
0.1
|
bounds
|
tuple
|
(min, max) bounds for the hyperparameter |
None
|
Source code in src/dlhub/tuning/population_based.py
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 | |
perturb ¶
perturb(value: float) -> float
Perturb value by adding Gaussian noise.
Source code in src/dlhub/tuning/population_based.py
192 193 194 195 196 197 198 199 | |
resample ¶
resample() -> float
Resample from uniform distribution.
Source code in src/dlhub/tuning/population_based.py
201 202 203 204 205 | |
ChoicePerturbation ¶
Bases: HyperparameterDistribution
Perturbation for categorical hyperparameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
choices
|
list
|
List of possible values |
required |
change_probability
|
float
|
Probability of changing to a different value |
0.3
|
Source code in src/dlhub/tuning/population_based.py
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 | |
perturb ¶
perturb(value: Any) -> Any
Perturb categorical value.
Source code in src/dlhub/tuning/population_based.py
224 225 226 227 228 229 230 231 | |
resample ¶
resample() -> Any
Resample from choices.
Source code in src/dlhub/tuning/population_based.py
233 234 235 | |
WorkerInterface ¶
Bases: ABC
Abstract interface for training workers in PBT.
Defines the methods that workers must implement to participate in population-based training.
Source code in src/dlhub/tuning/population_based.py
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 | |
train_step
abstractmethod
¶
train_step(hyperparams: dict[str, Any], steps: int = 1) -> tuple[float, Any]
Train for specified number of steps.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hyperparams
|
dict
|
Current hyperparameter configuration |
required |
steps
|
int
|
Number of training steps to perform |
1
|
Returns:
| Type | Description |
|---|---|
tuple
|
(performance_score, model_state) |
Source code in src/dlhub/tuning/population_based.py
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 | |
save_state
abstractmethod
¶
save_state() -> Any
Save current model state.
Returns:
| Type | Description |
|---|---|
any
|
Serializable model state |
Source code in src/dlhub/tuning/population_based.py
267 268 269 270 271 272 273 274 275 276 277 | |
load_state
abstractmethod
¶
load_state(state: Any) -> None
Load model state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
any
|
Model state to load |
required |
Source code in src/dlhub/tuning/population_based.py
279 280 281 282 283 284 285 286 287 288 289 | |
reset
abstractmethod
¶
reset() -> None
Reset worker to initial state.
Source code in src/dlhub/tuning/population_based.py
291 292 293 294 | |
FunctionWorker ¶
Bases: WorkerInterface
Function-based worker implementation.
Wraps user-provided training functions to conform to WorkerInterface.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
train_function
|
callable
|
Function that takes (hyperparams, steps) and returns (score, state) |
required |
save_function
|
callable
|
Function that returns current state |
required |
load_function
|
callable
|
Function that loads given state |
required |
reset_function
|
callable
|
Function that resets to initial state |
required |
Source code in src/dlhub/tuning/population_based.py
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 | |
train_step ¶
train_step(hyperparams: dict[str, Any], steps: int = 1) -> tuple[float, Any]
Train using wrapped function.
Source code in src/dlhub/tuning/population_based.py
327 328 329 330 331 | |
save_state ¶
save_state() -> Any
Save state using wrapped function.
Source code in src/dlhub/tuning/population_based.py
333 334 335 | |
load_state ¶
load_state(state: Any) -> None
Load state using wrapped function.
Source code in src/dlhub/tuning/population_based.py
337 338 339 | |
reset ¶
reset() -> None
Reset using wrapped function.
Source code in src/dlhub/tuning/population_based.py
341 342 343 | |
PopulationBasedTrainer ¶
Population-Based Training optimizer.
Manages a population of workers, periodically evaluating performance and updating hyperparameters through exploitation and exploration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
worker_factory
|
callable
|
Factory function that creates new WorkerInterface instances |
required |
initial_hyperparams
|
list
|
Initial hyperparameter configurations for population |
required |
hyperparam_distributions
|
dict
|
Mapping from hyperparameter names to HyperparameterDistribution objects |
required |
population_size
|
int
|
Size of the population |
10
|
eval_interval
|
int
|
Training steps between population evaluations |
100
|
exploit_fraction
|
float
|
Fraction of worst performers to replace |
0.2
|
explore_fraction
|
float
|
Fraction of hyperparameters to perturb during exploration |
0.2
|
truncation_selection
|
bool
|
Whether to use truncation selection (replace worst with best) |
True
|
random_state
|
int
|
Random seed for reproducibility |
None
|
Source code in src/dlhub/tuning/population_based.py
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 | |
train ¶
train(max_steps: int = 10000, max_generations: int = 100, timeout: float | None = None, verbose: bool = True) -> PBTResult
Run Population-Based Training.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_steps
|
int
|
Maximum total training steps |
10000
|
max_generations
|
int
|
Maximum number of generations |
100
|
timeout
|
float
|
Maximum training time in seconds |
None
|
verbose
|
bool
|
Whether to print progress information |
True
|
Returns:
| Type | Description |
|---|---|
PBTResult
|
Training results including best worker and population history |
Source code in src/dlhub/tuning/population_based.py
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 | |
pbt_optimize ¶
pbt_optimize(train_function: Callable[[dict, int], tuple[float, Any]], save_function: Callable[[], Any], load_function: Callable[[Any], None], reset_function: Callable[[], None], initial_hyperparams: list[dict[str, Any]], hyperparam_distributions: dict[str, HyperparameterDistribution], population_size: int = 10, max_steps: int = 10000, eval_interval: int = 100, exploit_fraction: float = 0.2, explore_fraction: float = 0.2, random_state: int | None = None, verbose: bool = True) -> PBTResult
Convenience function for Population-Based Training.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
train_function
|
callable
|
Function that takes (hyperparams, steps) and returns (score, state) |
required |
save_function
|
callable
|
Function that returns current model state |
required |
load_function
|
callable
|
Function that loads given model state |
required |
reset_function
|
callable
|
Function that resets model to initial state |
required |
initial_hyperparams
|
list
|
Initial hyperparameter configurations |
required |
hyperparam_distributions
|
dict
|
Hyperparameter perturbation distributions |
required |
population_size
|
int
|
Size of population |
10
|
max_steps
|
int
|
Maximum training steps |
10000
|
eval_interval
|
int
|
Steps between evaluations |
100
|
exploit_fraction
|
float
|
Fraction to exploit |
0.2
|
explore_fraction
|
float
|
Fraction to explore |
0.2
|
random_state
|
int
|
Random seed |
None
|
verbose
|
bool
|
Whether to print progress |
True
|
Returns:
| Type | Description |
|---|---|
PBTResult
|
Training results |
Examples:
>>> # Define training functions
>>> def train_step(hyperparams, steps):
... # Simulate training
... lr = hyperparams["learning_rate"]
... # Performance improves with more steps but depends on lr
... performance = 0.8 - (lr - 0.001) ** 2 + steps * 0.001
... return performance, {"step": steps}
>>>
>>> def save_state():
... return getattr(save_state, "state", {})
>>>
>>> def load_state(state):
... save_state.state = state
>>>
>>> def reset():
... save_state.state = {}
>>>
>>> # Define hyperparameters
>>> initial_configs = [
... {"learning_rate": 0.001},
... {"learning_rate": 0.01},
... {"learning_rate": 0.0001},
... ]
>>>
>>> distributions = {
... "learning_rate": LogUniformPerturbation((0.8, 1.2), (1e-5, 1e-1))
... }
>>>
>>> result = pbt_optimize(
... train_step,
... save_state,
... load_state,
... reset,
... initial_configs,
... distributions,
... population_size=5,
... )
Source code in src/dlhub/tuning/population_based.py
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 | |
simple_train_step ¶
simple_train_step(hyperparams: dict[str, Any], steps: int) -> tuple[float, Any]
Simulate training step with time-varying optimal hyperparameters.
Source code in src/dlhub/tuning/population_based.py
870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 | |
simple_save_state ¶
simple_save_state()
Save current worker state.
Source code in src/dlhub/tuning/population_based.py
894 895 896 897 | |
simple_load_state ¶
simple_load_state(state)
Load worker state.
Source code in src/dlhub/tuning/population_based.py
899 900 901 902 | |
simple_reset ¶
simple_reset()
Reset worker state.
Source code in src/dlhub/tuning/population_based.py
904 905 906 907 | |
nn_train_step ¶
nn_train_step(hyperparams: dict[str, Any], steps: int) -> tuple[float, Any]
Simulate neural network training with multiple hyperparameters.
Source code in src/dlhub/tuning/population_based.py
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 | |
nn_save_state ¶
nn_save_state()
Save current worker state.
Source code in src/dlhub/tuning/population_based.py
997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 | |
nn_load_state ¶
nn_load_state(state)
Load worker state.
Source code in src/dlhub/tuning/population_based.py
1009 1010 1011 1012 | |
nn_reset ¶
nn_reset()
Reset worker state.
Source code in src/dlhub/tuning/population_based.py
1014 1015 1016 1017 1018 1019 1020 1021 | |
fixed_nn_train_step ¶
fixed_nn_train_step(hyperparams: dict[str, Any], steps: int) -> tuple[float, Any]
Simulate neural network training with fixed hyperparameters.
Source code in src/dlhub/tuning/population_based.py
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 | |
random_search ¶
Random Search for Hyperparameter Tuning¶
Comprehensive random search implementation with proper probability distributions and parallel evaluation support. Random search has been shown to be more effective than grid search for high-dimensional hyperparameter optimization problems.
References
- Bergstra, J., & Bengio, Y. (2012). "Random search for hyper-parameter optimization." Journal of Machine Learning Research, 13, 281-305.
- Li, L., et al. (2017). "Hyperband: A novel bandit-based approach to hyperparameter optimization." Journal of Machine Learning Research, 18, 1-52.
License
MIT License
Notes
Random search is particularly effective when only a few hyperparameters matter for the final performance. It explores the hyperparameter space more efficiently than grid search by sampling more unique values per dimension.
RandomSearchResult
dataclass
¶
Container for random search optimization results.
Attributes:
| Name | Type | Description |
|---|---|---|
best_params |
dict
|
Best hyperparameter configuration found |
best_score |
float
|
Best objective function value achieved |
all_params |
list
|
All parameter configurations evaluated |
all_scores |
list
|
All scores corresponding to parameter configurations |
search_time |
float
|
Total search time in seconds |
statistics |
dict
|
Search statistics and analysis |
Source code in src/dlhub/tuning/random_search.py
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 | |
ParameterDistribution ¶
Base class for hyperparameter distributions.
Defines the interface for sampling hyperparameters from different probability distributions.
Source code in src/dlhub/tuning/random_search.py
72 73 74 75 76 77 78 79 80 81 82 83 84 85 | |
sample ¶
sample() -> Any
Sample a value from the distribution.
Source code in src/dlhub/tuning/random_search.py
80 81 82 | |
UniformDistribution ¶
Bases: ParameterDistribution
Uniform distribution for continuous parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
low
|
float
|
Lower bound of the distribution |
required |
high
|
float
|
Upper bound of the distribution |
required |
Source code in src/dlhub/tuning/random_search.py
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 | |
sample ¶
sample() -> float
Sample from uniform distribution.
Source code in src/dlhub/tuning/random_search.py
105 106 107 | |
LogUniformDistribution ¶
Bases: ParameterDistribution
Log-uniform distribution for parameters that vary over orders of magnitude.
Particularly useful for learning rates, regularization parameters, etc.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
low
|
float
|
Lower bound (must be positive) |
required |
high
|
float
|
Upper bound (must be positive) |
required |
Source code in src/dlhub/tuning/random_search.py
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 | |
sample ¶
sample() -> float
Sample from log-uniform distribution.
Source code in src/dlhub/tuning/random_search.py
134 135 136 | |
IntegerDistribution ¶
Bases: ParameterDistribution
Discrete uniform distribution for integer parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
low
|
int
|
Lower bound (inclusive) |
required |
high
|
int
|
Upper bound (exclusive) |
required |
Source code in src/dlhub/tuning/random_search.py
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 | |
sample ¶
sample() -> int
Sample from discrete uniform distribution.
Source code in src/dlhub/tuning/random_search.py
159 160 161 | |
ChoiceDistribution ¶
Bases: ParameterDistribution
Categorical distribution for discrete choices.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
choices
|
list
|
List of possible values to choose from |
required |
probabilities
|
list
|
Probability weights for each choice (uniform if None) |
None
|
Source code in src/dlhub/tuning/random_search.py
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 | |
sample ¶
sample() -> Any
Sample from categorical distribution.
Source code in src/dlhub/tuning/random_search.py
190 191 192 | |
PowerDistribution ¶
Bases: ParameterDistribution
Power law distribution for parameters with non-uniform preferences.
Useful when smaller values are preferred (common in regularization).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
low
|
float
|
Lower bound |
required |
high
|
float
|
Upper bound |
required |
power
|
float
|
Power parameter. Above 1 the mass concentrates near |
2.0
|
Source code in src/dlhub/tuning/random_search.py
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 | |
sample ¶
sample() -> float
Sample from power distribution.
Source code in src/dlhub/tuning/random_search.py
220 221 222 223 224 225 226 227 228 | |
RandomSearchOptimizer ¶
Random Search optimizer for hyperparameter tuning.
Implements efficient random sampling of hyperparameters with support for different probability distributions, parallel evaluation, and early stopping.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
objective_function
|
callable
|
Function to optimize. Should take hyperparameter dict and return float |
required |
search_space
|
dict
|
Dictionary mapping parameter names to ParameterDistribution objects |
required |
n_iter
|
int
|
Number of parameter configurations to sample and evaluate |
100
|
random_state
|
int(optional)
|
Random seed for reproducibility |
None
|
n_jobs
|
int
|
Number of parallel jobs (-1 for all available cores) |
1
|
early_stopping
|
bool
|
Whether to use early stopping based on improvement |
False
|
patience
|
int
|
Number of iterations without improvement before stopping |
10
|
Source code in src/dlhub/tuning/random_search.py
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 | |
sample_parameters ¶
sample_parameters() -> dict[str, Any]
Sample a single parameter configuration from the search space.
Returns:
| Type | Description |
|---|---|
dict
|
Sampled hyperparameter configuration |
Source code in src/dlhub/tuning/random_search.py
288 289 290 291 292 293 294 295 296 297 298 299 300 | |
sample_multiple_parameters ¶
sample_multiple_parameters(n_samples: int) -> list[dict[str, Any]]
Sample multiple parameter configurations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_samples
|
int
|
Number of configurations to sample |
required |
Returns:
| Type | Description |
|---|---|
list
|
List of parameter configurations |
Source code in src/dlhub/tuning/random_search.py
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 | |
optimize ¶
optimize(verbose: bool = True) -> RandomSearchResult
Run random search optimization.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
verbose
|
bool
|
Whether to print progress information |
True
|
Returns:
| Type | Description |
|---|---|
RandomSearchResult
|
Optimization results |
Source code in src/dlhub/tuning/random_search.py
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 | |
random_search ¶
random_search(objective_function: Callable[[dict], float], search_space: dict[str, ParameterDistribution | tuple | list], n_iter: int = 100, random_state: int | None = None, n_jobs: int = 1, early_stopping: bool = False, patience: int = 10, verbose: bool = True) -> RandomSearchResult
Convenience function for random search hyperparameter optimization.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
objective_function
|
callable
|
Function to optimize. Should accept hyperparameter dict and return float |
required |
search_space
|
dict
|
Search space definition. Can contain:
- ParameterDistribution objects
- Tuples |
required |
n_iter
|
int
|
Number of parameter configurations to evaluate |
100
|
random_state
|
int(optional)
|
Random seed for reproducibility |
None
|
n_jobs
|
int
|
Number of parallel jobs (-1 for all cores) |
1
|
early_stopping
|
bool
|
Whether to use early stopping |
False
|
patience
|
int
|
Early stopping patience |
10
|
verbose
|
bool
|
Whether to print progress |
True
|
Returns:
| Type | Description |
|---|---|
RandomSearchResult
|
Optimization results |
Examples:
>>> def objective(params):
... lr, wd = params["learning_rate"], params["weight_decay"]
... return -((lr - 0.001) ** 2) - (wd - 0.0001) ** 2 + np.random.normal(0, 0.01)
>>> # Simple tuple/list format
>>> search_space = {
... "learning_rate": (1e-5, 1e-1), # Will use log-uniform
... "batch_size": [16, 32, 64, 128], # Will use choice
... "hidden_units": (64, 512), # Will use uniform
... }
>>> result = random_search(objective, search_space, n_iter=50, random_state=42)
>>> # Advanced distribution format
>>> from scipy.stats import truncnorm
>>> search_space_advanced = {
... "learning_rate": LogUniformDistribution(1e-5, 1e-1),
... "weight_decay": PowerDistribution(1e-6, 1e-2, power=2.0),
... "batch_size": ChoiceDistribution([16, 32, 64, 128], [0.1, 0.3, 0.4, 0.2]),
... "dropout_rate": UniformDistribution(0.0, 0.5),
... }
Source code in src/dlhub/tuning/random_search.py
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 | |
analyze_parameter_importance ¶
analyze_parameter_importance(result: RandomSearchResult, top_n: int = 10) -> dict[str, float]
Analyze parameter importance using correlation with objective values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
result
|
RandomSearchResult
|
Results from random search optimization |
required |
top_n
|
int
|
Number of top configurations to analyze |
10
|
Returns:
| Type | Description |
|---|---|
dict
|
Parameter importance scores (correlation coefficients) |
Source code in src/dlhub/tuning/random_search.py
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 | |
quadratic_objective ¶
quadratic_objective(params)
Example objective - quadratic function with noise.
Source code in src/dlhub/tuning/random_search.py
655 656 657 658 | |
nn_objective ¶
nn_objective(params)
Realistic neural network objective function simulation.
Source code in src/dlhub/tuning/random_search.py
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 | |
simple_nn_objective ¶
simple_nn_objective(params)
Simple neural network objective for testing.
Source code in src/dlhub/tuning/random_search.py
691 692 693 694 695 696 697 | |