CertSafari
    Databricks Certified Machine Learning Associate· Lessons

    Domain 3 · Lesson 34/48

    Parallel Hyperopt tuning with SparkTrials vs Trials

    Parallelize single node models for hyperparameter tuning

    17 min read
    2.07% of exam
    5 sources
    Published 22 Oct 2026
    Docs as of 30 Sep 2026

    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?

    Sources12

    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.

    Distributing an existing fmin() search by passing a SparkTrials object as the trials argumentpython
    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)

    Sources31

    3.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.

    How SparkTrials and Trials differ in where trials run and what they suit
    AspectSparkTrialsTrials (default)
    Model inside the objectiveSingle-machine, e.g. scikit-learnDistributed, e.g. MLlib or Horovod
    Where each trial is evaluatedIn one Spark task on a workerOn the driver, which starts the model's own distributed training
    Concurrency between trialsUp to parallelism trials at onceOne trial at a time
    Automatic MLflow logging on DatabricksYes: parent run plus a child run per trialNo. 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.

    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?

    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?

    Sources41

    4.Setting parallelism and timeout

    SparkTrials takes two optional arguments, and both limit how the search uses the cluster:

    The two optional SparkTrials arguments
    ArgumentMeaningDefault and limits
    parallelismMaximum number of trials evaluated at the same timeDefaults to the number of Spark executors available. Maximum 128. Reduced automatically if it exceeds the cluster's concurrent task limit
    timeoutMaximum number of seconds the fmin() call may runNo 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?

    Sources15

    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?

    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?

    Sources35

    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.

    Sources14

    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. 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. 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. 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. 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. 1.
      “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. 2.
      “MlflowSparkStudy class enables launching parallel Optuna studies using PySpark executors.”
      ↩︎ Why single-node tuning parallelizes across a cluster
    3. 3.
      “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. 4.
      “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. 5.
      “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

    Ready to test yourself?

    Practise the 7 questions on this subdomain.

    Spotted a mistake, or was something unclear? Tell us.