Skip to main content

Multi-Channel Storage Roadmap

Overview

This roadmap tracks planned improvements to the multi-channel TensorData infrastructure. For documentation of what is already implemented (AnalogToTensor, TensorToAnalog, TensorCAR, TensorColumnAnalogStorage), see Multi-Channel Storage & Cross-Channel Transforms.

See GitHub Issue #240 for the original feature request.

Completed

  • toLibTorch() zero-copy stride fix: TensorData::toLibTorch() uses torch::from_blob with column-major strides, eliminating \(O(n)\) virtual calls.
  • AnalogToTensor / TensorToAnalog transforms: Bridge between independent AnalogTimeSeries channels and unified TensorData. Registered, tested (12 cases).
  • Common Average Reference (CAR) transform: TensorData → TensorData, supports mean/median, channel exclusion, CPU/GPU via LibTorch. Registered, tested.
  • TensorColumnAnalogStorage: Zero-copy AnalogTimeSeries views backed by TensorData columns. TensorToAnalog uses this automatically. 17 test cases.
  • ParameterSchema std::vector<T> support: Multi-select lists and CSV line edits for vector parameters in AutoParamWidget.
  • Phase 4a — Eliminate Armadillo copy overhead (CPU): Removed matToFlat() helper from TensorCAR.cpp. All three output paths (TimeFrameIndex, Interval, Ordinal) now use std::move(result_mat) into arma::fmat factory overloads, reducing copies from 3 to 1. Added createFromIntervals(arma::fmat) overload to TensorData.
  • Phase 4b — LibTorch compute path for TensorCAR: Added conditional LibTorch backend to TensorCAR behind TENSOR_BACKEND_LIBTORCH. When use_gpu = true, uses toLibTorch() → device transfer → mean/median → subtract → download. TimeFrameIndex output path is zero-copy via LibTorchTensorStorage. TransformsV2 CMakeLists.txt links Torch privately with find_package(OpenCV) workaround for the protobuf target conflict.
  • Tensor-backed binary loading (Phase 1 — in-memory path): Added use_tensor_backed option to BinaryAnalogLoaderOptions. When enabled with num_channels > 1 and in-memory loading, reads interleaved binary → arma::fmat → TensorData → N TensorColumnAnalogStorage zero-copy views. BinaryFormatLoader, AnalogImport_Widget, and BinaryAnalogImport_Widget updated to register both the TensorData and per-channel views. Also fixed the hardcoded int16_t bug in the in-memory multi-channel path — now dispatches on binary_data_type. 9 test cases (764 assertions).
  • Shared block-cached mmap storage (Phase 2): Added SharedMmapBlockCache — a single mmap of an interleaved binary file with a FIFO circular buffer of decoded float32 blocks. When one channel loads a time window, all channels are decoded. BlockCachedMmapAnalogStorage provides per-channel AnalogTimeSeries views; MmapTensorStorage provides TensorData access. New TensorData::createTimeSeries2DFromStorage() factory method for custom storage backends. TensorStorageType::MemoryMapped added. loadTensorBacked() updated: use_tensor_backed + use_memory_mapped + num_channels > 1 takes the block-cached mmap path. 5 new test cases (540 assertions).

Roadmap

1. Tensor-Backed Binary Loading

Note

Status: Complete (in-memory path). The mmap path is deferred to Phase 2 (Shared Block Cache).

Today the binary loader (src/IO/formats/Binary/analogtimeseries/Analog_Time_Series_Binary.cpp) returns independent AnalogTimeSeries objects — each channel with either VectorAnalogDataStorage (in-memory) or MemoryMappedAnalogDataStorage (mmap, per-channel stride). No TensorData is created and no channels share state.

Goals

  1. Add use_tensor_backed option to BinaryAnalogLoaderOptions.
  2. When enabled with num_channels > 1:
    • In-memory path: Read interleaved binary → arma::fmat → TensorData → N TensorColumnAnalogStorage views.
    • Mmap path: Deferred to shared block cache (see below).
  3. Return BinaryAnalogLoadResult containing both the TensorData (memory owner) and per-channel AnalogTimeSeries views.
  4. Update AnalogImport_Widget and BinaryFormatLoader to register both the TensorData and per-channel views in DataManager.
  5. Expose use_tensor_backed in JSON loading configs (reflect-cpp automatic).
  6. Fix the existing hardcoded int16_t bug in the in-memory multi-channel path (should dispatch on binary_data_type).

