Skip to content

Data pipeline

timber.data turns time-series recordings into the batches the model is trained on. The examples of this section, like the rest of the Training part, follow the fMRI application of the paper: each entity is a subject, each recording a run, and each channel a cortical vertex.

files  ->  NpyTimeSeriesDataset  ->  PartitionSampler  ->  TimberDataModule  ->  batches
(arrays)   (reads a window)         (draws the grid)      (splits the entities)  (signal, positions, labels)

Input files

Each file is one recording of one entity, stored as a NumPy .npy array of shape (time, channel), typically float32. You describe the files with a mapping from keys to paths:

files = {
    ("subject-01", 0): "data/subject-01_run-0.npy",   # (entity, recording)
    ("subject-01", 1): "data/subject-01_run-1.npy",
    ("subject-02", 0): "data/subject-02_run-0.npy",
}

Storage order. Random channel subsets read much faster from files stored channel by channel, that is in Fortran order. Save such files with np.save(path, np.asfortranarray(array)): the shape stays (time, channel), and both orders are read correctly. The fMRI experiments include a converter for existing folders (experiments/data/convert_to_channel_major.py).

Sampling: a random grid of chunks

The paper never feeds a whole recording to the model. Each recording has about 60,000 channels and 1,200 time points, and attention over all of them is out of reach. Instead, every training sample is a random sub-grid of the data:

  • Channels: a random subset of 1,024 of the 59,412 cortical vertices (node sampling), so that the attention runs over 1,024 channels;
  • Time: a random window of 900 of the 1,200 time points (the window is contiguous, so that the temporal attention sees a real time course).

