Skip to content

Initial design

make_initial_design #

make_initial_design(
    *,
    parameters: Mapping[str, Parameter],
    encoder: ConfigEncoder,
    sampler: Literal["sobol", "prior", "uniform"] | Sampler,
    sample_size: int | Literal["ndim"] | None = "ndim",
    sample_prior_first: bool = True,
    seed: Generator | None = None,
    constraints_func: (
        Callable[[Mapping[str, Any]], float] | None
    ) = None,
    oversampling_factor: int = 1
) -> list[dict[str, Any]]

Generate the initial design of the optimization process.

PARAMETER DESCRIPTION
encoder

The encoder to use for encoding/decoding configurations.

TYPE: ConfigEncoder

sampler

The sampler to use for the initial design.

If set to "sobol", a Sobol sequence will be used. If set to "uniform", a uniform random sampler will be used. If set to "prior", a prior sampler will be used, based on the defaults, and confidence scores of the hyperparameters. If set to a custom sampler, the sampler will be used directly.

TYPE: Literal['sobol', 'prior', 'uniform'] | Sampler

sample_size

The number of configurations to sample.

If "ndim", the number of configs will be equal to the number of dimensions. If None, no configurations will be sampled.

TYPE: int | Literal['ndim'] | None DEFAULT: 'ndim'

sample_prior_first

Whether to sample the prior configuration first.

TYPE: bool DEFAULT: True

seed

The seed to use for the random number generation.

TYPE: Generator | None DEFAULT: None

constraints_func

A constraint that is >= 0 for valid configurations. Invalid configurations are dropped from the design.

TYPE: Callable[[Mapping[str, Any]], float] | None DEFAULT: None

oversampling_factor

Draw sample_size * oversampling_factor candidates to find sample_size valid ones when using constraints_func.

TYPE: int DEFAULT: 1

Source code in scalefm/optimizers/utils/initial_design.py
def make_initial_design(  # noqa: C901, PLR0912
    *,
    parameters: Mapping[str, Parameter],
    encoder: ConfigEncoder,
    sampler: Literal["sobol", "prior", "uniform"] | Sampler,
    sample_size: int | Literal["ndim"] | None = "ndim",
    sample_prior_first: bool = True,
    seed: torch.Generator | None = None,
    constraints_func: Callable[[Mapping[str, Any]], float] | None = None,
    oversampling_factor: int = 1,
) -> list[dict[str, Any]]:
    """Generate the initial design of the optimization process.

    Args:
        encoder: The encoder to use for encoding/decoding configurations.
        sampler: The sampler to use for the initial design.

            If set to "sobol", a Sobol sequence will be used.
            If set to "uniform", a uniform random sampler will be used.
            If set to "prior", a prior sampler will be used, based on the defaults,
                and confidence scores of the hyperparameters.
            If set to a custom sampler, the sampler will be used directly.

        sample_size:
            The number of configurations to sample.

            If "ndim", the number of configs will be equal to the number of dimensions.
            If None, no configurations will be sampled.

        sample_prior_first: Whether to sample the prior configuration first.
        seed: The seed to use for the random number generation.
        constraints_func: A constraint that is `>= 0` for valid configurations.
            Invalid configurations are dropped from the design.
        oversampling_factor: Draw `sample_size * oversampling_factor` candidates
            to find `sample_size` valid ones when using `constraints_func`.

    """
    configs: list[dict[str, Any]] = []
    prior_configs: list[dict[str, Any]] = []
    if sample_prior_first:
        prior_configs.append(
            {
                name: p.prior if p.prior is not None else p.center
                for name, p in parameters.items()
            }
        )

    for conf in prior_configs:
        if constraints_func is None or constraints_func(conf) >= 0:
            configs.append(conf)

    ndims = len(parameters)
    if sample_size == "ndim":
        sample_size = ndims
    elif sample_size is not None and not sample_size > 0:
        raise ValueError(
            "The sample size should be a positive integer if passing an int."
        )

    if sample_size is not None:
        match sampler:
            case "sobol":
                sampler = Sampler.sobol(ndim=ndims)
            case "uniform":
                sampler = Sampler.uniform(ndim=ndims)
            case "prior":
                sampler = Prior.from_parameters(parameters)
            case _:
                pass
        n_draws = sample_size * (oversampling_factor if constraints_func else 1)
        encoded_configs = sampler.sample(n_draws, to=encoder.domains, seed=seed)
        # NOTE: `torch.unique` sorts its output, which would bias us towards
        # small values of the first dimension when picking the first valid configs.
        _, inverse = torch.unique(encoded_configs, dim=0, return_inverse=True)
        positions = torch.arange(len(inverse), device=inverse.device)
        first_seen = torch.full_like(inverse, len(inverse)).scatter_reduce(
            0, inverse, positions, reduce="amin"
        )
        uniq_x = encoded_configs[first_seen[: int(inverse.max()) + 1].sort().values]
        sample_configs = encoder.decode(uniq_x)
        if constraints_func is not None:
            valid_sample_configs = []
            for config in sample_configs:
                constraint_val = constraints_func(config)
                if constraint_val >= 0:
                    valid_sample_configs.append(config)
                    if len(valid_sample_configs) >= sample_size:
                        break
            sample_configs = valid_sample_configs
            if len(sample_configs) < sample_size:
                raise ConstraintViolationError(
                    f"Could not sample {sample_size} valid configurations out of "
                    f"{n_draws} samples, only got {len(sample_configs)} valid samples."
                )
        sample_configs = sample_configs[:sample_size]
        configs.extend(sample_configs)

    return configs