Skip to content
King Jin

16 November 2026 · ML System reading notes · 4/6

ML System 04: Data Processing Frameworks

Part four is chapter 8 of the book: the data processing framework. Before training starts, data has to be read from disk, shuffled, transformed, batched and sent to the GPU. This chapter is about making that pipeline easy to write, fast, and reproducible in its ordering, and about scaling it when one machine isn't enough. Afterwards I chased a question of my own: I'd always assumed distributed training ran on Ray, so how do Ray and PyTorch actually relate, and how is large-model training usually layered? That's the last section.

Data processing as a pipeline

What a data processing framework does can be summed up as ETL: Extract, Transform, Load. The book breaks it into five components:

  • Load: reads the dataset from storage, and has to cope with many kinds of storage devices and many dataset formats at once.
  • Shuffle: randomly reorders the input data in a way the user specifies, which makes the model more robust.
  • Map: does the actual transformations, with built-in preprocessing operators for each data type, such as resizing and flipping for images or adding random noise to audio.
  • Batch: assembles one batch (mini-batch) of data and hands it to training or inference.
  • Send: sends the processed data to an accelerator such as a GPU for the model computation and updates that follow.

Frameworks like PyTorch have all of these. In PyTorch they live in DataLoader.

For the interface, the book uses a LINQ-style programming abstraction. LINQ is a C# feature that reads a lot like writing SQL. You only describe the operations to apply to the dataset, chained one after another, and leave it to the framework to run them efficiently:

ds = ds.shuffle(1000).map(operations=resize, input_columns="image").batch(32)

That turns data processing into a pipeline. pandas method chaining follows the same idea. Spark, the classic big-data framework, uses this model too, built around the RDD (Resilient Distributed Dataset).

Read, preprocess and consume rates

Call the rate of reading data from storage FF, the rate of preprocessing PP, and the rate at which the chip consumes data GG. Ideally

G<min⁡(F,P)G < \min(F, P)

so the accelerator never stalls waiting for data. In practice it's often G>min⁡(F,P)G > \min(F, P): either reading is too slow (low FF, called I/O bound) or preprocessing is too slow (low PP, called CPU bound), and the chip sits idle. Most of the rest of the chapter is about raising FF and PP in turn.

Too many data types: one storage format

Text may be stored as txt, images as JPEG, video as mov, and the I/O behavior of these types differs a lot. The book's answer is to convert everything into one unified storage format first, which hides those I/O differences, and then design and optimize data loading around that one format:

txt, jpeg, mov and other raw datasets → Unirecord dataset → data reader

Unirecord is a name the book made up for teaching; the real-world example it uses is MindSpore's MindRecord. The format also has to fit how training reads data:

  • within each epoch, every sample is visited once, in random order;
  • each epoch visits all the data in a different random order.

So it has to support fast random reads.

Parallelizing preprocessing

Raising PP means running preprocessing in parallel. There are two ways to do it, depending on how finely compute is handed out.

Pipeline parallelism: split by whole pipeline

Run the user's whole processing pipeline sequentially inside one thread, and start several threads to run several copies of the pipeline in parallel. With NN samples and a parallelism of MM, each worker handles N/MN/M samples.

PyTorch's DataLoader works this way, and num_workers sets how many Python processes it starts. There are two kinds of process, the main process and the worker processes, and they talk through two queues: index_queue and worker_result_queue. During training, the main process sends data processing tasks to the workers through index_queue. Each worker runs the preprocessing logic the user wrote in the dataset and sends the result back to the main process through worker_result_queue.

That's a lot of inter-process communication. PyTorch has a shared-memory mechanism for it, but with large amounts of data it still slows preprocessing down. The root cause is CPython's GIL: if pipeline parallelism is implemented in Python, it can only use multiple processes. PyTorch is also working on removing the GIL so pipeline parallelism can use threads instead.

Operator parallelism: split by single operator

The other approach hands out compute per operator: more for expensive operators, less for cheap ones. JPEG decoding is slow, so give it a parallelism of 8; flipping is fast, so 1 is enough. MapReduce is another big-data processing model with only two operators, Map and Reduce, and it also uses operator parallelism.

