Skip to content
Edit this page

Optimizer API

Optimizers is much like optimizers in PyTorch, but for the purpose of optimizing queries and search. Each optimizer would perform a few steps that collectively would guide the search towards the optimal trajectory.

AxServiceOptimizer

AxServiceOptimizer(
    index_eval: IndexEvaluator,
    index: Index,
    *,
    sobol_steps: int = 0,
    device: Device = "cpu",
    task: Task = Task.EXPLORE,
    acqf: str | AcquisitionFunc = AcquisitionFunc.AUTO,
    surrogate: str | SurrogateModel = SurrogateModel.AUTO,
    surrogate_kwargs: SurrogateOptions | None = None
)

Bases: Optimizer

The Ax optimizer that uses the service API. See https://ax.dev/tutorials/gpei_hartmann_service.html

Parameters:

Name Type Description Default
index_eval IndexEvaluator

The evaluator to use for the query.

required
index Index

The index to for querying.

required
sobol_steps int

The number of steps to use for the Sobol sequence.

0
device Device

The device to use for the optimization.

'cpu'
task Task

The task to use for the optimization.

EXPLORE
acqf str | AcquisitionFunc

The acquisition function to use for the optimization.

AUTO
surrogate str | SurrogateModel

The surrogate model to use for the optimization.

AUTO
surrogate_kwargs SurrogateOptions | None

The keyword arguments to pass to the surrogate model.

None
Source code in src/bocoel/optim/ax/optim.py
def __init__(
    self,
    index_eval: IndexEvaluator,
    index: Index,
    *,
    sobol_steps: int = 0,
    device: Device = "cpu",
    task: Task = Task.EXPLORE,
    acqf: str | AcquisitionFunc = AcquisitionFunc.AUTO,
    surrogate: str | SurrogateModel = SurrogateModel.AUTO,
    surrogate_kwargs: SurrogateOptions | None = None,
) -> None:
    """
    Parameters:
        index_eval: The evaluator to use for the query.
        index: The index to for querying.
        sobol_steps: The number of steps to use for the Sobol sequence.
        device: The device to use for the optimization.
        task: The task to use for the optimization.
        acqf: The acquisition function to use for the optimization.
        surrogate: The surrogate model to use for the optimization.
        surrogate_kwargs: The keyword arguments to pass to the surrogate model.
    """

    silence_ax()

    acqf = AcquisitionFunc.lookup(acqf)
    task = Task.lookup(task)

    check_acquisition_task_combo(acqf=acqf, task=task)

    self._device = device
    self._acqf = acqf
    self._surrogate = SurrogateModel.lookup(surrogate).surrogate(surrogate_kwargs)
    self._task = task

    self._ax_client = ax_client.AxClient(
        generation_strategy=self._gen_strat(sobol_steps)
    )
    self._create_experiment(index.boundary)

    self._index_eval = index_eval
    self._index = index
    self._terminate = False

step

step() -> cabc.Mapping[int, float]

Optimize one step with the ax optimizer.

Note

Somehow it seems that with recent versions of Ax, it would crash when workers > 1 in get_next_trials.

Therefore, it's removed.

Raises:

Type Description
StopIteration

When there are no more steps.

Returns:

Type Description
Mapping[int, float]

The resulting trial-id to the evaluation result.

Source code in src/bocoel/optim/ax/optim.py
def step(self) -> cabc.Mapping[int, float]:
    """
    Optimize one step with the ax optimizer.

    Note:
        Somehow it seems that with recent versions of `Ax`,
        it would crash when `workers > 1` in `get_next_trials`.

        Therefore, it's removed.

    Raises:
        StopIteration: When there are no more steps.

    Returns:
        The resulting trial-id to the evaluation result.
    """
    if self._terminate:
        raise StopIteration

    idx_param, done = self._ax_client.get_next_trials(1)

    if done:
        self._terminate = True

    return {
        tidx: self._eval_one_query(tidx, parameters)
        for tidx, parameters in idx_param.items()
    }

