-
Notifications
You must be signed in to change notification settings - Fork 0
Hyperparameter tuning #69
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
SarahAlidoost
wants to merge
18
commits into
main
Choose a base branch
from
hyperparameter_tuning
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
6e0c1d9
use ray tune for hyperparameter search
SarahAlidoost fd32d1e
Merge branch 'data_time_subsetting' into hyperparameter_tuning
SarahAlidoost d3ae5b2
implement chunk processing for month_attn
SarahAlidoost 61fa825
add scripts for tuning
SarahAlidoost 305008b
fix dtype of few tensors in dataset
SarahAlidoost d55e91e
fix chunk_attn in the model
SarahAlidoost de3295d
fix tuning scripts
SarahAlidoost 0d73cc4
run ruff
SarahAlidoost 5386f1d
Merge branch 'main' into hyperparameter_tuning
SarahAlidoost f59fa3a
use as_tensor instead tensor
SarahAlidoost f1e6891
fix test_best_model function
SarahAlidoost 4e4f502
update hyperparameter ranges
SarahAlidoost 211daa7
run ruff
SarahAlidoost 8533e19
update accumulation_steps
SarahAlidoost 96e440b
update some parameters in tuning
SarahAlidoost e4ba58d
use ray get for data
SarahAlidoost c924291
fix and rename test_bet_model function
SarahAlidoost 7a5427d
add an example nb for tuning
SarahAlidoost File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
| @@ -0,0 +1,161 @@ | ||||||
| import ray | ||||||
| import xarray as xr | ||||||
|
|
||||||
| from ray.tune.schedulers import ASHAScheduler | ||||||
| from climanet.dataset import STDataset | ||||||
| from climanet.predict import predict_monthly_var | ||||||
| from climanet.st_encoder_decoder import SpatioTemporalModel | ||||||
| from climanet.train import train_monthly_model | ||||||
| from climanet.utils import set_seed | ||||||
|
|
||||||
|
|
||||||
| def _train(tune_config): | ||||||
| """Helper function to train the model with Ray Tune.""" | ||||||
|
|
||||||
| device = tune_config["device"] | ||||||
| dataloader_num_workers = tune_config["dataloader_num_workers"] | ||||||
| train_dataset = ray.get(tune_config["train_dataset"]) | ||||||
| validation_dataset = ray.get(tune_config["validation_dataset"]) | ||||||
| patch_size = tune_config["patch_size"] | ||||||
| overlap = tune_config["overlap"] | ||||||
| embed_dim = tune_config["embed_dim"] | ||||||
| dropout = tune_config["dropout"] | ||||||
| hidden = tune_config["hidden"] | ||||||
| spatial_depth = tune_config["spatial_depth"] | ||||||
| spatial_heads = tune_config["spatial_heads"] | ||||||
| run_dir = tune_config["run_dir"] | ||||||
| num_epoch = tune_config["num_epoch"] | ||||||
|
|
||||||
| set_seed() | ||||||
|
|
||||||
| model = SpatioTemporalModel( | ||||||
| patch_size=(1, patch_size, patch_size), | ||||||
| overlap=overlap, | ||||||
| embed_dim=embed_dim, | ||||||
| dropout=dropout, | ||||||
| hidden=hidden, | ||||||
| spatial_depth=spatial_depth, | ||||||
| spatial_heads=spatial_heads, | ||||||
| ) | ||||||
|
|
||||||
| batch_size = tune_config["batch_size"] | ||||||
| accumulation_steps = tune_config["accumulation_steps"] | ||||||
| optimizer_lr = tune_config["optimizer_lr"] | ||||||
|
|
||||||
| _ = train_monthly_model( | ||||||
| model, | ||||||
| train_dataset, | ||||||
| validation_dataset=validation_dataset, | ||||||
| batch_size=batch_size, | ||||||
| num_epoch=num_epoch, | ||||||
| accumulation_steps=accumulation_steps, | ||||||
| optimizer_lr=optimizer_lr, | ||||||
| device=device, | ||||||
| run_dir=run_dir, | ||||||
| dataloader_num_workers=dataloader_num_workers, | ||||||
| store_model=False, | ||||||
| verbose=False, | ||||||
| tune_checkpoint=True, | ||||||
| ) | ||||||
|
|
||||||
|
|
||||||
| def tune_data_preparation(data_config: dict, is_hourly=True) -> STDataset: | ||||||
| """Prepare the data for training and validation.""" | ||||||
| input_data = xr.open_mfdataset(data_config["input_filenames"]) | ||||||
| monthly_data = xr.open_mfdataset(data_config["monthly_filenames"]) | ||||||
| lsm_mask = xr.open_dataset(data_config["landmask_filename"]) | ||||||
|
|
||||||
| # calculate residuals as target | ||||||
| input_data_averaged = input_data.resample(time="MS").mean(skipna=True) | ||||||
| input_data_averaged["time"] = monthly_data["time"] | ||||||
|
|
||||||
| # Residuals | ||||||
| monthly_data_res = monthly_data - input_data_averaged | ||||||
|
|
||||||
| var_name = data_config["var_name"] | ||||||
|
|
||||||
| dataset = STDataset( | ||||||
| input_da=input_data[var_name], | ||||||
| monthly_da=monthly_data_res[var_name], | ||||||
| land_mask=lsm_mask["lsm"], | ||||||
| patch_size=data_config["patch_size"], | ||||||
| stride=data_config["stride"], | ||||||
| sh_embed_dim=96, | ||||||
| sh_order_L=10, | ||||||
| is_hourly=is_hourly, | ||||||
| ) | ||||||
| return dataset | ||||||
|
|
||||||
|
|
||||||
| def run_tune(tune_config: dict): | ||||||
| """Run Ray Tune to find the best hyperparameters for the model. | ||||||
|
|
||||||
| Args: | ||||||
| tune_config: dictionary containing the hyperparameters to tune and their | ||||||
| ranges and other config parameters. | ||||||
| """ | ||||||
| scheduler = ASHAScheduler( | ||||||
| time_attr="training_iteration", | ||||||
| max_t=tune_config["max_num_epochs"], | ||||||
| grace_period=1, | ||||||
| reduction_factor=2, | ||||||
| ) | ||||||
|
|
||||||
| tuner = ray.tune.Tuner( | ||||||
| ray.tune.with_resources( | ||||||
| ray.tune.with_parameters(_train), | ||||||
| resources={ | ||||||
| "cpu": tune_config["cpu_per_trial"], | ||||||
| "gpu": tune_config["gpu_per_trial"], | ||||||
| }, | ||||||
| ), | ||||||
| tune_config=ray.tune.TuneConfig( | ||||||
| metric="loss", | ||||||
| mode="min", | ||||||
| scheduler=scheduler, | ||||||
| num_samples=tune_config["num_trials"], | ||||||
| max_concurrent_trials=tune_config["max_concurrent_trials"], | ||||||
| ), | ||||||
| param_space=tune_config, | ||||||
| run_config=ray.tune.RunConfig(storage_path=tune_config["run_dir"]), | ||||||
| ) | ||||||
| results = tuner.fit() | ||||||
| return results | ||||||
|
|
||||||
|
|
||||||
| def check_best_model(experiment_path: str, test_dataset: STDataset, run_dir): | ||||||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I think both paths here can also accept
Suggested change
|
||||||
| """Test the best model from a Ray Tune experiment. | ||||||
|
|
||||||
| Args: | ||||||
| experiment_path: path to the Ray Tune experiment directory | ||||||
| test_dataset: Dataset object containing the test data | ||||||
| run_dir: directory to save logs and model | ||||||
| Returns: | ||||||
| test_loss: the loss on the test dataset | ||||||
|
|
||||||
| """ | ||||||
| if not ray.is_initialized(): | ||||||
| ray.init() | ||||||
| analysis = ray.tune.ExperimentAnalysis(experiment_path) | ||||||
| best_result = analysis.get_best_trial("loss", "min") | ||||||
|
|
||||||
| batch_size = best_result.config["batch_size"] | ||||||
| device = best_result.config["device"] | ||||||
| dataloader_num_workers = best_result.config["dataloader_num_workers"] | ||||||
| best_checkpoint = best_result.checkpoint | ||||||
|
|
||||||
| model_path = f"{best_checkpoint.path}/checkpoint.pt" | ||||||
|
|
||||||
| _, test_loss = predict_monthly_var( | ||||||
| model_path, | ||||||
| test_dataset, | ||||||
| batch_size=batch_size, | ||||||
| device=device, | ||||||
| return_numpy=False, | ||||||
| save_predictions=False, | ||||||
| return_loss=True, | ||||||
| verbose=False, | ||||||
| run_dir=run_dir, | ||||||
| dataloader_num_workers=dataloader_num_workers, | ||||||
| ) | ||||||
| return test_loss | ||||||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I have some small concerns of wrapping this into a function, since this hides API of
xr.open_mfdatasetWith our current data, for Python<=3.13 this works. While I am using Python=3.14, where the CF concention changed. Then loading
input_dataandmonthly_datawill cause kernel error if not specifying chunksizes inopen_mfdataset. But this also relates to the Python version where nc files are created.Maybe we should either expose the args of open_mfdataset, or mention Python<=3.13 in
pyproject.toml?