Skip to content
Merged
Show file tree
Hide file tree
Changes from 14 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
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
115 changes: 114 additions & 1 deletion tests/utils_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,15 @@
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,
get_unique_param_names,
)


class MockComponent(BaseModel):
Expand Down Expand Up @@ -78,6 +86,111 @@ 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_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_get_unique_param_names_abbreviates_parent_components():
keys = [
"data.train.dataloader.batch_size",
"data.val.dataloader.batch_size",
"optimizer.lr",
]

assert get_unique_param_names(keys) == [
"D-T-D-batch_size",
"D-V-D-batch_size",
"O-lr",
]


def test_get_unique_param_names_handles_single_component():
assert get_unique_param_names(["batch_size"]) == ["batch_size"]


def make_dummy_config(root_dir: Path, device: str | None = None) -> ProjectConfig:
return ProjectConfig(
project_name="test_proj",
Expand Down
17 changes: 12 additions & 5 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.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



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
71 changes: 71 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,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":

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

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

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?



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), {})]

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


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

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

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


return configs


# ==========================================
# Builders (Dataset, Dataloader, Model Setup)
# ==========================================
Expand Down