coco_pipe.decoding.foundation_models.extraction#

Reusable extraction and preflight utilities for EEG foundation models.

Classes#

CapabilityResult

Preflight result for one model/training-mode/input combination.

FoundationEmbeddingResult

Window embeddings plus extraction provenance.

FoundationEmbeddingExtractor

Compose model loading, metadata binding, extraction, and pooling.

Functions#

check_capability(model_key, train_mode[, sfreq, ...])

Check registry support and obvious signal incompatibilities without loading.

normalize_inclusive_endpoint(container, *, ...[, ...])

Drop MNE's inclusive-endpoint extra sample from epoched windows.

extract_weight_sets(extractors, recording)

Extract one recording with several extractors, resampling it once.

Module Contents#

class coco_pipe.decoding.foundation_models.extraction.CapabilityResult#

Preflight result for one model/training-mode/input combination.

train_mode: str#
status: str#
reason: str = ''#
details: dict[str, Any]#
to_dict()#
Return type:

dict[str, Any]

coco_pipe.decoding.foundation_models.extraction.check_capability(model_key, train_mode, sfreq=None, ch_names=None, backend='auto', backend_kwargs=None)#

Check registry support and obvious signal incompatibilities without loading.

Parameters:
Return type:

CapabilityResult

coco_pipe.decoding.foundation_models.extraction.normalize_inclusive_endpoint(container, *, segment_duration, expected_sfreq, model_key='model', on_mismatch='error')#

Drop MNE’s inclusive-endpoint extra sample from epoched windows.

MNE epochs span [tmin, tmax] inclusively, yielding expected_n_times + 1 samples; foundation backends want the half-open count. This trims the trailing sample (recording it in meta) when the off-by-one is observed, so prepare does not raise on the mismatch.

Returns (container, None) when the window is already correct or was normalized. On any other length mismatch, returns (None, reason) if on_mismatch == "skip" and otherwise raises ValueError.

Parameters:
Return type:

tuple[coco_pipe.io.DataContainer | None, str | None]

class coco_pipe.decoding.foundation_models.extraction.FoundationEmbeddingResult#

Window embeddings plus extraction provenance.

token_embeddings holds the native backbone feature tensor, without reshaping or normalization, and is populated only when the extractor is built with store_tokens=True.

channel_embeddings (window, channel, feature) holds each channel’s tokens averaged over time patches, and patch_embeddings (window, time_patch, feature) each time patch’s tokens averaged over channels. Each is populated when the backend’s tokens have its axis and another one to average over (CBraMod, REVE and LaBraM without channel interpolation have both), unless the extractor caches window embeddings. They are not normalized, whatever normalize_embeddings says.

extra_window_embeddings maps each of the extractor’s extra_poolings to its window vectors, pooled from the same tokens as window_embeddings and normalized like them.

window_embeddings: numpy.ndarray#
window_start: numpy.ndarray#
window_stop: numpy.ndarray#
window_index: numpy.ndarray#
metadata: dict[str, Any]#
token_embeddings: numpy.ndarray | None = None#
channel_embeddings: numpy.ndarray | None = None#
patch_embeddings: numpy.ndarray | None = None#
extra_window_embeddings: dict[str, numpy.ndarray]#
class coco_pipe.decoding.foundation_models.extraction.FoundationEmbeddingExtractor(model_key, *, backend='auto', device='auto', pretrained=True, seed=None, pooling='mean', extra_poolings=(), normalize_embeddings=True, resample=True, cache_embeddings=False, store_tokens=False, batch_size=None, backend_kwargs=None, model=None)#

Compose model loading, metadata binding, extraction, and pooling.

pooling makes the window vectors; extra_poolings names other poolings the backend offers (("attention",) for REVE), whose vectors come from the same forward pass, in extra_window_embeddings.

pretrained=False with an integer seed gives the model’s architecture random weights drawn from the seed, the same for every recording. The metadata records the weights of the model used (weights, and seed for random ones).

Parameters:
backend = 'auto'#
device = 'auto'#
pretrained = True#
seed = None#
pooling = 'mean'#
extra_poolings#
normalize_embeddings = True#
resample = True#
cache_embeddings = False#
store_tokens = False#
batch_size = None#
backend_kwargs#
model = None#
clear_cache()#

Drop all memoized window embeddings.

Return type:

None

extract(epochs, *, signal_metadata, window_start=None, window_stop=None, window_index=None, metadata=None)#

Extract one embedding per input window.

window_index is the number of each window in its recording; by default the windows are numbered in the order given.

Parameters:
Return type:

FoundationEmbeddingResult

extract_recording(recording)#

Extract the windows of one recording the BIDS loader read, by condition.

recording holds the loader’s rows of one recording, with their condition and epoch coordinates. Each condition’s result numbers its windows by their epoch, and their samples count as if the epochs were back to back. write_recording_embeddings() takes the results. extract_weight_sets() extracts a recording with several extractors, resampling it once.

Parameters:

recording (coco_pipe.io.DataContainer)

Return type:

dict[str, FoundationEmbeddingResult]

coco_pipe.decoding.foundation_models.extraction.extract_weight_sets(extractors, recording)#

Extract one recording with several extractors, resampling it once.

The extractors are typically one model’s weight sets, its pretrained weights and random ones of several seeds, each keeping its model loaded. Each condition’s windows are resampled once for all the extractors whose models take the same rate, instead of once per extractor; the models’ own input scaling stays theirs. Returns, in the order of extractors, what each one’s extract_recording() returns.

Parameters:
Return type:

list[dict[str, FoundationEmbeddingResult]]