skip to content

With the Kubeflow SDK 0.5, what does OptimizerClient().optimize() create on the cluster, and can you kubectl apply an OptimizationJob instead?

level: seniorimportance: nice to knowfreq 3%

answer

  1. an SDK name over an older engine
  2. same TrainJobTemplate as train()
  3. search_space becomes parameters
  4. defaults: random, loss, one at a time
  5. KEP-3562 is a design, not a CRD

basics

~20 s

optimize() creates a Katib kubeflow.org/v1beta1 Experiment whose trial template is a Kubeflow Trainer TrainJob, and returns its name. OptimizationJob is the SDK's name for that object and a design proposal, KEP-3562, in Trainer v2.3.0; no such kind is installed.

solid answer

~40 s

In the Kubeflow SDK 0.5.0, `OptimizerClient().optimize(trial_template=..., search_space=..., trial_config=..., objectives=..., algorithm=...)` builds a Katib `Experiment` under `kubeflow.org/v1beta1` in the target namespace. Its `trialTemplate.trialSpec` is a `trainer.kubeflow.org/v1alpha1` TrainJob generated from the `TrainJobTemplate` (runtime plus `CustomTrainer`); each `search_space` entry becomes an Experiment parameter and a `trialParameter`, and the matching `func_args` entry becomes a `${trialParameters.<name>}` placeholder. Defaults: `RandomSearch`, objective `loss` minimised, and `TrialConfig` with 10 trials, 1 in parallel. It returns the generated name; `get_job()` and `list_jobs()` return the SDK's `OptimizationJob` dataclass built from the Experiment and its Trials. A YAML with `kind: OptimizationJob` cannot be applied: KEP-3562 sits in Trainer v2.3.0's proposals, not its API types.

code

python · 22 lines
python
from kubeflow.trainer import CustomTrainer, TrainJobTemplate
from kubeflow.optimizer import Objective, OptimizerClient, Search, TrialConfig

def fine_tune(lr: str, warmup_steps: str):
    ...  # train; the first node's rank-0 process prints f"val_loss={val_loss}"

template = TrainJobTemplate(
    runtime="torch-distributed",
    trainer=CustomTrainer(func=fine_tune, num_nodes=4, resources_per_node={"gpu": 8}),
)
client = OptimizerClient()
name = client.optimize(
    trial_template=template,
    trial_config=TrialConfig(num_trials=12, parallel_trials=2, max_failed_trials=3),
    search_space={
        "lr": Search.loguniform(0.00001, 0.0003),
        "warmup_steps": Search.choice([200, 500, 1000, 2000]),
    },
    objectives=[Objective(metric="val_loss", direction="minimize")],
)
client.wait_for_job_status(name, timeout=24 * 3600)  # default is 3600 s
print(client.get_best_results(name))

go deeper

for a junior

Recall that OptimizerClient().optimize() starts hyperparameter tuning by creating a Katib Experiment whose trials are TrainJobs.

for a middle

Explain the translation: search_space to parameters and trialParameters, func_args to placeholders, and the SDK defaults of random search, loss minimised, ten trials, one at a time.

for a senior

Separate shipped from proposed: the SDK's OptimizationJob dataclass and Katib's Experiment are real, the OptimizationJob CRD is a KEP, and plan cluster prerequisites accordingly.

for a principal

Decide whether teams tune through the SDK or through reviewed Experiment YAML, weighing ease of use against defaults, such as serial trials and the loss objective, that silently shape the search.

