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?
Databricks recommends single-machine training when possible, because distributed code is more complex and slower per unit of work due to communication overhead. Distribution is warranted when the model or data no longer fits in one machine's memory.
“you should consider distributed training and inference if your model or your data are too large to fit in memory on a single machine”Source: docs.databricks.com
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.
| Technique | What is split across devices | Use when |
|---|---|---|
| DDP (Distributed Data Parallel) | Each batch of data; every GPU holds the full model | Full model fits in single GPU memory; need to scale data throughput |
| FSDP (Fully Sharded Data Parallel) | Model parameters, gradients and optimizer states are sharded | Very large models that don't fit in single GPU memory |
| DeepSpeed ZeRO | Model state, with advanced memory optimization | Large 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?
Data parallelism (DDP) puts a full copy of the model on every GPU, so every copy runs into the same memory limit, and smaller batches don't shrink the parameters. A model that doesn't fit needs model parallelism, where its state is split across devices. The DeepSpeed distributor is the option Databricks recommends for memory-limited models.
“is a recommended solution for customers with models that require higher compute power, but are limited by memory constraints”Source: docs.databricks.com
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?
Correct answer: A — Model parallelism, which splits the model's layers or parameters across multiple devices so no single device must hold the full parameter set.
- A. Correct: model parallelism partitions the model itself across devices, which is exactly the fix when the parameter set is too large for one device's memory, independent of batch size.
- B. Data parallelism still requires a full model replica on every device, so it does nothing to relieve a per-device memory bottleneck caused by the model's own parameter footprint.
- C.
applyInPandas-based partitioning distributes independent per-group models, not the layers of a single oversized model, so it does not solve a single model's device-memory limit. - D. Hyperparameter search runs many independent full model instances to compare configurations; it does not shrink the memory footprint of any one instance's parameters.
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?
Correct answer: A — Data parallelism, replicating the model on each GPU and splitting each batch across devices so gradients are computed in parallel and averaged.
- A. Correct: since the model already fits on one device, replicating it and splitting batches across GPUs (data parallelism) increases per-step throughput and reduces wall-clock time without needing to fragment the model.
- B. Model parallelism is aimed at models too large for one device's memory; applying it here adds cross-device coordination overhead without addressing the team's actual goal of processing more samples per step.
- C. A single bigger GPU can speed up one replica but does not add the extra concurrent compute of several devices working on different batch shards simultaneously, so it caps the throughput gain versus multi-GPU data parallelism.
- D. GPU devices are the normal target for data-parallel and pipeline-parallel training; restricting batch-splitting strategies to CPUs ignores the GPUs the team already has available.
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.
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()groupBy().applyInPandas() passes each group's rows to the function as a pandas.DataFrame and combines the returned DataFrames using the declared output schema. mapInPandas works on an iterator of DataFrames without grouping, and cogroup needs a second grouped DataFrame.
Source: docs.databricks.comCheckpoint 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?
applyInPandas loads all of a group's data into memory before calling the function, and maxRecordsPerBatch does not apply to groups. A single oversized group can therefore cause an out-of-memory error, and it is up to you to make sure each group fits.
“This can lead to out of memory exceptions, especially if the group sizes are skewed. The configuration for maxRecordsPerBatch is not applied on groups”Source: docs.databricks.com
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.
| Workload | Better fit | Reason |
|---|---|---|
| Joins, filtering, aggregation, feature engineering | Spark | Same operation over every element of a large dataset |
| Large-scale ML algorithms on tabular data | Spark (MLlib / Spark ML) | Optimized for large-scale machine learning and statistical modeling |
| Reinforcement learning, simulation, hyperparameter search | Ray | Many independent, compute-heavy tasks running concurrently |
| Deep learning training, hierarchical time series forecasting | Ray | Listed 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.
Spark is built for data parallelism and Ray for task parallelism. Databricks recommends Spark for data handling and Ray for computation, using from_spark to hand data from one to the other, and running heavy ETL as its own workflow task so each task gets a suitable cluster.
“Ray excels at task parallelism - Run a set of independent tasks concurrently.”Source: docs.databricks.com
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?
Correct answer: A — Ray Tune, since Ray's dynamic task scheduler handles independent, variable-duration tasks more responsively than Spark's static execution plan.
- A. Correct: Ray excels at task parallelism with dynamic scheduling, making it well suited to independent, variable-duration tasks like reinforcement learning trials, unlike Spark's more static execution planning.
- B.
CrossValidatoruses Spark's static execution plan, which is optimized for data-parallel, relatively uniform tasks and is not designed to dynamically reschedule wildly uneven independent trials. - C. Grouped Pandas UDFs process fixed groups determined at planning time; they do not provide Ray-style dynamic, opportunistic rescheduling of independent variable-length tasks across free capacity.
- D.
local_mode=Trueconfines TorchDistributor to processes on a single machine for one coordinated training job, which is unrelated to dynamically scheduling many independent RL trials cluster-wide.
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.
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
%pipon 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_clustercan 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)min_worker_nodes and max_worker_nodes set the range of Ray worker nodes that setup_ray_cluster creates. If you leave out min_worker_nodes, you get a fixed-size cluster with max_worker_nodes workers. num_cpus_head_node sets the head node's CPUs and does not affect the worker range.
Source: docs.databricks.comSources
(7)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 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.
“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.
“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.
“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.
“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.
“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.
“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