Because it uses compute more fully, and because its dataflow scheduling is implemented efficiently in C++, operator parallelism performs better: tf.data is nearly twice as fast as PyTorch's DataLoader.

The cost is that every operator needs a sensible parallelism setting. That asks a lot of the user, and a bad setting can make performance worse. To help, frameworks like tf.data also tune key pipeline parameters dynamically.

Pipeline parallelismOperator parallelism
Unit of parallelismwhole pipelinesingle operator
ExamplePyTorch DataLoadertf.data
Where scheduling runsPython, multiple processesC++
Strengthsimple, just set num_workersfiner-grained compute, faster
Weaknesshigh inter-process communication costevery operator needs tuning

A data processing pipeline is itself a computational graph, so like the graph optimizations in part two, it can use operator fusion too.

Order preservation: what happens to ordering after parallelism

When several threads run map in parallel, each sample takes a different amount of time, whichever finishes first comes out first, and the order gets scrambled. That causes two problems: experiments can't be reproduced, and you can't run fair comparisons between them. The shuffle itself is fixed, because the seed is fixed; what's random is the order in which parallel work finishes.

The book uses MindSpore's Connector as the example. Between an upstream and a downstream operator sits a connector, with MM threads upstream and NN downstream, all numbered from 0.

  1. Round-robin assignment: sample jj always goes to producer thread j mod Mj \bmod M.
  2. Push: each producer thread only puts data into the queue with its own number.
  3. Pop: the connector takes from the queues in turn, 0, 1, 2, …, which rebuilds the original global order. Sample jj can only go to consumer thread j mod Nj \bmod N.

Input0 1 2 3 4 5Producer 00 2 4 → queue 0Producer 11 3 5 → queue 1sample j → j mod MConnectorpops queuesin turnConsumer 00 3Consumer 11 4Consumer 22 5j mod NOutput0 1 2 3 4 5

This way each operator's output order matches its input order, and passing that down stage by stage keeps the order of the whole pipeline.

The cost

If one sample is slow, samples behind it that are already done have to wait for it. This is head-of-line blocking. Order preservation trades a little throughput for determinism.

When one machine isn't enough

AI chips keep getting faster while CPUs, held back by the slowdown of Moore's law, can't keep up, so multi-core CPU parallelism stops being enough. There are two ways out.

Hand it to the accelerator: DALI

Some preprocessing can move to the accelerator. NVIDIA's DALI is a fairly general GPU preprocessing framework with three core concepts:

  • DataNode: a collection of tensors.
  • Operator: an operator that transforms DataNodes. It can run in cpu, gpu or mixed mode; in mixed mode the input is on the CPU and the output is on the GPU.
  • Pipeline: a data processing pipeline made of operators.

It has one restriction: once an operator is in mixed or gpu mode, every operator downstream of it must be in gpu mode. In other words, once data is on the GPU it never goes back to the CPU.

Distributed preprocessing: Spark and Ray Dataset

A common setup is to preprocess with a big-data framework such as Spark, write the result to a distributed file system, and have the training machines read it from there. This has a few problems:

  • data processing and training use two separate frameworks;
  • the two systems can't share data with zero copy, so serialization and deserialization are expensive;
  • big-data frameworks weren't designed for ML, and a global shuffle, for example, can't be done efficiently.

Ray Dataset fixes some of these. Preprocessing and training live in the same framework, it supports parallel operators such as map and filter, and it also supports sorting, random shuffling and groupby.

Follow-up: Ray and PyTorch

Reading about Ray Dataset made me go and work out what Ray actually does. This part isn't from the book; it's my own understanding.

Not the same layer

At first I thought distributed training was done with Ray. In fact PyTorch and Ray sit at different layers, so it's not a choice between them.

  • PyTorch handles "how to train": the model, autograd, gradient computation. Gradient sync across GPUs is DDP or FSDP, with NCCL doing the all-reduce underneath.
  • Ray handles "where it runs and how it's scheduled": managing machines, assigning GPUs, launching processes, retrying on failure. Ray Train starts a set of workers, each worker still runs the PyTorch training code I wrote, and gradient sync is still PyTorch DDP.