UI Changes

BinaryAnalogImport_Widget needs a “Tensor-backed (shared storage)” checkbox, enabled only when num_channels > 1.

Files to Modify

Files affected by tensor-backed binary loading
File Change
src/IO/formats/Binary/analogtimeseries/Analog_Time_Series_Binary.hpp Add use_tensor_backed option, BinaryAnalogLoadResult return type
src/IO/formats/Binary/analogtimeseries/Analog_Time_Series_Binary.cpp Tensor-backed in-memory path, data type dispatch fix
src/IO/formats/Binary/BinaryFormatLoader.cpp Handle BinaryAnalogLoadResult in loadAnalogBatch()
src/WhiskerToolbox/DataImport_Widget/AnalogTimeSeries/AnalogImport_Widget.cpp Register TensorData + per-channel views
src/WhiskerToolbox/DataImport_Widget/AnalogTimeSeries/Binary/BinaryAnalogImport_Widget.cpp Add checkbox

Tests

  • Load multi-channel binary with use_tensor_backed=true. Verify TensorData column count matches num_channels. Verify each view shares memory (pointer comparison). Verify values match legacy independent-channel path.
  • Data type dispatch fix: Load float32 binary files with legacy in-memory path.
  • JSON round-trip for BinaryAnalogLoaderOptions with use_tensor_backed=true.

2. Shared Block-Cached Mmap Storage

Note

Status: Complete. SharedMmapBlockCache, BlockCachedMmapAnalogStorage, and MmapTensorStorage are implemented and integrated into loadTensorBacked().

The current per-channel mmap storage (MemoryMappedAnalogDataStorage) reads the same file pages independently per channel. For 384 channels, each OS page is read ~384 times. Additionally, getSpanRangeImpl() always returns an empty span, forcing element-by-element virtual dispatch with per-element stride calculation, memcpy, type conversion, and scaling.

Design: SharedMmapBlockCache

A shared resource that memory-maps an interleaved binary file and maintains a circular buffer of decoded float blocks.

New files:

  • src/DataObjects/AnalogTimeSeries/storage/SharedMmapBlockCache.hpp
  • src/DataObjects/AnalogTimeSeries/storage/SharedMmapBlockCache.cpp
  • src/DataObjects/AnalogTimeSeries/storage/BlockCachedMmapAnalogStorage.hpp
  • src/DataObjects/Tensors/storage/MmapTensorStorage.hpp

Key properties:

  • Circular buffer of \(N\) decoded blocks (default 16).
  • Each block: block_size_samples × num_channels float32 values.
  • FIFO eviction (optimized for sequential temporal access).
  • Reader-writer lock for thread safety.
  • Bulk type conversion at block load time (single vectorized pass via LibTorch from_blob + .to(kFloat32) or plain C++ with SIMD).

Access pattern: When DataViewer renders a time window for one channel, all \(N\) channels’ data for that window is decoded into the cache. Subsequent channels hit the cache. The first channel pays the decode cost; the remaining \(N - 1\) are free lookups.

Cache sizing:

\[M = N_{\text{blocks}} \times B_{\text{samples}} \times N_{\text{channels}} \times 4 \;\text{bytes}\]

Cache memory footprint for common configurations
Channels Block Size Num Blocks Memory
32 4096 16 8 MB
384 4096 8 48 MB

BlockCachedMmapAnalogStorage

Per-channel AnalogTimeSeries storage backend that delegates to the shared cache:

BlockCachedMmapAnalogStorage CRTP methods
Method Implementation
getValueAtImpl(i) O(1) lookup in cached block
getSpanRangeImpl(s, e) Span from cache block if within one block; temp buffer for cross-block
isContiguousImpl() false (interleaved in cache blocks)

MmapTensorStorage

TensorData storage backend backed by SharedMmapBlockCache. Enables loading interleaved binary files directly as TensorData with shape [time, channels].

Tests & Benchmarks

  • Values match element-by-element against MemoryMappedAnalogDataStorage.
  • Block loads = ⌈range/block_size⌉, not range × num_channels.
  • Cross-block read stitching.
  • Benchmark: block-cached vs element-by-element for 384-channel data.

3. Cross-Channel Transforms

Additional transforms that operate on multi-channel TensorData:

  • Spatial Whitening (ZCA): GitHub Issue #245 — Decorrelates channels and normalizes variances using eigendecomposition. Supports ZCA, PCA, and Cholesky methods.

  • Per-Channel IIR Filter: GitHub Issue #246 — Applies the same IIR filter to every column of a tensor. Operates on contiguous Armadillo columns for optimal cache utilization.