AxServiceParameter

Bases: TypedDict

The parameter for the AxServiceOptimizer.

name instance-attribute

name: str

The name of the parameter.

type instance-attribute

type: str

The type of the parameter.

bounds instance-attribute

bounds: tuple[float, float]

The boundaries of the parameter.

value_type instance-attribute

value_type: NotRequired[str]

The value type of the parameter.

log_scale instance-attribute

log_scale: NotRequired[bool]

Whether the parameter is on a log scale.

CorpusEvaluator dataclass

CorpusEvaluator(corpus: Corpus, adaptor: Adaptor)

Bases: IndexEvaluator

Evaluates the corpus with the given adaptor.

__call__

__call__(idx: ArrayLike) -> npt.NDArray

Evaluates the given batched query.

Parameters:

Name Type Description Default
idx ArrayLike

The indices to evaluate.

required

Returns:

Type Description
NDArray

The results of the query. Must be in the same order as the query.

Source code in src/bocoel/optim/corpora.py
def __call__(self, idx: npt.ArrayLike, /) -> npt.NDArray:
    """
    Evaluates the given batched query.

    Parameters:
        idx: The indices to evaluate.

    Returns:
        The results of the query. Must be in the same order as the query.
    """

    indices = np.array(idx)

    if indices.ndim != 1:
        raise ValueError(
            f"Expected indices to have dimensions [batch]. Got {indices.shape}"
        )

    LOGGER.debug("Evaluating indices", indices=indices.shape)
    evaluated = self.adaptor.on_corpus(corpus=self.corpus, indices=indices)
    assert (
        evaluated.shape == indices.shape
    ), f"Expected {indices.shape}. Got {evaluated.shape}"
    return evaluated

IndexEvaluator

Bases: Protocol

A protocol for evaluating with the indices.

__call__ abstractmethod

__call__(idx: ArrayLike) -> npt.NDArray

Evaluates the given batched query. The order of the results must be kept in the original order.

Parameters:

Name Type Description Default
idx ArrayLike

The indices to evaluate. Must be a 1D array.

required

Returns:

Type Description
NDArray

The indices of the results. Must be in the same order as the query.

Source code in src/bocoel/optim/interfaces/evals.py
@abc.abstractmethod
def __call__(self, idx: npt.ArrayLike, /) -> npt.NDArray:
    """
    Evaluates the given batched query.
    The order of the results must be kept in the original order.

    Parameters:
        idx: The indices to evaluate. Must be a 1D array.

    Returns:
        The indices of the results. Must be in the same order as the query.
    """

    ...

CachedIndexEvaluator

CachedIndexEvaluator(index_eval: IndexEvaluator)

Bases: IndexEvaluator

Since there might be duplicate indices (and a lot of them during evaluation), this utility evaluator would cache the results and only compute the unseen indices. This would help evaluating the larger models of evaluation a lot faster.

Source code in src/bocoel/optim/interfaces/evals.py
def __init__(self, index_eval: IndexEvaluator, /) -> None:
    LOGGER.warning("Caching index evaluation. This may use a lot of memory.")

    self._index_eval = index_eval
    self._cache: dict[int, npt.NDArray] = {}

Optimizer

Optimizer(
    index_eval: IndexEvaluator, index: Index, **kwargs: Any
)

Bases: Protocol

The protocol for optimizers. Optimizers are used for optimizing the search space, Find the best exploration sequence for a given task.

Parameters:

Name Type Description Default
index_eval IndexEvaluator

The id evaluator. Evalutes the items at the given storage indices.

required
index Index

The index that contains information about the domain.

required
**kwargs Any

The keyword arguments.

{}
Source code in src/bocoel/optim/interfaces/optim.py
def __init__(
    self, index_eval: IndexEvaluator, index: Index, **kwargs: typing.Any
) -> None:
    """
    Parameters:
        index_eval: The id evaluator. Evalutes the items at the given storage indices.
        index: The index that contains information about the domain.
        **kwargs: The keyword arguments.
    """

    # Included s.t. constructors of Index can be used.
    ...