Sampling is a computational necessity, and it also helps learning. The paper argues that nearby and functionally related vertices are highly correlated, so a subset preserves the dominant spatiotemporal patterns: each draw is a noisy view of the same recording. The model sees a different view at every step, which reduces overfitting and makes it more robust to spatial and temporal perturbations (see the paper's sampling and patching section).

The sampler works on a grid with one axis per dimension: entities, recordings, channels, time and, optionally, shards. Along each axis it cuts the indices into chunks of chunk_shape consecutive elements, and a batch takes chunks_per_batch chunks along every axis. Each combination of chunks is one sample:

  • a channel chunk is a set of channels of one recording (for example 32 of the 1,024 sampled channels);
  • a time chunk is a window of consecutive time points (for example 128 samples of a 900-sample window).

The steps, in order: shuffle each axis if asked (shuffle_before_chunking), cut it into chunks, optionally stratify the chunks by label (labels: one element of every label per chunk), pad the axis to a multiple of the batch size, group the chunks into batches, and crop each chunk randomly (crop_shape, for example to take 900 of 1,200 samples).

Setting Meaning
partition_shape Size of every axis: (entities, recordings, channels, time).
chunk_shape Elements per chunk along each axis. The paper: (1, 1, 1024, 900) for one entity, one recording, 1,024 channels and a 900-sample window.
chunks_per_batch Chunks per batch along each axis; the batch holds the product of these.
shuffle_before_chunking Shuffle each axis before cutting it into chunks. Set it to False for time, otherwise a chunk of time points is spread over the recording instead of forming a window.
crop_shape Elements randomly cropped from each chunk. The paper crops 1,200 samples to 900 with (0, 0, 0, 300).
labels Stratify an axis by label, so that each chunk holds every class.
resample_per_batch Redraw the indices of every batch along the chosen axes.
seed Base seed; the batches of an epoch depend only on seed and the epoch number.

The paper's batch of 8 runs is chunks_per_batch = (2, 2, 2, 1): 2 subjects, 2 runs, 2 channel chunks of 1,024 vertices, one time window. ChunkCollator reshapes the samples back to (*chunks_per_batch, channel, time).

sampler = {
    "partition_shape": [100, 2, 59412, 1200],
    "chunk_shape": [1, 1, 1024, 900],                       # 1,024 random vertices, a 900-sample window
    "chunks_per_batch": [2, 2, 2, 1],
    "shuffle_before_chunking": [True, True, True, False],   # time windows stay contiguous
    "crop_shape": [0, 0, 0, 300],                           # 1,200 samples -> random 900-sample window
}

Shards

A shard is a file that holds a subset of the channels of a recording. A recording stored as several shards is one recording split by channel: the files subject-01_run-0_shard-0.npy and subject-01_run-0_shard-1.npy could hold the first and the second half of the vertices. The key of a shard is (entity, recording, shard), and channel_index maps the local channels of each shard to the global channel indices, so that the model still knows which vertex is which.

In the fMRI application, a shard is a set of cortical vertices of a recording. The paper draws 1,024 random vertices out of about 60,000 for every sample; storing the recording split by vertex subsets gives the same channel split on disk. The package reads any number of shards per recording. To sample across shards, add the shard count as a fifth axis of partition_shape (see the example in Usage); with four axes the sampler always reads shard 0.

files = {
    ("subject-01", 0, 0): "data/subject-01_run-0_shard-0.npy",  # vertices 0 to 31 of the cortex
    ("subject-01", 0, 1): "data/subject-01_run-0_shard-1.npy",  # vertices 32 to 63
    ("subject-02", 0, 0): "data/subject-02_run-0_shard-0.npy",
    ("subject-02", 0, 1): "data/subject-02_run-0_shard-1.npy",
}
channel_index = {0: np.arange(0, 32), 1: np.arange(32, 64)}   # local channel -> global vertex, per shard

Preprocessing the paper applies

The package does not preprocess the signals; the model expects them preprocessed as in the paper:

  • HCP (S1200, resting state): the HCP minimal preprocessing pipeline (motion correction, spatial normalisation to MNI space, ICA-FIX denoising), a band-pass filter of 0.01–0.1 Hz, and a z-score per vertex. The paper uses 948 subjects with complete data (four runs of 1,200 time points, TR = 0.72 s) and pretrains on 200 of them. The cortex has 59,412 vertices without the medial wall (fsLR 32k).
  • ABIDE I: 871 subjects (403 ASD, 468 controls), processed with C-PAC (motion correction, normalisation, nuisance regression). Each run is resampled to TR = 0.72 s and brought to 1,200 time points by repeating it, then band-pass filtered and z-scored per vertex, as for HCP.

Datasets and data modules

  • NpyTimeSeriesDataset reads one window per index. Its load(path) method can be overridden to read another storage layout. It can also resample the time window and the channels at random, deterministically for each index and epoch.
  • TimberDataModule splits the entities into train, validation and test sets (by number, or by explicit lists) and builds one data loader per split. It is configured with DataModuleConfig.
  • Batches are tuples (signal, positions, labels): signal is the float32 (view..., channel, time) tensor, positions a SamplePositions with the entity, recording, channel and timestep of every sample, and labels the targets of the entities, or None.

Every option and its default is in the reference below.

Reference

timber.data.sampler

Sampler that cuts an (entity, recording, channel, time) data grid into chunks and batches.

The data is a grid with one axis per dimension: entities (what carries the labels: a subject, a patient, a machine), recordings of an entity, channels, timepoints, and optionally shards (a recording stored as several channel-subset files). Along each axis the indices are (optionally) shuffled and cut into chunks of chunk_shape[axis] consecutive elements. A batch takes chunks_per_batch[axis] chunks along every axis, and the sampler yields one index tuple per combination (the Cartesian product of the chunks), so a batch has prod(chunks_per_batch) samples. ChunkCollator reshapes it back to (*chunks_per_batch, channel, time).

Example: partition_shape = (entities, 4 recordings, 10000 channels, 1200 timepoints), chunk_shape = (1, 1, 1024, 1200), chunks_per_batch = (2, 2, 2, 1): each batch has 2 entities x 2 recordings x 2 sets of 1024 channels x 1 window of 1200 timepoints (cropped to 900 with crop_shape = (0, 0, 0, 300)).

The batches of an epoch depend only on seed + epoch (call set_epoch).

PartitionSampler

Bases: Sampler

Yield index tuples (entity, recording, channels, timepoints[, shard]) batch by batch.

Parameters:

Name Type Description Default
partition_shape Sequence[int]

Size of every axis of the data grid.

required
chunk_shape Sequence[int]

Elements per chunk along every axis (a chunk of size 1 yields an int, larger chunks yield sorted index arrays).

required
chunks_per_batch Sequence[int]

Chunks per batch along every axis.

required
shuffle_before_chunking Sequence[bool] | bool

Shuffle the indices of each axis (or all axes) before cutting them into chunks.

True
crop_shape Sequence[int] | None

Elements randomly cropped from every chunk (chunk - crop are kept), per axis.

None
labels Sequence[Sequence[int] | None] | None

Optional per-axis labels; chunks along that axis then contain one element of every label (stratified), e.g. balanced classes per batch.

None
shuffle_batches bool

Shuffle the order of the batches.

True
max_batches int | None

Keep only the first batches of every epoch.

None
max_batches_per_axis Sequence[int] | None

Keep only the first chunk groups along every axis.

None
resample_per_batch Sequence[bool] | None

Per axis, redraw the indices of every batch (for shuffled axes).

None
seed int

Base seed; the epoch seed is seed + epoch.

42
batch_size property
batch_size: int

Samples per batch: prod(chunks_per_batch).

groups_per_axis property
groups_per_axis: list[int]

Number of chunk groups (batch positions) along every axis in the current epoch.

set_epoch
set_epoch(epoch: int) -> None

Select the batches of an epoch (they only depend on seed + epoch).

ChunkIndex

Bases: tuple

Index of one sample, (entity, recording, channels, timepoints[, shard]), with the epoch it was drawn in.

It compares equal to the plain tuple. The epoch reaches the dataset (also in persistent workers) and seeds its random resampling, so resampled windows and channels change from one epoch to the next.

timber.data.dataset

Dataset of memory-mapped (time, channel) arrays, one .npy file per (entity, recording, shard).

The dataset is given the files explicitly, so it makes no assumption about file names or folders: an application maps its own storage to {(entity, recording, shard): path}. A recording may be split into several shards (channel-subset files); channel_index then maps the local channel indices of every shard to global channel indices.

Files are memory-mapped: the OS page cache is shared by the DataLoader workers, so the data is not duplicated per worker. Override NpyTimeSeriesDataset.load to read another storage layout.

Storage order: a random subset of channels is read much faster from a file stored channel by channel. Save such files in Fortran order (np.save(path, np.asfortranarray(series)); the array keeps its (time, channel) shape, the .npy header records the order): a chunk then reads one contiguous run per channel instead of scattered bytes of every time row (about 50x less I/O for 1024 of 60k channels). Both orders are read transparently.

Threaded reads: on drives with a high latency (USB SSDs, network file systems), a memory map reads one page at a time per process. With read_threads > 0, the channels of channel-major files are read with concurrent os.pread calls instead (they release the GIL), which keeps many requests in flight (about 7x faster per process on a USB SSD). The items are identical.

NpyTimeSeriesDataset

Bases: Dataset

Map-style dataset indexed by the tuples of PartitionSampler.

An index is (entity_index, recording, channels, timepoints[, shard]) where entity_index indexes entities (sorted entity ids), channels are local channel indices in the file and timepoints a contiguous window.

Parameters:

Name Type Description Default
files Mapping[Any, str | Path]

{(entity, recording[, shard]): path} of (time, channel) .npy arrays.

required
labels Mapping[str, Sequence[float]] | None

Optional {entity: values} targets (one row per entity).

None
channel_index Mapping[int, Sequence[int]] | None

Optional {shard: global_channel_indices} mapping the local channels of every shard to global channel indices (identity when None).

None
resample_time_window bool

Replace the requested window by a random window of the same length (deterministic per index and epoch, see ChunkIndex).

False
resample_channels bool

Replace the requested channels by random channels (deterministic per index and epoch).

False
num_resample_channels int | None

Channels to draw from when resampling (default: all the channels of the file).

None
read_threads int

Read channel-major files with this many concurrent pread calls per process (0: through the memory map). Faster on high-latency drives; the items are identical.

0

Items are (signal, positions, target): signal (channel, time) float32, positions (entity_index, recording, global_channel_indices, timepoints) and target (num_labels,).

__len__
__len__() -> int

Number of files.

load
load(path: Path) -> np.ndarray

Read a file as a (time, channel) array (memory-mapped).

global_channels
global_channels(
    series: ndarray, shard: int, local_channels: ndarray
) -> np.ndarray

Global indices of the local_channels of a shard (see channel_index).

is_channel_major

is_channel_major(series: ndarray) -> bool

Whether a (time, channel) array is stored channel by channel (Fortran order).

timber.data.datamodule

Batches, data loaders and the Lightning data module.

A batch is (signal, positions, labels):

  • signal: (*chunks_per_batch, channel, time) float32 (the leading axis is the entity axis);
  • positions: SamplePositions of (*chunks_per_batch, 1) entity indices and recordings, (*chunks_per_batch, channel) global channel indices and (*chunks_per_batch, time) timepoints;
  • labels: (entity, num_labels) (one row per entity), or None without labels.

TimberDataModule receives the files and labels explicitly (no file-name convention); an application builds them from its own storage. All the settings live in DataModuleConfig (single source of defaults).

SamplerConfig dataclass

Arguments of PartitionSampler (see there). partition_shape[0] is set to the number of entities.

DataModuleConfig dataclass

Settings of TimberDataModule.

Attributes:

Name Type Description
sampler SamplerConfig

Training sampler (SamplerConfig or dict).

eval_sampler_overrides dict | None

Sampler fields overridden for validation and test (max_batches is always None).

num_train_entities, (num_val_entities, num_test_entities)

Sizes of the random entity split.

train_entities, (val_entities, test_entities)

Explicit splits (override the sizes).

resample_time_window, (resample_channels, num_resample_channels, read_threads)

See NpyTimeSeriesDataset.

drop_last bool

Drop the last incomplete batch.

use_batch_sampler bool

Wrap the sampler in a BatchSampler.

num_workers, prefetch_factor

DataLoader workers (workers are persistent).

seed int

Seed of the entity split.

from_dict classmethod
from_dict(
    values: DataModuleConfig | Mapping,
) -> DataModuleConfig

Build a config from a mapping (a config is returned unchanged); unknown keys raise.

TimberDataModule

Bases: LightningDataModule

Entity-level train / validation / test split and the matching data loaders.

Parameters:

Name Type Description Default
config DataModuleConfig | Mapping

DataModuleConfig or the same fields as a dict (e.g. from Hydra).

required
files Mapping[tuple, str | Path]

{(entity, recording[, shard]): path} of (time, channel) .npy arrays.

required
labels Mapping[str, Sequence[float]] | None

Optional {entity: values}; entities without labels are excluded.

None
channel_index Mapping[int, Sequence[int]] | None

Optional {shard: global_channel_indices} (see NpyTimeSeriesDataset).

None

Subclasses can set dataset_class to adapt how files are read.

make_dataset
make_dataset(
    entities: Sequence[str],
) -> NpyTimeSeriesDataset | None

Dataset over the files of entities (None when there is none).

setup
setup(stage: str | None = None) -> None

Build the datasets of the train, validation and test splits.

sampler_config
sampler_config(stage: str) -> SamplerConfig

The training SamplerConfig.

train_dataloader
train_dataloader() -> DataLoader

Data loader of the training split.

val_dataloader
val_dataloader() -> DataLoader | None

Data loader of the validation split (eval_sampler_overrides applied).

test_dataloader
test_dataloader() -> DataLoader | None

Data loader of the test split (eval_sampler_overrides applied).

ChunkCollator

Stack the samples of a PartitionSampler batch and reshape them to chunks_per_batch.

SamplePositions

Bases: NamedTuple

Where every sample of a batch comes from.