Skip to content
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

Add utils for config instantiation. #250

Merged
merged 7 commits into from
May 16, 2024
Merged
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
30 changes: 29 additions & 1 deletion mart/utils/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,17 @@

import os

import hydra
from hydra import compose as hydra_compose
from hydra import initialize_config_dir
from lightning.pytorch.callbacks.callback import Callback
from omegaconf import OmegaConf

DEFAULT_VERSION_BASE = "1.2"
DEFAULT_CONFIG_DIR = "."
DEFAULT_CONFIG_NAME = "lightning.yaml"

__all__ = ["compose"]
__all__ = ["compose", "instantiate", "Instantiator", "CallbackInstantiator"]


def compose(
Expand All @@ -40,3 +43,28 @@ def compose(
cfg = cfg[key]

return cfg


def instantiate(cfg_path):
"""Instantiate an object from a Hydra yaml config file."""
config = OmegaConf.load(cfg_path)
obj = hydra.utils.instantiate(config)
return obj


class Instantiator:
def __new__(cls, cfg_path):
return instantiate(cfg_path)


class CallbackInstantiator(Callback):
"""Satisfying type checking for Lightning Callback."""

def __new__(cls, cfg_path):
obj = instantiate(cfg_path)
if isinstance(obj, Callback):
return obj
else:
raise ValueError(
f"We expect to instantiate a lightning Callback from {cfg_path}, but we get {type(obj)} instead."
)
Loading