Both follow the TensorCAR transform pattern (container transform, TensorData → TensorData, LibTorch compute backend).


4. GPU-Accelerated Processing

Note

Status: Phase 4a and 4b complete. Ad-hoc benchmarks confirmed large GPU speedups for CAR transforms. See TensorCAR GPU vs CPU Benchmark Analysis for full results. Phase 4c (in-place transform support) remains.

Benchmark Summary

Ad-hoc benchmarks compared Armadillo CPU, LibTorch CPU, and LibTorch CUDA for mean-CAR and median-CAR across channel counts (32–384) and block sizes (1k–900k rows). Key findings at 384 channels:

Transform Armadillo (30k rows) Torch CPU Torch CUDA GPU speedup
Mean-CAR 11.4 ms 7.5 ms 0.5 ms 15×
Median-CAR 126.5 ms 32.3 ms 2.3 ms 14×
  • GPU crossover: Mean-CAR wins above ~5k rows. Median-CAR wins even at 1k rows because the per-row sort is compute-heavy.
  • Threading: Armadillo is single-threaded for these reductions. LibTorch CPU parallelizes across rows using its thread pool (4.2× speedup for median on 6 cores). LibTorch CUDA parallelizes most aggressively with one warp per row.
  • Transfer overhead: CPU↔︎GPU copies saturate PCIe at ~7 Gi/s. At 900k × 384 (1.4 GB), transfer takes ~467 ms vs 13 ms compute. GPU wins when data is already on-device or the compute exceeds the transfer cost.
  • Recommended gpu_block_hint: 100,000 rows (~3.3 s at 30 kHz, 153 MB at 384 channels). Achieves 80–95% peak GPU throughput.

Production Code Copy Overhead

The current Armadillo-based TensorCAR performs 2–3 unnecessary full-matrix copies per invocation:

  1. arma::fmat result_mat = input_mat — full copy (\(N \times C \times 4\) bytes)
  2. matToFlat(result_mat) — column-major to row-major conversion (another full copy)
  3. TensorData::createTimeSeries2D(flat) — copy into new storage (third full copy)

For 384 channels × 100k rows (153 MB per copy), this wastes ~460 MB of memory bandwidth. The subtraction itself (each_col() -= ref) is in-place on the first copy — the overhead is entirely in format conversion and storage creation.

Implementation Plan

The GPU path decomposes into three sub-phases that can be landed independently.

Phase 4a: Eliminate Armadillo Copy Overhead (CPU-only improvement) ✅
Tip

Complete. Removed matToFlat() helper. All output paths use std::move(result_mat) into arma::fmat factory overloads. Added TensorData::createFromIntervals(arma::fmat). Copies reduced from 3 to 1.

Phase 4b: LibTorch Compute Path for TensorCAR ✅
Tip

Complete. Added tensorCARLibTorch() behind #ifdef TENSOR_BACKEND_LIBTORCH. Dispatched when use_gpu = true. Uses toLibTorch() → .to(device) → mean/median with index_select for excluded channels → subtract → .to(kCPU) → buildResultFromTorch(). TimeFrameIndex output wraps the result tensor in LibTorchTensorStorage (zero-copy). Interval and Ordinal paths materialize to flat/arma. TransformsV2 links Torch privately; find_package(OpenCV) before find_package(Torch) works around the protobuf target conflict.

Phase 4c: In-Place Transform Support

Eliminate the final storage copy by allowing transforms to mutate their input. This benefits both CPU and GPU paths.

Motivation: Container Transform Return-Type Redesign

Today, container transforms return std::shared_ptr<OutContainer>, which forces every invocation to heap-allocate a new data object — even when the transform could safely mutate the input. nullptr is overloaded to mean “failure,” so there is no way for a transform to signal “I mutated the input, reuse it.”

The fix changes the container transform signature to return a raw pointer and accept a non-const reference:

// Before (current)
auto tensorCAR(TensorData const& input, TensorCARParams const& params,
               ComputeContext const& ctx) -> std::shared_ptr<TensorData>;

// After
auto tensorCAR(TensorData& input, TensorCARParams const& params,
               ComputeContext const& ctx) -> TensorData*;

The raw pointer return encodes three unambiguous states:

Container transform return-value protocol
Return value Meaning Executor action
new TensorData(…) New allocation (out-of-place) Wrap in shared_ptr (takes ownership)
&input In-place mutation (pointer identity with input) Reuse original shared_ptr
nullptr Failure Throw / propagate error

The executor already holds the shared_ptr and can perform the address comparison:

auto* raw = transform->execute(*input_ptr, params, ctx);
if (!raw) {
    throw std::runtime_error("transform '" + name + "' failed");
}
if (raw == input_ptr.get()) {
    // In-place: reuse existing shared_ptr, no new allocation
    return DataTypeVariant{input_ptr};
} else {
    // New allocation: take ownership
    return DataTypeVariant{std::shared_ptr<OutContainer>(raw)};
}

Backward compatibility: Existing transforms that accept InContainer const& bind to InContainer& with no source changes. Transforms that currently return std::make_shared<Out>(…) need a mechanical change to new Out(…).

TransformsV2 Plumbing Changes
Files affected by container transform return-type redesign
File Change
ContainerExecutor.hpp TypedContainerTransform::FuncType: InContainer const& → InContainer&, shared_ptr<Out> → Out*. IContainerExecutor::execute(): DataTypeVariant const& → DataTypeVariant&, return unchanged.
ElementRegistry.hpp registerContainerTransform(), executeContainerTransform(), RegisterContainerTransform RAII helper, TypedContainerExecutor::executeTyped() — same signature changes. Add pointer-identity check in TypedContainerExecutor::execute().
All container transform .cpp files Mechanical: return std::make_shared<T>(…) → return new T(…); return nullptr unchanged. Input parameter const& → & (only for transforms that opt into mutation).
TensorCAR In-Place Path

Add bool in_place = false to TensorCARParams. When true, the transform mutates the input’s storage directly and returns &input:

Armadillo CPU path:

auto* arma_storage = input.storage().getMutableAsChecked<ArmadilloTensorStorage>(
        TensorStorageType::Armadillo);
arma::fmat& mat = arma_storage->mutableMatrix();
mat.each_col() -= ref_col;  // zero output allocation
return &input;

LibTorch CPU path:

auto& t = lt_storage->mutableTensor();
t.sub_(ref);  // PyTorch in-place subtraction
return &input;

LibTorch GPU path: Upload → compute → download → assign back to mutableTensor(). Eliminates CPU-side output TensorData allocation.

Savings: Eliminates the remaining storage copy from Phase 4b, bringing total copy overhead to: 1 upload + 1 download (GPU) or 0 copies (CPU in-place).

Temporal Block Processing for Large Datasets

When a dataset exceeds GPU memory, process it in temporal blocks:

  1. Iterate over time in chunks of \(B\) samples (default \(B = 100{,}000\)).
  2. For each chunk: toLibTorch() → .to(kCUDA) → compute → .to(kCPU) → write back.
  3. Concatenate results (or write in-place per block).

This wraps any transform — no per-transform batching code needed.

Benchmarks Completed

  • ✅ GPU vs CPU CAR on 384 channels × 1k–900k samples.
  • ✅ Block upload/download overhead measurement (PCIe ~7 Gi/s).
  • ✅ GPU crossover point determination (mean: ~5k rows, median: always).
  • ✅ Threading analysis (Armadillo single-threaded, LibTorch multi-threaded).
  • ✅ In-place vs out-of-place allocation overhead (negligible when original preserved).
  • ⬚ GPU vs CPU whitening (requires §3 ZCA implementation).

Dependency Graph

Tensor-Backed Binary Loading (§1)
  ├── In-memory path: DONE ✓
  └── Mmap path: DONE ✓ (uses Shared Block Cache §2)

Shared Block-Cached Mmap (§2): DONE ✓

Cross-Channel Transforms (§3)
  ├── ZCA Whitening (#245): ready now (uses toLibTorch() ✓)
  └── IIR Filter (#246): ready now (uses Armadillo columns ✓)

GPU Acceleration (§4)
  ├── §4a: Eliminate Armadillo copy overhead (no dependencies)
  ├── §4b: LibTorch compute path (depends on §4a for clean baseline)
  └── §4c: In-place transform support (independent of §4a/§4b, benefits both)

Excluded Scope

  • UI widgets for multi-channel configuration or channel group management.
  • Spectral transforms (FFT, spectrogram) — future work using the same TensorData infrastructure.
  • madvise / PrefetchVirtualMemory hints for mmap prefetching.
  • Distributed / multi-GPU compute.