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
Changes from 14 commits
b564ee4
1282b1a
2c987b0
23af8f4
5ba73d2
dc0fa3c
60e9cfe
e66a6fe
281666e
aa45001
06eb6f2
0b29672
707c3ed
c4eebf7
48c8026
5b3a93f
c7ad3b0
a231f4b
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| 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,76 @@ 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) or type(v).__name__ == "DictConfig": | ||
|
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 dont think its possible for there to be a dictconfig since we used
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. hmm , right |
||
| items.extend(flatten_sweep_config(v, new_key, sep=sep).items()) | ||
| continue | ||
| items.append((new_key, v)) | ||
| return dict(items) | ||
|
|
||
|
|
||
| def get_unique_param_names(keys: list[str]) -> list[str]: | ||
| """Abbreviate parent components using their uppercase initials.""" | ||
| names = [] | ||
|
|
||
| for key in keys: | ||
| parts = key.split(".") | ||
| parent_initials = [part[0].upper() for part in parts[:-1]] | ||
| names.append("-".join([*parent_initials, parts[-1]])) | ||
|
|
||
| return names | ||
|
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. what is purpose of this? Also, this actually doesn't gurantee uniqueness. For instance, between
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. Any suggestions for a naming convention?
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. why not use full dotted paths instead? |
||
|
|
||
|
|
||
| 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(base_run_conf), {})] | ||
|
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. same here. need to convert before |
||
|
|
||
| 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: | ||
|
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 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? |
||
| if OmegaConf.select(base_run_conf, key, default="__MISSING__") == "__MISSING__": | ||
| raise KeyError(f"Sweep key '{key}' does not exist in the base configuration.") | ||
|
|
||
| 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: | ||
| short_keys = get_unique_param_names(list(combo_dict.keys())) | ||
| name_suffix = "_".join(f"{key}={value}" for key, value in zip(short_keys, combo_dict.values())) | ||
| 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(run_conf), combo_dict)) | ||
|
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. is it allowed to validate the configuration directly before converting to dictionary? Can you check?
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. checked , both validation works , used this temporary test def test_pydantic_validation_input_types():
conf = OmegaConf.create({
"optimizer": {"lr": 0.01},
"batch_size": 16,
"notes": "test",
})
# Validate the OmegaConf DictConfig directly.
direct = MockSweepConfig.model_validate(conf)
# Convert it to a regular Python dictionary first.
converted = MockSweepConfig.model_validate(
OmegaConf.to_container(conf, resolve=True)
)
assert direct == converted
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. @tamrind69 While both works, prior to this PR, we were using def load_config(path: str | Path, config_cls: type[T]) -> T:
raw_conf = OmegaConf.load(path)
# PyYAML cannot serialize OmegaConf's DictConfig and ListConfig objects when the resolved config is saved.
return config_cls.model_validate(OmegaConf.to_container(raw_conf, resolve=True))I think we should stick to converting to dictionary since the loggers, clearml, and other things expect dictionary rather than We should also add a test to verify that we are getting configs as dictionary rather than |
||
|
|
||
| return configs | ||
|
|
||
|
|
||
| # ========================================== | ||
| # Builders (Dataset, Dataloader, Model Setup) | ||
| # ========================================== | ||
|
|
||
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.
non-needed change.
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 change was from pr #191 itself
will revert