What you will be able to do
- Add SparkTrials to a Hyperopt fmin() call so that single-node models such as scikit-learn are tuned in parallel on Spark workers
- Choose between SparkTrials and the default Trials class depending on whether the model inside the objective function is already distributed
- Set the parallelism and timeout arguments, and explain the trade-off between parallelism and adaptive search
- Recognise when SparkTrials gives little or no speedup, and when it should not be used at all
- Describe how SparkTrials logs a tuning run to MLflow as a parent run with one child run per trial
Key concept
SparkTrials — A Hyperopt trials object, built by Databricks, that keeps the search on the driver and sends each trial (one model fit on one set of hyperparameters) to a Spark worker. It only helps when each model trains on a single machine. A model that is already distributed should be tuned with the default Trials class.
1.Why single-node tuning parallelizes across a cluster
A scikit-learn model trains on one machine, however large your cluster is. Hyperparameter tuning still gives the rest of the cluster plenty to do, because the search fits many separate models. In Hyperopt each of these fits is a trial: one model trained on one setting of hyperparameters and then scored. The trials of a random search don't depend on each other, and a Bayesian search only needs earlier results to pick its next points. Several trials can therefore run at the same time on different machines.
The max_evals argument of fmin() sets the size of the search: the total number of hyperparameter settings to try, which is also the number of models fitted. It is a budget. It says nothing about concurrency, so raising max_evals from 16 to 50 means 50 fits, and they still run one after another unless something else spreads them out. Reshaping the training data, for example converting a pandas DataFrame to a Spark DataFrame and calling .repartition(), doesn't change how trials are scheduled either. Concurrency comes only from the object you pass as the trials argument.
Checkpoint 1 of 9· Check yourself
A data scientist tunes a scikit-learn classifier with Hyperopt's fmin() on a multi-node Databricks cluster, and the search runs one trial at a time. Which change makes several trials run at once on different machines?
max_evals only sets how many models are fitted in total, and reshaping the data doesn't change how trials are scheduled. Trials run concurrently only when you pass SparkTrials as the trials argument, which sends each single-machine trial to a Spark worker.
“Use SparkTrials when you call single-machine algorithms such as scikit-learn methods in the objective function.”Source: docs.databricks.com
2.Adding SparkTrials to an fmin() call
You turn a sequential Hyperopt search into a parallel one by passing one extra argument. The objective function, search space and search algorithm all stay as they are. You create a SparkTrials object and pass it to fmin() as trials. Below, an SVM is tuned on the Iris dataset with 16 trials. The only change from the single-machine version is trials=spark_trials and the surrounding MLflow run.
spark_trials = SparkTrials()
with mlflow.start_run():
argmin = fmin(
fn=objective,
space=search_space,
algo=algo,
max_evals=16,
trials=spark_trials)Under the hood, the work is split between the driver and the workers. The driver runs the search algorithm and generates new trials. Each trial becomes a Spark job with a single task, and a worker evaluates it inside that task: it fits the scikit-learn model and returns the loss. If the cluster allows several tasks per worker, one worker can evaluate several trials at the same time. Because each trial runs as one task on one machine, the model inside it has to fit on a single machine. That limit is why SparkTrials is meant for single-node models.
Checkpoint 2 of 9· Fill the gap
This fmin() call tunes a scikit-learn SVM. Which class should be instantiated so that each trial runs as its own Spark task on a worker?
spark_trials = ? ()
with mlflow.start_run():
argmin = fmin(
fn=objective,
space=search_space,
algo=algo,
max_evals=16,
trials=spark_trials)SparkTrials keeps the search on the driver and sends each trial to a worker as a single-task Spark job, so single-machine scikit-learn fits run at the same time. The default Trials class runs trials on the driver one after another. MlflowSparkStudy is Optuna's class, not a Hyperopt trials object.
Source: docs.databricks.com3.SparkTrials or Trials: decided by where the model trains
The question that decides between the two classes is whether the model inside the objective function is already distributed. A scikit-learn model isn't, so SparkTrials adds the parallelism the cluster would otherwise leave unused. An MLlib estimator or a HorovodRunner job is different: each training run already spreads across the cluster. For these, Databricks says not to pass a trials argument at all, and specifically not to use SparkTrials. Hyperopt then falls back to the default Trials class. With Trials, each trial is evaluated on the driver, where the algorithm can start its own distributed training with access to the full cluster. If you wrapped that in SparkTrials instead, every MLlib fit would be launched from inside one task on one worker, which works against the distribution MLlib provides.
A plain Trials object does not spread anything across workers. It runs the trials one at a time on the driver. A scikit-learn search that uses Trials is therefore exactly as sequential as one with no trials argument, however many workers the cluster has.
| Aspect | SparkTrials | Trials (default) |
|---|---|---|
| Model inside the objective | Single-machine, e.g. scikit-learn | Distributed, e.g. MLlib or Horovod |
| Where each trial is evaluated | In one Spark task on a worker | On the driver, which starts the model's own distributed training |
| Concurrency between trials | Up to parallelism trials at once | One trial at a time |
| Automatic MLflow logging on Databricks | Yes: parent run plus a child run per trial | No. Log trials yourself |
Checkpoint 3 of 9· Match them up
Match each tuning setup to what happens when fmin() runs on a multi-node cluster.
Tap a term, then the definition that fits it.
The class should match where the model trains. Single-machine scikit-learn fits gain concurrency only from SparkTrials, because a plain Trials object runs them one after another on the driver. Distributed MLlib fits should use the default Trials class so that each one starts on the driver and can use the whole cluster.
“With distributed training algorithms, use the default Trials class, which runs on the cluster driver.”Source: docs.databricks.com
Checkpoint 4 of 9· Exam question
A machine learning engineer is training a scikit-learn RandomForestClassifier on a pandas DataFrame that fits comfortably in the memory of the Databricks driver node. The model itself trains as a single-node process, but the engineer wants to test 50 hyperparameter combinations by distributing the trials across the worker nodes of an all-purpose cluster using Hyperopt's fmin. Which approach correctly parallelizes this hyperparameter search?
Correct answer: A — Pass a SparkTrials object as the trials argument to fmin, since it distributes each single-node scikit-learn model evaluation to a separate Spark task on the cluster's workers.
- A. SparkTrials is the Hyperopt trials class built for exactly this case: it takes a single-node model's objective function and schedules each trial as its own Spark task, so evaluations run concurrently across the cluster's workers instead of one at a time on the driver.
- B. The base Trials class evaluates every trial sequentially on the driver process. It has no cluster-awareness of its own, so swapping in Trials would leave the scikit-learn search running one combination at a time regardless of how many workers the cluster has.
- C. Repartitioning a Spark DataFrame changes how Spark's own data processing is parallelized, but Hyperopt's trial scheduling is governed entirely by which trials object is passed to fmin, not by how the training data happens to be partitioned.
- D. max_evals only sets how many hyperparameter combinations fmin will evaluate in total; it says nothing about how many of those evaluations run at the same time. Concurrency is controlled by the parallelism setting on a SparkTrials object, not by the size of the evaluation budget.
Checkpoint 5 of 9· Exam question
A team is tuning hyperparameters for an MLlib RandomForestClassifier that Spark already trains as a distributed algorithm across the cluster, spreading each training job over multiple executors. They ask whether wrapping the tuning loop in SparkTrials will speed up the search the same way it did for their earlier scikit-learn model. What should they be told?
Correct answer: A — Use a plain Trials object instead of SparkTrials, because MLlib already parallelizes the training of each individual model, and layering SparkTrials on top would compete for the same executor slots.
- A. MLlib already spreads a single model's training across the cluster's executors on its own. Adding SparkTrials on top would try to run multiple already-distributed training jobs concurrently, contending for the same executor resources, so the plain sequential Trials class is the correct fit here.
- B. The two-level distribution that helped the scikit-learn workload worked because that model trained on one machine and had spare cluster capacity to exploit. An MLlib model already consumes cluster resources to train itself, so stacking a higher parallelism value on top does not give the same benefit and instead risks resource contention.
- C. MLlib does not require a fixed ratio of hyperparameter combinations to executors, and max_evals is unrelated to worker count. This describes a constraint that does not exist in either Hyperopt or MLlib's training model.
- D. Converting the data to pandas would defeat the purpose of using MLlib, which is designed to train on distributed Spark DataFrames, and Hyperopt is not restricted to pandas-based objective functions in the first place.
4.Setting parallelism and timeout
SparkTrials takes two optional arguments, and both limit how the search uses the cluster:
| Argument | Meaning | Default and limits |
|---|---|---|
| parallelism | Maximum number of trials evaluated at the same time | Defaults to the number of Spark executors available. Maximum 128. Reduced automatically if it exceeds the cluster's concurrent task limit |
| timeout | Maximum number of seconds the fmin() call may run | No limit by default. When it is exceeded, all runs stop, fmin() exits, and results of completed runs are kept |
Higher parallelism isn't automatically better, because it costs you some adaptivity. TPE, Hyperopt's Bayesian algorithm (tpe.suggest), picks each new setting based on the results it already has. Take a budget of 16 trials. With parallelism 16, every trial starts before any result exists, so the search is effectively random. With parallelism 4, later trials can use what earlier ones found. For a fixed max_evals, greater parallelism finishes sooner, while lower parallelism may find better hyperparameters. Parallelism doesn't restart the search or throw away earlier results. It only reduces how many results each new proposal can see. Random search (rand.suggest) doesn't use past results, so it gives up nothing at high parallelism.
A related fmin() argument, max_queue_len, sets how many settings Hyperopt generates in advance. Generating TPE proposals can be slow, so raising it above the default of 1 can help, but it should generally stay at or below the SparkTrials parallelism value.
Checkpoint 6 of 9· Check yourself
A tuning job uses tpe.suggest, max_evals=32 and SparkTrials(parallelism=32) on a cluster with enough task slots. It finishes much faster than an earlier run with parallelism=4, but its best loss is worse. What best explains this?
TPE proposes each new setting from the results it already has. With parallelism equal to max_evals, no results exist when the proposals are made, so the search runs faster but adapts less. timeout has no limit by default, parallelism does not restart the search, and each trial runs as its own single-task Spark job.
“lower parallelism may lead to better results since each iteration has access to more past results.”Source: docs.databricks.com
5.When SparkTrials makes tuning slower
Every trial under SparkTrials pays a fixed cost before any training starts: a Spark job is scheduled, a task is launched on a worker, and the result travels back to the driver. When a fit takes minutes, that cost is negligible and running eight at once brings the total time down sharply. When a fit takes milliseconds, the overhead dominates and the speedup can be small or zero. The Iris SVM example on Databricks shows this: its objective is so cheap that the distributed run takes longer than the single-machine run. A slower search in this situation doesn't mean extra models were trained. SparkTrials still fits exactly max_evals models. The extra time comes from the per-trial overhead.
In practice, SparkTrials pays off when each trial does real work, such as a large random forest, a deep search over boosting rounds, or cross-validation inside the objective. A tiny model on a small dataset is usually better tuned on the driver. Every trial also needs the training data on the worker that runs it, so moving the dataset to the workers is part of the cost to plan for.
Checkpoint 7 of 9· Check yourself
Of these four Hyperopt searches on a multi-node Databricks cluster, which one is most likely to finish noticeably faster after switching from sequential Trials to SparkTrials?
SparkTrials pays off when each trial does real work, so the fixed cost of starting a Spark job per trial is small next to the fit time. Cheap fits like Iris or a small tree stay dominated by that overhead no matter how many trials or partitions there are, and an MLlib model should use the default Trials class.
“For typical real-world problems, the objective function is more complex, and using SparkTrails to distribute the calculations is faster than single-machine tuning.”Source: docs.databricks.com
Checkpoint 8 of 9· Exam question
A data scientist is tuning a scikit-learn LogisticRegression model on a dataset with 2,000 rows. Each trial trains and scores in under half a second. After wrapping the search in SparkTrials with parallelism=8, the engineer notices the tuning job takes longer in wall-clock time than running the same search sequentially with a plain Trials object on the driver. What most likely explains this?
Correct answer: A — The objective function is so cheap that the overhead of launching and scheduling Spark tasks for each trial outweighs the time saved by running trials concurrently.
- A. For a fast-running objective function, the fixed cost of starting a Spark job and scheduling a task for each trial can exceed the trial's own training time. SparkTrials pays off on expensive objective functions; on cheap ones like sub-second logistic regression fits, the distribution overhead itself becomes the bottleneck.
- B. max_evals sets the total number of trials for both trials classes identically; SparkTrials does not silently evaluate more combinations than requested. The slowdown here comes from per-trial overhead, not from an inflated evaluation count.
- C. Neither trials class re-reads data from disk on every trial by default; how the objective function loads its data is up to the code the data scientist wrote, not a behavior SparkTrials imposes. This does not explain the wall-clock difference described.
- D. The parallelism setting controls how many trials run concurrently; it does not reset or discard the search algorithm's state between trials. TPE continues incorporating completed trial results regardless of the parallelism value chosen.
6.How SparkTrials logs to MLflow
SparkTrials logs to MLflow automatically, as a set of nested runs. The fmin() call becomes the parent (main) run, and each trial becomes a child run under it. This is what lets you open the experiment, select the child runs, click Compare, and plot the hyperparameter (for example C) against loss on a scatter plot.
Whether you have an active run decides how the parent run is handled. If a run is active when fmin() starts, SparkTrials logs into it and leaves it open when fmin() returns. Otherwise it creates a run and closes it before returning. Databricks recommends wrapping each fmin() call in with mlflow.start_run(): so that every search gets its own parent run. If you call fmin() twice inside the same active run, both calls log to that one run, and MLflow adds a UUID to any parameter or tag names that clash.
Inside the objective function, you can log without managing runs. A call such as mlflow.log_param("param_from_worker", x) running on a worker is recorded under that trial's child run, and parameters, metrics, tags and artifacts all work the same way. The default Trials class doesn't get this on Databricks: automatic MLflow logging isn't supported with it, so when you tune distributed models you have to log each trial yourself.
Checkpoint 9 of 9· Match them up
Each of these fmin() setups logs to MLflow differently on Databricks. Pair each setup with what you will find in the experiment.
Tap a term, then the definition that fits it.
SparkTrials always logs a parent run with one child run per trial. Whether it creates and closes that parent run depends on whether a run is already active. Calling fmin() twice in one active run puts both searches in a single parent run. The default Trials class gets no automatic logging on Databricks.
“If there is no active run, SparkTrials creates a new run, logs to it, and ends the run before fmin() returns.”Source: docs.databricks.com
Practise it for real
Tune a scikit-learn SVC's C parameter in parallel with SparkTrials and inspect the nested MLflow runs it produces.
1.On a Databricks Runtime ML cluster that still includes Hyperopt (16.4 LTS ML or earlier), write an objective function that fits SVC(C=C) on the Iris data and returns {'loss': -accuracy, 'status': STATUS_OK}, using the mean of cross_val_score as accuracy.
Why: Hyperopt minimizes the loss, so you return negative accuracy to make it look for the highest accuracy.
You should see: Calling objective(1.0) returns a dictionary with a negative loss close to -0.98.
2.Define search_space = hp.lognormal('C', 0, 1.0) and set algo=tpe.suggest, then run fmin with max_evals=16 and no trials argument.
Why: This gives you the sequential baseline and its timing.
You should see: fmin prints the best value found for C after 16 trials that ran one after another on the driver.
3.Create spark_trials = SparkTrials() and rerun the same fmin call inside with mlflow.start_run(), adding trials=spark_trials.
Why: Adding the trials argument is the only code change needed to send trials to Spark workers.
You should see: The search completes, possibly more slowly than the baseline because the Iris objective is so cheap.
4.Open the notebook's Experiment panel, select the child runs under the new parent run, click Compare, and plot C on the X-axis against loss on the Y-axis.
Why: SparkTrials logs each trial as a child run of the fmin() parent run, so you can compare the results without writing any logging code.
You should see: One parent run with 16 child runs, and a scatter plot showing how loss changes with C.
Stuck? Get a nudge
If the parallel run was slower than the baseline, compare how long one fit takes with the cost of launching a Spark job for it.
Sources
(5)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.https://docs.databricks.com/aws/en/machine-learning/automl-hyperparam-tuning/hyperopt-conceptsOfficial docs
“In Hyperopt, a trial generally corresponds to fitting one model on one setting of hyperparameters.”
↩︎ Why single-node tuning parallelizes across a cluster“Number of hyperparameter settings to try (the number of models to fit).”
↩︎ Why single-node tuning parallelizes across a cluster“Hyperopt is not included in Databricks Runtime for Machine Learning after 16.4 LTS ML.”
↩︎ Why single-node tuning parallelizes across a cluster“Databricks recommends using either Optuna for single-node optimization or RayTune”
↩︎ Why single-node tuning parallelizes across a cluster“With SparkTrials, the driver node of your cluster generates new trials, and worker nodes evaluate those trials.”
↩︎ Adding SparkTrials to an fmin() call“Each trial is generated with a Spark job which has one task, and is evaluated in the task on a worker machine.”
↩︎ Adding SparkTrials to an fmin() call“In this case the model building process is automatically parallelized on the cluster and you should use the default Hyperopt class Trials.”
↩︎ SparkTrials or Trials: decided by where the model trains“If the value is greater than the number of concurrent tasks allowed by the cluster configuration, SparkTrials reduces parallelism to this value.”
↩︎ Setting parallelism and timeout“lower parallelism may lead to better results since each iteration has access to more past results.”
↩︎ Setting parallelism and timeout“When this number is exceeded, all runs are terminated and fmin() exits. Information about completed runs is saved.”
↩︎ Setting parallelism and timeout“The call to fmin() is logged as the main run.”
↩︎ How SparkTrials logs to MLflow“wrap the call to fmin() inside a with mlflow.start_run(): statement”
↩︎ How SparkTrials logs to MLflow“SparkTrials accelerates single-machine tuning by distributing trials to Spark workers.”
↩︎ Key concept“Use SparkTrials when you call single-machine algorithms such as scikit-learn methods in the objective function.”
↩︎ Exam trap 1“Number of hyperparameter settings to try (the number of models to fit).”
↩︎ Exam trap 3“lower parallelism may lead to better results since each iteration has access to more past results.”
↩︎ Exam trap 4“Use SparkTrials when you call single-machine algorithms such as scikit-learn methods in the objective function.”
↩︎ Checkpoint“Use Trials when you call distributed training algorithms such as MLlib methods or Horovod in the objective function.”
↩︎ Prediction“If there is no active run, SparkTrials creates a new run, logs to it, and ends the run before fmin() returns.”
↩︎ Checkpoint - 2.
“MlflowSparkStudy class enables launching parallel Optuna studies using PySpark executors.”
↩︎ Why single-node tuning parallelizes across a cluster - 3.https://docs.databricks.com/aws/en/machine-learning/automl-hyperparam-tuning/hyperopt-spark-mlflow-integrationOfficial docs
“To distribute tuning, add one more argument to fmin(): a Trials class called SparkTrials.”
↩︎ Adding SparkTrials to an fmin() call“the function runs quickly and the overhead of starting the Spark jobs dominates the calculation time”
↩︎ When SparkTrials makes tuning slower“For typical real-world problems, the objective function is more complex, and using SparkTrails to distribute the calculations is faster than single-machine tuning.”
↩︎ Checkpoint - 4.https://docs.databricks.com/aws/en/machine-learning/automl-hyperparam-tuning/hyperopt-distributed-mlOfficial docs
“do not pass a trials argument to fmin(), and specifically, do not use the SparkTrials class.”
↩︎ SparkTrials or Trials: decided by where the model trains“Each trial is executed from the driver node, giving it access to the full cluster resources.”
↩︎ SparkTrials or Trials: decided by where the model trains“Databricks does not support automatic logging to MLflow with the Trials class.”
↩︎ How SparkTrials logs to MLflow“SparkTrials is designed to distribute trials for algorithms that are not themselves distributed.”
↩︎ Exam trap 2“With distributed training algorithms, use the default Trials class, which runs on the cluster driver.”
↩︎ Checkpoint - 5.https://docs.databricks.com/aws/en/machine-learning/automl-hyperparam-tuning/hyperopt-best-practicesOfficial docs
“Hyperopt selects the parallelism value when execution begins.”
↩︎ Setting parallelism and timeout“The speedup you observe may be small or even zero.”
↩︎ When SparkTrials makes tuning slower“SparkTrials runs the trials on Spark worker nodes.”
↩︎ When SparkTrials makes tuning slower“The speedup you observe may be small or even zero.”
↩︎ Exam trap 5“Both Hyperopt and Spark incur overhead that can dominate the trial duration for short trial runs (low tens of seconds).”
↩︎ Prediction