I have a Pytorch datasets that contains graphs to be used in TransformerConv and other GNNs. The complete dataset has about 500000 graphs divided into 5 datasets of graphs of various sizes. Each dataset has various sizes but (if needed) they can be separated into files of constant length (although it would be inconvenient for the users to specify tens of datasets instead of 5). This is a typical graphs: Data(x=[104, 1], edge_index=[2, 312], edge_attr=[312, 1], y=[1], num_nodes=104). There are always 3 edges per vertex. There are graphs between 52 and 160 num_nodes. I currently load it as a complete set with torch.load (with on-the-fly zst decompression that does not add any significant time). Loading the whole dataset takes 15 minutes, even though after zst compression, this is only 200 MB. Propose how to store this data format so it can be read more quickly that 15 minutes as the raw files read in seconds on this system. Writing will be rare but reading will be frequent and has to be fast. The dataset can be loaded into memory but consider also reading chunk by chunk.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Given your requirements (fast reading, infrequent writing, and the ability to handle large datasets with varying graph sizes), here are several optimized storage and loading strategies for your PyTorch Geometric dataset:
1. Optimized PyTorch Geometric Dataset Storage
Since you're using PyTorch Geometric, the best approach is to store the data in a format that leverages PyG's built-in optimizations while minimizing I/O overhead.
Option A: PyG InMemoryDataset with Efficient Serialization
Store as .pt files (PyTorch's serialized format) but split into smaller chunks (e.g., 10,000 graphs per file).
Use torch.save with pickle_protocol=5 (highest efficiency for large tensors).
Load in parallel using torch.utils.data.DataLoader with num_workers > 0.
Pros:
Fast loading (PyTorch's serialization is optimized).
Can be loaded in chunks (avoids full dataset load).
Works well with PyG's InMemoryDataset.
Cons:
Still requires some disk I/O, but much faster than 15 minutes.
Implementation:
python
from torch_geometric.data import InMemoryDataset
import torch
class MyDataset(InMemoryDataset):
def __init__(self, root, transform=None, pre_transform=None):
super().__init__(root, transform, pre_transform)
self.data, self.slices = torch.load(self.processed_paths[0])
@property
def raw_file_names(self):
return ['data.pt']
@property
def processed_file_names(self):
return ['data.pt']
def process(self):
# Split into chunks and save
data_list = [...] # Your list of graphs
torch.save(data_list, self.processed_paths[0])
2. Memory-Mapped Storage (Fastest for Frequent Access)
If you can afford to keep the dataset in memory, memory-mapped files (mmap) are the fastest option.
Option B: Memory-Mapped .pt Files
Store the dataset in a single .pt file and load it with mmap=True.
Use torch.load(..., mmap=True) to avoid full loading.
Pros:
Near-instant access (only loads what's needed).
No need to split into chunks.
Cons:
Requires enough RAM to hold the dataset.
Implementation:
python
data = torch.load("data.pt", mmap=True) # Loads lazily
3. HDF5 Storage (Balanced I/O and Memory)
If you need chunked access without full memory loading, HDF5 is a good choice.
Option C: HDF5 with PyTorch Tensors
Store each graph's tensors (x, edge_index, edge_attr, y) in an HDF5 file.
Use h5py to read chunks efficiently.
Pros:
Fast random access.
Works well with large datasets.
Cons:
Slightly more complex to implement.
Implementation:
python
import h5py
# Writing
with h5py.File('data.h5', 'w') as f:
for i, graph in enumerate(graphs):
f.create_dataset(f'graph_{i}/x', data=graph.x)
f.create_dataset(f'graph_{i}/edge_index', data=graph.edge_index)
# ... (other tensors)
# Reading
def get_graph(i):
with h5py.File('data.h5', 'r') as f:
x = f[f'graph_{i}/x'][()]
edge_index = f[f'graph_{i}/edge_index'][()]
# ... (other tensors)
return Data(x=x, edge_index=edge_index, ...)
If you need columnar storage (e.g., for feature extraction), Parquet is a good choice.
Option D: PyArrow + Parquet
Store each graph as a row in a Parquet file.
Use pyarrow for fast I/O.
Pros:
Very fast for large datasets.
Works well with distributed storage.
Cons:
Requires conversion to PyG Data objects.
Implementation:
python
import pyarrow as pa
import pyarrow.parquet as pq
# Writing
table = pa.Table.from_pylist([{
'x': graph.x.numpy(),
'edge_index': graph.edge_index.numpy(),
# ... other tensors
} for graph in graphs])
pq.write_table(table, 'data.parquet')
# Reading
table = pq.read_table('data.parquet')
for batch in table.to_batches():
x = torch.tensor(batch['x'])
edge_index = torch.tensor(batch['edge_index'])
# ... (other tensors)
yield Data(x=x, edge_index=edge_index, ...)
5. Custom Binary Format (Fastest for Custom Workloads)
If you need maximum speed, a custom binary format (e.g., NumPy .npy or a custom binary layout) can be the fastest.
Option E: NumPy .npy Files
Store each graph's tensors in separate .npy files.
Use numpy.memmap for lazy loading.
Pros:
Extremely fast for random access.
Works well with PyTorch.
Cons:
Requires manual file management.
Implementation:
python
import numpy as np
# Writing
for i, graph in enumerate(graphs):
np.save(f'graph_{i}_x.npy', graph.x.numpy())
np.save(f'graph_{i}_edge_index.npy', graph.edge_index.numpy())
# ... (other tensors)
# Reading
def get_graph(i):
x = torch.tensor(np.load(f'graph_{i}_x.npy', mmap_mode='r'))
edge_index = torch.tensor(np.load(f'graph_{i}_edge_index.npy', mmap_mode='r'))
# ... (other tensors)
return Data(x=x, edge_index=edge_index, ...)
Recommendation
If you can keep the dataset in memory: Use memory-mapped .pt files (mmap=True).
If you need chunked loading: Use HDF5 or PyArrow Parquet.
If you need maximum speed: Use custom binary storage (e.g., .npy with mmap).
Would you like a full implementation for any of these options?
User
I probably wasn't clear enough. There are no thousands of files. There are only a few dataset each with about hundred of thousands of graphs. Reading them all by torch.load takes a long time. Here is the relevant code: def _load_compressed(path): if not path.endswith(".zst"): path += ".zst" dctx = zstd.ZstdDecompressor() with open(path, 'rb') as f: with dctx.stream_reader(f) as decompressor: buffer = io.BytesIO(decompressor.read()) # Use memory mapping for large files graphs = torch.load(buffer, map_location='cpu', weights_only=False) return [upcast_graph(g) for g in graphs]
There is additional upcasting but it takes a minor amount of time. The code is used inside of InMemoryDataset. Can you update your recommendations based on this info?
Assistant
Given your clarification, the bottleneck is in decompressing and loading a large .zst file (200 MB compressed, but likely much larger when decompressed). Since you're using InMemoryDataset and reading the entire dataset at once, here are optimized approaches:
1. Optimized Zstandard (ZST) Loading
Since you're already using ZST compression, the issue is likely in decompression + PyTorch deserialization. Here’s how to optimize:
Option A: Pre-Decompress and Cache
Pre-decompress the .zst file into a temporary .pt file (only once).
Load the .pt file directly (no decompression needed on subsequent runs).
Pros:
Near-instant loading after the first run.
No need to modify your dataset code.
Cons:
Requires extra disk space for the decompressed .pt file.
Implementation:
python
import os
import zstandard as zstd
import torch
def pre_decompress_zst(input_path, output_path):
dctx = zstd.ZstdDecompressor()
with open(input_path, 'rb') as f_in, open(output_path, 'wb') as f_out:
decompressor = dctx.stream_reader(f_in)
f_out.write(decompressor.read())
# Run this once to pre-decompress:
pre_decompress_zst("data.zst", "data.pt")
# Now load directly:
graphs = torch.load("data.pt", map_location='cpu')
2. Memory-Mapped ZST Loading
If you must keep the dataset compressed, use memory-mapped decompression:
Option B: mmap + ZST Streaming
Use zstd's streaming API with mmap to avoid full decompression.
import mmap
import zstandard as zstd
def load_zst_mmap(path):
with open(path, 'rb') as f:
# Memory-map the file
mm = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
# Decompress on-the-fly
dctx = zstd.ZstdDecompressor()
decompressor = dctx.stream_reader(mm)
buffer = io.BytesIO(decompressor.read())
graphs = torch.load(buffer, map_location='cpu')
return graphs
3. Split into Smaller .zst Files
If the dataset is too large for a single file, split it into smaller chunks (e.g., 10,000 graphs per file).
Option C: Chunked ZST Files
Split the dataset into smaller .zst files (e.g., data_0.zst, data_1.zst, ...).
Load them in parallel using DataLoader with num_workers > 0.
Pros:
Faster loading (parallel I/O).
Works with InMemoryDataset.
Cons:
Requires modifying the dataset structure.
Implementation:
python
from torch.utils.data import DataLoader
class ChunkedDataset(InMemoryDataset):
def __init__(self, root, num_chunks=10):
super().__init__(root)
self.chunks = [torch.load(f"{root}/data_{i}.pt") for i in range(num_chunks)]
self.data = sum(self.chunks, []) # Flatten
def process(self):
# Split into chunks and save
for i, chunk in enumerate(self.split_into_chunks(self.raw_data)):
torch.save(chunk, f"{self.processed_dir}/data_{i}.pt")
4. Use PyTorch’s lazy Loading (Experimental)
If you're using PyTorch ≥ 2.0, try torch.load(..., lazy=True) (experimental but may help).