|
| 1 | +import os |
| 2 | +import json |
| 3 | +import dataclasses |
| 4 | +from typing import Any, Type, TypeVar |
| 5 | + |
| 6 | +from sagemaker.modules import logger |
| 7 | + |
| 8 | +T = TypeVar("T") |
| 9 | + |
| 10 | + |
| 11 | +class DictConfig: |
| 12 | + """Class that supports both dict and dot notation access""" |
| 13 | + |
| 14 | + def __init__(self, **kwargs): |
| 15 | + # Store the original dict |
| 16 | + self._data = kwargs |
| 17 | + |
| 18 | + # Set all items as attributes for dot notation |
| 19 | + for key, value in kwargs.items(): |
| 20 | + # Recursively convert nested dicts to DictConfig |
| 21 | + if isinstance(value, dict): |
| 22 | + value = DictConfig(**value) |
| 23 | + setattr(self, key, value) |
| 24 | + |
| 25 | + def __getitem__(self, key: str) -> Any: |
| 26 | + """Enable dictionary-style access: config['key']""" |
| 27 | + return self._data[key] |
| 28 | + |
| 29 | + def __setitem__(self, key: str, value: Any): |
| 30 | + """Enable dictionary-style assignment: config['key'] = value""" |
| 31 | + self._data[key] = value |
| 32 | + setattr(self, key, value) |
| 33 | + |
| 34 | + def __str__(self) -> str: |
| 35 | + """String representation""" |
| 36 | + return str(self._data) |
| 37 | + |
| 38 | + def __repr__(self) -> str: |
| 39 | + """Detailed string representation""" |
| 40 | + return f"DictConfig({self._data})" |
| 41 | + |
| 42 | + |
| 43 | +class Hyperparameters: |
| 44 | + """Class to load hyperparameters in training container.""" |
| 45 | + |
| 46 | + @staticmethod |
| 47 | + def load() -> DictConfig: |
| 48 | + """Loads hyperparameters in training container |
| 49 | +
|
| 50 | + Example: |
| 51 | +
|
| 52 | + .. code:: python |
| 53 | + from sagemaker.modules.hyperparameters import Hyperparameters |
| 54 | +
|
| 55 | + hps = Hyperparameters.load() |
| 56 | + print(hps.batch_size) |
| 57 | +
|
| 58 | + Returns: |
| 59 | + DictConfig: hyperparameters as a DictConfig object |
| 60 | + """ |
| 61 | + hps = json.loads(os.environ.get("SM_HPS", "{}")) |
| 62 | + if not hps: |
| 63 | + logger.warning("No hyperparameters found in SM_HPS environment variable.") |
| 64 | + return DictConfig(**hps) |
| 65 | + |
| 66 | + @staticmethod |
| 67 | + def load_structured(dataclass_type: Type[T]) -> T: |
| 68 | + """Loads hyperparameters as a structured dataclass |
| 69 | +
|
| 70 | + Example: |
| 71 | +
|
| 72 | + .. code:: python |
| 73 | + from sagemaker.modules.hyperparameters import Hyperparameters |
| 74 | +
|
| 75 | + @dataclass |
| 76 | + class TrainingConfig: |
| 77 | + batch_size: int |
| 78 | + learning_rate: float |
| 79 | +
|
| 80 | + config = Hyperparameters.load_structured(TrainingConfig) |
| 81 | + print(config.batch_size) # typed int |
| 82 | +
|
| 83 | + Args: |
| 84 | + dataclass_type: Dataclass type to structure the config |
| 85 | +
|
| 86 | + Returns: |
| 87 | + dataclass_type: Instance of provided dataclass type |
| 88 | + """ |
| 89 | + |
| 90 | + if not dataclasses.is_dataclass(dataclass_type): |
| 91 | + raise ValueError(f"{dataclass_type} is not a dataclass type.") |
| 92 | + |
| 93 | + hps = json.loads(os.environ.get("SM_HPS", "{}")) |
| 94 | + if not hps: |
| 95 | + logger.warning("No hyperparameters found in SM_HPS environment variable.") |
| 96 | + |
| 97 | + # Convert hyperparameters to dataclass |
| 98 | + return dataclass_type(**hps) |
0 commit comments