(num_trials=10, max_num_epochs=10, gpus_per_trial=0, cpus_per_trial=2)
| 482 | # ----------------------- |
| 483 | |
| 484 | def main(num_trials=10, max_num_epochs=10, gpus_per_trial=0, cpus_per_trial=2): |
| 485 | print("Starting hyperparameter tuning.") |
| 486 | ray.init(include_dashboard=False) |
| 487 | |
| 488 | data_dir = os.path.abspath("./data") |
| 489 | load_data(data_dir) # Pre-download the dataset |
| 490 | device = "cuda" if torch.cuda.is_available() else "cpu" |
| 491 | config = { |
| 492 | "l1": tune.choice([2**i for i in range(9)]), |
| 493 | "l2": tune.choice([2**i for i in range(9)]), |
| 494 | "lr": tune.loguniform(1e-4, 1e-1), |
| 495 | "batch_size": tune.choice([2, 4, 8, 16]), |
| 496 | "device": device, |
| 497 | } |
| 498 | scheduler = ASHAScheduler( |
| 499 | max_t=max_num_epochs, |
| 500 | grace_period=1, |
| 501 | reduction_factor=2, |
| 502 | ) |
| 503 | |
| 504 | tuner = tune.Tuner( |
| 505 | tune.with_resources( |
| 506 | partial(train_cifar, data_dir=data_dir), |
| 507 | resources={"cpu": cpus_per_trial, "gpu": gpus_per_trial} |
| 508 | ), |
| 509 | tune_config=tune.TuneConfig( |
| 510 | metric="loss", |
| 511 | mode="min", |
| 512 | scheduler=scheduler, |
| 513 | num_samples=num_trials, |
| 514 | ), |
| 515 | param_space=config, |
| 516 | ) |
| 517 | results = tuner.fit() |
| 518 | |
| 519 | best_result = results.get_best_result("loss", "min") |
| 520 | print(f"Best trial config: {best_result.config}") |
| 521 | print(f"Best trial final validation loss: {best_result.metrics['loss']}") |
| 522 | print(f"Best trial final validation accuracy: {best_result.metrics['accuracy']}") |
| 523 | |
| 524 | best_trained_model = Net(best_result.config["l1"], best_result.config["l2"]) |
| 525 | best_trained_model = best_trained_model.to(device) |
| 526 | if gpus_per_trial > 1: |
| 527 | best_trained_model = nn.DataParallel(best_trained_model) |
| 528 | |
| 529 | best_checkpoint = best_result.checkpoint |
| 530 | with best_checkpoint.as_directory() as checkpoint_dir: |
| 531 | checkpoint_path = Path(checkpoint_dir) / "checkpoint.pt" |
| 532 | best_checkpoint_data = torch.load(checkpoint_path) |
| 533 | |
| 534 | best_trained_model.load_state_dict(best_checkpoint_data["net_state_dict"]) |
| 535 | test_acc = test_accuracy(best_trained_model, device, data_dir) |
| 536 | print(f"Best trial test set accuracy: {test_acc}") |
| 537 | |
| 538 | |
| 539 | if __name__ == "__main__": |
no test coverage detected