task abstractmethod property

task: Task

The task to use for the optimization.

Returns:

Type Description
Task

One of Task.EXPLORE or Task.MINIMIZE or Task.MAXIMIZE.

step abstractmethod

step() -> cabc.Mapping[int, float]

Perform a single step of optimization. This is a shortcut into the optimization process. For methods that evaluate the entire search at once, this method would output the slices of the entire search.

Returns:

Type Description
Mapping[int, float]

A mapping of storage indices to the corresponding scores.

Raises:

Type Description
StopIteration

If the optimization is complete.

Source code in src/bocoel/optim/interfaces/optim.py
@abc.abstractmethod
def step(self) -> cabc.Mapping[int, float]:
    """
    Perform a single step of optimization.
    This is a shortcut into the optimization process.
    For methods that evaluate the entire search at once,
    this method would output the slices of the entire search.

    Returns:
        A mapping of storage indices to the corresponding scores.

    Raises:
        StopIteration: If the optimization is complete.
    """

    ...

RandomOptimizer

RandomOptimizer(
    index_eval: IndexEvaluator,
    index: Index,
    *,
    samples: int,
    batch_size: int
)

Bases: Optimizer

The random optimizer that uses random search.

Parameters:

Name Type Description Default
index_eval IndexEvaluator

The evaluator to use for the storage.

required
index Index

The index to use for the query.

required
samples int

The number of samples to use for the optimization.

required
batch_size int

The number of samples to evaluate at once.

required
Source code in src/bocoel/optim/random.py
def __init__(
    self,
    index_eval: IndexEvaluator,
    index: Index,
    *,
    samples: int,
    batch_size: int,
) -> None:
    """
    Parameters:
        index_eval: The evaluator to use for the storage.
        index: The index to use for the query.
        samples: The number of samples to use for the optimization.
        batch_size: The number of samples to evaluate at once.
    """

    LOGGER.info("Instantiating RandomOptimizer", total=len(index), samples=samples)

    self._index_eval = index_eval
    self._index = index
    self._generator = iter(BatchedGenerator(self._gen_random(samples), batch_size))

KMeansOptimizer

KMeansOptimizer(
    index_eval: IndexEvaluator,
    index: Index,
    *,
    batch_size: int,
    embeddings: NDArray,
    model_kwargs: KMeansOptions
)

Bases: ScikitLearnOptimizer

The KMeans optimizer that uses clustering algorithms.

Parameters:

Name Type Description Default
index_eval IndexEvaluator

The evaluator to use on the storage.

required
index Index

The index to use for the query.

required
batch_size int

The number of embeddings to evaluate at once.

required
embeddings NDArray

The embeddings to cluster.

required
model_kwargs KMeansOptions

The keyword arguments to pass to the KMeans model.

required
Source code in src/bocoel/optim/sklearn/kmeans.py
def __init__(
    self,
    index_eval: IndexEvaluator,
    index: Index,
    *,
    batch_size: int,
    embeddings: npt.NDArray,
    model_kwargs: KMeansOptions,
) -> None:
    """
    Parameters:
        index_eval: The evaluator to use on the storage.
        index: The index to use for the query.
        batch_size: The number of embeddings to evaluate at once.
        embeddings: The embeddings to cluster.
        model_kwargs: The keyword arguments to pass to the KMeans model.
    """

    model = cluster.KMeans(**model_kwargs)

    super().__init__(
        index_eval=index_eval,
        index=index,
        embeddings=embeddings,
        model=model,
        batch_size=batch_size,
    )

    self._model_kwargs = model_kwargs

KMedoidsOptimizer

KMedoidsOptimizer(
    index_eval: IndexEvaluator,
    index: Index,
    *,
    batch_size: int,
    embeddings: NDArray,
    model_kwargs: KMedoidsOptions
)

