Data Dataset Mmap#
dataset_mmap
#
| CLASS | DESCRIPTION |
|---|---|
DatasetWeightedMemoryMapped |
Memory-mapped weighted dataset for large datasets with on-demand loading. |
Classes#
DatasetWeightedMemoryMapped(data_path: str | Path, weights_path: str | Path | None = None, target_path: str | Path | None = None, mode: Literal['r', 'r+', 'c'] = 'r', labels: list | None = None, dtype: torch.dtype = torch.float32, transform: Callable | None = None, cache_size: int = 0)
#
Bases: Dataset
Memory-mapped weighted dataset for large datasets with on-demand loading.
Uses numpy memory-mapped arrays to handle datasets that do not fit in RAM.
Data is loaded on-demand from disk with minimal memory footprint, enabling
efficient handling of large-scale datasets. API-compatible with
DatasetWeighted for seamless integration with data loaders and modules.
| PARAMETER | DESCRIPTION |
|---|---|
data_path
|
Path to memory-mapped data file (.npy format).
TYPE:
|
weights_path
|
Path to memory-mapped weights file. If None, generates unit weights.
TYPE:
|
target_path
|
Path to memory-mapped target file. If None, dataset is unsupervised.
TYPE:
|
mode
|
File opening mode: "r" (read-only), "r+" (read-write), "c" (copy-on-write).
TYPE:
|
labels
|
Feature labels. Auto-generated as ["x_1", "x_2", ...] if None.
TYPE:
|
dtype
|
Tensor data type for conversion.
TYPE:
|
transform
|
Optional transform function applied to data during
TYPE:
|
cache_size
|
Number of most recent samples to cache in memory. 0 disables caching.
Note: Cache stores full tensor copies. For large feature dimensions,
memory usage can be significant. Use
TYPE:
|
Properties
data : np.memmap Memory-mapped data array.
weights : np.memmap | np.ndarray Memory-mapped weights array or generated unit weights.
target : np.memmap | None Memory-mapped target array, if provided.
labels : list[str] Feature labels.
shape : tuple[int, ...] Shape of the data array.
Examples:
Create and use memory-mapped dataset:
>>> import numpy as np
>>> import torch
>>> from spectre.data import DatasetWeightedMemoryMapped
>>> # Create large dataset on disk
>>> X = np.random.randn(1_000_000, 50)
>>> np.save("large_data.npy", X)
>>> # Load as memory-mapped dataset
>>> dataset = DatasetWeightedMemoryMapped("large_data.npy")
>>> len(dataset)
1000000
>>> batch = dataset[0]
>>> batch.data.shape
torch.Size([50])
With weights and targets:
>>> weights = np.random.rand(1_000_000)
>>> np.save("weights.npy", weights)
>>> targets = np.random.randint(0, 10, (1_000_000, 1))
>>> np.save("targets.npy", targets)
>>> dataset = DatasetWeightedMemoryMapped(
... data_path="large_data.npy",
... weights_path="weights.npy",
... target_path="targets.npy",
... )
>>> batch = dataset[0]
>>> batch.data.shape, batch.weights.shape, batch.target.shape
(torch.Size([50]), torch.Size([]), torch.Size([1]))
With caching for frequently accessed data:
>>> dataset = DatasetWeightedMemoryMapped("large_data.npy", cache_size=1000)
>>> # First access loads from disk
>>> batch1 = dataset[0]
>>> # Second access uses cache (faster)
>>> batch2 = dataset[0]
Efficient validation and statistics for large datasets using sampling:
>>> # For very large datasets, validate a sample instead of the entire dataset
>>> dataset = DatasetWeightedMemoryMapped("large_data.npy")
>>> validation_results = dataset.validate(sample_size=10000)
>>> validation_results["has_nan_data"]
False
>>> # Quick NaN check on sample
>>> has_nan = dataset.check_nan(sample_size=10000)
>>> # Compute statistics on sample
>>> stats = dataset.get_statistics(sample_size=10000)
>>> stats["mean"].shape
torch.Size([50])
Notes
- Memory-mapped files must be in .npy format created by
numpy.save() - Data is not loaded into memory until accessed via
__getitem__() - Use caching for datasets with repeated access patterns
- Copy-on-write mode ("c") is useful for read-mostly with occasional modifications
- For very large datasets, use
sample_sizeparameter in validation methods
| METHOD | DESCRIPTION |
|---|---|
clear_cache |
Clear the sample cache. |
has_target |
Check if the dataset has target values. |
get_cache_memory_usage |
Get current cache memory usage. |
validate |
Validate dataset for common data quality issues. |
get_statistics |
Compute basic statistics for the dataset. |
check_nan |
Check if dataset contains NaN values in data, weights, or targets. |
check_inf |
Check if dataset contains infinite values in data, weights, or targets. |
| ATTRIBUTE | DESCRIPTION |
|---|---|
shape |
Shape of the data array.
TYPE:
|
Source code in spectre/data/dataset_mmap.py
Attributes#
shape: tuple[int, ...]
property
#
Shape of the data array.
Functions#
clear_cache() -> None
#
has_target() -> bool
#
Check if the dataset has target values.
| RETURNS | DESCRIPTION |
|---|---|
bool
|
True if dataset has targets, False otherwise. |
get_cache_memory_usage() -> dict[str, float]
#
Get current cache memory usage.
| RETURNS | DESCRIPTION |
|---|---|
dict[str, float]
|
Dictionary with "cache_size" (number of cached items) and "estimated_mb" (estimated memory usage in megabytes). |
Examples:
>>> dataset = DatasetWeightedMemoryMapped("data.npy", cache_size=1000)
>>> # Access some data
>>> for i in range(100):
... _ = dataset[i]
>>> usage = dataset.get_cache_memory_usage()
>>> print(f"Cached {usage['cache_size']} items")
>>> print(f"Using ~{usage['estimated_mb']:.2f} MB")
Source code in spectre/data/dataset_mmap.py
validate(sample_size: int | None = None) -> dict[str, bool]
#
Validate dataset for common data quality issues.
Checks for NaN values, infinite values, and zero weights in memory-mapped
arrays. For large datasets, use sample_size to validate a random subset.
| PARAMETER | DESCRIPTION |
|---|---|
sample_size
|
If provided, validate only a random sample of this size instead of the entire dataset. Useful for large datasets where full validation would be too slow.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict[str, bool]
|
Dictionary with validation results: |
Source code in spectre/data/dataset_mmap.py
get_statistics(sample_size: int | None = None) -> dict[str, torch.Tensor]
#
Compute basic statistics for the dataset.
Computes statistics on memory-mapped arrays. For large datasets, use
sample_size to compute statistics on a random subset.
| PARAMETER | DESCRIPTION |
|---|---|
sample_size
|
If provided, compute statistics only on a random sample of this size instead of the entire dataset. Useful for large datasets where computing statistics on the full dataset would be too slow.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict[str, Tensor]
|
Dictionary with statistics: |
Source code in spectre/data/dataset_mmap.py
check_nan(sample_size: int | None = None) -> bool
#
Check if dataset contains NaN values in data, weights, or targets.
For large datasets, use sample_size to check a random subset instead
of the entire dataset.
| PARAMETER | DESCRIPTION |
|---|---|
sample_size
|
If provided, check only a random sample of this size instead of the entire dataset.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
bool
|
True if NaN values are found, False otherwise. |
Source code in spectre/data/dataset_mmap.py
check_inf(sample_size: int | None = None) -> bool
#
Check if dataset contains infinite values in data, weights, or targets.
For large datasets, use sample_size to check a random subset instead
of the entire dataset.
| PARAMETER | DESCRIPTION |
|---|---|
sample_size
|
If provided, check only a random sample of this size instead of the entire dataset.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
bool
|
True if infinite values are found, False otherwise. |