Repository navigation
Improve grid search configuration handling #205
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
Merged
TahaZahid05
merged 18 commits into
pytorch-ignite:main
from
tamrind69:study/pr-191-review-fixes
Oct 29, 2026
Merged
Changes from all commits
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
b564ee4
feat: implement grid search parameter sweeping using itertools
Arun-sunny23 1282b1a
Merge branch 'main' into feature/grid-search
Arun-sunny23 2c987b0
style: apply automatic pre-commit formatting fixes
Arun-sunny23 23af8f4
Merge branch 'main' into feature/grid-search
Arun-sunny23 5ba73d2
feat: implement grid search config loading and generator tests
Arun-sunny23 dc0fa3c
style: apply ruff formatting
Arun-sunny23 60e9cfe
chore: revert changes to existing examples
Arun-sunny23 e66a6fe
Merge branch 'main' into feature/grid-search
Arun-sunny23 281666e
refactor: support nested sweep yaml, add typo validation, update prin…
aa45001
style: apply ruff formatting and end-of-file fixes
06eb6f2
refactor: optimize grid search logic based on review feedback
0b29672
style: fix formatting issues
707c3ed
Improve grid sweep configuration handling
tamrind69 c4eebf7
Merge remote-tracking branch 'origin/main' into study/pr-191-review-f…
tamrind69 48c8026
fix: validate grid sweep parameters
tamrind69 5b3a93f
style: fixed import
tamrind69 c7ad3b0
dict validation and grid search to docs
tamrind69 a231f4b
Merge branch 'main' into study/pr-191-review-fixes
tamrind69 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,5 +1,6 @@ | ||
| import importlib | ||
| import inspect | ||
| import itertools | ||
| import logging | ||
| import os | ||
| from datetime import datetime | ||
|
|
@@ -139,6 +140,67 @@ def load_config(path: str | Path, config_cls: type[T]) -> T: | |
| return config_cls.model_validate(OmegaConf.to_container(raw_conf, resolve=True)) | ||
|
|
||
|
|
||
| def flatten_sweep_config(d: dict, parent_key: str = "", sep: str = ".") -> dict: | ||
| items = [] | ||
| for k, v in d.items(): | ||
| if sep in k: | ||
| raise ValueError(f"Sweep keys must use nested YAML, not flattened keys: '{k}'") | ||
| new_key = f"{parent_key}{sep}{k}" if parent_key else k | ||
| if isinstance(v, dict): | ||
| items.extend(flatten_sweep_config(v, new_key, sep=sep).items()) | ||
| continue | ||
| items.append((new_key, v)) | ||
| return dict(items) | ||
|
|
||
|
|
||
| def load_grid_configs(path: str | Path, config_cls: type[T]) -> list[tuple[T, dict[str, Any]]]: | ||
| raw_conf = OmegaConf.load(path) | ||
| sweep_params = raw_conf.get("sweep", None) | ||
|
|
||
| # Delete sweep block once upfront | ||
| base_run_conf = raw_conf.copy() | ||
| if "sweep" in base_run_conf: | ||
| del base_run_conf["sweep"] | ||
|
|
||
| if not sweep_params: | ||
| return [(config_cls.model_validate(OmegaConf.to_container(base_run_conf, resolve=True)), {})] | ||
|
|
||
| sweep_params_dict = OmegaConf.to_container(sweep_params, resolve=True) | ||
| flat_sweep_params = flatten_sweep_config(sweep_params_dict) | ||
|
|
||
| keys = list(flat_sweep_params.keys()) | ||
|
|
||
| # Safely handle explicit nulls in the YAML | ||
| for key in keys: | ||
| if OmegaConf.select(base_run_conf, key, default="__MISSING__") == "__MISSING__": | ||
| raise KeyError(f"Sweep key '{key}' does not exist in the base configuration.") | ||
|
|
||
| for key, value in flat_sweep_params.items(): | ||
| if isinstance(value, list) and not value: | ||
| raise ValueError(f"Sweep parameter '{key}' must contain at least one value.") | ||
|
|
||
| values = [v if isinstance(v, list) else [v] for v in flat_sweep_params.values()] | ||
| combinations = list(itertools.product(*values)) | ||
|
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. This could fail for the following case: sweep:
optimizer:
lr = []
Contributor
Author
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. agreed for key, value in flat_sweep_params.items():
if isinstance(value, list) and not value:
raise ValueError(
f"Sweep parameter '{key}' must contain at least one value."
)
values = [v if isinstance(v, list) else [v] for v in flat_sweep_params.values()]
combinations = list(itertools.product(*values))also a test for your given example def test_load_grid_configs_rejects_empty_sweep_parameter(tmp_path):
config_file = tmp_path / "config_empty_sweep.yaml"
config_file.write_text(
"optimizer:\n"
" lr: 0.01\n"
"sweep:\n"
" optimizer:\n"
" lr: []\n"
)
with pytest.raises(
ValueError,
match="Sweep parameter 'optimizer.lr' must contain at least one value",
):
load_grid_configs(config_file, MockSweepConfig) |
||
|
|
||
| configs = [] | ||
| for combo in combinations: | ||
| run_conf = base_run_conf.copy() | ||
| combo_dict = {} | ||
|
|
||
| for key, val in zip(keys, combo): | ||
| OmegaConf.update(run_conf, key, val) | ||
| combo_dict[key] = val | ||
|
|
||
| if combo_dict: | ||
| name_suffix = "_".join(f"{key}={value}" for key, value in combo_dict.items()) | ||
| if OmegaConf.select(run_conf, "output.run_name") is not None: | ||
| run_conf.output.run_name = f"{run_conf.output.run_name}_{name_suffix}" | ||
|
|
||
| configs.append((config_cls.model_validate(OmegaConf.to_container(run_conf, resolve=True)), combo_dict)) | ||
|
|
||
| return configs | ||
|
|
||
|
|
||
| # ========================================== | ||
| # Builders (Dataset, Dataloader, Model Setup) | ||
| # ========================================== | ||
|
|
||
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
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.
this seems weird to me. It feels quite restrictive that for a parameter to be used in sweep, it needs to be mentioned in the yaml as well. @aaishwarymishra any thoughts on this?