PyTorch is the engine; Ray is the dispatch system for the fleet.

I went through how DDP's all-reduce syncs gradients in my ZeRO post.

Without Ray, the scheduling layer is handled by torchrun (one machine or a few), Slurm or K8s. For something like EUFS (my Formula Student team), with one machine and a few GPUs, torchrun is enough. Ray fits better when you have:

  • RLHF and reinforcement learning, which need training, inference and the reward model coordinated at the same time;
  • preprocessing, training and inference you want in one framework;
  • hyperparameter search (Ray Tune).

The same training job, written two ways

Plain PyTorch, launched with torchrun --nproc_per_node=4 train_ddp.py:

dist.init_process_group("nccl")
rank = int(os.environ["LOCAL_RANK"]); torch.cuda.set_device(rank)
model = DDP(nn.Linear(10, 1).cuda(), device_ids=[rank])
loader = DataLoader(ds, batch_size=32, sampler=DistributedSampler(ds))
# training loop: loss.backward() does the all-reduce automatically

Ray Train, run directly with python train_ray.py:

def train_loop(config):
    model = ray.train.torch.prepare_model(nn.Linear(10, 1))      # wraps in DDP and moves to the right GPU
    loader = ray.train.torch.prepare_data_loader(DataLoader(ds, batch_size=32))  # adds DistributedSampler
    # training loop is almost the same as above

TorchTrainer(train_loop, scaling_config=ScalingConfig(num_workers=4, use_gpu=True)).fit()

The only difference is who launches the processes. On multiple machines, torchrun has to be run once on each machine. With Ray you connect to the cluster and change num_workers, and you also get failure retries and checkpoint recovery built in.

Why it feels like nobody uses Ray for preprocessing

Ray itself is widely used: OpenAI, Uber, ByteDance and Ant Group all use it, and a lot of RLHF and inference frameworks such as vLLM and verl run on Ray. It just isn't the mainstream choice for data preprocessing:

  • Ray Dataset arrived late and is fairly lightweight. Large-scale ETL still runs on Spark, whose ecosystem, SQL support and operations experience are all mature.
  • For preprocessing inside training, DataLoader, tf.data and DALI are already enough, so there's no reason to bring in a cluster framework for it.
  • You have to deploy and maintain a Ray cluster yourself, and debugging the object store or out-of-memory errors isn't easy. Small teams decide it isn't worth it.
  • The early API changed fast and upgrades had a cost, which left an impression that it wasn't stable.
  • It's a general distributed computing framework, not a dedicated data framework, so it has no overwhelming edge on data-heavy work.

So Ray is popular for scheduling and orchestrating AI workloads, while data preprocessing is still mostly Spark, DataLoader and DALI.

How large-model training is usually layered

OpenAI doesn't publish the training details of its latest models, so what follows is the general layering across the industry. It's my own summary, not something specific to OpenAI. And it isn't "PyTorch + Ray and you're done": PyTorch handles the computation, Ray or Kubernetes handles scheduling, and in between sits a large amount of parallelism and communication engineering.

  1. Model and training code: PyTorch, with a few using JAX (Google, for example).
  2. Parallelism strategy: a mix of data, tensor, pipeline and expert parallelism, implemented with Megatron-LM, DeepSpeed, FSDP or in-house libraries.
  3. Communication: NCCL, running over NVLink and InfiniBand.
  4. Custom operators: fused kernels written in Triton or CUDA.
  5. Cluster scheduling: Kubernetes or Slurm, plus an orchestration layer like Ray, especially in RL post-training, where several roles (training, inference, the reward model) have to be coordinated.
  6. Fault tolerance: frequent checkpoints and automatic replacement of failed nodes. With thousands of GPUs running together, something breaks every day.

Ray and Slurm

Slurm is the cluster's resource allocator, sitting outside the job: you ask it for N GPUs to run a script. Ray is a Python distributed runtime inside the job, handling fine-grained tasks and actors. The two are often stacked: Slurm allocates the nodes, then a Ray cluster is started on top of them. University clusters mostly run Slurm, and for ordinary training sbatch + torchrun is enough.