Files
lancedb/docs/web/training/data-loading.mdx
147fdb25a0 feat(python): add two-phase shuffled reads (2PSR) to elastic dataloader (#5066)
Supersedes #4263, which I can no longer push to. This PR continues the
same branch, so the review history is there.

## Summary

Adds two-phase shuffled reads (2PSR) to `StreamingDataset`, enabled with
`block_size`:

1. **Block shuffle:** contiguous blocks of `block_size` live rows are
shuffled and assigned to splits. This replaces 1-phase's per-row take
with mostly contiguous range scans, which are much cheaper on object
storage.
2. **Bounded row shuffle:** each split shuffles rows over a rolling
window of `window_blocks` blocks. `max_shuffle_distance` bounds how far
a row can move.

The feature also supports `filter` (sparse takes of live rows),
`reshuffle_blocks_per_epoch`, resume and checkpointing, background block
prefetch, and multi-worker DataLoaders. 2PSR stays opt-in:
`block_size=None` keeps today's 1-phase behavior.

Since the last review round:

- **Fixed worker startup with small blocks.** The pickled dataset no
longer grows with the number of blocks; the block order is rebuilt in
`__setstate__`. Once that pickle passed the 64 KiB pipe buffer, spawned
DataLoader workers started one at a time (~280 s with 128 workers at
≤2,048-row blocks).
- **Fixed per-call block copies.** Each loaded block is combined into a
single chunk. Before, `take` on a multi-chunk block concatenated the
whole block on every call.
- **Fixed early eviction.** Blocks are evicted only behind the
contiguous prefix of rows already served. With `io_queue_depth > 1`,
calls can arrive out of order and previously evicted blocks that were
still needed, causing 5–40% extra reads.
- **New default:** `window_blocks` now defaults to 8, and the docstring
recommends `block_size=512` with DataLoader workers.

None of these fixes changes which rows are read or their order. A check
across 12 config, epoch and seed combinations on 8 ranks gave identical
per-rank order before and after.

## Benchmarks

Throughput was measured on EC2 i4i.32xlarge in us-west-2, reading a
FineWeb-Edu table of 4,096 B rows. Each number is the median of 3
trials, and each trial is a full pass. 2PSR used 512-row blocks, 256
splits, 128 workers and `io_queue_depth=4`. 1-phase used 32 splits, 8
workers and `io_queue_depth=32`.

| Storage | Rows | 2PSR | 1-phase | Speedup |
|---|---|---|---|---|
| S3 | 8.4M (34 GB) | 16.9 s | 230 s | 13.6× |
| S3 | 33.6M (137 GB) | 45.6 s | 781 s | 17.1× |
| S3 | 134M (550 GB) | 168 s | 3,098 s | 18.4× |
| Local NVMe | 8.4M | 16.4 s | 116 s | 7.1× |

On the 8.4M-row S3 table, 2PSR reads 1.5–2.0 GB/s at every block size
from 128 to 65,536 rows. A fit across the three S3 sizes gives 2PSR
about 7 s fixed cost plus 3.4 GB/s, and 1-phase about 39 s plus 0.18
GB/s. That puts the large-table limit near 19×.

Quality was measured by pretraining GPT-2 124M on 2^21 FineWeb-Edu docs
for 16 epochs on 8×H100. The table shows final validation loss, mean ±
SD over 3 seeds:

| Reader | Final val loss |
|---|---|
| 1-phase | 2.8464 ± 0.0006 |
| 2PSR, `block_size=128`, msd 4,096 | 2.8457 ± 0.0011 |
| 2PSR, `block_size=512`, msd 4,096 | 2.8457 ± 0.0007 |
| 2PSR, `block_size=2048`, msd 32,768 | 2.8466 ± 0.0009 |
| No shuffle (1 seed) | 2.8606 |

Every 2PSR config is within seed noise of 1-phase. The 95% confidence
intervals of the difference all include zero and are at most 13% of the
no-shuffle penalty. Training throughput was the same for every reader
(3.15–3.18M tok/s, GPU-bound).

## Testing

- `test_elastic_dataloader.py` and `test_permutation.py`: all 324 tests
pass after merging `main`. The new tests cover:
  - pickle size independent of block count;
  - single-chunk blocks;
  - no re-reads under out-of-order calls;
  - window defaults;
  - resume, filter, worker and checkpoint behavior.
- `ruff check` and `ruff format --check` are clean.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Co-authored-by: Xuanwo <github@xuanwo.io>
2026-11-25 09:08:39 -08:00

356 lines
16 KiB
Plaintext

---
title: "PyTorch Data Loader"
sidebarTitle: "PyTorch Data Loader"
description: "Stream, shuffle, transform, and resume model training data with StreamingDataset."
icon: boxes-stacked
availability:
embedded: available
enterprise: available
---
Advanced data loading scenarios can be handled by the `StreamingDataset`. This object allows you to apply preprocessing before training, pipelined reads, and more. Use this when the training data does not fit in memory, or when you need deterministic global batches across cluster sizes.
<CodeGroup>
```py Python icon=Python
import torch
from lancedb.streaming import StreamingDataset
db = lancedb.connect("file://some/db/path")
table = db.open_table("some_table")
dataset = StreamingDataset(table, shuffle_seed=42)
dataloader = torch.utils.data.DataLoader(
dataset,
batch_size=128,
num_workers=0,
)
for batch in dataloader:
train_step(batch)
```
</CodeGroup>
The `StreamingDataset` wraps a LanceDB `Table` and yields plain Python dictionaries by default. Whether iterating directly or through a PyTorch `DataLoader`, only one iterator can be simultaneously active on a `StreamingDataset` instance.
<Note>
`StreamingDataset` is built on the [`Permutation`](/training/permutation) API and works with both LanceDB Embedded and LanceDB Enterprise. The underlying table data can live on local disk or object storage.
</Note>
## Filtering {#filtering}
The `StreamingDataset` object allows you to train models on only the subset of rows that satisfy a user-defined filter, specified using the `filter` parameter. This can be useful for removing large rows, badly-sourced data, and a wide range of other applications.
You can also use the `columns` parameter to load only a subset of columns.
<CodeGroup>
```py Python icon=Python
ds = StreamingDataset(
table,
shuffle_seed=42,
columns=["image", "label"], # skip all other columns
filter="category = 'train'", # only training rows
)
```
</CodeGroup>
## Shuffling Rows {#shuffling-rows}
In model training, model quality can be hurt by unintentionally learning patterns in the ordering of the source data. Shuffling the dataset before training alleviates this problem. However, fetching rows with scattered sparse reads across object storage can be dramatically slower than fetching contiguous batches. `StreamingDataset` shuffles rows individually by default; `shuffle_clump_size` and `block_size` each trade some randomness for more contiguous reads.
<Note>
`StreamingDataset` shuffle seeds combine `shuffle_seed` with `epoch`; each epoch produces a different permutation while runs
with the same inputs remain reproducible. Set `shuffle_seed = None` to generate a random seed upon pipeline initialization.
</Note>
### Row-Level Shuffle {#one-phase-shuffle}
By default, `shuffle_clump_size` is `None` and rows are shuffled individually: the rows of the source dataset are shuffled according to a pseudorandom permutation, then fed in batches to the accelerator. This gives the best possible randomness, but can exhibit low throughput.
<CodeGroup>
```py Python icon=Python
# 1-phase shuffled read: rows shuffled individually.
for epoch in range(num_epochs):
ds = StreamingDataset(
table,
shuffle_seed=42,
epoch=epoch, # changes the permutation each epoch
)
for sample in ds:
train_step(sample)
#Evaluation: deterministic sequential order, no shuffle.
eval_ds = StreamingDataset(table, shuffle=False)
for sample in eval_ds:
eval_step(sample)
```
</CodeGroup>
### Clumped Shuffle {#two-phase-shuffle}
Setting `shuffle_clump_size` to an integer shuffles contiguous groups ("clumps") of that many rows instead of single rows. Each clump keeps its rows in storage order and moves as a unit, so storage I/O consists mostly of contiguous reads rather than single-row fetches. Larger clumps improve I/O locality, which matters most on object storage, at the cost of randomness.
<CodeGroup>
```py Python icon=Python
# Clumped shuffled read: rows are shuffled in groups of contiguous rows
# instead of individually, trading a bit of randomness for much cheaper I/O.
for epoch in range(num_epochs):
ds = StreamingDataset(
table,
shuffle_seed=42,
epoch=epoch,
shuffle_clump_size=1024, # contiguous rows that move together
)
for sample in ds:
train_step(sample)
# Evaluation: deterministic sequential order, no shuffle.
eval_ds = StreamingDataset(table, shuffle=False)
for sample in eval_ds:
eval_step(sample)
```
</CodeGroup>
### Block Shuffle {#block-shuffle}
Setting `block_size` enables a two-phase shuffled read. First, contiguous blocks of `block_size` rows are shuffled and read with range scans. Then each split shuffles rows across a rolling window of `window_blocks` blocks (default `8`). Unlike a clump, a block does not stay together: a row can move up to `max_shuffle_distance` positions (default `window_blocks * block_size`) from its place in the block order. Every split serves the same number of rows, so a split can start or end partway through a block, and fewer than `num_splits` rows are left out per epoch.
`block_size=512` is a good starting point. Use [DataLoader workers](#dataloader-workers), because throughput comes from reading many splits in parallel; `num_splits` must be divisible by `world_size * num_workers`. Keep in mind:
- The table needs at least `num_splits * block_size` live rows (after `filter`), so that each split gets at least one full block. The example below needs at least 32,768.
- `block_size` cannot be combined with `shuffle_clump_size` or `split_strategy`; passing both raises `ValueError`.
- On LanceDB Embedded, reading on-disk tables requires the optional `pylance` package (`pip install "lancedb[pylance]"`).
<CodeGroup>
```py Python icon=Python
# Block shuffle: shuffle contiguous blocks, then rows within a bounded window.
for epoch in range(num_epochs):
ds = StreamingDataset(
table,
shuffle_seed=42,
epoch=epoch,
num_splits=64,
block_size=512, # rows per contiguous block read
window_blocks=8, # blocks per split whose rows are mixed together
)
loader = StreamingDataLoader(ds, batch_size=32, num_workers=16)
for batch in loader:
train_step(batch)
```
</CodeGroup>
## Fetching {#fetching}
Traditional datasets have often been designed to yield a single sample at a time upon iteration. However, in modern use cases, accessing data on object storage one row at a time introduces too much per-call overhead. Thus, `StreamingDataset` fetches data in read batches, whose size is controlled by the `read_batch_size` parameter (defaults = `64`).
In addition to batching requests, the prefetching mechanism reads ahead in the background. While one batch is being processed, `StreamingDataset` reads several subsequent batches. The `io_queue_depth` parameter specifies the number of batches simultaneously kept in flight per split (default = `4`); it replaces `prefetch_batches`, which still works but is deprecated. A larger value provides more buffering against jittery workloads, but also increases memory use and I/O concurrency.
<CodeGroup>
```py Python icon=Python
ds = StreamingDataset(
table,
shuffle_seed=42,
read_batch_size=256, # rows fetched per LanceDB call per split
io_queue_depth=8, # batches to keep in flight per split
)
```
</CodeGroup>
## Transforming {#transforming}
Many model training workloads require performing a transformation to the data after it is loaded from object storage and before it is passed to the GPU. For example, we may need to decode images, tokenize text, or normalize vectors. A transformation function can be provided using the `transform` parameter.
A transformation function must receive a PyArrow `RecordBatch` and return an iterable. For example, the default transform function returns a list of Python dictionaries. Furthermore, the input expected by PyTorch must match the collation function used in the PyTorch data loader. PyTorch's default collation function accepts a Python dictionary and several other types, and is thus compatible with the default `StreamingDataset` transform function. If your custom transform function returns something different (for example, Arrow record batches), you may need to provide a compatible PyTorch collation function.
<CodeGroup>
```py Python icon=Python
import pyarrow as pa
def normalize(batch: pa.RecordBatch) -> list[dict]:
# This pure-Python loop holds the GIL and is shown for illustration only.
# In practice, prefer a library like torchvision or numpy that releases the
# GIL so the ThreadPoolExecutor can run transforms in parallel.
rows = batch.to_pylist()
for row in rows:
row["image"] = [v / 255.0 for v in row["image"]]
return rows
ds = StreamingDataset(table, shuffle_seed=42, transform=normalize)
```
</CodeGroup>
`StreamingDataset` manages expensive transforms through a
`ThreadPoolExecutor` whose worker count equals the number of available CPUs (`transform_parallelism`). Furthermore, transformations are applied to batches (instead of individual samples) to amortize per-batch overhead.
Heavier per-sample work belongs in the same function, such as decoding
video. Store each clip in a Blob v2 column (`lancedb.blob("video")`). A scan
returns small descriptors instead of the video bytes, so reading other
columns never pulls video in. `fetch_blob_files` opens the clips for a batch
of rows as file handles, and `torchcodec`'s `VideoDecoder` decodes just the
frames you ask for. `ExtractFrames` samples 8 evenly spaced frames from each
clip:
<CodeGroup>
```py Python icon=Python
import functools
from torchcodec.decoders import VideoDecoder
class ExtractFrames:
def __init__(self, uri: str, name: str, num_frames: int = 8) -> None:
self.uri, self.name, self.num_frames = uri, name, num_frames
@functools.cached_property
def table(self) -> lancedb.table.Table:
return lancedb.connect(self.uri).open_table(self.name)
def __call__(self, rb: pa.RecordBatch) -> list[dict[str, torch.Tensor]]:
samples = []
for blob in self.table.fetch_blob_files("video", rb["_rowid"]):
decoder = VideoDecoder(blob)
idx = torch.linspace(0, len(decoder) - 1, self.num_frames).long()
samples.append({"frames": decoder.get_frames_at(idx.tolist()).data})
return samples
# `clips` is the table "clips" in the database at `uri`, with a Blob v2 column "video"
train = StreamingDataset(clips, columns=["_rowid"], transform=ExtractFrames(uri, "clips"))
```
</CodeGroup>
Real data has bad rows, such as a truncated frame. Raise inside the
transform and set `on_transform_error="skip"` (or `"warn"` to log each
failure). `StreamingDataset` re-runs the failing batch one row at a time,
drops only the rows that raise, and counts them in `dataset.rows_skipped`.
When the bad rows match a SQL predicate, prefer `filter=` instead: it runs
before the splits are built, so every split keeps the same length.
### DataLoader Workers {#dataloader-workers}
The thread-based transformation model that `StreamingDataset` uses by default is only effective when the transform
function releases the GIL. This is true for many Python scientific libraries, including NumPy, PyArrow, and
TorchVision, but not for pure-Python transforms. PyTorch can launch multiple DataLoader worker processes per rank,
and `StreamingDataset` uses `get_worker_info()` to give each worker a non-overlapping group of splits.
Multiprocessing adds pickling and transfer overhead and increases memory use. Start with `num_workers=0`, which keeps
loading in the rank's main process, and add workers only after confirming an unavoidable GIL bottleneck. If you use
workers, `num_splits` must be divisible by `world_size * num_workers`. Use the `forkserver` or `spawn` multiprocessing
context because LanceDB uses internal threads.
<CodeGroup>
```py Python icon=Python
dataloader = torch.utils.data.DataLoader(
dataset,
batch_size=batch_size,
num_workers=2,
multiprocessing_context="forkserver",
persistent_workers=True,
)
```
</CodeGroup>
By default, `StreamingDataset` and `Permutation` pickle the native table's
reopen state, including its connection, table identity, open options and
explicit storage overrides. A standard-mode handle reopens at the latest
version; `checkout(version)` and branch-scoped handles keep their pinned
version and branch. `memory://` tables are exported as an Arrow snapshot, so
workers see the data as of pickling; an in-memory connection by itself is not
picklable.
Connections opened with a `Session` cannot be pickled. For a Session-backed
table, pass a picklable `connection_factory` to
`Permutation.with_connection_factory` or `StreamingDataset(connection_factory=...)`
so each worker creates its own connection and Session.
Remote LanceDB Enterprise tables (`db://...`) work the same way: workers
reopen the table from the pickled connection state. Replace the URI, API key,
region and endpoint below with your deployment details. In application code,
load credentials from environment variables or a secrets manager:
<CodeGroup>
```py Python icon=Python
import torch
from lancedb.util import tbl_to_tensor
db = lancedb.connect(
"db://my-database",
api_key="your-api-key",
region="us-east-1",
host_override="https://your-endpoint",
)
table = db.open_table("my_table")
dataloader = torch.utils.data.DataLoader(
table,
batch_size=512,
num_workers=4,
multiprocessing_context="forkserver",
collate_fn=tbl_to_tensor,
)
```
</CodeGroup>
<Note>
This sends the connection state, including the API key, to each worker. Use a connection factory if credentials should be loaded inside the worker or your `client_config` contains a non-serializable `header_provider`.
</Note>
#### Providing a custom connection factory {#providing-a-custom-connection-factory}
For custom connection setup, pass a picklable `connection_factory` callable
that accepts a table name and returns an open table. This avoids
serializing connection credentials into worker state: it loads the API key
inside each worker instead. Set it in the shell before starting the Python
program, then replace the database URI, region and endpoint in the factory
with your deployment details:
<CodeGroup>
```bash Bash icon="terminal"
export LANCEDB_API_KEY="your-api-key"
```
</CodeGroup>
<CodeGroup>
```py Python icon=Python
import os
import torch
from lancedb.permutation import Permutation
def open_table(name: str):
db = lancedb.connect(
"db://my-database",
api_key=os.environ["LANCEDB_API_KEY"],
region="us-east-1",
host_override="https://your-endpoint",
)
return db.open_table(name)
table = open_table("my_table")
permutation = (
Permutation.identity(table)
.with_connection_factory(open_table)
)
dataloader = torch.utils.data.DataLoader(
permutation,
batch_size=512,
num_workers=4,
multiprocessing_context="forkserver",
)
```
</CodeGroup>
## Next steps {#next}
<CardGroup cols={2}>
<Card title="Permutation" icon="shuffle" href="/training/permutation">
The lower-level row ordering StreamingDataset is built on.
</Card>
<Card title="Observability" icon="gauge" href="/training/observability">
Pipeline counters for diagnosing loader bottlenecks.
</Card>
<Card title="Distributed Training" icon="server" href="/training/distributed-training">
Multi-GPU sharding and elastic determinism.
</Card>
<Card title="Checkpointing" icon="floppy-disk" href="/training/checkpointing">
Save progress so a failed run can pick back up.
</Card>
<Card title="Training Cache" icon="gauge-high" href="/training/training-cache">
How an Enterprise connection speeds up repeated epochs.
</Card>
</CardGroup>