CertSafari
    Databricks Certified Machine Learning Professional· Lessons

    Domain 1 · Lesson 2/11

    Distributed hyperparameter tuning with Optuna and Ray Tune

    Scaling and Tuning

    10 min read
    11% of exam
    4 sources
    Published 21 Oct 2026
    Docs as of 30 Sep 2026

    What you will be able to do

    • Explain why Hyperopt and SparkTrials should be migrated, and to what
    • Run a parallel Optuna study on Spark executors with MlflowStorage and MlflowSparkStudy
    • Log Ray Tune trials as MLflow child runs under one parent run
    • Choose between MlflowSparkStudy and Ray Tune for a given tuning workload

    1.Moving off Hyperopt

    Hyperparameter tuning means training the same model many times with different settings and keeping the best. Each trial is independent of the others, so the search parallelizes well. On Databricks, the usual tool for this used to be Hyperopt, with fmin and SparkTrials.

    There are two reasons to migrate. The open-source Hyperopt project is no longer maintained, and Hyperopt is not included in Databricks Runtime ML after 16.4 LTS ML. Databricks recommends Optuna for single-node optimization and Ray Tune for an experience similar to Hyperopt's distributed tuning. Optuna on its own runs on one node and can be parallelized there with Joblib. MLflow 3 adds MlflowSparkStudy, which runs its trials on Spark executors, so Optuna can reach a cluster too.

    Checkpoint 1 of 4· Match them up

    A team is migrating its hyperparameter tuning off Hyperopt on Databricks. Match each tool to the role Databricks gives it.

    Tap a term, then the definition that fits it.

    Sources1

    2.Parallel Optuna studies with MlflowStorage and MlflowSparkStudy

    An Optuna workflow starts with an objective function. It receives a trial, calls suggest methods such as trial.suggest_float, trial.suggest_int or trial.suggest_categorical to define the search space, trains a model, and returns the metric to optimize. Because the search space is built inside the function, it can be dynamic: a trial that picks a random forest asks for max_depth, and one that picks an SVR asks for C.

    Distributed trials need a shared store where they record what they tried. MlflowStorage makes the MLflow Tracking Server that store. It batches writes, so many parallel trials don't hit REST API throttling. MLflow 3.0 comes pre-installed in Databricks Runtime 17.0 ML and above. On older runtimes, install it with %pip install mlflow --upgrade and %pip install optuna.

    Creating the shared MLflow-backed storage for the studypython
    import mlflow
    from mlflow.optuna.storage import MlflowStorage
    
    experiment_id = mlflow.get_experiment_by_name(dbutils.notebook.entry_point.getDbutils().notebook().getContext().notebookPath().get()).experiment_id
    
    mlflow_storage = MlflowStorage(experiment_id=experiment_id)

    MlflowSparkStudy wraps Optuna's Study so that trials run in parallel on PySpark executors and report through the MLflow experiment. Because the storage is MLflow, every trial lands on the tracking server without manual logging code in the objective. The parent/child structure itself is covered in MLflow nested runs, and explicit log_param/log_metric calls in Programmatic MLflow logging (params, metrics, tags, artifacts). Here, n_trials=8 means eight calls of the objective with different hyperparameter values.

    Launching the study on Spark executorspython
    from mlflow.pyspark.optuna.study import MlflowSparkStudy
    
    mlflow_study = MlflowSparkStudy(
        study_name="spark-mlflow-tuning",
        storage=mlflow_storage,
    )
    
    mlflow_study.optimize(objective, n_trials=8, n_jobs=4)
    Constructor parameters of MlflowStorage and MlflowSparkStudy
    ParameterMeaning
    MlflowStorage: experiment_idMLflow experiment ID for the storage
    MlflowStorage: batch_flush_intervalSeconds between automatic batch flushes (default 1.0)
    MlflowStorage: batch_size_thresholdMaximum items in a batch before a flush (default 100)
    MlflowSparkStudy: storageThe mlflow.optuna.MlflowStorage instance
    MlflowSparkStudy: samplerAlgorithm that suggests values; optuna.samplers.TPESampler by default
    MlflowSparkStudy: prunerDecides early stopping of unpromising trials; optuna.pruners.MedianPruner by default

    Checkpoint 2 of 4· Check yourself

    A data scientist builds an MlflowSparkStudy and passes only study_name and storage, with no sampler or pruner. How does the study choose hyperparameter values and handle trials that look unpromising?

    Sources2

    3.Ray Tune on Ray-on-Spark, logged as MLflow child runs

    Ray Tune is the hyperparameter tuning library that ships with Ray, and it uses Ray as its distributed backend. Databricks Runtime ML includes Ray, so Ray Tune runs on a Ray cluster started inside the Spark cluster with setup_ray_cluster. A tune.Tuner takes a training function, a param_space such as tune.randint(10, 100), and a TuneConfig that sets num_samples, the number of trials. Calling tuner.fit() runs the trials.

    To track the search in MLflow, use a parent run and child runs. Start a parent run in the driver process and pass its run ID into the trainable. Each Ray Tune trial then opens a nested run under that parent, giving a clear hierarchy of results. Each worker needs Databricks credentials, which the example gets with get_databricks_env_vars("databricks") and applies with os.environ.update, along with the same experiment name as the driver.

    A Ray Tune trainable that logs each trial as a nested MLflow run and reports the metric back to Tunepython
    def train_function_mlflow(config, run_id):
       os.environ.update(mlflow_db_creds)
       mlflow.set_experiment(EXPERIMENT_NAME)
    
       # Hyperparameters
       width = config["width"]
       height = config["height"]
    
       with mlflow.start_run(run_id=run_id, nested=True):
           for step in range(config.get("steps", 100)):
               # Iterative training function - can be any arbitrary training procedure
               intermediate_score = evaluation_fn(step, width, height)
               # Log the metrics to MLflow
               mlflow.log_metrics({"iterations": step, "mean_loss": intermediate_score})
               # Feed the score back to Tune.
               train.report({"iterations": step, "mean_loss": intermediate_score})
               time.sleep(0.1)

    Each step sends its result to two places: mlflow.log_metrics writes to the tracking server, and train.report sends it to Tune so the scheduler can compare trials. Resources also need care. Set each Ray worker's CPU count in resources_per_worker to one less than the node's total. If the trainer reserves every core for Ray actors, the job can fail with resource contention errors.

    Checkpoint 3 of 4· Fill the gap

    In this Ray Tune trainable, each step writes its score to the MLflow tracking server. It must also send the score to Tune so the scheduler can compare trials. Which call completes the second line?

    def train_function_mlflow(config, run_id):
       os.environ.update(mlflow_db_creds)
       mlflow.set_experiment(EXPERIMENT_NAME)
    
       # Hyperparameters
       width = config["width"]
       height = config["height"]
    
       with mlflow.start_run(run_id=run_id, nested=True):
           for step in range(config.get("steps", 100)):
               # Iterative training function - can be any arbitrary training procedure
               intermediate_score = evaluation_fn(step, width, height)
               # Log the metrics to MLflow
               mlflow.log_metrics({"iterations": step, "mean_loss": intermediate_score})
               # Feed the score back to Tune.
               train. ? ({"iterations": step, "mean_loss": intermediate_score})
               time.sleep(0.1)

    Sources13

    4.Choosing between MlflowSparkStudy and Ray Tune

    Both tools run trials in parallel on a cluster. The difference is the engine underneath. MlflowSparkStudy uses Spark executors and MLflow storage, which fits a team already on Optuna whose objective is a standard single-node model, such as scikit-learn, and that wants MLflow tracking with almost no setup. Ray Tune uses Ray's task parallelism, which Databricks lists as suited to hyperparameter search and deep learning training. It fits best when trials are compute-heavy or GPU-bound, vary widely in duration, and don't need to read large Spark DataFrames directly.

    Spark ML has its own tuner. CrossValidator and TrainValidationSplit evaluate parameter grids over a distributed Spark ML estimator, and MLflow PySpark ML autologging (mlflow.pyspark.ml.autolog(), enabled by default with Databricks Autologging) records them. The older MLlib automated MLflow tracking is deprecated. Use these tuners when the model being tuned is itself a Spark ML model, not as a general scheduler for unrelated trials.

    Checkpoint 4 of 4· Check yourself

    You are tuning a PyTorch reinforcement learning agent on GPU nodes. Some trials finish in minutes, others run for hours, and none of them read Spark DataFrames. Which tuning setup fits this workload best?

    Sources41

    Practise it for real

    Run a parallel Optuna study on Spark executors that records its trials in MLflow

    1. 1.On a runtime older than Databricks Runtime 17.0 ML, run %pip install mlflow --upgrade and %pip install optuna.

      Why: MlflowStorage and MlflowSparkStudy come with MLflow 3.0, which is pre-installed only from 17.0 ML.

      You should see: Both imports, mlflow.optuna.storage and mlflow.pyspark.optuna.study, succeed.

    2. 2.Define objective(trial) using trial.suggest_categorical, suggest_float and suggest_int, and return a validation error.

      Why: The objective defines the search space and the value Optuna minimizes.

      You should see: Calling the function once with a trial returns a numeric error.

    3. 3.Create MlflowStorage(experiment_id=experiment_id) for the notebook's experiment.

      Why: Parallel trials need a shared store, and this one is the MLflow Tracking Server.

      You should see: A storage object bound to the experiment ID.

    4. 4.Create MlflowSparkStudy(study_name="spark-mlflow-tuning", storage=mlflow_storage) and call optimize(objective, n_trials=8, n_jobs=4).

      Why: This launches the study's trials on PySpark executors.

      You should see: Eight trials appear in the MLflow experiment, each with its own parameters and objective value.

    Sources

    (4)

    Every claim above is drawn from one of these pages, quoted as it was written on the date shown.

    1. 1.
      “The open-source version of Hyperopt is no longer being maintained.”
      ↩︎ Moving off Hyperopt
      “Optuna can be easily parallelized with Joblib to scale workloads, and integrated with MLflow to track hyperparameters and metrics across trials.”
      ↩︎ Moving off Hyperopt
      “Ray Tune is a hyperparameter tuning library that comes with Ray and uses Ray as a backend for distributed computing.”
      ↩︎ Ray Tune on Ray-on-Spark, logged as MLflow child runs
      “Instead, use MLflow PySpark ML autologging by calling mlflow.pyspark.ml.autolog(), which is enabled by default with Databricks Autologging.”
      ↩︎ Choosing between MlflowSparkStudy and Ray Tune
      “Databricks recommends using either Optuna for single-node optimization or RayTune for a similar experience to the deprecated Hyperopt distributed hyperparameter tuning functionality.”
      ↩︎ Exam trap 1
      “Hyperopt is not included in Databricks Runtime for Machine Learning after 16.4 LTS ML.”
      ↩︎ Prediction
      “Databricks recommends using either Optuna for single-node optimization or RayTune for a similar experience to the deprecated Hyperopt distributed hyperparameter tuning functionality.”
      ↩︎ Checkpoint
    2. 2.
      “MlflowSparkStudy class enables launching parallel Optuna studies using PySpark executors.”
      ↩︎ Parallel Optuna studies with MlflowStorage and MlflowSparkStudy
      “MlflowStorage is a MLflow-based storage class for Optuna with batch processing to avoid REST API throttling.”
      ↩︎ Parallel Optuna studies with MlflowStorage and MlflowSparkStudy
      “MLflow 3.0 is pre-installed in Databricks Runtime 17.0 ML and above.”
      ↩︎ Parallel Optuna studies with MlflowStorage and MlflowSparkStudy
      “optuna.samplers.TPESampler is used as the default.”
      ↩︎ Exam trap 2
      “A pruner object that decides early stopping of unpromising trials. optuna.pruners.MedianPruner is used as the default.”
      ↩︎ Checkpoint
    3. 3.
      “Each Ray Tune task creates a child run under the parent run, maintaining a clear hierarchy of experiment results.”
      ↩︎ Ray Tune on Ray-on-Spark, logged as MLflow child runs
      “set the number of CPUs for each Ray worker to be one less than the total number of CPUs available”
      ↩︎ Ray Tune on Ray-on-Spark, logged as MLflow child runs
    4. 4.
      “Task parallelism: Ray is designed for task parallelism, where multiple tasks run concurrently and independently.”
      ↩︎ Choosing between MlflowSparkStudy and Ray Tune
      “Use Ray for workloads where Spark is less optimized, such as reinforcement learning, hierarchical time series forecasting, simulation modeling, hyperparameter search, deep learning training”
      ↩︎ Checkpoint

    Ready to test yourself?

    Practise the 32 questions on this subdomain.

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