W&B Sweeps (wandb Sweep): Tuning Anomaly-Baseline Sensitivity

How a wandb sweep works: config, controller and agents, method choice, parallel agents, Hyperband pitfalls and handing the winning run to the registry.

W&B Sweeps (wandb Sweep): Tuning Anomaly-Baseline Sensitivity
Written by TechnoLynx Published on 11 Jul 2026

A wandb sweep has three parts. A sweep configuration names the search method, the metric to optimise and the parameter ranges. A sweep controller, hosted by Weights & Biases by default, decides what the next run should be. Agents on your own machines fetch those instructions and run your training code. Here, the sweep tunes detection sensitivity across asset classes. For what those baselines are, see our article on condition monitoring of transformers and the anomaly reliability artefacts.

For an anomaly model, the most useful thing a sweep produces is the logged false-positive/true-positive trade-off at each point it tried, not the top-ranked run. A leaderboard tells you which config scored best on one snapshot of data. A logged trade-off surface tells you why a threshold was chosen, and you can pick again from it when the load pattern shifts. That is the reason we treat reliability as its own discipline, separate from accuracy: the deliverable is an artefact that catches alert fatigue and missed events, not a single high score.

What the Sweep Config, the Controller and the Agents Each Do

Initialising a sweep registers its configuration with W&B and returns a sweep ID. Agents use that ID to ask for their run instructions, and from then on the sweep can coordinate a search across one or more machines. Each time a run finishes, the controller issues instructions for the next one, and an agent picks them up. The Kempner Institute’s computing handbook (Harvard) breaks down what an agent does: it connects to the controller, fetches a set of hyperparameter values, runs the training script with them and reports the results back. Each agent runs one experiment from the sweep.

This split matters in practice. The search logic sits in the controller and the compute sits with you, so adding capacity means starting more agents against the same sweep ID. The wandb sweep CLI also has a --controller flag that starts a local controller after the sweep is created. For ordinary tuning, though, the hosted controller is the default and the simpler choice.

The returned sweep ID includes the entity and project names. If you leave out the project when you initialise, W&B puts the runs in an “Uncategorized” project. Set the project explicitly when you initialise the sweep. Otherwise the runs end up somewhere other than where you will go looking for the trade-off surface.

Writing a wandb Sweep Config: Method, Metric and Parameters

You can write a sweep configuration in YAML or as a nested Python dictionary. Two keys are required: method (the search strategy) and parameters (the bounds to search). metric names what to optimise, and only some search strategies and stopping criteria use it. If you use random search, give each hyperparameter a distribution under parameters. The command key controls how the agent calls your script. Its macros include ${env}, ${interpreter}, ${program} and ${args}, and ${args} passes hyperparameters as --param1=value1.

Worked Example: A Bayes-Plus-Hyperband Config for a Baseline Model

The W&B documentation includes an example that pairs Bayesian search with Hyperband early termination, so that weak runs stop early and the compute goes to more promising configs. Adapted to an anomaly baseline, the shape looks like this. The parameter names are assumptions for illustration, not a recommended search space.

program: train_baseline.py
method: bayes
metric:
  name: val/recall_at_target_fpr
  goal: maximize
parameters:
  baseline_window_days:
    values: [7, 14, 28]
  learning_rate:
    min: 0.0001
    max: 0.01
early_terminate:
  type: hyperband
  min_iter: 3
  eta: 3
command:
  - ${env}
  - ${interpreter}
  - ${program}
  - ${args}

The choice of metric is where the anomaly angle comes in. A sweep optimises the metric named in its metric key. If that metric is plain accuracy or loss, the sweep will happily pick a config that looks good on average and floods operators at the operating point you actually run. We would optimise a metric fixed at the operating point, such as recall at a target false-positive rate, and log the full curve next to it (more on that below).

Nested and Dependent Parameters

A sweep configuration is built from nested key-value pairs. Our route is to sweep the parameters independently and settle the dependency inside the training function. For example, ignore window_overlap when baseline_window_days is 7, and log the value you actually used so the run stays honest.

Changing a Config After the Sweep Exists

The wandb sweep command is documented as able to create, update or manage a sweep. The passages we rely on do not say when an update is accepted. So we treat a running sweep’s search space as fixed. When the space needs to change, create a new sweep and attach the useful earlier runs with --prior_run (-R), which can be given more than once. You can stop the old sweep with --stop, which lets active runs finish but starts no new ones, or with --cancel, which kills active runs. --pause and --resume are also available.

Grid, Random or Bayesian: Which Method, at What Compute Cost

W&B offers three search strategies: grid, random and Bayesian.

