The fastest way to load a dataset from a file into a PyTorch tensor depends on the file format and your hardware (CPU/GPU). Here are optimized approaches for common file types:
1. For NumPy Arrays (.npy or .npz files)
If your data is stored in NumPy format, use numpy.load and convert to a PyTorch tensor:
python
import numpy as np
import torch
# Load from .npy file
data = np.load('data.npy')
tensor = torch.from_numpy(data) # Zero-copy conversion (fastest)
2. For CSV/TSV Files
Use pandas for efficient CSV loading, then convert to a tensor:
python
import pandas as pd
import torch
# Read CSV (faster with `dtype` specification if possible)
df = pd.read_csv('data.csv', dtype=np.float32) # Use float32 to save memory
tensor = torch.from_numpy(df.values)
3. For Binary Files (e.g., .bin or .dat)
If your data is in raw binary format, use numpy.fromfile:
python
import numpy as np
import torch
# Load binary data (adjust dtype and shape as needed)
data = np.fromfile('data.bin', dtype=np.float32).reshape(shape)
tensor = torch.from_numpy(data)
4. For HDF5 Files (.h5 or .hdf5)
Use h5py for efficient loading of large datasets:
python
import h5py
import torch
with h5py.File('data.h5', 'r') as f:
data = f['dataset_name'][:] # Load as NumPy array
tensor = torch.from_numpy(data)
5. For PyTorch's Native .pt Files
If you previously saved a tensor with torch.save, load it directly:
python
tensor = torch.load('data.pt') # Fastest for PyTorch-native files
6. For Large Datasets (Memory-Mapped Tensors)
If the dataset is too large to fit in memory, use memory-mapping:
python
import numpy as np
import torch
# Memory-map a binary file
data = np.memmap('large_data.bin', dtype=np.float32, mode='r', shape=(...))
tensor = torch.from_numpy(data) # No actual copy until accessed
Optimization Tips
Use dtype=np.float32 instead of float64 to reduce memory usage and speed up loading.
Prefer binary formats (.npy, .h5, .pt) over text-based formats (CSV) for faster I/O.
Use torch.from_numpy for zero-copy conversion when possible.
For GPU acceleration, move the tensor to GPU after loading:
python
tensor = tensor.to('cuda', non_blocking=True) # Non-blocking transfer if possible
Benchmarking
If performance is critical, benchmark different methods for your specific use case. For example:
python
import time
start = time.time()
tensor = torch.load('data.pt') # or other methods
print(f"Loading time: {time.time() - start:.4f} seconds")
Choose the method that best fits your file format and performance needs!