Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion docs/training.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,10 @@ output:
logger: tensorboard
seed: 42
device: null

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

### How `_target_` works
Expand Down Expand Up @@ -107,6 +111,8 @@ Note that `dataloader` blocks accept standard PyTorch `DataLoader` options (such

**`device`** — `cpu`, `cuda`, or `null` to let Trainite pick automatically via PyTorch-Ignite's distributed utilities.

**`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

### Starter component choices

`trainite init` currently provides:
Expand Down Expand Up @@ -141,7 +147,7 @@ python main.py config.yaml

What happens under the hood:

1. The YAML is loaded and validated into a `ProjectConfig` instance.
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.
2. The preprocessor, model, and dataset/transform components are instantiated from their `_target_` entries. DataLoaders are constructed from the `dataloader` options and `collate_fn_target`. The optimizer is created with the model parameters.
3. Logging, metrics, and the output directory are set up.
4. `trainer.run()` starts the PyTorch-Ignite training loop — running epochs, evaluating on the validation set, saving checkpoints, and optionally running test evaluation at the end.
Expand Down
29 changes: 29 additions & 0 deletions tests/cli_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -459,6 +459,35 @@ def test_init_without_sky_flag_default(tmp_path):
assert "skypilot" not in pyproject_content


def test_generated_project_grid_search_logic() -> None:
"""Verifies that generated utils.py and main.py support parameter sweeping."""
with tempfile.TemporaryDirectory() as temp_dir:
project_dir = Path(temp_dir) / "sweep-test-project"

subprocess.run(
[
sys.executable,
"-m",
"trainite.cli",
"init",
"--model",
"rope-transformer",
"--dataset",
"counting",
"--trainer",
"decoder-trainer",
str(project_dir),
],
check=True,
)

generated_utils = (project_dir / "utils.py").read_text()
generated_main = (project_dir / "main.py").read_text()

assert "def load_grid_configs" in generated_utils
assert "load_grid_configs" in generated_main


def _recreation_command(project_dir: Path) -> str:
line = next(line for line in (project_dir / "README.md").read_text().splitlines() if "trainite init" in line)
return line.lstrip("> ").strip()
Expand Down
122 changes: 121 additions & 1 deletion tests/utils_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,14 @@
SplitConfig,
TrainerConfig,
)
from trainite.shared.utils import create_accelerator, create_run_dir, get_target, instantiate, dump_config, load_config
from trainite.shared.utils import (
create_accelerator,
create_run_dir,
get_target,
instantiate,
dump_config,
load_config,
)


class MockComponent(BaseModel):
Expand Down Expand Up @@ -78,6 +85,119 @@ def test_instantiate_kwargs_override():
assert result == {"key": "override"}


# ==========================================
# Grid Search Tests
# ==========================================

from trainite.shared.utils import load_grid_configs


class OptimizerConfig(BaseModel):
lr: float = 0.001


class MockSweepConfig(BaseModel):
optimizer: OptimizerConfig = Field(default_factory=OptimizerConfig)
batch_size: int = 32
notes: str = "default"


def test_load_grid_configs_no_sweep(tmp_path):
config_file = tmp_path / "config.yaml"
config_file.write_text("optimizer:\n lr: 0.01\nbatch_size: 16\nnotes: test\n")

configs = load_grid_configs(config_file, MockSweepConfig)
assert len(configs) == 1

config, params = configs[0]
assert config.optimizer.lr == 0.01
assert config.batch_size == 16
assert params == {}


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\nsweep:\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)


def test_load_grid_configs_with_nested_sweep(tmp_path):
config_file = tmp_path / "config_sweep.yaml"
yaml_content = (
"optimizer:\n"
" lr: 0.01\n"
"batch_size: 16\n"
"notes: test\n"
"sweep:\n"
" optimizer:\n"
" lr: [0.01, 0.001]\n"
" batch_size: [16, 64]\n"
)
config_file.write_text(yaml_content)

configs = load_grid_configs(config_file, MockSweepConfig)
assert len(configs) == 4

combos = {(c[0].optimizer.lr, c[0].batch_size) for c in configs}
assert combos == {
(0.01, 16),
(0.01, 64),
(0.001, 16),
(0.001, 64),
}


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]


def test_load_grid_configs_rejects_flattened_sweep_keys(tmp_path):
config_file = tmp_path / "config_flattened.yaml"
yaml_content = "optimizer:\n lr: 0.01\nbatch_size: 16\nsweep:\n optimizer.lr: [0.01, 0.001]\n"
config_file.write_text(yaml_content)

with pytest.raises(ValueError, match="nested"):
load_grid_configs(config_file, MockSweepConfig)


def test_load_grid_configs_sweep_typo(tmp_path):
config_file = tmp_path / "config_typo.yaml"
yaml_content = "optimizer:\n lr: 0.01\nbatch_size: 16\nsweep:\n optimizer:\n lrr: [0.01, 0.001]\n"
config_file.write_text(yaml_content)

with pytest.raises(KeyError, match="Sweep key 'optimizer.lrr' does not exist"):
load_grid_configs(config_file, MockSweepConfig)


def test_load_grid_configs_returns_dictionary(tmp_path):
class DictionaryCheckingConfig(BaseModel):
@classmethod
def model_validate(cls, obj, **kwargs):
assert isinstance(obj, dict)
return super().model_validate(obj, **kwargs)

name: str

config_file = tmp_path / "config.yaml"
config_file.write_text("name: test\n")

load_grid_configs(config_file, DictionaryCheckingConfig)


def make_dummy_config(root_dir: Path, device: str | None = None) -> ProjectConfig:
return ProjectConfig(
project_name="test_proj",
Expand Down
15 changes: 11 additions & 4 deletions trainite/shared/main.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,24 @@
import argparse
from pathlib import Path

from trainite.shared.utils import load_config
from trainite.shared.utils import load_grid_configs
from trainite.trainers.decoder_trainer import Trainer, ProjectConfig


def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("config", nargs="?", default="config.yaml")
args = parser.parse_args()
config = load_config(Path(args.config), ProjectConfig)
trainer = Trainer(config)
trainer.run()

configs = load_grid_configs(Path(args.config), ProjectConfig)

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


if __name__ == "__main__":
Expand Down
62 changes: 62 additions & 0 deletions trainite/shared/utils.py
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
Expand Down Expand Up @@ -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:

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?

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

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)


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)
# ==========================================
Expand Down
19 changes: 19 additions & 0 deletions trainite/templates/project/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -210,5 +210,24 @@ data:
1. Add the parameter to `config.yaml`.
2. (Optional) Update the corresponding Pydantic model in `config.py` if you want strict validation and IDE autocomplete for custom fields.

### Grid Search / Hyperparameter Sweeps
Trainite supports grid search through the optional sweep section in `config.yaml`. Specify the parameters to explore using the same nested structure as the main configuration, with a list of candidate values for each parameter.

For example, to try three learning rates:
```yaml
optimizer:
_target_: torch.optim.AdamW
lr: 0.0003

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

Trainite generates a training run for each combination of sweep parameter values. Parameters not specified in sweep retain their base configuration values.

Run the sweep using the usual command:
`uv run python main.py config.yaml`

## Design Philosophy
The code generated here is yours. There are no hidden abstractions or magic imports. Feel free to refactor or rewrite any part of it to suit your research needs.
Loading