## What optimize() builds The **Kubeflow SDK** (`pip install kubeflow`, release 0.5.0) gives one Python surface over several Kubeflow projects. Its `kubeflow.optimizer` package exposes **`OptimizerClient`**, and calling `optimize()` against a cluster does this: 1. **Copies the trial template.** The same `TrainJobTemplate` you would pass to `TrainerClient().train(**template)`, a runtime name plus a `CustomTrainer` with the training function, nodes and resources. 2. **Turns the search space into Katib parameters.** Each key in `search_space`, built with `Search.uniform()`, `Search.loguniform()` or `Search.choice()`, becomes an Experiment parameter, and a `trialParameter` with the same name and `reference`. 3. **Wires the function arguments.** For every searched name, the trainer's `func_args` gets the string `${trialParameters.<name>}`, which each Katib Trial replaces with its assigned value. 4. **Builds the TrainJob spec** for `trialTemplate.trialSpec`, with `primaryContainerName: node` and `retain: true`, so finished trial TrainJobs are kept. 5. **Creates a Katib `Experiment`** (`kubeflow.org/v1beta1`) with a generated name and returns that name as a string. Katib, not Kubeflow Trainer, then creates the Suggestion, the Trials and one TrainJob per trial. The search helpers map onto Katib's parameter types directly: | SDK helper | Katib `parameterType` | `feasibleSpace` | |---|---|---| | `Search.uniform(min, max)` | `double` | `min`, `max`, distribution `uniform` | | `Search.loguniform(min, max)` | `double` | `min`, `max`, distribution `logUniform` | | `Search.choice(values)` | `categorical` | `list` of the values as strings | Because every value travels through a placeholder in the TrainJob spec, the training function receives each hyperparameter as a string and converts it itself, for example `float(lr)` and `int(warmup_steps)`. ## Defaults that differ from Katib's own | Setting | SDK 0.5 when the argument is omitted | Katib 0.19 when the YAML field is omitted | |---|---|---| | Parallel trials | `TrialConfig.parallel_trials = 1`, written explicitly | `parallelTrialCount` 3 | | Total trials | `TrialConfig.num_trials = 10` | `maxTrialCount` unset | | Failure limit | `max_failed_trials = None` | `maxFailedTrialCount` unset | | Algorithm | `RandomSearch()`, algorithm name `random` | written by you | | Objective | `Objective()`: metric `loss`, `minimize` | written by you | | Metrics collector | not set by the SDK | `StdOut` | Two consequences follow: - **A trial run from the SDK is serial by default.** Pass `TrialConfig(parallel_trials=...)` to run more at once. - **The function must print `loss=<value>`** (or whatever `Objective(metric=...)` names) as a `name=value` line, because the Experiment falls back to Katib's `StdOut` collector. The namespace also needs the Katib metrics-collector injection label. The SDK 0.5 offers two algorithm classes, `RandomSearch` and `GridSearch`. Only the first `Objective` is optimised; any further ones are recorded as additional metrics. ## Shipped against proposed - **Shipped:** Katib's `Experiment`, `Suggestion` and `Trial` kinds; the SDK's `OptimizerClient`; and an SDK dataclass called `OptimizationJob` that `get_job()`, `list_jobs()` and `wait_for_job_status()` return. It is a Python view of the Experiment with its trials, not a cluster object. - **Proposed:** an `OptimizationJob` custom resource under `trainer.kubeflow.org/v1alpha1`. What Trainer v2.3.0 carries for it is KEP-3562, a design document in `proposals/2605-optimization-job-crd` that describes a Phase 1 API. The v2.3.0 API package defines only `TrainJob`, `TrainingRuntime` and `ClusterTrainingRuntime`, and the Trainer roadmap lists integration with OptimizationJob as future work. - **Same scope, different layer:** the proposal limits its Phase 1 to random and grid search, the same two algorithm classes the SDK 0.5 exposes today. What it proposes to change is where the tuning object lives: a Trainer kind instead of a Katib Experiment. So `kubectl apply` of a manifest with `kind: OptimizationJob` fails: the API server has no such resource registered. Code that tunes today should treat the Katib Experiment as the object of record, because that is what `kubectl` and any dashboard will show. ## Reading the results - `OptimizerClient().get_job(name)`: the `OptimizationJob` view, with status `Created`, `Running`, `Complete` or `Failed` and its trials. - `get_best_results(name)`: the best trial's parameters and metrics, or `None` before one exists. - `get_job_logs(name)`: logs from the best trial so far (or the first trial), read from the first node pod's metrics collector container. - `wait_for_job_status(name)`: polls every 2 seconds, with a 3600-second default timeout. ## Prerequisites on the cluster 1. **Katib installed.** The SDK's compatibility table lists Katib v0.19.0 or later. 2. **Kubeflow Trainer installed**, with the runtime the template names. 3. **The namespace labelled** for Katib's metrics sidecar. 4. **A training function that prints the objective** from the first node's primary process.

  • The SDK run above finished, but get_best_results returns None. What is the first thing to check?
    Whether any trial recorded the objective. The SDK sets no metrics collector, so Katib's `StdOut` default applies: the namespace needs the metrics-collector injection label, and the function must print `val_loss=<value>` from the first node pod. Without that, trials end `MetricsUnavailable` and there is no best trial to return.
  • A colleague's notebook prints 'OptimizationJob created'. Does that mean the OptimizationJob CRD is installed?
    No. The SDK uses OptimizationJob as the name of its own Python view and in messages, but the object it created is a Katib `Experiment`. `kubectl get experiments.kubeflow.org` in the namespace shows it; there is no OptimizationJob resource in Trainer v2.3.0.

  • OptimizerClient creates an OptimizationJob custom resource in trainer.kubeflow.org
  • The SDK runs trials without Katib installed
  • Omitting trial_config runs three trials in parallel like Katib
  • The SDK picks Bayesian optimisation by default
  • KEP-3562 merging means OptimizationJob is a served kind in v2.3.0

Assumes the Kubeflow SDK 0.5.0 (OptimizerClient), Katib 0.19.0 and Kubeflow Trainer v2.3.0, where OptimizationJob exists only as the KEP-3562 design proposal.