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()usestorch::from_blobwith column-major strides, eliminating \(O(n)\) virtual calls. - AnalogToTensor / TensorToAnalog transforms: Bridge between independent
AnalogTimeSerieschannels and unifiedTensorData. 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
AnalogTimeSeriesviews backed byTensorDatacolumns.TensorToAnaloguses this automatically. 17 test cases. - ParameterSchema
std::vector<T>support: Multi-select lists and CSV line edits for vector parameters inAutoParamWidget. - Phase 4a — Eliminate Armadillo copy overhead (CPU): Removed
matToFlat()helper fromTensorCAR.cpp. All three output paths (TimeFrameIndex, Interval, Ordinal) now usestd::move(result_mat)intoarma::fmatfactory overloads, reducing copies from 3 to 1. AddedcreateFromIntervals(arma::fmat)overload toTensorData. - Phase 4b — LibTorch compute path for TensorCAR: Added conditional LibTorch backend to
TensorCARbehindTENSOR_BACKEND_LIBTORCH. Whenuse_gpu = true, usestoLibTorch()→ device transfer →mean/median→ subtract → download. TimeFrameIndex output path is zero-copy viaLibTorchTensorStorage. TransformsV2 CMakeLists.txt links Torch privately withfind_package(OpenCV)workaround for the protobuf target conflict. - Tensor-backed binary loading (Phase 1 — in-memory path): Added
use_tensor_backedoption toBinaryAnalogLoaderOptions. When enabled withnum_channels > 1and in-memory loading, reads interleaved binary →arma::fmat→TensorData→ NTensorColumnAnalogStoragezero-copy views.BinaryFormatLoader,AnalogImport_Widget, andBinaryAnalogImport_Widgetupdated to register both theTensorDataand per-channel views. Also fixed the hardcodedint16_tbug in the in-memory multi-channel path — now dispatches onbinary_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.BlockCachedMmapAnalogStorageprovides per-channelAnalogTimeSeriesviews;MmapTensorStorageprovidesTensorDataaccess. NewTensorData::createTimeSeries2DFromStorage()factory method for custom storage backends.TensorStorageType::MemoryMappedadded.loadTensorBacked()updated:use_tensor_backed + use_memory_mapped + num_channels > 1takes the block-cached mmap path. 5 new test cases (540 assertions).
Roadmap
1. Tensor-Backed Binary Loading
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
- Add
use_tensor_backedoption toBinaryAnalogLoaderOptions. - When enabled with
num_channels > 1:- In-memory path: Read interleaved binary →
arma::fmat→TensorData→ NTensorColumnAnalogStorageviews. - Mmap path: Deferred to shared block cache (see below).
- In-memory path: Read interleaved binary →
- Return
BinaryAnalogLoadResultcontaining both theTensorData(memory owner) and per-channelAnalogTimeSeriesviews. - Update
AnalogImport_WidgetandBinaryFormatLoaderto register both theTensorDataand per-channel views in DataManager. - Expose
use_tensor_backedin JSON loading configs (reflect-cpp automatic). - Fix the existing hardcoded
int16_tbug in the in-memory multi-channel path (should dispatch onbinary_data_type).
UI Changes
BinaryAnalogImport_Widget needs a “Tensor-backed (shared storage)” checkbox, enabled only when num_channels > 1.
Files to Modify
| 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. VerifyTensorDatacolumn count matchesnum_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
BinaryAnalogLoaderOptionswithuse_tensor_backed=true.
2. Shared Block-Cached Mmap Storage
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.
BlockCachedMmapAnalogStorage
Per-channel AnalogTimeSeries storage backend that delegates to the shared cache:
| 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
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:
arma::fmat result_mat = input_mat— full copy (\(N \times C \times 4\) bytes)matToFlat(result_mat)— column-major to row-major conversion (another full copy)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) ✅
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 ✅
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:
| 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
| 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:
- Iterate over time in chunks of \(B\) samples (default \(B = 100{,}000\)).
- For each chunk:
toLibTorch()→.to(kCUDA)→ compute →.to(kCPU)→ write back. - 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/PrefetchVirtualMemoryhints for mmap prefetching.- Distributed / multi-GPU compute.