Method How it picks the next run Cost behaviour Fits when
Grid Every combination, with no use of earlier results Can be computationally costly, and runs forever over a continuous space A handful of discrete values you must cover exhaustively, such as asset class × window length
Random A random draw from each parameter’s distribution, with no use of earlier results Runs until you stop it from the CLI, your script or the W&B App Many parameters, where only a few probably matter
Bayesian A probabilistic surrogate model chooses values before the objective is evaluated Works well for small numbers of continuous parameters but scales poorly A few continuous knobs with expensive runs

Bergstra and Bengio (JMLR, 2012) found that random search over the same domain found models as good as or better than pure grid search, in a small fraction of the computation time. Their explanation is low effective dimensionality. In one 7-dimensional problem only between one and four parameters really mattered, depending on the dataset. Random search optimised it with 8 to 16 trials, while a grid with four values per axis would already need 256 trials. They also pointed out that random trials are independent. You can stop an experiment at any point and still have a complete experiment, add trials when machines free up, and abandon a failed trial without damaging the rest.

Grid search puts too many trials into dimensions that do not matter and covers the important ones poorly. Which dimensions matter can also differ from dataset to dataset, so a grid designed on one asset class can be the wrong grid for the next. For the broader comparison with Bayesian methods, our explainer on Bayesian hyperparameter search in W&B sweeps goes further than this page.

Starting Agents from Python or the CLI, and Why You Must Cap the Run Count

From the terminal, wandb agent [SWEEP-ID] starts an agent. From Python, wandb.agent() takes the sweep ID and the function that serves as your training entrypoint. A function passed this way is called instead of the program in the sweep config.

By default, random and Bayesian searches run indefinitely. The W&B documentation says to cap how many runs each agent attempts. You do this with wandb agent --count 10 SWEEP_ID on the CLI, or wandb.agent(sweep_id, count=10) in Python. The agent also accepts a setting that shuts it down after a given number of runs fail back to back. Set it. A broken data path should stop the sweep, not burn through a night of GPU time reporting crashes.

import wandb

def main():
    with wandb.init(project="transformer-baselines") as run:
        cfg = run.config            # values chosen by the sweep controller
        train_and_evaluate(cfg, run)

if __name__ == "__main__":
    sweep_id = wandb.sweep(sweep_config, project="transformer-baselines")
    wandb.agent(sweep_id, function=main, count=20)

The training function reads its hyperparameter values from wandb.Run.config. When you use Python’s multiprocessing or PyTorch’s multiprocessing package, you must wrap the wandb.agent() and wandb.sweep() calls in an if __name__ == "__main__": guard.

Running Agents in Parallel Across GPUs, Machines and SLURM

Running several agents at once shortens the time it takes to explore the space. On one machine with several GPUs, give each agent its own device with CUDA_VISIBLE_DEVICES so the agents do not compete for the same GPU. For example, run CUDA_VISIBLE_DEVICES=0 wandb agent [SWEEP-ID] in one terminal and the same with 1 in the next. On several machines, run the same agent command on each one.

On a cluster, the Kempner handbook launches agents as a SLURM array job. #SBATCH --array=1-12%2 starts up to 12 jobs with at most 2 running at the same time. In that setup, each array task runs exactly one sweep run. That gives a one-to-one mapping between SLURM job IDs and W&B runs, which makes tracking and debugging easier and gives fine-grained control over timeouts and logs.

Logging Hyperparameters and the Trade-off Surface so Runs Can Be Compared

The run’s config property saves the training configuration: the hyperparameter inputs and any other independent variables of the experiment. Because the configuration is recorded with each run, you can group and compare runs by configuration values in the W&B App, see how each setting affects the output, and reproduce the work later. You can add keys during the script. Changing the value of an existing key raises an error unless you set allow_val_change=True. A config-defaults.yaml file next to the script is loaded into the config automatically.

For an anomaly sweep, put three things in the config: the asset class, the data window the baseline was fitted on, and every derived value the training function actually used. Then log the operating curve as one table at the end of the run, giving the false-positive and true-positive rate at each candidate threshold. Keep the metric the sweep optimises on a one-value-per-epoch schedule. The reason is that Hyperband brackets are based on the number of logged iterations, so extra logging steps for the swept metric change what an “iteration” means. We do not give the detection threshold a sweep dimension of its own. Moving it along an already-trained model’s score distribution needs no retraining, so each run can log the whole curve while the sweep spends its budget on the parameters that do need retraining.

If your team logs to TensorBoard rather than W&B, see TensorBoard logging for anomaly models and what to capture so calibration evidence survives.

When Does Hyperband Early Stopping in a wandb Sweep Cut Runs off Too Early?

Hyperband in W&B checks whether a run should stop or continue at pre-set iteration counts called brackets. When a run reaches a bracket, its metric is compared with all the values previously reported at that point, and the run is terminated if it is too poor for the goal you set. That makes it a stopping rule layered over whatever method chooses the configs. The original paper’s Hyperband instead cycles SuccessiveHalving brackets that allocate the budget.

What min_iter, max_iter, Eta and S Actually Do

