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.
Okay, let's break down the problem and explore solutions for faster data loading.
The core issue is likely the overhead associated with:
Opening/closing potentially hundreds of thousands of files.
Deserializing each individual graph object using torch.load.
The sheer number of operations, even if each is fast.
The goal is to reduce this overhead while maintaining compatibility with PyTorch Geometric (Data objects) and allowing for efficient reading (potentially chunked).
Here are a few strategies, ranging from simplest to more complex:
1. Single Large .pt File (Recommended First Step)
This is often the most straightforward and effective solution if the entire dataset can fit into memory (as you stated).
How it works: Instead of saving each graph as a separate file, save the entire collection (e.g., a list or dictionary of Data objects) into a single file using torch.save.
Saving:
python
import torch
from torch_geometric.data import Data # Assuming your graphs are Data objects
# Assume 'all_graphs' is a list containing all your 500k Data objects
# Example: all_graphs = [load_graph_i(...) for i in range(500000)]
# Make sure all_graphs is loaded into memory first (takes the 15 mins)
# Save the entire list to one file
output_file = 'full_dataset.pt'
torch.save(all_graphs, output_file)
# Optional: Apply compression during save if desired, though torch.save handles basic compression well.
# torch.save(all_graphs, f"your_data.zip") # Example using zip
print(f"Saved all graphs to {output_file}")
Loading:
python
import torch
from torch_geometric.loader import DataLoader # Or just use the list directly
# Load the entire list from the single file
full_dataset_list = torch.load('full_dataset.pt')
print(f"Loaded {len(full_dataset_list)} graphs.")
# Now you can use this list directly or wrap it in PyG utilities
# Example: Create a DataLoader
# loader = DataLoader(full_dataset_list, batch_size=32, shuffle=True)
# for batch in loader:
# # Process batch
# pass
# Example: Accessing a chunk (still requires the full list in memory)
# chunk = full_dataset_list[10000:20000]
# process_chunk(chunk)
Pros:
Drastic Speedup:torch.load is highly optimized for single files. Loading one large file is significantly faster than loading 500k small files.
Simplicity: Minimal changes required to your saving process. Loading code is also simpler.
Compatibility: Directly yields a list of PyTorch Geometric Data objects.
Cons:
Memory Usage: The entire dataset is loaded into memory at once upon calling torch.load. This is acceptable based on your description but is a limitation if memory becomes scarce.
Chunking: While you can access chunks via slicing (full_dataset_list[start:end]), the initial torch.load still loads everything. It doesn't load only the chunk.
File Size: The uncompressed file size might be larger than your 200MB compressed size, but torch.load is generally efficient.
2. LMDB (Lightning Memory-Mapped Database)
LMDB is a high-performance key-value store often used for large datasets in deep learning, especially with image data, but applicable here too.
How it works: Store each graph (or its serialized representation) as a value associated with a unique key (e.g., the graph's index). LMDB uses memory mapping, allowing efficient access to parts of the file without loading everything.
Saving:
python
import torch
import lmdb
import pickle # Or use torch.save/load within the value
env = lmdb.open('graph_db', map_size=int(1e10)) # Adjust map_size as needed
with env.begin(write=True) as txn:
# Assume graph_generator yields (index, Data_object) pairs
for i, graph_data in enumerate(graph_generator()):
# Serialize the Data object. Using pickle is common for Python objects.
# Ensure graph_data is detached from computation graph if necessary
serialized_data = pickle.dumps(graph_data)
# Alternative: serialized_data = torch.save(graph_data, None) # Save to bytes buffer
txn.put(str(i).encode('utf-8'), serialized_data)
if i % 10000 == 0:
print(f"Saved {i} graphs to LMDB")
env.close()
Loading: Requires a custom torch.utils.data.Dataset or torch_geometric.data.Dataset.
python
3. HDF5 (Hierarchical Data Format)
HDF5 is a file format designed for storing and organizing large amounts of data. Libraries like h5py provide Python interfaces.
How it works: You can structure the HDF5 file to store datasets (like tensors). You could store all 'x' matrices concatenated, all 'edge_index' lists, etc., along with metadata indicating where each graph starts and ends. Or, create a group for each graph.
Saving: This requires careful planning depending on how you want to access it. A common approach is to store tensors for features, edge indices, etc., and maybe store graph boundaries.
python
import h5py
import numpy as np
import torch
# Example structure: Store concatenated data and offsets
output_file = 'graphs.h5'
with h5py.File(output_file, 'w') as f:
# Prepare to store concatenated data (requires tensors to be on CPU)
all_x = []
all_edge_index = []
all_edge_attr = []
all_y = []
num_nodes_list = []
graph_offsets = [0] # Store start index for each graph's data
# Assume graph_generator yields Data objects
for i, graph_data in enumerate(graph_generator()):
graph_data = graph_data.cpu() # Ensure data is on CPU for numpy conversion
all_x.append(np.array(graph_data.x))
all_edge_index.append(np.array(graph_data.edge_index))
all_edge_attr.append(np.array(graph_data.edge_attr))
all_y.append(np.array(graph_data.y))
current_num_nodes = graph_data.num_nodes
num_nodes_list.append(current_num_nodes)
# Calculate offset for the next graph's data concatenation
# Assuming edge_index has shape [2, num_edges]
offset = graph_offsets[-1] + all_edge_index[-1].shape[1]
graph_offsets.append(offset)
if i % 10000 == 0:
print(f"Processed {i} graphs")
# Concatenate all arrays
f.create_dataset('x', data=np.concatenate(all_x, axis=0), compression="gzip") # or zstd
f.create_dataset('edge_index', data=np.concatenate(all_edge_index, axis=1), compression="gzip")
f.create_dataset('edge_attr', data=np.concatenate(all_edge_attr, axis=0), compression="gzip")
f.create_dataset('y', data=np.concatenate(all_y, axis=0), compression="gzip")
f.create_dataset('num_nodes', data=np.array(num_nodes_list), compression="gzip")
f.create_dataset('offsets', data=np.array(graph_offsets), compression="gzip")
print("Saved data to HDF5")
4. Petastorm / Other Frameworks
Frameworks like Petastorm (from Uber) are designed to serve ML data, often from formats like Parquet.
How it works: Convert your dataset into a format like Parquet, partitioned effectively. Petastorm provides readers that integrate with PyTorch.
Pros:
Standardized format.
Good tooling for large-scale data.
Cons:
Complexity: Requires converting the data to Parquet, which might be non-trivial for graph structures.
Overhead: Likely overkill for this specific problem unless you're already in a Spark/Hadoop ecosystem.
PyTorch Integration: Might require more boilerplate code.
Recommendation:
Try Option 1 (Single Large .pt file) first. It's the simplest and offers the highest chance of a significant speedup with the least implementation effort, given that the dataset fits in memory. Load it once, and then use the resulting list for training, validation, testing, or creating DataLoaders. Accessing chunks is just list slicing.
If Option 1 is insufficient OR if memory becomes a constraint later: Consider Option 2 (LMDB). It provides excellent read performance and memory efficiency through memory mapping, and works well with DataLoader for chunked processing. The trade-off is the increased implementation complexity.
Avoid complex formats like HDF5 or Petastorm unless the simpler options prove inadequate, as they require significantly more effort to implement correctly for graph data.
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
Okay, thanks for the clarification! This changes the context significantly. The issue isn't file I/O overhead from thousands of files, but the time taken by torch.load to deserialize a single large file (or one of the few files) containing hundreds of thousands of graph objects, even after Zstandard decompression.
Your current approach:
Decompress the .zst file into memory (using decompressor.read()).
Load the entire decompressed data (assumed to be a list of Data objects) using torch.load.
Iterate through the loaded list to upcast_graph each object.
The bottleneck is step 2: torch.load processing that large, decompressed object stream. torch.load is generally single-threaded for the deserialization process itself.
Given this, the goal is to find a storage format and loading mechanism that either:
a) Allows the data to be deserialized more efficiently (perhaps leveraging multiple cores).
b) Stores the numerical data in a way that allows faster reconstruction of Data objects.
Here are revised recommendations, focusing on parallel loading and more efficient numerical storage:
1. WebDataset (Highly Recommended)
Concept: WebDataset is a library designed for efficiently loading large datasets into PyTorch, especially from distributed storage or archives. It excels at parallel data loading and preprocessing using multiple worker processes (num_workers in DataLoader). Instead of one massive file, you store data in sharded archives (like .tar files).
How it Works:
Saving: You need to rewrite your saving process. Iterate through your existing large file (or load it once temporarily) and save each individual graph (or maybe small batches of graphs) into separate entries within .tar archives. You can compress these individual entries (e.g., using Zstd again).
import torch
import lmdb
import pickle
from torch_geometric.data import Dataset, Data
class GraphLMDBDataset(Dataset):
def __init__(self, db_path):
super().__init__()
self.db_path = db_path
self.env = lmdb.open(db_path, readonly=True, lock=False, meminit=False)
# Get number of items (e.g., by counting keys or storing count separately)
with self.env.begin() as txn:
self.num_items = txn.stat()['entries']
def __len__(self):
return self.num_items
def get(self, idx):
# Retrieve and deserialize the graph data for the given index
key = str(idx).encode('utf-8')
with self.env.begin() as txn:
serialized_data = txn.get(key)
# graph_data = torch.load(io.BytesIO(serialized_data)) # If using torch.save to buffer
graph_data = pickle.loads(serialized_data)
return graph_data
def close(self):
# Close the LMDB environment when done
self.env.close()
# Usage:
lmdb_dataset = GraphLMDBDataset('graph_db')
# Access individual graphs (fast)
# graph_5 = lmdb_dataset[5]
# Use with DataLoader
# from torch_geometric.loader import DataLoader
# loader = DataLoader(lmdb_dataset, batch_size=32, shuffle=True)
# for batch in loader:
# # Process batch
# pass
# Clean up
# lmdb_dataset.close()
Pros:
Very Fast Reads: Memory mapping provides efficient access.
Chunking/Iteration: Excellent support. You can iterate through the dataset using the custom Dataset and DataLoader, effectively processing in batches without loading everything upfront.
Scalability: Handles very large datasets well.
Cons:
Implementation Complexity: Requires writing a custom Dataset class.
Serialization Overhead: You still need to serialize/deserialize each graph, although LMDB's retrieval is fast. Using pickle is convenient but can be slower than more optimized serialization methods if performance is absolutely critical. Storing components separately might be faster but adds complexity.
Loading: Also requires a custom Dataset. Reading specific graphs involves slicing the concatenated datasets based on the offsets.
python
import h5py
import torch
import numpy as np
from torch_geometric.data import Dataset, Data
class GraphH5Dataset(Dataset):
def __init__(self, h5_path):
super().__init__()
self.h5_path = h5_path
with h5py.File(h5_path, 'r') as f:
self.num_graphs = len(f['num_nodes'])
self.offsets = np.array(f['offsets']) # Stores start index of edge list for each graph
def __len__(self):
return self.num_graphs
def get(self, idx):
with h5py.File(self.h5_path, 'r') as f:
# Determine slicing indices for concatenated arrays
start_offset = self.offsets[idx]
end_offset = self.offsets[idx+1]
num_edges = end_offset - start_offset
num_nodes = f['num_nodes'][idx]
# Calculate start/end indices for nodes (assuming nodes are stored contiguously)
# This requires knowing node offsets or recalculating based on num_nodes
# Let's assume nodes are also stored contiguously for simplicity here
# A more robust way involves storing node offsets too.
# For now, let's estimate node slicing based on num_nodes (might be incorrect if node storage isn't simple concatenation)
# A better HDF5 structure might store each graph in its own group.
# *** Assuming a simpler structure where we know node/edge counts easily ***
# A more robust implementation would precisely calculate node start/end indices
# For now, let's focus on edge_index slicing which is clear from offsets
# Read required slices
x_slice_start = self.offsets_for_nodes[idx] # Need to compute/store node offsets
x_slice_end = self.offsets_for_nodes[idx+1]
x = torch.from_numpy(f['x'][x_slice_start:x_slice_end]).float()
edge_index = torch.from_numpy(f['edge_index'][:, start_offset:end_offset]).long()
edge_attr = torch.from_numpy(f['edge_attr'][start_offset:end_offset]).float()
y = torch.from_numpy(f['y'][idx:idx+1]).float() # Assuming y is per graph
# Create Data object
data = Data(x=x, edge_index=edge_index, edge_attr=edge_attr, y=y, num_nodes=num_nodes)
return data
# Need to properly implement how node data is sliced based on num_nodes
# This might involve pre-calculating node offsets during saving.
Note: The HDF5 saving/loading code above is conceptual and might need adjustments based on the exact desired structure and how node/edge data align. Storing each graph in its own HDF5 group might be cleaner but potentially less performant for bulk reads.
Pros:
Efficient Reads: Supports reading specific slices/subsets of the data without loading the whole file.
Structured: Organizes data hierarchically.
Widely Used: Mature format and libraries.
Cons:
Implementation Complexity: Significantly more complex saving and loading logic, especially managing indices and slicing correctly. Requires a custom Dataset.
Potential Overhead: Depending on the structure, accessing individual graphs might involve more overhead than LMDB.
# Example Saving Snippet (Conceptual)
import webdataset as wds
import torch
from torch_geometric.data import Data
import zstandard as zstd
import io
import pickle # Or use torch.save directly
# Assume 'all_graphs' is the list loaded initially (the 15 min load)
# You might need to load it once to create the WebDataset format.
output_url = "my_graphs.tar" # Base name for sharded files
shard_size = 1000 # Number of samples per tar file shard
# Create a TarWriter sink. Compression can be handled per-sample.
sink = wds.TarWriter(output_url, shardsize=shard_size, compressed=False)
for i, graph in enumerate(all_graphs):
# Serialize the individual graph object
# Option 1: Pickle + Zstd compress
buffer = io.BytesIO()
pickle.dump(graph, buffer) # Or torch.save(graph, buffer)
compressed_data = zstd.compress(buffer.getvalue())
# Option 2: Torch save to buffer + Zstd compress
# buffer = io.BytesIO()
# torch.save(graph, buffer, _use_new_zipfile_serialization=False) # Ensure compatibility
# compressed_data = zstd.compress(buffer.getvalue())
# Create a sample entry for the tar file
sample = {
"__key__": f"{i:09d}", # Unique key for the sample
"data.zst": compressed_data # Store the compressed data
}
sink.write(sample)
if (i + 1) % 10000 == 0:
print(f"Written {i+1} graphs to shards...")
sink.close()
print("Finished writing WebDataset shards.")
Loading: Use wds.WebDataset and a PyTorch DataLoader with num_workers > 0. The workers will read, decompress, and deserialize individual graphs in parallel.
python
# Example Loading Snippet
from torch_geometric.data import Data
import webdataset as wds
import torch
import zstandard as zstd
import io
# Define the decoding function
def decode_graph_zst(sample):
key, stream = sample # stream is a file-like object from the tar archive
try:
# Decompress the Zstd data
decompressed_bytes = zstd.decompress(stream.read())
# Deserialize using torch.load
buffer = io.BytesIO(decompressed_bytes)
graph = torch.load(buffer, map_location='cpu')
# Apply your upcasting logic
return upcast_graph(graph) # Make sure upcast_graph is accessible
except Exception as e:
print(f"Error decoding sample {key}: {e}")
# Handle error appropriately, maybe return None or raise
return None
# Create the WebDataset source
# Use your_dataset.tar if you have only one shard, or a pattern like "my_graphs_shard_*.tar"
dataset_url = "my_graphs.tar" # Or glob pattern if sharded
dataset = (
wds.WebDataset(dataset_url)
.decode(decode_graph_zst) # Apply the custom decoding function
.filter(lambda x: x is not None) # Filter out any potential errors
# .shuffle(10000) # Optional: shuffle samples *after* decoding if needed
)
# Use PyTorch DataLoader with multiple workers
# Adjust batch_size based on your memory and graph sizes
loader = torch.utils.data.DataLoader(
dataset,
batch_size=32, # Or experiment with batch_size=1 if graph sizes vary a lot
num_workers=4, # CRITICAL: Use multiple workers to parallelize loading/decoding
pin_memory=True, # Often helps speed up data transfer to GPU
collate_fn=None # Use default collate_fn or a custom one if needed, PyG handles Batching
)
# Now iterate through the loader
# for batch in loader:
# # process batch
# pass
Pros:
Parallelism: Directly addresses the single-threaded bottleneck by distributing the loading/deserialization work across multiple CPU cores via DataLoader workers. This is likely the most significant speedup factor.
Streaming: Can handle datasets larger than RAM if needed (though you mentioned it fits).
Flexibility: Handles various data types and compressions well.
Cons:
Requires Rewriting Save Process: You need to convert your current storage format.
Overhead per Sample: Serializing/compressing/decompressing each graph individually adds some overhead compared to loading one large blob, but this is often outweighed by the parallel processing gains.
2. Apache Arrow / Parquet Format
Concept: Store the graph data in a columnar format like Parquet. Parquet is optimized for numerical data, supports efficient compression (like Snappy, Gzip, Zstd), and libraries like pyarrow offer parallel reading capabilities.
How it Works:
Saving: Convert your graphs into a structure that can be written as Parquet. This might involve storing components (x, edge_index, etc.) as lists or arrays within records. You might need to serialize tensors to byte arrays before storing them in Parquet if direct tensor storage isn't straightforward.
python
# Example Saving Snippet (Conceptual)
import pyarrow as pa
import pyarrow.parquet as pq
import torch
import numpy as np
# Assume 'all_graphs' is loaded
# Prepare data for Arrow table - this is the complex part
# Need to handle variable length lists/arrays per graph carefully
# Example: Store edge_index as lists of ints, x as lists of lists of floats
table_data = {
"x": [], # List of lists/arrays for node features
"edge_index": [], # List of lists/arrays for edge indices
"edge_attr": [], # List of lists/arrays for edge attributes
"y": [], # List of labels
"num_nodes": []
}
for graph in all_graphs:
table_data["x"].append(np.array(graph.x))
table_data["edge_index"].append(np.array(graph.edge_index))
table_data["edge_attr"].append(np.array(graph.edge_attr))
table_data["y"].append(np.array(graph.y))
table_data["num_nodes"].append(graph.num_nodes)
# Convert to Arrow Arrays (may require careful type handling for lists)
# This step is non-trivial for nested/variable structures
# Example: Using pa.array for lists requires careful structure definition
# Or serialize tensors to bytes first.
# Let's assume we serialize to numpy arrays first for simplicity here
# Convert dict of numpy arrays to Arrow Table
# This requires the structure to be more uniform or handled via StructType/ListType
# A simpler approach might serialize tensor components to bytes
serialized_tensors = {
"x_bytes": [],
"edge_index_bytes": [],
"edge_attr_bytes": [],
"y_bytes": [],
"num_nodes": []
}
for graph in all_graphs:
serialized_tensors["x_bytes"].append(np.array(graph.x).tobytes())
serialized_tensors["edge_index_bytes"].append(np.array(graph.edge_index).tobytes())
serialized_tensors["edge_attr_bytes"].append(np.array(graph.edge_attr).tobytes())
serialized_tensors["y_bytes"].append(np.array(graph.y).tobytes())
serialized_tensors["num_nodes"].append(graph.num_nodes)
table = pa.Table.from_pydict(serialized_tensors)
# Write to Parquet file with compression
pq.write_table(table, 'graphs.parquet', compression='zstd')
print("Saved to Parquet.")
Loading: Read the Parquet file using pyarrow, potentially in parallel, deserialize the byte arrays back into tensors, and reconstruct the Data objects.
python
# Example Loading Snippet (Conceptual)
import pyarrow.parquet as pq
import pyarrow as pa
import torch
import numpy as np
from torch_geometric.data import Data
# Read the Parquet file (potentially parallelized by pyarrow)
table = pq.read_table('graphs.parquet') # Add use_threads=True (default) or specify other options
# Convert Arrow Table back to Data objects
loaded_graphs = []
num_nodes_arr = table.column("num_nodes").to_numpy()
for i in range(len(table)):
row = table.take([i]) # Get row i
try:
x_bytes = row.column("x_bytes").to_pylist()[0]
edge_index_bytes = row.column("edge_index_bytes").to_pylist()[0]
edge_attr_bytes = row.column("edge_attr_bytes").to_pylist()[0]
y_bytes = row.column("y_bytes").to_pylist()[0]
num_nodes = num_nodes_arr[i]
# Deserialize bytes back to numpy arrays
x_np = np.frombuffer(x_bytes, dtype=np.float32) # Adjust dtype
edge_index_np = np.frombuffer(edge_index_bytes, dtype=np.int64) # Adjust dtype
edge_attr_np = np.frombuffer(edge_attr_bytes, dtype=np.float32) # Adjust dtype
y_np = np.frombuffer(y_bytes, dtype=np.float32) # Adjust dtype
# Reshape numpy arrays based on graph structure info (num_nodes, num_edges)
# This requires knowing the shape beforehand or storing it.
# Example: Inferring shape is tricky without storing dims. Let's assume shapes were known during save.
# A better approach: store shapes alongside bytes or use Arrow List/Struct types.
# For now, let's assume simple reshape based on num_nodes and fixed edges/node:
# Calculate expected number of nodes/edges based on graph structure if possible
# Example placeholder:
num_edges = len(edge_index_np) // 2 # Assuming edge_index is flattened [u1, v1, u2, v2, ...]
x = torch.from_numpy(x_np.reshape(num_nodes, -1)) # Adjust reshape based on feature dim
edge_index = torch.from_numpy(edge_index_np.reshape(2, num_edges))
edge_attr = torch.from_numpy(edge_attr_np.reshape(num_edges, -1)) # Adjust reshape based on edge_attr dim
y = torch.from_numpy(y_np) # Adjust shape if needed
data = Data(x=x, edge_index=edge_index, edge_attr=edge_attr, y=y, num_nodes=num_nodes)
loaded_graphs.append(upcast_graph(data)) # Apply upcasting
except Exception as e:
print(f"Error processing row {i}: {e}")
# Handle error
# Now loaded_graphs contains all Data objects
# You can use this list directly or wrap in DataLoader (batch_size=N, num_workers=0)
Pros:
Efficient Numerical Storage: Stores raw tensor data compactly.
Potential Parallel Read:pyarrow can utilize multiple cores for reading.
Standard Format: Widely used in big data ecosystems.
Cons:
Complex Implementation: Converting graph data (especially variable-length edge lists) to/from Parquet requires careful handling of data types and shapes. Serialization/deserialization adds steps.
Reconstruction Logic: You need robust logic to reshape the deserialized byte arrays back into the correct tensor shapes. Storing shape metadata alongside the bytes is crucial.
Concept: Store each serialized graph as a key-value pair in an LMDB database. LMDB uses memory mapping for efficient access.
How it Works: Similar to the previous suggestion, but focused on LMDB.
Saving: Iterate through graphs, serialize each one (e.g., pickle.dumps(graph)), and put it into the LMDB database with its index as the key. The saving process itself might not be faster than torch.load, but the database structure is efficient for access.
Loading: Create a custom torch.utils.data.Dataset that reads from the LMDB database. You can then use this dataset with a DataLoader. To achieve parallelism, you'd rely on DataLoader's num_workers. Each worker would independently access the LMDB database.
Pros:
Efficient Access: Memory mapping provides fast access.
Database Structure: Well-suited for key-value data.
Cons:
Still Serialization Overhead: Each graph object still needs to be serialized and deserialized.
Parallelism Benefit: While DataLoader workers can access LMDB concurrently, the actual deserialization bottleneck for each graph remains. The benefit over a single torch.load might be less pronounced than WebDataset unless LMDB's internal access is significantly faster than decompressor.read() + torch.load.
Requires Custom Dataset: More boilerplate code than using WebDataset directly.
Recommendation Summary:
WebDataset: This is likely your best bet. It's designed precisely for this kind of problem: speeding up PyTorch data loading by leveraging parallel processing (num_workers) during deserialization. The main effort is converting your data to the WebDataset format.
Apache Arrow/Parquet: A strong alternative if you prefer a more structured, numerical format. It offers efficient storage and potential parallel reads, but the implementation complexity for graph data can be higher.
LMDB: A viable option, but potentially less effective at speeding up the total load time compared to WebDataset's parallel deserialization, though good for key-value access.
Given your description, focusing on parallelizing the deserialization is key. WebDataset provides the most direct path to achieve this within the standard PyTorch ecosystem.