A volunteer types a memorized sentence on a hidden keyboard while a MEG scanner listens. The decoder writes it back with 32% character error on average, and 19% for the best volunteer.
Learn how three stages turn 500 ms windows of magnetic and electric brain signals into Spanish sentences, and why the scanner matters as much as the model.
Pick a sentence, then step through the stages: what was typed, what the convolutional module alone writes, what the transformer adds, and what the language model fixes. Then we build each stage, piece by piece, from the sensors up.
You need a feel for what a neural network layer does and a little Python. We teach the brain signals, the convolutions, attention and the language model from zero.
Based on Brain-to-Text Decoding: A Non-invasive Approach via Typing by Jarod Lévy, Mingfang (Lucy) Zhang, Svetlana Pinet, Jérémy Rapin, Hubert Banville, Stéphane d’Ascoli and Jean-Rémi King (Meta AI and partners, arXiv 2502.17480, 2025), and on its ancestor, Decoding speech perception from non-invasive brain recordings by Défossez et al. (Nature Machine Intelligence, 2023). Every idea is re-taught here in our own words and devices. It is a reading of the lecture Brain Rhythms.
The sentences and every decoded line are copied from the paper: Table 2 (MEG, the two stage-by-stage examples) and Table 1 (the best-decoded EEG example, where the paper prints only the final output). Each sentence was picked by the authors as a good case; the paper’s average over all MEG sentences is 32% CER. The per-sentence error rate here is computed live in your browser against the sentence that was read.
Chapter 0
See why a hidden keyboard turns a hard brain-reading problem into a task a scanner can answer
Picture a volunteer sitting in front of a screen. A cardboard box hides her hands and the keyboard under them. Words flash on a screen, one at a time. When the screen goes blank, she types the sentence she just read. No letters appear as she types. A scanner around her head records the whole time.
Now the question: can a computer read the sentence from the scanner alone? Not from her fingers, not from the screen. Only from the faint signals her brain gives off while her fingers move.
This is the problem of Brain2Qwerty, a model from Meta AI and the Basque Center on Cognition, Brain and Language. The paper is a proof that a safe, non-invasive device can decode sentences her brain is producing, one character at a time. This chapter sets out why that is hard, and why typing is a smart way to make it easier.
A brain-computer interface (BCI) is a system that turns brain activity into a command or into text. Think of it as a microphone for thought, with a translator behind it. The best results so far come from a neuroprosthesis: electrodes placed in the brain, sensing the motor regions that drive speech and hand movement. Several patients with paralysis have used one to produce full sentences. The paper cites decoding at rates close to normal speech.
The price is surgery. The authors list the risks as brain hemorrhage and infection. They also point out that implants are hard to keep working over many years. So an implant is hard to offer to a large group of patients, including those who barely respond and whose needs doctors still cannot assess.
The other way is to listen from outside the skull. EEG (electroencephalography) puts electrodes on the scalp and measures tiny voltages. MEG (magnetoencephalography) puts sensors near the head and measures the tiny magnetic fields the same neural activity creates. Neither one opens the skull. Both pay for this with weaker signals.
The signal-to-noise ratio says how loud the thing you want is compared with everything else. Picture a radio in a storm: the song is the signal, the crackle is the noise. A scalp recording is mostly crackle. So older EEG interfaces ask users to do loud, simple things. They stare at a flickering light, or they imagine moving a hand for a long time. A linear classifier can spot those patterns.
Even then, results are modest. The paper quotes a public benchmark where EEG motor imagery reaches only 43.3% accuracy on four choices. Chance on four choices is 25%. That is a slow and unreliable keyboard.
The authors name two ways out. First, MEG has a higher signal-to-noise ratio than EEG. Second, deep learning had just decoded speech that people heard from MEG, much better than from EEG. Chapter 2 tells that story. Put the two together and try a task where the brain does something rich and quick: producing language.
Typing gives the decoder three gifts. The brain does it fast and in a rhythm. The motor cortex sends a different command for each finger, so each key leaves a different trace. And every keystroke has an exact time stamp, so the data come already cut into labelled pieces: this 500 ms of signal goes with the letter R.
The study had 35 healthy volunteers. Each one typed Spanish sentences of 5 to 8 words, with the keyboard hidden and no backspace. Twenty were recorded with EEG and twenty with MEG, and five did both. They typed about 152 characters per minute. In total the study has 193,000 characters in MEG and 146,000 in EEG.
Before building the big model, the authors ran a sanity check. Did the brain data hold the expected signs of finger movement at all? They trained a plain ridge classifier (a linear model with a penalty that keeps its weights small) on each time sample around each key press. The task was to say which hand pressed the key. Then they asked it to say which key.
The next device shows what they found. Left versus right is a coin flip at 50%. Naming one key out of the 29 classes (Chapter 7 explains the 29) has a chance level of 14%, because the most common character is right about 14% of the time.
Each bar is the best accuracy a plain linear model reaches at any moment around a key press. Choose the question, then compare MEG, EEG and chance.
Numbers are from the paper (Section 2.1): hand, MEG 74 ± 1.3% and EEG 64 ± 0.8% against a chance of 50%; key, MEG 22 ± 0.8% and EEG 16 ± 0.5% against a chance of 14%. The error bars are standard errors across volunteers. Both peak 40 ms after the key press. The key chance level of 14% is the paper’s.
MEG wins both times, and both beat chance. Notice how small the key numbers are. A plain model gets 22% of keys right with MEG. That is not a keyboard. It is a proof that the motor signals are there. The rest of the lesson shows how the three stages of Brain2Qwerty dig out the rest.
For each key press, take 0.5 s of brain signal. A convolutional module turns it into one vector of numbers. A transformer reads all the vectors of the sentence together and corrects each one with its neighbours. A language model then pushes the guesses toward text that real Spanish would produce. The output is a string, scored with the character error rate (CER): the share of characters that need editing to match the sentence that was read.
Where the paper puts it: MEG 32% CER on average, EEG 67%, and 19% for the best MEG volunteer.
Chapter 1
Turn a raw recording into one small table of numbers for each key press
A volunteer presses the letter R. A sensor array catches a flicker of magnetic field. Less than half a second later she presses E. The recording does not stop between letters. It is one long unbroken stream of numbers, 1,000 of them every second, for every sensor.
The model cannot eat a stream. It needs a fixed-size table for each key press. This chapter builds that table from the raw data, step by step, and keeps track of its shape at every step.
The MEG system is a Megin machine with 306 channels. A channel is one sensor’s signal over time. Of the 306, 102 are magnetometers and 204 are planar gradiometers. A magnetometer measures the magnetic field at one spot. A gradiometer measures how the field changes across a short distance, which cancels far-away noise. The machine records at 1 kHz (1,000 samples per second) and filters the signal online between 0.1 Hz and 330 Hz.
The EEG system is a BrainVision actiCAP slim cap with 64 channels: 61 scalp electrodes and 3 that watch the eyes. It also samples at 1 kHz. Its online high-pass filter is set at 0.02 Hz.
One practical trap: MEG sensors feel metal. A normal keyboard has springs and circuits that would swamp the signal. So the team used a magnetic-resonance-compatible keyboard from HybridMojo and replaced the metal springs with non-ferromagnetic silver ones. The keyboard sat 70 cm from the sensors, covered by a box.
The paper filters both recordings with a band-pass filter between 0.1 and 20 Hz. A band-pass filter keeps the frequencies inside a band and removes the rest. (Hz means cycles per second: a 20 Hz wave wiggles 20 times each second.) Slow drifts below 0.1 Hz go away. So does fast electrical hiss above 20 Hz. The paper keeps this slow band for decoding. (The lecture Brain Rhythms explains what each band means. Our DFT lesson shows how to see which frequencies a signal holds.)
Then the recording is resampled to 50 Hz: only every twentieth sample is kept, after the filter has made that safe. Why is 50 Hz safe for a signal that stops at 20 Hz? The rule is the Nyquist limit. A sampling rate of fs can describe waves up to fs / 2 and no higher. At 50 Hz that limit is 25 Hz, which sits above the 20 Hz filter. A wave faster than the limit does not vanish. It folds back and shows up as a slower wave that was never there. That fold is called aliasing.
The filter and resampling come from MNE-Python, a standard open tool for brain recordings, used with its default settings. The next device lets you feel what resampling does to a window.
One toy channel around a key press at time 0: a slow response with a faster 15 Hz ripple on top and a drift. Dots are the samples that stay. Pick a sample rate, then switch baseline correction on and off.
Illustrative: a made-up channel, not recorded data. The window (−0.2 s to +0.3 s), the 50 Hz rate and the baseline step (subtract the channel’s mean over −0.2 to 0 s) are the paper’s. The pale line is the straight-line join of the dots, which is what a coarse sample rate can rebuild.
At 50 Hz the join through the dots follows the whole shape. At 20 Hz, the limit is 10 Hz, and the 15 Hz ripple folds into the wrong shape. This is why the sample rate and the filter must be chosen together.
The data are then cut into windows. Each key press gets one window from 0.2 s before the press to 0.3 s after. That is 0.5 s long. At 50 Hz it holds 50 × 0.5 = 25 samples. Notice the window starts before the key press, so it holds the lead-up to the press as well as what follows it.
Each window is a table with one row per channel and one column per time sample. The paper calls it X, with shape s × t, where s is the number of sensors and t the number of time samples. For MEG, X is 306 × 25, which is 7,650 numbers. For EEG, it is 64 × 25, which is 1,600 numbers.
Baseline correction. Each channel sits at its own resting level, and that level drifts. The team subtracts, for each channel, its average over the 0.2 s before the key press. After that, every channel starts near zero and the window shows only the change caused by the press. In the device, switch the correction on and watch the trace drop to zero at time 0.
Robust scaling. Channels also have different sizes. A magnetometer reads numbers thousands of times smaller than a gradiometer. A RobustScaler from scikit-learn fixes this. It subtracts the median and divides by the interquartile range (the width of the middle half of the values). Unlike a mean and a standard deviation, the median and the interquartile range barely move when a few huge spikes appear. Then a clamp cuts any value that is still far outside the normal range.
Worked example with toy numbers. A channel has the nine values 1, 2, 3, 4, 5, 6, 7, 8 and 90. The median is 5. The middle half runs from 3 to 7, so the interquartile range is 4. The scaled values are (1 − 5) / 4 = −1, then −0.75, −0.5 and so on up to (8 − 5) / 4 = 0.75, and (90 − 5) / 4 = 21.25. The spike is still large, so the clamp then cuts it. A mean-and-standard-deviation scaler would have let the spike stretch the scale for all the normal values.
The ancestor paper says why the clamp matters. When Défossez et al. removed it, their model fell from 70.7% to 23.6% top-10 accuracy on one MEG dataset, and from 17.7% to 0.5% on one EEG dataset (their Table 3). Chapter 2 explains those numbers. The Brain2Qwerty paper does not state its clamp threshold. The ancestor clamps values beyond 20 standard deviations.
Chapter 2
Learn the contrastive trick from Défossez 2023 that taught a network to decode heard speech, and see what Brain2Qwerty keeps and what it changes
A volunteer sits in a MEG scanner and listens to a short story. Three seconds of her brain signal are saved, next to the three seconds of sound she heard. A computer is shown the signal alone and a list of more than 1,000 sound clips. It must say which clip she heard.
That is the task of Défossez et al. 2023, the paper Brain2Qwerty builds on. Its model is the direct ancestor of the Brain2Qwerty convolutional module. To see why the new paper looks the way it does, we first need the old one.
The obvious plan is regression: predict the sound itself. The ancestor paper writes it as a function freg that maps a brain table X (C sensors by T time steps) to a Mel spectrogram Y (F frequency bands by T time steps). A Mel spectrogram is a picture of a sound, with time across and pitch up the side, where pitch bands are spaced the way the ear hears them. The model learns by shrinking the squared difference between its picture and the true one.
The authors saw this fail. The predicted picture was dominated by one smooth, broadband smear that is the same whenever speech is present. It did not tell one sentence from another. Squared error treats every pitch band as equally important and equally scaled. The brain does not care about every band equally, and some bands vary by orders of magnitude less than others.
The goal was never to paint the sound. The goal was to tell the sounds apart.
So the authors changed the question. Instead of “draw the sound”, ask “which of these N sounds was it?” This is a lineup. The brain signal is the witness, and the N clips are the people in the lineup. The loss is the CLIP loss, first designed to match pictures with captions (see our contrastive learning lesson).
The network maps the brain signal X to a vector Z. For each candidate sound Yj, take the inner product of Z and Yj: multiply them number by number and add. The inner product is large when two vectors point the same way, so it works as a similarity score. A softmax turns the N scores into N probabilities that add up to 1.
Training uses cross-entropy. If the true sound is candidate N, the loss is the negative log of its probability.
Worked example with three candidates and toy scores. The true clip scores 2.0, and the other two score 1.0 and 0.0. The exponentials are 7.389, 2.718 and 1.000, which add up to 11.107. The true clip gets 7.389 / 11.107 = 0.665. The loss is −ln 0.665 = 0.408. If all three scored the same, each would get 1/3 and the loss would be ln 3 = 1.099. Try it below.
Candidates sit on a circle as unit vectors. The blue one is the true sound. The teal arrow is the brain vector Z. Turn it toward blue, make it longer for more confidence, and add candidates. Dot size is probability.
Illustrative geometry, the paper’s equations: the score is 〈Z, Yj〉 = |Z| cos(angle between them), the probabilities are the softmax of Eq. (2) and the loss is Eq. (3). The real vectors have hundreds of dimensions, not two.
Two details matter later. In training the other items in the same batch serve as the wrong candidates, so no extra data are needed. At test time the wrong candidates are every other segment of the test set, more than 1,000 of them. Because the candidates are vectors from a speech model, the decoder can pick clips that never appeared in training. This is zero-shot decoding.
The ancestor also changed what Y is. A Mel spectrogram is a low-level picture. The authors used wav2vec 2.0 instead, a speech network trained on 56,000 hours of audio to predict hidden pieces of its own internal states. The target for each 3 s clip is the average of its last four transformer layers. The brain model learns to match a rich description of the sound, not its surface.
The ancestor ran on four public datasets, two MEG and two EEG, with 175 volunteers in all. On one MEG dataset (Gwilliams) the model picks the right clip among 1,363 in the top 10 with the numbers in the next table. Each step in the table adds one idea.
| Model (top-10 accuracy, %) | Gwilliams MEG | Schoffelen MEG | Brennan EEG | Broderick EEG |
|---|---|---|---|---|
| Random | 0.7 | 0.8 | 5.3 | 0.5 |
| Regression on Mel | 12.4 | 20.6 | 6.0 | 1.0 |
| + CLIP loss | 55.1 | 55.1 | 8.0 | 9.7 |
| + wav2vec 2.0 target | 70.7 | 67.5 | 25.7 | 17.7 |
The table is Table 2 of the ancestor paper. The jump from regression to CLIP is the biggest single gain on MEG: 12.4 to 55.1. MEG beats EEG on every row. The ancestor’s results text gives the stricter top-1 score, where the true clip must rank first: up to 41.3% on average across MEG volunteers, and above 80% for the best one. A caution: the Brain2Qwerty paper quotes the 41% figure as a top-10 accuracy. The ancestor’s own text says top-1, so we use that.
Brain2Qwerty keeps the brain module: spatial attention, a subject layer and a stack of dilated convolutions (Chapters 3 and 4). It also keeps the idea of training across all volunteers at once.
It drops the contrastive loss. The answer set is now closed: 29 classes. With a fixed list of classes, plain cross-entropy over the list is the right tool. There is no sound to match against, and nothing to generalise to beyond the keys on the keyboard. It adds two new stages on top: a transformer across the sentence, and a language model.
Chapter 3
Let each learned channel choose which sensors to listen to, then give every volunteer a private matrix that lines their brain up with the rest
You stand in a hall with 306 microphones on the walls, each one a sensor on the head. Someone is speaking in one corner. You do not want to average all 306 microphones. You want to listen mostly to the few near the speaker, and to ignore the rest.
Now add a second problem. Twenty volunteers each wear the same helmet, but every head is shaped differently and every brain folds differently. The same finger movement lands on slightly different sensors for each person. A single model has to serve them all.
The first two parts of the Brain2Qwerty convolutional module solve these two problems. They are inherited from Défossez 2023. We use that paper’s details for the sizes, and we say so when a size is not stated in Brain2Qwerty.
The input is a table X of s sensors by t time samples. Spatial attention builds a new table with D1 output channels. Each output channel is a weighted average of the input sensors. The weights are not free numbers for each sensor. They come from a smooth map laid over the head, so nearby sensors get similar weights.
The positions come first. The 3D position of every sensor is flattened onto a 2D plane with an MNE-Python function, and rescaled to a square from 0 to 1. Sensor i then has a position (xi, yi).
For each output channel j, the model learns a function aj over that square. It writes aj as a sum of waves, which is a Fourier series: a sum of sines and cosines with different spatial frequencies. The model learns the weight of each wave. The ancestor uses K = 32 waves along each axis.
Then a softmax turns the height map into weights over the sensors, and the channel is the weighted sum.
Play with one channel below. Each slider changes the map and the weights follow.
49 toy sensors on a head. Dot size is each sensor’s weight in one output channel, built from a single wave. Change the slant of the wave, move it, sharpen it, then press Drop out a patch.
Toy layout and a single wave with a made-up amplitude. The paper’s version sums 32 × 32 learned waves per channel over the real flattened sensor positions. Spatial dropout is the paper’s: pick a random spot and remove every sensor within 0.2 of it from the softmax.
Read the dots as a spotlight. Make the sharpness 0 and every weight equals 1/49, a plain average. Raise it and the weights concentrate on the sensors where the wave is high. The spatial dropout button copies a training trick: remove a patch of sensors at random so the model cannot rely on any single region. The ancestor’s ablation table shows the pay-off. Removing the dropout cost 1.7 points on one EEG dataset and 1.7 on one MEG dataset. Removing spatial attention altogether cost 2.5 points on average.
After the softmax sum, a 1×1 convolution (a small matrix mixing the channels at each time step, with the same number of channels) follows. The result has D1 channels. The ancestor uses D1 = 270. For the example shape, a MEG window goes from 306 × 25 to 270 × 25.
Next comes a different kind of fix. For each volunteer s, the model learns one square matrix Ms of size D1 by D1. It multiplies every time column of the table. With D1 = 270 that is 270 × 270 = 72,900 weights for each person. For 20 MEG volunteers it adds up to 1,458,000 weights, a tiny part of a model with about 400 million.
Think of a translator who stands between each person and a shared dictionary. Everyone speaks the same language, but each speaks with an accent. Ms is that person’s accent correction. Its job is to put every volunteer’s sensors into one common space before the shared convolutions look at them. This follows what the ancestor calls decades of research on subject alignment. Classical tools such as PCA and ICA also rotate and rescale channels, but they are fitted one subject at a time. Here the matrices train together with the rest of the network.
The symptom of leaving it out is simple to see. Volunteer B looks different from volunteer A, so shared filters fit one and miss the other. The measurement is the ancestor’s Table 3. Without the subject layer, the top-10 accuracy falls from 67.5% to 42.4% on Schoffelen MEG and from 70.7% to 47.0% on Gwilliams MEG. The EEG sets fall too: 17.7% to 8.1% on Broderick, and 25.7% to 20.2% on Brennan. No other part of the brain module matters as much, except the clamp of Chapter 1.
One honest caution. In Brain2Qwerty, every volunteer is in the training set. The splits are made over sentences, not people. So the subject layer is trained for each person who is tested. A brand-new volunteer would have no matrix. The paper lists generalisation across participants as an open problem.
Chapter 4
Stack dilated convolutions so that every output sees the whole key-press window, then squeeze the window into one vector of 2,048 numbers
After the subject layer, a MEG window is a table of about 270 channels by 25 time samples. Somewhere in those 25 columns is the brain’s plan to press a key, the press itself, and the feedback after it. Each moment alone is weak and noisy. The shape across several neighbouring moments is what tells one key from another.
A convolution is the tool for shapes across time. It slides a small window of learned weights along the time axis and, at each step, takes a weighted sum of the samples it covers. The window is called the kernel. In Brain2Qwerty it covers 3 samples, which is 60 ms at 50 Hz. (Our convolutional networks lesson builds this from zero.)
A kernel of 3 sees only 60 ms. To see the whole 500 ms window, you can stack layers. Each new layer sees a bit further. The span of input samples that can influence one output is its receptive field. With kernel k and no tricks, each layer adds k − 1 = 2 samples to the field. Eight layers see 17 samples. That is 340 ms of the 500 ms window.
A dilated convolution spreads the same 3 weights apart. With dilation d, the kernel touches samples that are d steps apart: one at the centre, one d to the left, one d to the right. It still has 3 weights. But each layer now adds 2d samples to the field. With d = 4 the kernel touches samples 4 steps to each side, so one layer adds 8 samples to the field instead of 2, for free.
The Brain2Qwerty paper says only that the module has 8 sequential blocks with a kernel of 3 and a “dilation period of 3”. It does not list the dilations. The ancestor uses powers of two that cycle: 1, 2, 4, 8, 16 and back to 1. The device below lets you try three plans. The cycle 1, 2, 4 is one possible reading of a period of 3, shown to help you feel the idea, not as the paper’s exact list.
The bottom row is the 25-sample key-press window. Each row above is one layer. Pick a plan and a number of layers. The teal cells are every input that the highlighted output at the top depends on. Move the output with the slider.
Illustrative stack: one kernel-3 convolution per layer, zero padding at the window edges so the length stays 25 (the paper says padding keeps the time steps constant). The window length of 25 and the kernel of 3 are the paper’s. The three dilation plans are ours.
Try it. With all dilations 1 and 8 layers, the middle output sees 17 of 25 samples. With the cycle it sees all 25 and more. With doubling, even the end of the window has the whole window in view. When the field is wider than the window, the extra reach lands on padding, which adds nothing. So in this task the point is to cover the window, not to go beyond it.
Each block does more than convolve. The paper lists the parts, and the ancestor paper shows what each one earns.
Count the weights for scale. One convolution from 2,048 channels to 2,048 channels with a kernel of 3 has 3 × 2,048 × 2,048 = 12,582,912 weights. About 20 such layers would add up to roughly 252 million. The paper reports 258 million parameters for the convolutional module. This is arithmetic for scale, not the paper’s layout.
After the blocks, the table still has a time axis of 25. The transformer in the next chapter wants exactly one vector per key press. So the module pools the time axis with a single-head self-attention layer. In plain words, the layer learns how much each of the 25 moments should count, then combines them. The result is z in Rh with h = 2,048.
The data flow for one key press, with shapes. Input window: 306 × 25 for MEG. After spatial attention and the subject layer: about 270 × 25, using the ancestor’s size. After the blocks: a table with 2,048 channels over the same 25 steps (our reading of the paper’s description). After pooling: 2,048. One vector for one key.
The failure mode shows why this is not the end. The symptom: a key press is decoded from its own 0.5 s only. The measurement: the paper’s Table 2 shows the module alone writing “las tangpas re udnndl slindiis” for “las teorias reducen los numeros”. Nearly each letter is a guess. The fix is to let the neighbouring key presses help, which is the job of Chapter 5.
Chapter 5
Let every key press look at every other key press in its sentence, and turn one vector per key into 29 scores per key
Imagine you get a letter smudged by rain. You can read the first word, but the second one is a blur. You do not give up on the second word. You look at the words around it, and at the shape of the whole line, and you make a better guess.
The convolutional module of Chapter 4 reads each key press alone, as if no other key existed. It has no way to say “this letter came after that one”. In the paper’s Table 2 its MEG output for “las teorias reducen los numeros” is “las tangpas re udnndl slindiis”. The right letters are in there, but scattered.
The second stage lets the keys talk to each other. It is a transformer, the same kind of network behind modern language models. (Our transformer lesson builds it from zero. Here we keep only what this paper needs.)
For a sentence with n key presses, the convolutional module gives n vectors of size h = 2,048. Stack them and you get a table Z of shape n × 2,048. For the 31-character sentence “las teorias reducen los numeros”, that is 31 × 2,048. Row i is the summary of key press i.
The paper restricts the transformer to one sentence at a time. Keys from a different sentence never see each other. The transformer has 4 layers and 2 attention heads per layer. Input and output keep the same size. A final linear layer then maps every row from 2,048 numbers to C = 29 numbers, one score for each possible character. The output is Ỹ of shape n × 29. These scores are the logits: raw scores that a softmax would turn into probabilities.
Every layer uses self-attention. Each key press asks a question, every key press offers a label, and the answer is a blend. In symbols, each row of Z is turned into three vectors by learned matrices: a query Q, a key K and a value V.
A head is one such attention. Having two heads per layer lets the layer learn two different patterns of listening at the same time. The outputs of the heads are joined and mixed back to the full size.
The grid shows how much each key press (row) listens to each other key press (column) in one toy sentence of 8 keys. Each row sums to 100%. Pick a head, pick a row, and change the sharpness of the softmax.
Illustrative: the scores come from made-up seeded query and key vectors in 4 dimensions, not from the trained model. Trained values are not published in the paper. The mechanism is the paper’s: softmax(QKT / √d) over the keys of one sentence, 2 heads per layer.
Look at head 1 and head 2 on the same row. They put their weight in different places. That is why a layer has more than one head. Raise the sharpness and a row concentrates on its best match. Lower it to 0.2 and the row becomes a plain average of the whole sentence.
Worked count for the example sentence. With n = 31 key presses, one head makes a 31 × 31 grid, which is 961 weights. Two heads and 4 layers give 8 such grids, or 7,688 attention weights for one sentence. They are computed in one matrix multiplication per head, not key by key.
The transformer sees the whole sentence before it answers, so each key can listen both backward and forward. The paper does not describe masks or position codes. It does say the cost: the model is not real time. The sentence must be finished before any text appears.
The two modules train together, end to end, as one network. The transformer has about 138 million parameters. The convolutional module has about 258 million. The total is around 400 million.
What does the transformer buy? The paper’s ablation says it improves the character error rate for both EEG and MEG. It does not clearly improve the hand error rate (Chapter 7 defines both). That fits the picture. Which hand pressed a key is a signal the convolutional module already sees. Which letter it was benefits from sentence context.
See it in the paper’s Table 2. For the MEG sentence “el beneficio supera los riesgos” the convolutional module alone writes “el gefedisio suiera noa riestii”. Adding the transformer gives “el geneficon cupera los riesgoo”. Word shapes appear: the endings “ficon” and “riesgoo” are nearly right. The step from the first line to the second is the transformer at work. The last step, to the right spelling, belongs to the language model.
Chapter 6
Add a character language model to the model’s scores and search for the sentence that both the brain and the language like
You type “teh” on your phone and it fixes the word to “the”. The phone does not know what you meant. It knows that “teh” almost never appears in English, and that “the” appears all the time and is one slip away.
The third stage of Brain2Qwerty does the same job for brain-decoded text. After the transformer, the scores for each character are still noisy. A language model is a table of how likely each piece of text is in the language. Combine it with the scores and the sentence snaps toward real Spanish.
The paper’s language model is a 9-gram character model. An n-gram model predicts the next character from the n − 1 characters before it. It learns by counting. Take a large pile of Spanish text, count how often each string of 9 characters occurs, and divide. If “beneficio” shows up often and “beneficoo” never does, then after “benefic” the letter “i” gets high probability and “o” gets nearly none.
The authors built it with the KenLM library, which stores the counts in a prefix tree so lookups are fast and memory stays small. They trained it on Spanish Wikipedia. It never sees any brain data.
For the character at position i, the model has two opinions. The transformer says how well the brain signal fits each of the 29 characters. The language model says how well each character fits the 8 characters chosen before it. The paper joins them as a weighted sum of scores.
Worked example with toy numbers. After the text “benefic”, the transformer slightly prefers “o” (log score −0.9) over “i” (−1.1). The language model gives “i” a log score of −0.2 and “o” a log score of −5.0. With α = 5, “i” scores −1.1 + 5 × (−0.2) = −2.1, and “o” scores −0.9 + 5 × (−5.0) = −25.9. The language model rescues “i”. In fact any α above 0.042 would flip the choice here.
Choosing each character one at a time, always the best, is called greedy decoding. It can fail. The best letter now may lead to a dead end later. Beam search keeps the B best partial sentences at each step. It extends every one by all 29 characters, scores them with the formula above, and keeps the top B again. At the end it returns the best full sentence. The paper uses a beam of 30, picked by grid search as a trade between speed and accuracy.
One step costs B × 29 scored extensions. For a 31-character sentence and B = 30 that is 31 × 30 × 29 = 26,970 scored extensions. The next device runs this search for real, on a toy.
The sentence was read; the brain scores are noisy. Move the language model weight α, the beam width and the brain noise. Cells are green where the decoded character is right and red where it is wrong.
A toy that runs the paper’s search for real: the brain scores are made up (a seeded noisy score for each of 27 symbols, with extra score for keys next to the right one on a QWERTY keyboard), and the language model is a 3-gram counted from 22 invented Spanish sentences, not a 9-gram on Wikipedia. The word “riesgos” is absent from its text, like the out-of-vocabulary words of Chapter 8. The paper’s own values are α = 5 and a beam of 30; the right α depends on the scale of the scores, so ours differs.
Test three settings. At α = 0 the language model is silent, and the result equals the raw best guess. At a moderate α the decoder repairs most characters. At a high α, such as 5 with a small beam, the language model overrules the brain and writes fluent Spanish that is simply wrong. The symptom is a clean sentence with the wrong words. The measurement is a high error rate despite fluent text. The fix is to lower α or widen the beam, which is what the grid search does.
Out-of-vocabulary words are the other limit. The toy has never seen “riesgos”, so near the end the language model pulls toward words it knows, such as “reducen”. In the paper, words absent from training were decoded with a CER of 68% (measured with the Conv + Transformer stages, before the language model), against much lower rates for frequent words (Chapter 8).
One striking line in the paper: a volunteer typed “ek benefucui syoera kis ruesgis” and the model wrote “el beneficio supera los riesgos”, perfectly. The brain carried the intention, the fingers slipped, and the language model pulled the output back to the sentence that was read. That is a feature for a communication device. It is also a reason to be careful: a good language model can hide what the brain actually said.
Chapter 7
Follow one training run from the 29 classes to the cross-entropy loss, keep similar sentences apart, and compute the two error rates the paper reports
You now have every part. A recording becomes a window, a window becomes a vector, a sentence of vectors becomes a table of scores, and a language model turns scores into text. This chapter asks two plain questions. How does the network learn its weights? And how do we know a number such as “32%” means anything?
The task is classification. For each key press the network must pick one of C = 29 classes: the 26 letters of the Latin alphabet, plus three special classes. One is for space, one for numbers, and one for every other special character. The paper writes the model as a function f that maps a window of shape s × t to a list of C probabilities, each between 0 and 1.
The convolutional module and the transformer train together, end to end, with an unweighted cross-entropy loss. For one key press, cross-entropy is −log of the probability the model gave the correct class. Chapter 2 used the same idea for the CLIP loss. If the network gives the right key 0.5, the loss is −ln 0.5 = 0.69. If it gives 0.05, the loss is 3.0. “Unweighted” means every class counts the same, so common letters such as “e” dominate by their number, not by a rule.
The recipe in numbers, all from the paper: the same settings for EEG and MEG, 100 epochs, a batch size of 128, the AdamW optimiser with early stopping, and a OneCycle schedule with a weight decay of 10−4. The learning rate warms up to 10−4 over the first 10 epochs, then decays in a straight line. One model takes about 12 hours on a single NVIDIA V100 GPU with 32 GB of memory. The language model of Chapter 6 is not trained with this loss. It is built once from Wikipedia counts.
Volunteers typed 128 unique sentences each, and many sentences resemble one another: the same sentence with a word added, for example. If one version sits in training and a near twin in the test set, the model can memorise the text and look smart. The authors split the unique sentences into train (80%), validation (10%) and test (10%) with care.
First they turned each sentence into a TF-IDF vector, a list that gives each word a weight that is high when the word is common in this sentence and rare in the rest. Then they clustered sentences whose cosine similarity was above 0.5 and kept each cluster whole inside one split. Cosine similarity is 1 for identical word lists and 0 for no shared words.
Worked example with plain word counts, to keep the arithmetic short. Sentence A has the 5 words “la silla ocasiona las lesiones”. Sentence B adds “graves” and has 6 words. They share 5. The cosine is 5 / (√5 × √6) = 5 / 5.48 = 0.91. That is above 0.5, so A and B go to the same split. The symptom of skipping this step is a test score that looks too good. The measurement is a gap between seen and unseen sentences. The fix is the cluster split.
The paper also drops sentences with more than 10 typing errors (under 5% of the data in both EEG and MEG). Typing errors are found by aligning what was typed against what was read, with the standard library difflib. Each key press then has two labels: the key pressed and the key that should have been pressed, the target. Unless stated, all analyses use the target.
The character error rate (CER) counts the edits needed to turn the decoded text into the target. An edit is a swap (substitution), a drop (deletion) or an extra letter (addition). The minimum count is the Levenshtein distance. The paper writes CER = (s + d + a) / n, where n is the number of characters in the target sentence, and averages it over sentences.
The hand error rate (HER) asks a coarser question: did the decoder pick the right hand? Keys left of Y, H and B belong to the left hand. Keys from Y, H and B rightward belong to the right hand. Space, numbers and special characters are left out, because volunteers may use either hand for them. HER is the share of key presses on the wrong side. It is the measure old BCI studies used, which is why the paper reports it.
The target is the sentence that was read. Choose a decoded line from the paper, or type your own. Watch the edit counts and the two error rates update.
The target “las teorias reducen los numeros” and the three decoded lines are the paper’s Table 2 (MEG). The calculator follows the paper’s definitions: Levenshtein CER, and HER over the letters that line up, using the left and right hand split of the keyboard. Counts come from one optimal alignment; other optimal alignments can split the same distance differently between swaps, drops and additions.
Try deleting a few letters from the line. A missing letter costs one edit, and so does a wrong one. Add letters to the end and CER can climb past 100%, because it divides by the target length only. Now note a subtle thing: the line “las geoolas redicen los numeios” has a CER of 16% (5 edits in 31 characters) but a hand error rate of only 7% (2 of 27 letters). Many wrong letters still sit on the right hand. The Conv line is wrong on 52% of characters yet picks the wrong hand for only 15% of letters (4 of 27). That is what the paper means when it says the transformer helps CER more than HER.
A number needs a comparison. The paper uses two baselines, both trained on the same data. The first is a ridge classifier (RidgeClassifierCV) fitted per volunteer on one time sample of the recording, with its penalty chosen from 10−2 to 108 by nested cross-validation. The second is EEGNet, a small, popular convolutional network for BCIs, with depth 6 and dropout 0.3. It is trained across volunteers the same way as Brain2Qwerty, though it has no subject layer. Chance is the score of a dummy model that always answers with the most frequent character.
For comparisons across models on the same volunteers the paper uses the Wilcoxon signed-rank test. For comparisons between groups of volunteers, such as EEG against MEG, it uses the Mann-Whitney U test. Both are non-parametric: they use ranks, not means, so they do not assume a bell-shaped spread.
Chapter 8
Read each figure and table for its number, test what the errors say about motor signals, and mark the limits before anyone calls this a product
A number alone is cheap. The paper earns trust by asking what the number would look like if the story were wrong. If the decoder really reads finger movements, its mistakes should look like finger mistakes. If the language model does the work, errors should not depend on the brain. We go through the tests one at a time.
Brain2Qwerty reaches a mean character error rate of 32% ± 0.6 with MEG and 67% ± 1.5 with EEG. The gap is significant (p < 10−8). Here p is the chance of seeing a gap this large if the two scanners were truly equal, so a tiny p means luck is not the explanation. The best MEG volunteer reaches 19% ± 1.1 and the worst 45% ± 1.2. The best EEG volunteer gets 61% and the worst 71%. The abstract adds that the best volunteers’ sentences from outside the training set can be decoded perfectly. At 67%, EEG output is rarely readable (Table 1, left). At 19%, MEG output can be.
The ancestor paper hinted at this. When it matched recording time, sensors and volunteers across datasets, MEG still beat EEG with every p-value under 10−6. The MEG advantage is not a quirk of one dataset.
Brain2Qwerty beats EEGNet by 1.14-fold in CER on EEG and by 2.25-fold on MEG. Read that as roughly: EEGNet’s error rate is 1.14 and 2.25 times as large. The convolutional module alone already beats EEGNet on both devices. Adding the transformer improves CER but not clearly HER. Adding the language model improves CER again, on EEG (p < 10−5) and MEG (p < 10−6). Every stage earns its place, and the table of examples shows it: “las tangpas re udnndl slindiis”, then “las geoolas redicen los numeios”, then the exact sentence.
Pick a finding. Each bar is a number printed in the paper’s text, with its error bar where the paper gives one.
All values are from the paper’s text (Sections 2.2, 2.6 and 2.8) with their ± standard errors. Scanner: mean, best and worst volunteer, full model. Typing errors: Conv + Transformer and the Conv module alone, on correctly typed against wrongly typed characters, MEG. Word type: determiners and words absent from training, Conv + Transformer, MEG. Timing: inter-key interval around correct and wrong keystrokes.
Table 1 lists the best-decoded sentences. The EEG side shows why 67% is a poor keyboard: “la presencia de los tipos impone los retos” came out as “la declarada de los celos eran a los actos”, even though it was among the best EEG cases. The MEG side shows the other end. “las teorias reducen los numeros” came out exactly.
Figure 3 plots every sentence for three volunteers, ranked from easy to hard. Take the sentence “la estadistica sigue la distribucion”. The best MEG volunteer’s decoding is exact. The median volunteer gets “stamistosa sigue la distribucion”, with the first two words damaged. The worst volunteer gets “la estadistica figura de petrilla lo”. One sentence, three people, three very different results. This is why the authors show the spread and not only the mean.
Now a worked example of “fold”, with illustrative arithmetic. Suppose EEGNet gets 72 of every 100 characters wrong on MEG. A 2.25-fold gain means Brain2Qwerty gets 72 / 2.25 = 32 wrong. For EEG the gain is only 1.14-fold: from, say, 76 wrong down to 67. The paper’s text gives the folds and p-values, not EEGNet’s own average error, so these starting values are ours. The lesson is in the ratio. The new model helps far more on MEG, where the signal is clean enough to use.
One more design point about the ablations. The text gives each step as a p-value across volunteers (the convolutional module beats EEGNet, the transformer beats the convolutional module on CER, the language model beats both). The step-by-step bars are in the paper’s Figure 2. The tests in the next section use the Conv + Transformer model, before the language model. So Spanish statistics cannot explain them.
Four checks say yes, in part. First, the error pattern follows the keyboard. A wrongly decoded character tends to sit physically close to the right one: confusion rate and keyboard distance correlate at R = 0.73 (p = 0.02). Second, the authors clustered the hidden vectors of the convolutional module with k-means. Two clusters split the left-hand keys from the right-hand keys completely. Ten clusters still fit the keyboard layout.
Third, typing errors hurt. The volunteers made errors on about 3.6 to 3.9% of keystrokes (the paper says 3.9% in Results and 3.6% in Methods), and 65% of sentences held at least one. For a correctly typed character the full Conv + Transformer has a CER of 38%. For a mistyped one it is 65%. The convolutional module alone shows the same split, 52% against 71%. That test does not lean on sentence context. When the fingers do the wrong thing, the brain signal points there, and the decoder follows the fingers.
Fourth, the volunteers slowed down on mistakes. The time between key presses rose from 50 ± 7 ms to 114 ± 12 ms for wrong keystrokes. The authors link this to hesitation or monitoring. Together with the earlier test, they say decoding also involves “higher-level cognitive factors”. That claim is the paper’s reading, not a proven mechanism.
Frequent things are easier. All grammatical categories are decoded above chance, with determiners the best at 17 ± 1.9% CER, probably because they are short and common. Words absent from training are harder: 68 ± 2.1% CER. The authors note that in a random split, unseen words tend to be rare ones. Character frequency matters too: it correlates with decoding at R = 0.85. Rare Spanish letters such as z, k and w, which are 0.08%, 0.08% and 0.05% of the characters, are not decoded above chance.
More data help. Retraining on smaller slices shows the CER falling as recording time grows, with R = 0.93 (up to about 20 hours of training data).
For fairness: for EEG with 10 letters, an earlier study reached 75.8% CER, and this paper reaches 68% with 29 characters. That is progress, but both numbers are far from a usable keyboard.
Chapter 9
Trace the shapes end to end, keep the numbers and terms in one place, and carry the core code away
Brain2Qwerty is a pipeline of four moves. Filter and cut the recording into 0.5 s windows. Turn each window into one vector with a convolutional module that starts with spatial attention and a subject layer. Let a transformer refine the vectors of one sentence into scores for 29 characters. Search for the sentence that best fits those scores and a Spanish character model. With MEG this reaches a character error rate of 32% on average, and 19% for the best volunteer.
Choose a scanner and a sentence length. Each box is a stage; its shape and its count of numbers are for one sentence of n key presses.
Shapes follow the paper (window 25 samples, h = 2,048, 29 classes). The 270 channels after spatial attention are the ancestor’s D1; Brain2Qwerty does not state its own. The default n = 31 is the length of “las teorias reducen los numeros”.
| Item | Value | Where |
|---|---|---|
| Volunteers | 35 healthy adults, 20 with EEG and 20 with MEG (5 did both) | Section 4.1 |
| Data | MEG: 193K characters, 5.1K sentences. EEG: 146K characters, 4K sentences | Intro, Section 4.1 |
| MEG sensors | 306 channels (102 magnetometers, 204 gradiometers), 1 kHz | Section 4.1 |
| EEG sensors | 64 channels (61 scalp, 3 eye), 1 kHz | Section 4.1 |
| Preprocessing | Band-pass 0.1 to 20 Hz, resample to 50 Hz, window −0.2 to +0.3 s (25 samples), baseline correction, RobustScaler, clamp | Section 4.1 |
| Classes | C = 29: 26 letters, space, numbers, other | Section 4.2 |
| Convolutional module | Output h = 2,048 per key press; 258M parameters | Section 4.2.1 |
| Transformer | 4 layers, 2 heads per layer, one sentence at a time; 138M parameters | Section 4.2.1 |
| Language model | 9-gram character model, KenLM, Spanish Wikipedia; α = 5, beam 30 | Section 4.2.1 |
| Training | 100 epochs, batch 128, AdamW, learning rate 10−4, OneCycle; about 12 h on one V100 | Section 4.2.2 |
| Splits | 80 / 10 / 10 by sentence; sentences with TF-IDF cosine above 0.5 stay together | Section 4.1 |
| Linear baseline | Hand: MEG 74%, EEG 64% (chance 50%). Key: MEG 22%, EEG 16% (chance 14%) | Section 2.1 |
| Brain2Qwerty CER | MEG 32% ± 0.6 (best 19%, worst 45%). EEG 67% ± 1.5 (best 61%, worst 71%) | Section 2.2 |
| Against EEGNet | 1.14-fold CER improvement with EEG, 2.25-fold with MEG | Section 2.3 |
| Typing errors | 3.9% of keystrokes, 65% of sentences; CER 38% on correct keys, 65% on wrong ones | Section 2.8 |
| Keyboard link | Confusion against key distance: R = 0.73, p = 0.02 | Section 2.7 |
| Ancestor | Défossez 2023: 175 volunteers, 4 datasets; top-1 up to 41% (more than 1,000 clips), top-10 70.7% on Gwilliams MEG | Défossez Abstract, Table 2 |
| Term | Meaning |
|---|---|
| CER | Character error rate: (swaps + drops + additions) divided by the target length. |
| HER | Hand error rate: the share of key presses decoded on the wrong hand. |
| Channel | One sensor’s signal over time. |
| Window | The 0.5 s of signal around one key press: s × 25. |
| Receptive field | How many input samples one output sample depends on. |
| Spatial attention | Learned softmax weights over sensors, from a smooth map of positions. |
| Subject layer | One learned matrix per volunteer that aligns their sensors to a shared space. |
| Logits | Raw scores per class, before the softmax. |
| α | The language model weight in the beam score. |
| Beam search | Keep the B best partial sentences at each step. |
| OOV | Out of vocabulary: a word absent from the training set. |
# A sketch of Brain2Qwerty from the paper's description. Not the authors' code:
# sizes marked (ancestor) come from Defossez 2023, the paper does not state them.
import torch, torch.nn as nn
class Brain2Qwerty(nn.Module):
def __init__(self, n_subjects, D1=270, h=2048, C=29):
super().__init__()
self.spatial = SpatialAttention(out_channels=D1) # Fourier map, softmax over sensors (ancestor)
self.subject = nn.ModuleList( # one D1 x D1 matrix per volunteer
[nn.Conv1d(D1, D1, kernel_size=1, bias=False) for _ in range(n_subjects)])
self.conv = DilatedConvStack(D1, h, blocks=8, kernel=3) # skips, dropout, GELU, GLU
self.pool = AttentionPool(h) # single-head attention over the 25 steps
layer = nn.TransformerEncoderLayer(h, nhead=2, batch_first=True)
self.trans = nn.TransformerEncoder(layer, num_layers=4)
self.head = nn.Linear(h, C) # 29 classes
def forward(self, windows, subject):
# windows: (n, s, 25), one sentence of n key presses, s = 306 (MEG) or 64 (EEG)
x = self.spatial(windows) # (n, 270, 25)
x = self.subject[subject](x) # (n, 270, 25)
z = self.pool(self.conv(x)) # (n, 2048)
y = self.trans(z.unsqueeze(0)).squeeze(0) # (n, 2048), one sentence only
return self.head(y) # (n, 29) logits
# training: unweighted cross-entropy against the target key, all volunteers together
opt = torch.optim.AdamW(model.parameters(), lr=1e-4, weight_decay=1e-4)
sched = torch.optim.lr_scheduler.OneCycleLR(opt, max_lr=1e-4, pct_start=0.1, total_steps=T)
loss = nn.functional.cross_entropy(model(windows, subj), target_keys)
# inference: beam search over transformer scores plus a 9-gram character LM
def decode(logits, lm, alpha=5.0, beam=30):
logp = logits.log_softmax(-1) # (n, 29)
hyps = [("", 0.0)]
for t in range(logp.shape[0]):
grown = [(s + ch, sc + logp[t, k].item() + alpha * lm.score(s, ch))
for s, sc in hyps for k, ch in enumerate(ALPHABET)]
hyps = sorted(grown, key=lambda h: -h[1])[:beam]
return hyps[0][0]
# scoring: CER = (substitutions + deletions + additions) / len(target)
import Levenshtein
cer = lambda target, out: Levenshtein.distance(target, out) / len(target)Brain2Qwerty is a bridge. On one side stand implants, which decode typing and speech with low error but need surgery. On the other stand scalp devices, which are safe but noisy. This paper shows that with MEG and a sentence-level model, typing can cross a good part of that gap, and it shows exactly where the rest of the gap lies: in the sensors, the supervised protocol and the real-time requirement.
Keep going. The lecture this paper belongs to is Brain Rhythms. For the mathematics of the pieces, see the transformer, convolutional networks, contrastive learning, PCA and ICA for channel alignment, the DFT and the STFT for frequency content, and hidden Markov models for another way to put language statistics on top of noisy symbols.
Open Teach mode to explain the pipeline back on a whiteboard, or go back to the decoder at the top and step through the stages again.
Credit. Brain-to-Text Decoding: A Non-invasive Approach via Typing, by Jarod Lévy, Mingfang (Lucy) Zhang, Svetlana Pinet, Jérémy Rapin, Hubert Banville, Stéphane d’Ascoli and Jean-Rémi King, arXiv 2502.17480. Decoding speech perception from non-invasive brain recordings, by Alexandre Défossez, Charlotte Caucheteux, Jérémy Rapin, Ori Kabeli and Jean-Rémi King, Nature Machine Intelligence, 2023, arXiv 2208.12266. All figures, numbers and examples here come from those papers; the toy devices are marked illustrative.