Skip to content

yaml_model_schema

Module for handling YAML configuration files and converting them to Ray Tune format.

Classes:

CustomTunableParameter

Bases: BaseModel

Custom tunable parameter.

Data

Bases: BaseModel

Data parameters.

Loss

Bases: BaseModel

Loss parameters.

Model

Bases: BaseModel

Model configuration.

RayTuneModel

Bases: BaseModel

Ray Tune compatible model configuration.

RunParams

Bases: BaseModel

Run parameters.

Scheduler

Bases: BaseModel

Scheduler parameters.

TunableParameter

Bases: BaseModel

Tunable parameter.

Methods:

validate_mode

validate_mode() -> TunableParameter

Validate that mode is supported by Ray Tune.

Source code in src/stimulus/utils/yaml_model_schema.py
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
@pydantic.model_validator(mode="after")
def validate_mode(self) -> "TunableParameter":
    """Validate that mode is supported by Ray Tune."""
    if not hasattr(tune, self.mode):
        raise AttributeError(
            f"Mode {self.mode} not recognized, check the ray.tune documentation at https://docs.ray.io/en/master/tune/api_docs/suggestion.html",
        )

    mode = getattr(tune, self.mode)
    if mode.__name__ not in [
        "choice",
        "uniform",
        "loguniform",
        "quniform",
        "qloguniform",
        "qnormal",
        "randint",
        "sample_from",
    ]:
        raise NotImplementedError(f"Mode {mode.__name__} not implemented yet")

    return self

Tune

Bases: BaseModel

Tune parameters.

TuneParams

Bases: BaseModel

Tune parameters.

YamlRayConfigLoader

YamlRayConfigLoader(model: Model)

Load and convert YAML configurations to Ray Tune format.

This class handles loading model configurations and converting them into formats compatible with Ray Tune's hyperparameter search spaces.

Parameters:

  • model (Model) –

    Pydantic Model instance containing configuration

Methods:

Source code in src/stimulus/utils/yaml_model_schema.py
127
128
129
130
131
132
133
134
def __init__(self, model: Model) -> None:
    """Initialize the config loader with a Model instance.

    Args:
        model: Pydantic Model instance containing configuration
    """
    self.model = model
    self.ray_model = self.convert_config_to_ray(model)

convert_config_to_ray

convert_config_to_ray(model: Model) -> RayTuneModel

Convert Model configuration to Ray Tune format.

Converts parameters in network_params and optimizer_params to Ray Tune search spaces.

Parameters:

  • model (Model) –

    Model configuration

Returns:

Source code in src/stimulus/utils/yaml_model_schema.py
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
def convert_config_to_ray(self, model: Model) -> RayTuneModel:
    """Convert Model configuration to Ray Tune format.

    Converts parameters in network_params and optimizer_params to Ray Tune search spaces.

    Args:
        model: Model configuration

    Returns:
        Ray Tune compatible model configuration
    """
    return RayTuneModel(
        network_params={k: self.convert_raytune(v) for k, v in model.network_params.items()},
        optimizer_params={k: self.convert_raytune(v) for k, v in model.optimizer_params.items()},
        loss_params={k: self.convert_raytune(v) for k, v in model.loss_params},
        data_params={k: self.convert_raytune(v) for k, v in model.data_params},
        tune=model.tune,
    )

convert_raytune

convert_raytune(
    param: TunableParameter | CustomTunableParameter,
) -> Any

Convert parameter configuration to Ray Tune format.

Parameters:

Returns:

  • Any

    Ray Tune compatible parameter configuration

Source code in src/stimulus/utils/yaml_model_schema.py
169
170
171
172
173
174
175
176
177
178
179
180
181
182
def convert_raytune(self, param: TunableParameter | CustomTunableParameter) -> Any:
    """Convert parameter configuration to Ray Tune format.

    Args:
        param: Parameter configuration

    Returns:
        Ray Tune compatible parameter configuration
    """
    mode = getattr(tune, param.mode)

    if isinstance(param, TunableParameter):
        return self.raytune_space_selector(mode, param.space)
    return self.raytune_sample_from(mode, param)

get_config

get_config() -> RayTuneModel

Return the current configuration.

Returns:

Source code in src/stimulus/utils/yaml_model_schema.py
203
204
205
206
207
208
209
def get_config(self) -> RayTuneModel:
    """Return the current configuration.

    Returns:
        Current configuration dictionary
    """
    return self.ray_model

raytune_sample_from

raytune_sample_from(
    mode: Callable, param: CustomTunableParameter
) -> Any

Apply tune.sample_from to a given custom sampling function.

Parameters:

Returns:

  • Any

    Configured sampling function

Raises:

Source code in src/stimulus/utils/yaml_model_schema.py
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
def raytune_sample_from(self, mode: Callable, param: CustomTunableParameter) -> Any:
    """Apply tune.sample_from to a given custom sampling function.

    Args:
        mode: Ray Tune sampling function
        param: TunableParameter containing sampling parameters

    Returns:
        Configured sampling function

    Raises:
        NotImplementedError: If the sampling function is not supported
    """
    if param.function == "sampint":
        return mode(lambda _: self.sampint(param.sample_space, param.n_space))

    raise NotImplementedError(f"Function {param.function} not implemented yet")

raytune_space_selector

raytune_space_selector(mode: Callable, space: list) -> Any

Convert space parameters to Ray Tune format based on the mode.

Parameters:

  • mode (Callable) –

    Ray Tune search space function (e.g., tune.choice, tune.uniform)

  • space (list) –

    List of parameters defining the search space

Returns:

  • Any

    Configured Ray Tune search space

Source code in src/stimulus/utils/yaml_model_schema.py
136
137
138
139
140
141
142
143
144
145
146
147
148
149
def raytune_space_selector(self, mode: Callable, space: list) -> Any:
    """Convert space parameters to Ray Tune format based on the mode.

    Args:
        mode: Ray Tune search space function (e.g., tune.choice, tune.uniform)
        space: List of parameters defining the search space

    Returns:
        Configured Ray Tune search space
    """
    if mode.__name__ == "choice":
        return mode(space)

    return mode(*tuple(space))

sampint staticmethod

sampint(sample_space: list, n_space: list) -> list[int]

Return a list of n random samples from the sample_space.

This function is useful for sampling different numbers of layers, each with different numbers of neurons.

Parameters:

  • sample_space (list) –

    List [min, max] defining range of values to sample from

  • n_space (list) –

    List [min, max] defining range for number of samples

Returns:

  • list[int]

    List of randomly sampled integers

Note

Uses Python's random module which is not cryptographically secure. This is acceptable for hyperparameter sampling but should not be used for security-critical purposes (S311 fails when linting).

Source code in src/stimulus/utils/yaml_model_schema.py
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
@staticmethod
def sampint(sample_space: list, n_space: list) -> list[int]:
    """Return a list of n random samples from the sample_space.

    This function is useful for sampling different numbers of layers,
    each with different numbers of neurons.

    Args:
        sample_space: List [min, max] defining range of values to sample from
        n_space: List [min, max] defining range for number of samples

    Returns:
        List of randomly sampled integers

    Note:
        Uses Python's random module which is not cryptographically secure.
        This is acceptable for hyperparameter sampling but should not be
        used for security-critical purposes (S311 fails when linting).
    """
    sample_space_list = list(range(sample_space[0], sample_space[1] + 1))
    n_space_list = list(range(n_space[0], n_space[1] + 1))
    n = random.choice(n_space_list)  # noqa: S311
    return random.sample(sample_space_list, n)