Skip to content

Improve grid search configuration handling - #205

Merged
TahaZahid05 merged 18 commits into
pytorch-ignite:mainfrom
tamrind69:study/pr-191-review-fixes
Oct 29, 2026
Merged

TahaZahid05 merged 18 commits into
pytorch-ignite:mainfrom
tamrind69:study/pr-191-review-fixes

Conversation

@tamrind69

Copy link
Copy Markdown
Contributor

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.py

Previously, the logic for generating run-name suffixes was in main.py. I moved it into load_grid_configs() (following the review suggestion).

so below logic is in load_grid_configs() , get_unique_param_names() is discussed below

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())
    )

2. 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:

if "sweep" in base_run_conf:
        del base_run_conf["sweep"]

3. Require nested YAML for sweep parameters

A key such as optimizer.lr was earlier accepted by the flattening logic , changed so that is a ValueError

So this logic inside of flatten_sweep_config()
sep is just "."

for k, v in d.items():
    if sep in k:
        raise ValueError(
            f"Sweep keys must use nested YAML, not flattened keys: '{k}'"
        )

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

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()

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:

data.train.dataloader.batch_size -> D-T-D-batch_size
data.val.dataloader.batch_size   -> D-V-D-batch_size
optimizer.lr                     -> O-lr

I'm open to suggestions for better naming.

Testing

  • Added regression tests for null-valued base parameters, flattened sweep keys, and parameter-name generation.
  • Ran uv run pytest: 159 passed, 1 deselected.
  • Pre-commit checks passed after applying Ruff formatting.
  • git diff --check passed.

I'll add documentation changes after getting feedback on the implementation.

AI usage

  • No AI tools were used for this contribution
  • AI tools were used to assist this contribution

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

  • Tests added or updated where needed
  • Existing tests and checks pass
  • Documentation updated if needed

@netlify

netlify Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for trainite canceled.

Name Link
🔨 Latest commit a231f4b
🔍 Latest deploy log https://app.netlify.com/projects/trainite/deploys/6ae1c3e474e6a7b6ec64efa7

@aaishwarymishra

Copy link
Copy Markdown
Member

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.

@tamrind69

Copy link
Copy Markdown
Contributor Author

Hi @aaishwarymishra , apologoies if im misinterpreting your query.
As explained above , the below function in shared/utils.py is used to generate the abbreviated names i mentioned

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

And this logic below in load_grid_configs() is used to combine them to generate a run name for the config

        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 output.run_name field as
O-lr=0.001_D-T-D-batch_size=16 and so on

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 :
=== Starting Grid Search Run 1 of 4 (optimizer.lr=0.001, data.train.dataloader.batch_size=16) ===

@tamrind69

Copy link
Copy Markdown
Contributor Author

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
So something like

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
open to discuss another approach

Comment thread trainite/shared/main.py Outdated
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

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
from trainite.trainers.decoder_trainer import ProjectConfig, Trainer
from trainite.trainers.decoder_trainer import Trainer, ProjectConfig

non-needed change.

Copy link
Copy Markdown
Contributor Author

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

Comment thread trainite/shared/utils.py Outdated
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))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The 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?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The 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

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@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

Comment thread trainite/shared/utils.py Outdated
Comment on lines +156 to +165
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

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The 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 data.train.dataloader.batch_size and data.test.dataloader.batch_size

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Any suggestions for a naming convention?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why not use full dotted paths instead?

Comment thread trainite/shared/utils.py
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))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This could fail for the following case:

sweep:
  optimizer:
      lr = []

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)

Comment thread trainite/shared/utils.py Outdated
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":

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The 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 to_container prior to calling this function.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hmm , right
we already do OmegaConf.to_container() before in load_config() so this is redundant
ill remove this

Comment thread trainite/shared/utils.py
keys = list(flat_sweep_params.keys())

# Safely handle explicit nulls in the YAML
for key in keys:

Copy link
Copy Markdown
Collaborator

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?

Comment thread trainite/shared/utils.py Outdated
Comment on lines +156 to +165
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

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why not use full dotted paths instead?

@tamrind69

Copy link
Copy Markdown
Contributor Author

The changes made from the last commit are :

1

Full dotted path names (utils.py\load_grid_configs())

  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}"

2

Removed redundant dictconfig check (utils.py\flatten_sweep_config())

if isinstance(v, dict):
  items.extend(flatten_sweep_config(v, new_key, sep=sep).items())
  continue

3

Added check for empty parameter list (utils.py\load_grid_configs())

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 tests\utils_test.py

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 TahaZahid05 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Last pass of comments. Rest looks fine! We can move to documentation once we address these.

Comment thread trainite/shared/utils.py Outdated
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))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@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

Comment thread trainite/shared/utils.py Outdated
del base_run_conf["sweep"]

if not sweep_params:
return [(config_cls.model_validate(base_run_conf), {})]

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same here. need to convert before model_validate

@tamrind69

Copy link
Copy Markdown
Contributor Author

This commit is addressing the last review comments and adding docs. Below is overview of what changed.

1

load_grid_configs() now only converts the configs to dicts before validation as it was before this pr.

essentially

config_cls.model_validate(config)

is now

config_cls.model_validate(OmegaConf.to_container(config))

2

changes to training.md :

below example structure added in the yaml structure example

sweep:
  optimizer:
    lr: [0.0001, 0.0003, 0.001]

description added under Configuration blocks

sweep — Optional grid-search configuration. Specify the parameters to explore using the same nested structure as the main configuration, with a list of candidate values for each parameter. Trainite generates and runs every combination of the specified values, while parameters not included in sweep retain their base configuration values


this line modified in the Running training part

  1. The YAML is loaded. If a sweep section is present, Trainite generates all combinations of the specified parameter values; otherwise, it creates a single configuration. Each configuration is validated into a ProjectConfig instance.

3

Essentially the same change to the Readme.md template under templates\project

@TahaZahid05
TahaZahid05 merged commit ae582a1 into pytorch-ignite:main Oct 29, 2026
11 checks passed
@TahaZahid05

Copy link
Copy Markdown
Collaborator

Thanks @tamrind69!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants