CertSafari
    Databricks Certified Machine Learning Professional· Lessons

    Domain 1 · Lesson 2/11

    Scaling ML training on Databricks: scale up, parallelize, or distribute

    Scaling and Tuning

    16 min read
    11% of exam
    7 sources
    Published 21 Oct 2026
    Docs as of 17 Oct 2026

    What you will be able to do

    • Decide when a training workload should stay on one larger node and when it has to be distributed
    • Choose data parallelism or model parallelism based on whether the model fits on one device
    • Train and score one single-node model per group with groupBy().applyInPandas()
    • Compare Ray's task parallelism with Spark's data parallelism and start a Ray cluster on a Databricks Spark cluster

    Key concept

    Scale up before you scale out — Run training on one machine, using a larger node if needed, for as long as the model and data fit in its memory. Move to distributed training only when memory or time limits force it, because every extra worker adds coordination overhead and complexity.

    1.Vertical vs horizontal scaling

    A slow or memory-hungry training job can be scaled in two ways. Vertical scaling moves it to a bigger single machine with more memory, more cores or a larger GPU. Horizontal scaling spreads it across several workers. Databricks' default is clear: when possible, train on a single machine. The code stays simple, and nothing waits on the network.

    Distribution has a cost. Workers have to exchange gradients, parameters or intermediate results, and that communication is time a single node never spends. Code that coordinates several processes is also harder to write, debug and test. A job that already fits comfortably on one node usually gets more from a bigger instance than from more nodes.

    The trigger for going horizontal is a hard limit: the model or the data is too large to fit in memory on a single machine, or the largest node available still can't finish in the time you have. For those workloads, Databricks Runtime ML includes TorchDistributor (which launches PyTorch training as Spark jobs), the DeepSpeed distributor built on top of it, and Ray. Spark ML models can be trained in a distributed way through the pyspark.ml.connect module.

    Checkpoint 1 of 9· Check yourself

    A team is deciding whether to move a training job from one Databricks node to several workers. Which situation is the documented reason to switch to horizontal scaling?

    Sources1

    2.Data parallelism vs model parallelism

    Once a job has to run on several devices, the next question is what gets split: the data or the model. The deciding fact is whether the full model fits in one device's memory.

    Data parallelism keeps a complete copy of the model on every device and gives each copy a different slice of every batch. Each device computes gradients on its slice, and the gradients are averaged so all the copies stay identical. PyTorch Distributed Data Parallel (DDP) is the most common form. It fits when the model already fits on one GPU and the goal is more throughput: more samples per step and shorter wall-clock training time.

    Model parallelism handles the opposite case, where the parameters themselves no longer fit on one device even if each batch is small. Copying the model onto more GPUs can't help here, because every copy would hit the same memory limit. Instead, the model's state is spread across devices so that no single device holds all of it. FSDP shards model parameters, gradients and optimizer states across GPUs. The DeepSpeed distributor adds optimized memory usage and pipeline parallelism, and Databricks recommends it for models that need more compute but are limited by memory.

    Which technique matches which constraint
    TechniqueWhat is split across devicesUse when
    DDP (Distributed Data Parallel)Each batch of data; every GPU holds the full modelFull model fits in single GPU memory; need to scale data throughput
    FSDP (Fully Sharded Data Parallel)Model parameters, gradients and optimizer states are shardedVery large models that don't fit in single GPU memory
    DeepSpeed ZeROModel state, with advanced memory optimizationLarge models with advanced memory optimization needs

    Scaling and parallelism answer different questions. The scale-up-first rule decides whether to use several devices at all. Data parallelism versus model parallelism decides how to use them once you have. A team that already wants multiple GPUs for throughput has made the first decision, and a bigger single GPU is an answer to a different question.

    Checkpoint 2 of 9· Check yourself

    Your model's parameters and optimizer states are too large for one GPU, even at a batch size of one. You already train on the largest GPU instance available, and the cluster has several of them. Which approach lets training run?

    Checkpoint 3 of 9· Exam question

    A deep learning model's parameters no longer fit in the memory of a single GPU, even though each training batch itself is modest in size. Which parallelization strategy directly addresses this specific constraint?

    Checkpoint 4 of 9· Exam question

    A team is training a moderately sized neural network whose parameters comfortably fit on one GPU, but they want to cut wall-clock training time by processing more samples per step across multiple GPUs. Which parallelization strategy fits this goal?

    Sources231

    3.Horizontal options on Spark: Spark ML and per-group pandas models

    Spark is built for data parallelism: it applies the same operation to every element of a large dataset. When vertical scaling runs out, its two training options are distributed Spark ML algorithms and many independent single-node models. Spark ML trains one model over a dataset partitioned across executors (see When to use Spark ML for when that is the right library). From Databricks Runtime 17.0, Spark ML is enabled by default on Standard compute through pyspark.ml.connect, so you don't have to manage a full cluster. How the stages of a Spark ML Pipeline (transformers and estimators) run is covered there.

    The second option suits a common case: many small models instead of one big one, such as a forecast per store or a classifier per region. Each model fits on one machine, but there are thousands of them. The pandas function API groupBy().applyInPandas() follows a split-apply-combine pattern. It splits the DataFrame into groups, applies a Python function to each group, and combines the results into a new DataFrame. The function receives all the rows and columns of one group as a pandas.DataFrame and returns a pandas.DataFrame, so its body can fit any single-node library on that group, or load a fitted model and score the group's rows for per-group inference.

    Two things must be defined: the per-group Python function, and the output schema as a StructType or a string. The returned column labels must match the schema's field names when they are strings, or match the field types by position otherwise. Data moves between Spark and pandas over Apache Arrow, the same way as in pandas UDFs, but type hints are optional.

    The split-apply-combine shape: each group arrives as a pandas DataFrame, and the output schema is declaredpython
    df = spark.createDataFrame(
        [(1, 1.0), (1, 2.0), (2, 3.0), (2, 5.0), (2, 10.0)],
        ("id", "v"))
    
    def subtract_mean(pdf):
        # pdf is a pandas.DataFrame
        v = pdf.v
        return pdf.assign(v=v - v.mean())
    
    df.groupby("id").applyInPandas(subtract_mean, schema="id long, v double").show()

    The main risk is memory. All data for a group is loaded into memory before the function runs, and maxRecordsPerBatch does not apply to groups. One oversized customer or region can therefore cause an out-of-memory error even when every other group is tiny. Spark does not rebalance skewed groups for you, and making sure each group fits is your job. For inference without grouping, mapInPandas() takes an iterator of pandas DataFrames and can return output of any length.

    Checkpoint 5 of 9· Fill the gap

    Which DataFrame method completes this per-group split-apply-combine sample?

    df = spark.createDataFrame(
        [(1, 1.0), (1, 2.0), (2, 3.0), (2, 5.0), (2, 10.0)],
        ("id", "v"))
    
    def subtract_mean(pdf):
        # pdf is a pandas.DataFrame
        v = pdf.v
        return pdf.assign(v=v - v.mean())
    
    df.groupby("id"). ? (subtract_mean, schema="id long, v double").show()

    Checkpoint 6 of 9· Check yourself

    Per-region classifiers are trained with groupBy("region").applyInPandas(). One region has 50 times more rows than the rest, which are all small. What is the most likely outcome for that region?

    Sources41

    4.Ray vs Spark for distributing ML work

    Spark and Ray parallelize different things. Spark excels at data parallelism: one operation applied across a large dataset, which suits ETL, joins, aggregations, feature engineering and Spark ML's large-scale algorithms. Ray excels at task parallelism: a set of independent tasks running concurrently, each potentially doing different and compute-heavy work. Ray gives Python developers basic primitives for building distributed applications and handles orchestration, scheduling and fault tolerance.

    This split decides which engine fits a workload. Databricks lists Ray for workloads where Spark is less optimized: reinforcement learning, hierarchical time series forecasting, simulation modeling, hyperparameter search, deep learning training and HPC. Hyperparameter search for a reinforcement learning agent, with trials of very different lengths, is a set of unrelated tasks that should each start as soon as capacity frees up. Ray is designed for exactly that. Spark ML's CrossValidator evaluates parameter grids as Spark ML jobs, and applyInPandas processes groups without rebalancing uneven ones. Neither is built for independent tasks of very different lengths.

    The two engines also work together. Databricks recommends using Spark for data handling and Ray for computation: read and prepare data with Spark, pass it to Ray Data with databricks.ray.data.from_spark, train with Ray, then save the model to MLflow or the output to Unity Catalog tables. When ETL is heavy, run it as its own task in a Databricks workflow so each task gets a cluster suited to it.

    Picking the engine by the shape of the work
    WorkloadBetter fitReason
    Joins, filtering, aggregation, feature engineeringSparkSame operation over every element of a large dataset
    Large-scale ML algorithms on tabular dataSpark (MLlib / Spark ML)Optimized for large-scale machine learning and statistical modeling
    Reinforcement learning, simulation, hyperparameter searchRayMany independent, compute-heavy tasks running concurrently
    Deep learning training, hierarchical time series forecastingRayListed among workloads where Spark is less optimized

    Checkpoint 7 of 9· Match them up

    Match each Spark-and-Ray concept to what it describes on Databricks.

    Tap a term, then the definition that fits it.

    Checkpoint 8 of 9· Exam question

    A team wants to run hyperparameter search for a reinforcement learning agent where trial durations vary widely and unrelated trials should be scheduled independently and opportunistically as executor capacity frees up. Which distributed tuning approach best matches this workload's characteristics?

    Sources56

    5.Running Ray on a Databricks Spark cluster

    With Ray 2.3.0 and above, a Ray cluster runs inside a Databricks Spark cluster. ray.util.spark.setup_ray_cluster starts a background Spark job in which each Spark task creates a Ray worker node, and the Ray head node is created on the driver. min_worker_nodes and max_worker_nodes set the range of Ray workers. If you leave out min_worker_nodes, you get a fixed-size cluster of max_worker_nodes.

    Starting an autoscaling Ray-on-Spark cluster (Ray 2.10 and later)python
    from ray.util.spark import setup_ray_cluster, shutdown_ray_cluster
    
    setup_ray_cluster(
      min_worker_nodes=2,
      max_worker_nodes=4,
      num_cpus_per_node=4,
      collect_log_to_path="/Volumes/<catalog>/<schema>/<volume>/path/to/ray_collected_logs"
    )
    
    # Pass any custom Ray configuration with ray.init
    ray.init(ignore_reinit_error=True)

    Sizing follows a few documented defaults. The Ray head node gets 0 CPUs and 0 GPUs by default because it only coordinates. Each Ray worker node should have at least 4 CPU cores and 10 GB of heap memory. The best setup gives each Spark worker one Ray worker node that uses all its cores and GPUs. On a cluster that runs both engines, lower spark.executor.memory (for example, to 4g), because Spark's lazy garbage collection and dataset cache otherwise leave less memory for Ray. Make either the Databricks cluster or the Ray cluster autoscale, so that idle Ray workers hand resources back to Spark.

    Three operational rules catch people out:

    • Running %pip on a running Ray cluster shuts the cluster down, so install libraries before you initialize it.
    • Ray on Spark is supported only on dedicated access mode, no isolation shared access mode, and jobs clusters. It cannot start on serverless-based runtimes.
    • Integrations that override the configuration from setup_ray_cluster can make the Ray cluster unstable.

    Checkpoint 9 of 9· Fill the gap

    This cluster should autoscale between 2 and 4 Ray worker nodes instead of running at a fixed size. Which argument goes in the blank?

    from ray.util.spark import setup_ray_cluster, shutdown_ray_cluster
    
    setup_ray_cluster(
       ? =2,
      max_worker_nodes=4,
      num_cpus_per_node=4,
      collect_log_to_path="/Volumes/<catalog>/<schema>/<volume>/path/to/ray_collected_logs"
    )
    
    # Pass any custom Ray configuration with ray.init
    ray.init(ignore_reinit_error=True)

    Sources76

    Sources

    (7)

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

    1. 1.
      “When possible, Databricks recommends that you train neural networks on a single machine”
      ↩︎ Vertical vs horizontal scaling
      “Databricks Runtime ML includes the TorchDistributor, DeepSpeed distributor and Ray packages”
      ↩︎ Vertical vs horizontal scaling
      “offers optimized memory usage, reduced communication overhead, and advanced pipeline parallelism”
      ↩︎ Data parallelism vs model parallelism
      “In Databricks Runtime 17.0 and above, Spark ML is enabled by default in Standard compute resources”
      ↩︎ Horizontal options on Spark: Spark ML and per-group pandas models
      “distributed code for training and inference is more complex than single-machine code and slower due to communication overhead”
      ↩︎ Key concept
      “When possible, Databricks recommends that you train neural networks on a single machine”
      ↩︎ Exam trap 1
      “distributed code for training and inference is more complex than single-machine code and slower due to communication overhead”
      ↩︎ Prediction
      “you should consider distributed training and inference if your model or your data are too large to fit in memory on a single machine”
      ↩︎ Checkpoint
      “is a recommended solution for customers with models that require higher compute power, but are limited by memory constraints”
      ↩︎ Checkpoint
    2. 2.
      “DDP is the most common parallelism technique for distributed training”
      ↩︎ Data parallelism vs model parallelism
      “the full model is replicated on each GPU and data batches are split across GPUs”
      ↩︎ Exam trap 2
    3. 3.
      “FSDP shards model parameters, gradients, and optimizer states across GPUs, enabling training of very large models that don't fit in a single GPU's memory.”
      ↩︎ Data parallelism vs model parallelism
    4. 4.
      “Apply a function on each group. The input and output of the function are both pandas.DataFrame.”
      ↩︎ Horizontal options on Spark: Spark ML and per-group pandas models
      “All data for a group is loaded into memory before the function is applied.”
      ↩︎ Horizontal options on Spark: Spark ML and per-group pandas models
      “it is up to you to ensure that the grouped data fits into the available memory”
      ↩︎ Exam trap 3
      “This can lead to out of memory exceptions, especially if the group sizes are skewed. The configuration for maxRecordsPerBatch is not applied on groups”
      ↩︎ Checkpoint
    5. 5.
      “Ray excels at task parallelism - Run a set of independent tasks concurrently.”
      ↩︎ Ray vs Spark for distributing ML work
      “Use Ray for workloads where Spark is less optimized, such as reinforcement learning, hierarchical time series forecasting, simulation modeling, hyperparameter search, deep learning training”
      ↩︎ Ray vs Spark for distributing ML work
    6. 6.
      “it offers the same ease of use as standard Python while managing orchestration, scheduling, and fault tolerance”
      ↩︎ Ray vs Spark for distributing ML work
      “cannot be initiated on clusters using serverless-based runtimes”
      ↩︎ Running Ray on a Databricks Spark cluster
      “Avoid running %pip to install packages on a running Ray cluster, as it will shut down the cluster.”
      ↩︎ Exam trap 4
    7. 7.
      “Each Apache Spark task in the job creates a Ray worker node, and the Ray head node is created on the driver.”
      ↩︎ Running Ray on a Databricks Spark cluster
      “Minimum 4 CPU cores per Ray worker node. Minimum 10GB heap memory for each Ray worker node.”
      ↩︎ Running Ray on a Databricks Spark cluster

    Continue to part 2 of 2

    Distributed hyperparameter tuning with Optuna and Ray Tune

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