The W&B sweeps source code builds the brackets in one of two ways. With max_iter and s, it divides max_iter by eta up to s times and keeps each result that is at least 1. With min_iter, it starts at min_iter and multiplies by eta. As a worked example of that arithmetic: max_iter: 27, eta: 3, s: 2 gives brackets at iterations 3 and 9, and min_iter: 3, eta: 3 gives 3, 9, 27 and so on. At each bracket, the threshold is the value at the 1/eta position of the sorted metric values from every run that reached that bracket, so with eta: 3 a run has to sit roughly in the best third to survive. By default the termination test is conservative: it compares the run’s best value so far against the threshold. Setting strict: true compares the value at the bracket instead, which is more aggressive.

The paper behind the algorithm, by Li and colleagues (JMLR, 2018), suggests eta of 3 or 4 in practice. It also says results are not very sensitive to the choice, and that eta should give roughly five brackets, with at least three. On deep-learning and kernel problems, the same paper measured Hyperband at 5× to 30× faster than popular Bayesian optimisation algorithms.

Diagnostic Checklist: Runs Stopped Too Early, or Never Stopped

  • Never stopped: the metric name in metric does not match the key you log. With no matching history at a bracket, the threshold becomes infinite and nothing is terminated.
  • Never stopped: runs log fewer iterations than the first bracket, so no bracket applies yet.
  • Stopped too early: some configs converge slowly but end up better. The paper names drastically different convergence rates, from learning-rate decay or layer counts, as an open problem for Hyperband.
  • Stopped too early: a parameter’s best setting depends on the resource. Performance on a small resource then says little about performance on a large one, and the benefit of early stopping can be muted.
  • Stopped too early: strict: true on a noisy validation metric. A single bad logged value at a bracket is enough to kill a run.
  • No speedup at all: training is fast and per-run overhead dominates. The paper’s experiments on 117 datasets found no significant speedup where training took seconds and initialisation was costly.

The anomaly case adds one more trap. We expect a baseline fitted on a longer window to look worse at early iterations, having seen less of its signal. That is a resource-dependent parameter in practice, so we would leave window length out of any sweep that uses Hyperband, or set min_iter high enough that every window has converged before the first bracket.

Moving the Winning Run into the Registry and the Retraining Pipeline

The public API’s Sweep.best_run() returns the best run, sorted by the metric defined in the config or by an order you pass in. The W&B support documentation shows how to sort a sweep’s runs, take the top one and download every artifact it logged. From there, you link the model artifact to a registry collection at a path of the form wandb-registry-{REGISTRY_NAME}/{COLLECTION_NAME}. You can do this with wandb.Artifact.link() on an existing committed artifact, passing the path as target_path, which links it without creating a new run. The artifact must be logged under a team entity to be linkable.

import wandb

api = wandb.Api()
sweep = api.sweep("team-entity/transformer-baselines/SWEEP_ID")
best = sweep.best_run()

for artifact in best.logged_artifacts():
    if artifact.type == "model":
        artifact.link(target_path="wandb-registry-model/oil-temp-baselines")

The registry entry is only half of the handoff. What makes a retrain repeatable is that the pipeline reads the winning run’s config and its logged operating curve, not a value someone copied into a YAML file. When retraining starts, it re-runs a config whose selection you can trace. For how to version that sensitivity-calibration evidence per asset class, see W&B Artifacts for condition monitoring. Building the trigger, the retrain and the release gate around the registry is MLOps engineering work, and it belongs in the pipeline, not in a notebook.

Combining W&B Sweeps with Hydra

W&B Sweeps work with Hydra projects without code changes. You need a sweep configuration file, and the command uses ${args_no_hyphens} so the arguments arrive in Hydra’s override syntax. Running wandb sweep sweep.yaml creates the sweep and returns an agent command to run on each machine. Hydra also has its own multirun, which launches a set of configurations from the command line. A reasonable split is to let Hydra compose the configuration and let the W&B sweep drive the search and keep the comparison. You get structured configs and a hosted controller with early stopping, without keeping two search spaces in sync. If the team only needs a small fixed set of overrides and no shared comparison view, Hydra’s multirun on its own may be enough.

Re-Tuning After the Season Changes

The real test of a sweep comes at the first re-tune after the load pattern shifts. One option is to re-run the old search blind and ship whatever ranks first. The other is to start a new sweep against the same objective, attach the previous runs with --prior_run, and compare the new trade-off surface with the old one at the operating point the alerts actually use. Only the second gives an answer to the question an operator will ask: why did this threshold move? Hyperband’s theoretical guarantees assume the validation losses of sampled configs come from a stationary distribution. We read that as a reminder that a sweep’s ranking describes the conditions it ran under. What stays open is how often each asset class needs that re-selection. The sweep cannot answer that. The monitoring side has to, using alert action rates.