Part VII: Health, Biosignals, and Wearable AI
Chapter 31: EEG, Neural Signals, and Brain-Computer Interfaces

Non-invasive language/speech decoding

"Give me a scalp electrode and enough teacher forcing, and I will reconstruct Hamlet from a coin flip."

A Skeptical AI Agent

The big picture

The previous section put electrodes inside the skull and read speech at conversational rates. This section keeps the sensors outside: EEG on the scalp, MEG in a magnetically shielded room, fNIRS or fMRI measuring hemodynamics. The prize is a language interface with no surgery, no infection risk, and no informed-consent asymmetry. The physics fights back. Scalp signals are spatially blurred, noise dominated, and lag the underlying neural events. The honest state of the art decodes perceived and imagined language into constrained outputs, not fluent open telepathy. This section teaches what genuinely works, why the strongest published claims collapsed under scrutiny, and how to evaluate a decoder so you do not fool yourself.

This section assumes the montage, band, and artifact material from Section 31.1 and Section 31.2, the foundation-model encoders from Section 31.4, and the contrastive-learning machinery from Chapter 17. If any of those are unfamiliar, read them first; the decoders below are thin heads on top of exactly that stack.

Three problems that all get called "mind reading"

Vague press coverage collapses three very different tasks. Separating them is the single most useful thing you can do before reading any paper. Speech perception decoding asks: while a subject listens to audio, can we identify which speech segment they heard? Imagined or inner-speech decoding asks: while a subject silently rehearses words, can we recover them? Semantic reconstruction asks: can we produce text whose meaning tracks a story the subject is hearing or watching, without word-for-word fidelity? These differ in difficulty by orders of magnitude. Perception decoding has a strong, time-locked stimulus and is the easiest. Inner speech has no external anchor, weak and idiosyncratic signals, and is the hardest. Semantic reconstruction sits between, and crucially it is evaluated on meaning overlap, not exact strings, which changes what counts as success.

Key insight: classification into a closed set, not generation

The robust non-invasive results are retrieval results. Meta's 2023 work (Defossez and colleagues, published in Nature Machine Intelligence) did not generate free text from MEG or EEG. It learned a joint embedding and, given a brain segment, ranked which of a fixed candidate set of audio clips was heard, reaching roughly 40 percent top-10 accuracy from MEG against large candidate pools. That is a genuine, reproducible signal, and it is a closed-set classification metric. The moment a system claims open-vocabulary sentence generation from scalp EEG, ask whether the decoder was ever run without the ground-truth text fed into it. Usually it was not.

Contrastive brain-to-speech alignment

The workhorse architecture borrows directly from CLIP-style multimodal learning (see Chapter 21). A brain encoder maps a windowed multichannel recording \(x \in \mathbb{R}^{C \times T}\) to an embedding \(z_b\); a frozen self-supervised speech model such as wav2vec 2.0 maps the concurrent audio to \(z_a\). Both are L2-normalized and trained so that matching brain-audio pairs align while mismatched pairs repel, using the symmetric InfoNCE objective

$$ \mathcal{L} = -\frac{1}{2N}\sum_{i=1}^{N}\left[\log\frac{e^{\,s(z_b^i, z_a^i)/\tau}}{\sum_j e^{\,s(z_b^i, z_a^j)/\tau}} + \log\frac{e^{\,s(z_b^i, z_a^i)/\tau}}{\sum_j e^{\,s(z_b^j, z_a^i)/\tau}}\right], $$

where \(s\) is cosine similarity and \(\tau\) a learned temperature. The brain encoder is a subject-conditioned convolutional or transformer stack: a per-subject spatial layer absorbs individual electrode geometry and skull anatomy, then a shared backbone does the temporal work. This subject-embedding trick is what lets one model pool many people despite each brain being wired slightly differently, and it connects directly to the adaptation methods in Section 31.7. At inference you embed the brain segment and retrieve the nearest audio candidate. No text is generated, and there is nothing to leak.

import torch, torch.nn.functional as F

def clip_brain_speech_loss(z_brain, z_audio, temperature=0.07):
    # z_brain, z_audio: (N, D) segment embeddings from the same time windows
    zb = F.normalize(z_brain, dim=-1)
    za = F.normalize(z_audio, dim=-1)
    logits = (zb @ za.t()) / temperature      # (N, N) similarity matrix
    targets = torch.arange(z_brain.size(0), device=z_brain.device)
    # symmetric: brain->audio and audio->brain both classify the diagonal
    return 0.5 * (F.cross_entropy(logits, targets) +
                  F.cross_entropy(logits.t(), targets))

# retrieval eval: does the true clip rank in the top-k for each brain window?
@torch.no_grad()
def topk_retrieval(z_brain, z_audio, k=10):
    sims = F.normalize(z_brain, -1) @ F.normalize(z_audio, -1).t()
    ranks = sims.argsort(dim=-1, descending=True)[:, :k]
    hit = (ranks == torch.arange(len(z_brain))[:, None]).any(-1)
    return hit.float().mean().item()