Bases: ScikitLearnOptimizer

The KMedoids optimizer that uses clustering algorithms.

Parameters:

Name Type Description Default
index_eval IndexEvaluator

The evaluator to use for the index.

required
index Index

The index to use for the query.

required
batch_size int

The number of embeddings to evaluate at once.

required
embeddings NDArray

The embeddings to cluster.

required
model_kwargs KMedoidsOptions

The keyword arguments to pass to the KMedoids model.

required
Source code in src/bocoel/optim/sklearn/kmedoids.py
def __init__(
    self,
    index_eval: IndexEvaluator,
    index: Index,
    *,
    batch_size: int,
    embeddings: npt.NDArray,
    model_kwargs: KMedoidsOptions,
) -> None:
    """
    Parameters:
        index_eval: The evaluator to use for the index.
        index: The index to use for the query.
        batch_size: The number of embeddings to evaluate at once.
        embeddings: The embeddings to cluster.
        model_kwargs: The keyword arguments to pass to the KMedoids model.
    """

    # Optional dependency.
    from sklearn_extra import cluster

    model = cluster.KMedoids(**model_kwargs)

    super().__init__(
        index_eval=index_eval,
        index=index,
        embeddings=embeddings,
        model=model,
        batch_size=batch_size,
    )

    self._model_kwargs = model_kwargs

ScikitLearnOptimizer

ScikitLearnOptimizer(
    index_eval: IndexEvaluator,
    index: Index,
    embeddings: NDArray,
    model: ScikitLearnCluster,
    batch_size: int,
)

Bases: Optimizer

The sklearn optimizer that uses clustering algorithms. See the following webpage for options https://scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html

Parameters:

Name Type Description Default
index_eval IndexEvaluator

The evaluator to use for the query.

required
index Index

The index to use for the query.

required
model ScikitLearnCluster

The model to use for the optimization.

required
batch_size int

The number of embeddings to evaluate at once.

required
Source code in src/bocoel/optim/sklearn/optim.py
def __init__(
    self,
    index_eval: IndexEvaluator,
    index: Index,
    embeddings: npt.NDArray,
    model: ScikitLearnCluster,
    batch_size: int,
) -> None:
    """
    Parameters:
        index_eval: The evaluator to use for the query.
        index: The index to use for the query.
        model: The model to use for the optimization.
        batch_size: The number of embeddings to evaluate at once.
    """

    self._index_eval = index_eval
    self._index = index

    model.fit(embeddings)
    validation.check_is_fitted(model)
    ids = model.predict(model.cluster_centers_)

    self._generator = iter(BatchedGenerator(ids, batch_size))

UniformOptimizer

UniformOptimizer(
    index_eval: IndexEvaluator,
    index: Index,
    *,
    grids: Sequence[int],
    batch_size: int
)

Bases: Optimizer

The uniform optimizer that uses grid-based search.

Parameters:

Name Type Description Default
index_eval IndexEvaluator

The evaluator to use for the storage.

required
index Index

The index to use for the query.

required
grids Sequence[int]

The number of grids to use for the optimization.

required
batch_size int

The number of grids to evaluate at once.

required
Source code in src/bocoel/optim/uniform.py
def __init__(
    self,
    index_eval: IndexEvaluator,
    index: Index,
    *,
    grids: cabc.Sequence[int],
    batch_size: int,
) -> None:
    """
    Parameters:
        index_eval: The evaluator to use for the storage.
        index: The index to use for the query.
        grids: The number of grids to use for the optimization.
        batch_size: The number of grids to evaluate at once.
    """

    LOGGER.info("Instantiating UnfiromOptimizer", grids=grids)

    self._index_eval = index_eval
    self._index = index

    self._generator = iter(BatchedGenerator(self._gen_locs(grids), batch_size))

    if len(grids) != self._index.dims:
        raise ValueError(f"Expected {self._index.dims} strides, got {grids}")