dataio

dataio is a Rust-backed data loader and IO layer for Python. It reads and writes
local files, S3, R2, GCS, Azure, HTTP(S) and the Hugging Face Hub, runs
decode/transform/batch pipelines on native worker pools, and returns NumPy,
PyTorch, JAX, DLPack or Arrow data. It supports free-threaded CPython and ships a
command line that replaces s5cmd.
Install
pip install dataio-rs
python -m dataio # report this host's capabilities
Python 3.11 or newer on Linux x86_64 (glibc 2.28+) gets a prebuilt wheel: abi3 for
CPython with the GIL, cp314t for free-threaded CPython 3.14; other platforms build
from the sdist (Develop). Nothing else is required: install NumPy,
PyTorch, JAX or PyArrow for the outputs you use. CUDA, nvJPEG, cuFile (GDS) and
libfabric load on first use, so the wheels run without them. To upgrade, read the
changelog and the migration guide.
Quick start
This runs without input files or a framework:
import dataio
records = [{"key": "a", "payload": b"red"}, {"key": "b", "payload": b"sky"}]
pipe = dataio.pipeline(dataio.slot("payload").decode_bytes(), dataio.batch(2))
with pipe.bind(records).run("dlpack") as loader:
for batch in loader:
print(batch.keys, batch["payload"].shape) # ['a', 'b'] [2, 3]
output= selects the framework. The loader's run() defaults to "torch" and
also takes "numpy", "jax", "dlpack", a name registered with
register_output_adapter, or a callable. Readers default to "numpy" (read_dcp
to "torch"): read_image takes the loader's choices, and tensor readers such as
read_safetensors take "numpy" or "torch". Column-batch iterators
(iter_batches, iter_arrow_batches) yield {column: [values]} unless
output="numpy". The examples are complete scripts.
Build a pipeline
A pipeline is optional record maps, one or more slot chains, one batch stage
(batch, collate or group_by), then optional batch transforms and maps.
Building it does no IO; .bind(records).run(...) starts a loader.
pipe = dataio.pipeline(
dataio.map(lambda row: {"image": row["path"], "label": row["class_id"]}),
dataio.slot("image").decode_image(mode="rgb").resize_short(size=256)
.center_crop(h=224, w=224).normalize("imagenet"),
dataio.slot("label").passthrough(),
dataio.batch(64, drop_last=True, prefetch=4),
)
with pipe.bind(records).run("torch", concurrency=64) as loader:
for batch in loader:
train_step(batch["image"], batch["label"])
Slot methods are shorthand for the factories in these namespaces:
| Namespace |
Operations |
dataio.decoders |
Image, audio (resampling="sinc" anti-aliases), JSON, NPY, safetensors, text, bytes and PT decoding |
dataio.transforms |
Resize, crop, normalize, augment and conditional transforms |
dataio.batch_transforms |
MixUp, CutMix, padding, shuffle and normalization |
dataio.cond |
Field and shape predicates for slot activation and transforms |
A dataio.map before the batch stage gets input records, one after it the decoded
Batch: a passthrough slot plus dataio.map(lambda b: collate_fn(b["sample"]))
reuses an existing collator. collate() keeps the batches a source yields,
group_by(key) batches each run of equal keys, and
from_sampler(batch_sampler, row_fn) tags a batch sampler's rows for
group_by("batch_id"). Examples: batch boundaries,
conditional slots,
conditional transforms; contracts:
callbacks.
Choose sources
bind takes a reusable iterable or a zero-argument factory and reads it once per
epoch; from_iterable(...) is single-pass. Wrap a source to index, compose,
shuffle or mix it:
photos = dataio.records(dataset, indexed=True) # len() + integer __getitem__
art = dataio.webdataset(manifest="s3://b/art/manifest.json")
records = dataio.mix([photos, art], [0.7, 0.3], seed=0, stop="first")
| Call |
Effect |
records(dataset, indexed=True) |
Integer row access, bypassing the dataset's iterator; with batch(N), __getitems__(indices) fetches rows together |
.map_records(fn), .flat_map_records(fn), .concat(*sources) |
Replace one record, emit zero or more, append sources without opening them early |
.shuffle(seed=42, buffer_size=4096) |
Mix nearby records in a buffer of that many records; no buffer_size means a full permutation |
mix(sources, weights, seed=, stop=) |
Interleave indexed sources by weight into an indexed source; stop="first" ends before a source repeats, "all" once every source was read, "never" after length= samples |
webdataset("shard-{0000..0099}.tar"), webdataset(manifest=...) |
Tar shards; a shard_writer manifest opens as an indexed, seekable source |
Expanded and streaming sources need a buffered shuffle. Contracts:
record sources, bulk reads,
weighted mix; examples:
callable sources, composition.
Configure execution
Loader options and process-wide environment settings bound concurrency and
memory; dataio.env_vars() lists every setting with its default.
| Setting |
Effect |
run(..., concurrency=N) |
Per-shard stage admission; start with the default "auto", measure higher values for high-latency sources |
batch(..., prefetch=K) |
Batches in flight |
run(..., max_prefetch_bytes=B) |
Logical bytes of pending native outputs with a fixed layout; not an RSS limit |
run(..., map_workers=N) |
Threads for record maps, sized-source __getitem__ and from_sampler record functions; output equals N=1, callbacks must be thread-safe |
run(..., order="completion") |
Deliver batches as they finish instead of in submit order; no mid-epoch resume |
DATAIO_CPU_WORKERS / DATAIO_IO_WORKERS |
Process-wide CPU / async IO worker pools |
DATAIO_HTTP_MAX_INFLIGHT_READS |
Process-wide GET/HEAD limit; 0 means unlimited |
DATAIO_OBJECT_SHARDS |
HTTP and object-store client shard fanout |
From async code, run async for batch in batches inside
async with loader.aiter() as batches: it reuses native prefetch and closes on
early exit. One iteration owns a loader at a time. Scheduling, memory bounds and
cleanup: plans and execution,
iteration and cancellation.
Handle errors
run(..., on_failure=...) decides what a failed row does; batch.errors lists each
failure (index, key, stage, op, message).
on_failure= |
Effect |
"skip" (default) |
Drop failed rows; raise when no row of a batch survives |
"strict" |
Raise on a failed row |
N |
Drop failed rows; raise when fewer than N rows of a batch survive |
log_errors=True logs each failure to the dataio.rows logger, or pass a callable.
Source-iteration and Python batch-map errors propagate as raised
(callback contracts).
Shard and resume
shard= splits each epoch across ranks; state_dict() / load_state_dict()
checkpoint a loader mid-epoch. A keyed shuffle reshuffles a huge indexed dataset
every epoch without materializing its index, and restores on any world size:
records = dataio.records(dataset, indexed=True, resume="seek")
loader = pipe.bind(records).run(
"torch", shard={"id": rank, "of": world_size}, seed=42, shuffle="keyed",
) # or shuffle=("block", 1024, 8) to read 1024-record blocks within 8-block windows
states = [None] * world_size
torch.distributed.all_gather_object(states, loader.state_dict()) # save `states`
# After restarting on any world size, every rank restores the gathered list:
loader.load_state_dict(states)
Ranks save after the same step; on an unchanged layout a rank can restore its own
state_dict() alone. "pad": True gives every rank the same batch count. A
restore replays the consumed prefix unless resume="seek" lets an indexed source
with index-determined lookups skip it. Contracts:
resume, checkpoint identity,
elastic resume.
Read and write objects
Local paths, s3://, r2://, gs://, az://, hf:// and HTTP(S) URIs share
these operations where the backend supports them:
dataio.configure_endpoint("r2", "https://<account>.r2.cloudflarestorage.com")
dataio.configure_transport("https", timeout_secs=30, readall_concurrency=32)
chunk = dataio.read("s3://bucket/file.bin", offset=0, size=1 << 20)
parts = dataio.fetch("s3://bucket/file.bin", ranges=[(0, 64), (4096, 256)]) # one GET
dataio.write("s3://bucket/out.bin", chunk, if_none_match="*") # create only
etag = dataio.copy("s3://bucket/out.bin", "s3://bucket/copy.bin")
dataio.exists("s3://bucket/out.bin") # False only when missing; other errors raise
dataio.ls("s3://bucket/prefix/", recursive=False, detail=True) # one level, size/etag/mtime
dataio.glob("s3://bucket/**/*.safetensors")
payload = dataio.reader("s3://bucket/shard.tar.gz").gunzip().tar_entry("0001.jpg").read_all()
with dataio.writer("s3://bucket/checkpoint.bin") as writer:
writer.write_chunks(huge_generator())
with dataio.shard_writer("s3://bucket/out/shard-{:06d}.tar", max_bytes=1 << 30) as shards:
for key, jpg, meta in samples():
shards.write({"__key__": key, "jpg": jpg, "json": meta})
records = dataio.webdataset(manifest=shards.manifest) # indexed; no tar headers read
fetch_into(uri, buffer) fills an existing buffer, stream(uri) reads a body on
demand (bytes, lines or server-sent events), head_many(uris) sends HEADs
concurrently, and copy(recursive=True), sync and delete(recursive=True) work
on trees like the command line. Requests retry 5xx,
resets and timeouts up to max_attempts=, and wait out a throttling object store (429/503)
within their time budget, narrowing what is in flight to the rate it takes;
deadline_secs= bounds one call.
On s3:// and r2://, the store verifies every upload's CRC64NVME, and every
whole-object download is checked against the stored one.
s3:// uses the AWS credential chain (environment, profiles, SSO, web identity,
ECS/EKS Pod Identity, instance metadata); configure_credentials(scheme, ...) sets
explicit credentials, and clear_credentials(scheme) re-reads them. Details:
network configuration,
byte and format IO.
Command line
python -m dataio runs the same operations with the same credentials, so shell
scripts need no other S3 tool; python -m dataio <command> --help lists its flags.
python -m dataio cp model.safetensors s3://bucket/models/ # -> .../models/model.safetensors
python -m dataio cp -r --workers 32 s3://bucket/models/vae /nvme/vae
python -m dataio cp -n 's3://bucket/ckpt/__3_*.distcp' /nvme/ckpt/
python -m dataio sync --workers 128 --delete --no-follow-symlinks /fsx/run s3://bucket/archive/run
python -m dataio rm -r s3://bucket/scratch/run-1 # prints "deleted 1234"
python -m dataio sync --dry-run --delete --exclude '*.tmp' /fsx/run s3://bucket/run # plan only
python -m dataio --json sync s3://bucket/data /nvme/data # {"copied": .., "skipped": .., "deleted": ..}
python -m dataio head --max-attempts 1 --deadline 5 s3://bucket/ckpt/COMMIT # a fast probe