A complete contrastive brain-to-speech head: the same symmetric InfoNCE loss used by Meta's MEG/EEG decoder, plus the top-k retrieval metric that is the honest way to report it. The diagonal of the similarity matrix is the matching pair.

Library shortcut: the encoders are pretrained already

You do not implement the speech tower. transformers loads a frozen wav2vec 2.0 in three lines (Wav2Vec2Model.from_pretrained("facebook/wav2vec2-base-960h")), turning raw audio into aligned embeddings; braindecode supplies the subject-conditioned EEG/MEG backbones (ShallowConvNet, EEGConformer) with standard windowing. Together they replace roughly 500 lines of dataloaders, spatial layers, and augmentation with about 20, so the only bespoke code you own is the loss above and the evaluation split.

Why EEG-to-text papers overclaimed

A wave of 2022 to 2023 papers reported fluent open-vocabulary sentence generation from EEG (the DeWave line and its relatives), with BLEU and ROUGE scores that looked transformative. In 2024 the results were shown to be an evaluation artifact. The sequence-to-sequence decoders were trained and, critically, tested with teacher forcing: at each step the model received the previous ground-truth token as input. A language decoder with teacher forcing produces fluent, on-topic text from noise, because it is really doing next-token prediction conditioned on the reference. Replace the EEG input with zeros or random values and the scores barely move. The lesson is a leakage lesson, the same family of failure catalogued in Chapter 5: if a control condition with the signal removed still "works," the signal was never the source of performance.

Practical example: the noise-control probe that saved a clinical review

A neurotechnology startup pitched a rehabilitation console that "reconstructs intended sentences" for stroke patients with aphasia, showing a demo video of clean generated text scrolling beside a patient in an EEG cap. The clinical reviewer, having read the 2024 critiques, asked one question: run the exact pipeline with the EEG channels shuffled across time, on stage, live. BLEU dropped by two points out of a reported forty. The output was almost entirely the language model's prior, not the patient's brain. The console was not fraudulent; the team had simply inherited a teacher-forced benchmark and never run the ablation. They pivoted to a closed-set retrieval interface with a 30-word functional vocabulary that survived the same probe, shipped it as an assistive-communication aid, and reported free-running (not teacher-forced) accuracy with conformal coverage per Chapter 18.

Modalities, and the semantic-reconstruction frontier

Modality choice sets the ceiling. EEG is portable and cheap but spatially smeared and artifact prone; it supports small closed vocabularies and coarse category decoding. MEG has far cleaner spatiotemporal structure and drives the best perception-retrieval numbers, but the machine is room sized and non-portable. fNIRS measures slow hemodynamics, useful for detecting speech intent or answering binary questions, not for word-rate decoding. fMRI is the outlier: Tang and colleagues (2023, Nature Neuroscience) reconstructed the gist of heard and imagined stories by pairing a GPT-class language model with a per-subject encoding model and beam search over candidate continuations, scored by predicted BOLD response. It reconstructs meaning, not words, requires roughly 16 hours of per-subject scanner training, and, notably, failed when the subject actively performed a distractor task, an inadvertent demonstration of mental privacy.

Research frontier: where the field actually stands (2025-2026)

Current SOTA for portable non-invasive language BCIs is honest and modest: subject-pooled contrastive models (Meta's MEG/EEG line) for closed-set perception retrieval; the fMRI semantic decoder (Tang et al.) for non-portable gist reconstruction; and inner-speech classification over small vocabularies from EEG datasets such as Thinking Out Loud, where subject-independent accuracy still hovers near chance for open sets. The live questions are (1) whether EEG foundation models from Section 31.4 transfer to language tasks, (2) whether OPM-MEG wearable magnetometers can bring MEG-grade signals out of the shielded room, and (3) leakage-proof benchmarks that mandate free-running, signal-ablated evaluation by construction. No published, replicated system produces open-vocabulary inner speech from scalp EEG.

Exercise

Take the retrieval head above and build the ablation that catches teacher-forcing-style leakage for a contrastive decoder. Train on a public MEG or EEG listening dataset (for example MEG-MASC), report top-10 retrieval, then re-run three controls: (a) temporally shuffle each brain window before embedding, (b) swap in Gaussian noise of matched variance, (c) evaluate across held-out subjects rather than held-out segments of trained subjects. Any accuracy that survives (a) and (b) is your leakage floor; the drop from within-subject to cross-subject in (c) is your generalization gap. Report all four numbers together, co-computed on one split.

Self-check

  1. Why is closed-set retrieval a more defensible claim for scalp EEG than open-vocabulary text generation, and what metric belongs with each?
  2. Explain in one sentence how teacher forcing lets a decoder produce fluent sentences that owe almost nothing to the brain signal.
  3. The fMRI semantic decoder fails when the subject counts backwards during scanning. Why is that failure a feature rather than a bug, and what does it tell you about consent?

What's Next

In Section 31.7, we turn from decoding accuracy to the surrounding obligations: subject adaptation so a model built on many brains works on a new one with minutes of calibration, safety and mental-privacy safeguards for signals that (as the distractor result showed) can be withheld by the user, and interpretability methods that tell you which cortical sources and frequency bands a decoder actually relies on before anyone trusts it in the clinic.