Repository navigation
Improve grid search configuration handling - #205
Conversation
…t statements and run folders
✅ Deploy Preview for trainite canceled.
|
|
hi, how do you propose to make run/sweep to be easily identified, by current code each run/sweep will have same name when being saved and hard to differentiate. |
|
Hi @aaishwarymishra , apologoies if im misinterpreting your query. 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 namesAnd this logic below in 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}"Lets take an example (took this from pr #191 ) sweep:
optimizer:
lr: [0.001, 0.0005]
data:
train:
dataloader:
batch_size: [16, 32]one generated config name will have if you're asking how user will know what combination is running atm , the below code is responsible for i, (config, active_params) in enumerate(configs):
if active_params:
display_params = ", ".join([f"{k}={v}" for k, v in active_params.items()])
print(f"\n=== Starting Grid Search Run {i + 1} of {len(configs)} ({display_params}) ===")
trainer = Trainer(config)
trainer.run()so header will look like : |
|
As previously stated , this naming logic has possible collision when 2 differnent nested fields have all the same first letter in hierarchy as well as final parameter is exactly same data:
train:
batch_size: [16,32]
dataset:
train:
batch_size: [16,32]will have collision , but im unsure of possible fields and maybe such a case cant practically happen |
| from trainite.shared.utils import load_config | ||
| from trainite.trainers.decoder_trainer import Trainer, ProjectConfig | ||
| from trainite.shared.utils import load_grid_configs | ||
| from trainite.trainers.decoder_trainer import ProjectConfig, Trainer |
There was a problem hiding this comment.
| from trainite.trainers.decoder_trainer import ProjectConfig, Trainer | |
| from trainite.trainers.decoder_trainer import Trainer, ProjectConfig |
non-needed change.
There was a problem hiding this comment.
This change was from pr #191 itself
will revert
| 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)) |
There was a problem hiding this comment.
is it allowed to validate the configuration directly before converting to dictionary? Can you check?
There was a problem hiding this comment.
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 == convertedThere was a problem hiding this comment.
@tamrind69 While both works, prior to this PR, we were using load_config which converts to dictionary before model_validate:
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 DictConfig
We should also add a test to verify that we are getting configs as dictionary rather than DictConfig
| 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 |
There was a problem hiding this comment.
what is purpose of this? Also, this actually doesn't gurantee uniqueness. For instance, between data.train.dataloader.batch_size and data.test.dataloader.batch_size
There was a problem hiding this comment.
Any suggestions for a naming convention?
There was a problem hiding this comment.
why not use full dotted paths instead?
| 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)) |
There was a problem hiding this comment.
This could fail for the following case:
sweep:
optimizer:
lr = []There was a problem hiding this comment.
agreed
will add empty parameter check before
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)| 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": |
There was a problem hiding this comment.
i dont think its possible for there to be a dictconfig since we used to_container prior to calling this function.
There was a problem hiding this comment.
hmm , right
we already do OmegaConf.to_container() before in load_config() so this is redundant
ill remove this
| keys = list(flat_sweep_params.keys()) | ||
|
|
||
| # Safely handle explicit nulls in the YAML | ||
| for key in keys: |
There was a problem hiding this comment.
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?
| 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 |
There was a problem hiding this comment.
why not use full dotted paths instead?
|
The changes made from the last commit are : 1Full dotted path names ( 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}"2Removed redundant dictconfig check ( if isinstance(v, dict):
items.extend(flatten_sweep_config(v, new_key, sep=sep).items())
continue3Added check for empty parameter list ( 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 this case def test_load_grid_configs_allows_null_base_value(tmp_path):
class NullableConfig(BaseModel):
optimizer: dict[str, float | None]
config_file = tmp_path / "config_null.yaml"
config_file.write_text("optimizer:\n lr: null\nsweep:\n optimizer:\n lr: [0.01, 0.001]\n")
configs = load_grid_configs(config_file, NullableConfig)
assert len(configs) == 2
assert [config.optimizer["lr"] for config, _ in configs] == [0.01, 0.001]4
|
TahaZahid05
left a comment
There was a problem hiding this comment.
Last pass of comments. Rest looks fine! We can move to documentation once we address these.
| 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)) |
There was a problem hiding this comment.
@tamrind69 While both works, prior to this PR, we were using load_config which converts to dictionary before model_validate:
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 DictConfig
We should also add a test to verify that we are getting configs as dictionary rather than DictConfig
| del base_run_conf["sweep"] | ||
|
|
||
| if not sweep_params: | ||
| return [(config_cls.model_validate(base_run_conf), {})] |
There was a problem hiding this comment.
same here. need to convert before model_validate
|
This commit is addressing the last review comments and adding docs. Below is overview of what changed. 1
essentially config_cls.model_validate(config)is now config_cls.model_validate(OmegaConf.to_container(config))2changes to below example structure added in the yaml structure example sweep:
optimizer:
lr: [0.0001, 0.0003, 0.001]description added under
this line modified in the
3Essentially the same change to the |
|
Thanks @tamrind69! |
Summary
This PR builds on the grid-search implementation in #191. I made a few changes based on the review and while testing different edge cases.
1. Moved run-name generation into
utils.pyPreviously, the logic for generating run-name suffixes was in
main.py. I moved it intoload_grid_configs()(following the review suggestion).so below logic is in
load_grid_configs(),get_unique_param_names()is discussed below2. Validate sweep exists before generating combinations once
Sweep keys were previously validated while processing each combination. I just moved the validation outside that loop(as per review comment) .
So this block is basically run once:
3. Require nested YAML for sweep parameters
A key such as
optimizer.lrwas earlier accepted by the flattening logic , changed so that is a ValueErrorSo this logic inside of
flatten_sweep_config()sep is just "."
4. Simplified run names when there are no sweep parameters
Removed the redundant run-name handling from
main.py.Now if no active_params , no different header gen
5. Abbreviated parent components in generated run names
I went with the first letter of each parent component and the full name of the final one. This keeps run names reasonably short but I'd want feedback on this. (Hypothetically there can be a collision if there are 2 parents with identical first letter and all children also having identical first letter as well as last child exactly same.)
example abbreviation:
I'm open to suggestions for better naming.
Testing
null-valued base parameters, flattened sweep keys, and parameter-name generation.uv run pytest: 159 passed, 1 deselected.git diff --checkpassed.I'll add documentation changes after getting feedback on the implementation.
AI usage
Tool(s) and usage:
ChatGPT was used to discuss implementation approaches, review edge cases, and suggest tests. I implemented the changes and ran the test suite.
Testing checklist