Saving large tensors efficiently while allowing incremental writes can be challenging with text-based formats like JSONL due to their overhead and lack of native support for binary data. Instead, consider using binary-based storage solutions specifically designed for handling large datasets and supporting efficient reads and writes. Here are a few recommended approaches:
1. HDF5 Format with h5py
HDF5 is a versatile, high-performance file format for storing large amounts of numerical data. It allows for hierarchical organization, efficient storage, and incremental writing, making it a suitable choice for your use case.
Advantages:
- Efficient Storage: Stores data in a binary format, reducing storage overhead compared to JSON.
- Incremental Writing: Supports appending data to datasets without rewriting the entire file.
- Hierarchical Structure: Organize tensors in groups and datasets for easy access.
Implementation Example:
import h5py
import torch
import numpy as np
# Define the HDF5 file and dataset
with h5py.File('tensors.h5', 'w') as h5f:
# Create a dataset with unlimited rows and fixed tensor shape
tensor_shape = (your_tensor_dimensions) # e.g., (100, 100)
max_shape = (None,) + tensor_shape
dset = h5f.create_dataset(
'tensors',
shape=(0,) + tensor_shape,
maxshape=max_shape,
dtype='float32', # Use appropriate dtype
chunks=True
)
for tensor in data_generator(): # Replace with your tensor generator
tensor_np = tensor.numpy()
dset.resize(dset.shape[0] + 1, axis=0)
dset[-1] = tensor_np
Reading the Data:
with h5py.File('tensors.h5', 'r') as h5f:
dataset = h5f['tensors']
for i in range(len(dataset)):
tensor = torch.tensor(dataset[i])
# Process your tensor
2. LMDB (Lightning Memory-Mapped Database)
LMDB is a high-performance key-value store that is efficient for read and write operations. It's particularly useful when you need random access to your data.
Advantages:
- High Performance: Optimized for fast read/write operations.
- Scalability: Can handle large datasets efficiently.
- Atomic Transactions: Ensures data integrity during writes.
Implementation Example:
import lmdb
import torch
import pickle
# Initialize LMDB environment
env = lmdb.open('tensors.lmdb', map_size=1e12) # Adjust map_size as needed
with env.begin(write=True) as txn:
for idx, tensor in enumerate(data_generator()): # Replace with your tensor generator
# Serialize the tensor
tensor_bytes = pickle.dumps(tensor)
# Use a unique key for each tensor
key = f'tensor_{idx}'.encode('ascii')
# Insert into the database
txn.put(key, tensor_bytes)
Reading the Data:
with lmdb.open('tensors.lmdb', readonly=True) as env:
with env.begin() as txn:
cursor = txn.cursor()
for key, value in cursor:
tensor = pickle.loads(value)
# Process your tensor
3. Appending Binary Data with Custom Format
If you prefer a more customized approach, you can append tensors to a binary file sequentially. This method requires handling the reading logic to parse individual tensors.
Implementation Example:
import torch
# Writing tensors
with open('tensors.bin', 'ab') as f:
for tensor in data_generator(): # Replace with your tensor generator
tensor.numpy().tofile(f)
# Reading tensors
tensor_size = your_tensor_dimensions # e.g., (100, 100)
with open('tensors.bin', 'rb') as f:
while True:
bytes_read = f.read(np.prod(tensor_size) * 4) # float32 has 4 bytes
if not bytes_read:
break
tensor = torch.from_numpy(
np.frombuffer(bytes_read, dtype=np.float32).reshape(tensor_size)
)
# Process your tensor
Note: This approach lacks metadata unless you implement it yourself, so it’s less flexible compared to HDF5 or LMDB.
Recommendation
For most use cases, HDF5 with h5py is recommended due to its balance of ease of use, flexibility, and performance. It allows you to efficiently append tensors and organize them hierarchically, which can be beneficial for data management and retrieval.
Additional Tips
-
Compression: HDF5 supports compression (e.g., gzip, lzf), which can reduce file size at the cost of some speed. Use the compression parameter in create_dataset if needed.
dset = h5f.create_dataset(
'tensors',
shape=(0,) + tensor_shape,
maxshape=max_shape,
dtype='float32',
chunks=True,
compression="gzip",
compression_opts=4
)
-
Chunking: Properly set chunk sizes in HDF5 to optimize read/write performance based on your access patterns.
-
Data Integrity: Regularly back up your data and consider using checksums or other integrity checks, especially when performing incremental writes.
By choosing an appropriate binary storage format like HDF5 or LMDB, you can efficiently serialize large tensors incrementally without the storage overhead associated with text-based formats like JSONL.