A brain implant only helps if the cursor answers fast. A public Neuralink description aims for 15 ms from neural stream to device control. Pick a bin width and watch where the milliseconds go.
Follow one burst of spikes from the electrode to a pixel on the screen. Learn what each stage costs in time, why the slowest moments matter more than the average, and what a delay does to the person in the loop.
Press each bin width in turn. Watch the warm cursor chase the teal target. A short bin gives a fresh but noisy cursor. A long bin gives a smooth cursor that arrives late. Then we build, stage by stage, everything between the electrode and the display.
You need a rough idea of a spike (a brief electrical pulse from one neuron) and a little Python. We build the rest from zero.
Built from primary sources: Wairagkar et al., Nature 2025, Ali et al., the BRAND platform, J Neural Eng 2024, Cunningham et al., J Neurophysiol 2011, the Microsoft SendInput and Linux uinput documentation, and a public Neuralink software description (a company statement). A lesson in the series on brain-computer interfaces.
Illustrative toy. The cursor shows the target as it was at the end of the last finished bin, plus a fixed 10 ms for decoding, injection and display. Counting noise falls as 1 over the square root of the bin width (12 px at 10 ms). The target moves at 300 px per second. Error = the square root of (lag squared + noise squared). The finding that bins of 25 to 50 ms beat the older 100 to 300 ms habit is Cunningham et al. 2011.
Chapter 0
Feel what a delayed cursor does to your own hand, then see why a brain interface counts its time in thousandths of a second
Picture a pointer that answers your mouse a third of a second late. You push right. Nothing happens. You push harder. The pointer arrives, sails past the button, and you pull back. It arrives late again. Within seconds you stop steering and start waiting.
That is a bad day with a laggy computer. For a person who controls a computer through an implant, it is the whole product. The person has no hand to fall back on. Every click, every letter, every spoken word passes through a chain of machines, and each machine takes a little time.
This lesson follows that chain from the electrode to the pixel. We will count the time at every stage, learn which delays are steady and which are spiky, and see what the person inside the loop does when the delay grows. First we need three plain words.
Latency is the time between a cause and its visible effect. The cause here is a neuron firing. The effect is a cursor moving on a screen. Latency is measured in milliseconds (ms), thousandths of a second. One ms is tiny, and a BCI still fights for each of them.
A closed loop is a system whose output returns to its input. In a BCI, the cursor moves, the person sees it, and the person changes their brain activity to correct it. The person is part of the control circuit. An open loop has no such return: you record the brain, then analyse it later on a laptop, and nobody watches the result as it happens.
A latency budget is a plan that splits the total allowed delay among the stages. You do it the way you split a monthly salary among rent, food and travel. If one stage overspends, another must cut back. The total is the number that counts.
Neuralink's public software description for its BCI applications work says the job is to "build native applications that convert a live neural stream into digital device control within 15ms". The same page asks for "accessibility, HID, and input-injection layers", and names Python, Rust and Swift in the stack. This is a company statement of a target. It is not a measured result, and it does not say exactly where the clock starts and stops. We use it as a goal to design against.
Two published systems give us measured numbers to compare. In the speech neuroprosthesis of Wairagkar and colleagues (Nature 2025), the paper states that "the entire neural processing, from signal acquisition to synthesis of speech samples, occurred within 10 ms". In the BRAND platform (Ali and colleagues, 2024), a recurrent decoder ran with "less than 8 ms of latency from neural data input to decoder prediction". Both numbers describe the computer's part. They leave out the screen or the loudspeaker, which add their own time.
A screen helps us do some arithmetic of our own. A display that redraws 60 times a second shows a new picture every 1,000 divided by 60, about 16.7 ms. So a new cursor position that just misses a redraw waits up to 16.7 ms more. One display refresh by itself is already larger than the 15 ms target. That tells you the budget is tight, and it tells you the stages cannot be designed one by one in isolation.
Try it on your own hand. The teal ring below moves on a loop. Move your pointer (or finger) to follow it. The warm dot is your cursor, shown after the delay you pick. The delay is added by the page, so you can set it exactly.
Move your pointer or finger over the box to follow the teal ring. The warm dot shows where your pointer was a moment ago. Drag the delay from 0 ms up to 300 ms and try again.
Your own pointer, a real test: nothing here is simulated except the delay. The average distance is measured over your last 4 seconds of movement. A real implant user has the same loop, with decoding and display delays you do not control.
At 0 ms the dot sits on your pointer, and following the ring is easy. As you add delay, the dot trails behind. At a long delay you may catch yourself overshoot, pull back, and overshoot again. Chapter 8 explains the maths behind that wobble. You cannot see where the dot is now, so you steer from stale information.
There is a second effect. A late cursor does not only look bad. It also hides cause and effect. When a mistake shows up long after the command, you cannot tell which command caused it. That makes it hard for the person to learn the interface, and hard for a decoder to learn from the person.
We work along the signal. Chapter 1 sets the clock: samples, packets and data rates. Chapter 2 groups spikes into bins. Chapter 3 builds the budget and the habit of measuring it. Chapter 4 runs a decoder on a stream. Chapter 5 shows why the slow outliers matter. Chapter 6 splits the work across processes and queues. Chapter 7 injects the result into the operating system. Chapter 8 returns to the person. Chapter 9 gathers the numbers and the code.
Chapter 1
Count how much data one millisecond holds, and see why every packet adds a small wait before anything can run
Start at the electrode. A tiny wire in the cortex senses a voltage that wobbles by a few hundredths of a millivolt. Something must read that voltage, over and over, fast enough to catch a spike that lasts about a millisecond. That something is an analog-to-digital converter (ADC), a chip that turns a voltage into a whole number.
One reading is a sample. The sampling rate is how many samples the chip takes each second, in hertz (Hz). The intracortical systems in this lesson sample at 30 kHz, which is 30,000 samples per second. The Wairagkar speech system and the BRAND platform both state 30 kHz. One sample then covers 1 second divided by 30,000, about 33.3 microseconds (a microsecond is a thousandth of a millisecond).
Why 30 kHz? The Wairagkar paper records the voltage filtered to the band 0.3 to 7.5 kHz and sampled at 30 kHz. A spike lives inside that band. A rule from the lesson on the discrete Fourier transform says you need to sample at more than twice the highest frequency you want to keep. Twice 7.5 kHz is 15 kHz, so 30 kHz leaves a safe margin. Chapters on the analog front end and on filtering explain the band in depth.
Software does not read one sample at a time. A function call has overhead, and 30,000 calls per second per channel would waste the computer. Instead the hardware gathers samples into a block and hands over the whole block. That block is a packet.
The BRAND paper streams data in "one-millisecond packets", with 30 samples per channel per packet. So a packet is a small table: one row per channel, 30 columns for time. Its shape is [channels, 30].
Now count the bytes. The Wairagkar system records from four 64-electrode Utah arrays, which is 256 channels. One packet holds 256 times 30, which is 7,680 samples. Suppose each sample is a 16-bit integer, which is 2 bytes. (This is our assumption. The papers do not give the sample width in the text we read.) One packet is then 15,360 bytes, and one second of packets is about 15.4 megabytes. The BRAND team tested 1,024 channels. That is 30,720 samples per packet, about 61,440 bytes, and about 61 megabytes every second.
Try the numbers yourself. Change the channel count and the packet length, and watch both the data rate and the wait.
Blue columns are samples arriving at 30 kHz. When a packet fills, it ships to the decoder. The yellow bar is the wait a typical sample suffers. Pick a packet length, then drag the channel count.
Exact arithmetic at 30 kHz. The 2 bytes per sample is our assumption (16-bit integers). The 256 channels are the Wairagkar system (four 64-electrode Utah arrays). The 1,024 channels and 1 ms packets are the BRAND benchmark. The animation runs slower than real time so you can see it.
At 256 channels and 1 ms packets, the read-out says each packet holds 7,680 samples and the stream runs near 15 MB per second. Raise the packet length to 10 ms and the data per packet grows ten times. The rate in bytes per second does not change. What changes is the wait.
A packet cannot leave until it is full. The first sample in a packet has to sit and wait for the other 29. The last sample leaves at once. A spike arrives at a random moment, so on average it waits for half a packet.
average wait = packet length ÷ 2 (1 ms packet: 0.5 ms; 10 ms packet: 5 ms)
So a 1 ms packet costs half a millisecond on average and at most 1 ms. A 10 ms packet costs five times as much. This looks small, but in a 15 ms budget it matters. It is also a first example of a rule we will meet in every stage: anything that groups data before it sends the data adds waiting time equal to about half the group.
A new packet arrives every millisecond whether or not the computer is ready. The code that handles it must finish before the next packet arrives, or the packets pile up. Engineers call this a deadline. If missing it only makes the picture look worse, it is a soft deadline. If missing it breaks the system, it is a hard deadline.
The BRAND paper makes a design choice because of this. It separates "critical, highly-optimized code like data acquisition" from "slower, experimental code like neural network inference", and runs them as separate processes. We return to that design in Chapter 6. For now, remember the budget for the acquisition code: under one millisecond per packet, every time.
Imagine the cursor stutters every few seconds. The symptom is a freeze of about a tenth of a second, then a jump. The cause could be anywhere. To find it, give each packet a sequence number, a counter that goes up by one per packet. Log the numbers at the decoder. If the log reads 4001, 4002, 4003, 4090, the system lost 86 packets, or held them back and released them in a burst.
That measurement tells you which side to look at. A gap in the numbers means packets were dropped before the decoder. A smooth count with bursty arrival times means they were delayed. The fix for a drop is usually a bigger buffer in the operating system and a dedicated acquisition process. The fix for a delay is the topic of Chapter 5. This sequence-number habit is standard engineering practice. It is our advice, not a result from the papers.
Chapter 2
Count spikes in short windows, and weigh the noise you remove against the delay you add
You stand at a gate and count cars. Ask yourself how busy the road is right now. If you count for one second, the answer is jumpy: two cars, then none, then four. If you count for a full minute, the answer is steady, but it describes the last minute, not this moment.
A decoder faces the same choice with neurons. A spike is a point in time, and a decoder wants a number per time step. So we cut time into equal windows and count the spikes in each. Each window is a bin, and its length is the bin width. The count per bin is a rough measure of how hard that neuron is firing.
In practice the system does not sort every spike to a neuron first. The Wairagkar paper extracts two features per electrode: threshold crossings, the number of times the voltage dips below a set level, and spike-band power, the energy in the spike band. Both come from the 1 ms packets of Chapter 1. With 256 electrodes and two features each, every 10 ms bin yields a vector of 512 numbers. We write its shape as [1, 512]. (The lesson on spike detection shows how a threshold crossing is found.)
The paper also normalises each feature with a rolling mean and standard deviation over the past 10 seconds. The word rolling matters. A real-time system cannot use the whole session's average, because the session has not finished. It may only use the past. We will call that rule causality in Chapter 4.
The BRAND paper's cursor decoder works the same way. It reads 192 channels of threshold crossings in 10 ms bins and passes them to a 76-unit LSTM (a recurrent network cell) followed by a two-unit linear layer. The two outputs are the cursor command, one number for each screen axis. Input shape per step: [1, 192]. Output: [1, 2].
Spikes arrive at random times. A neuron that fires 20 times a second on average does not fire every 50 ms like a clock. The count in a window varies, even when the neuron's true rate is steady. For random events of this kind (a Poisson process), the typical size of the variation equals the square root of the expected count.
Work it through for a neuron at 20 spikes per second. This rate is illustrative. In a 10 ms bin you expect 20 times 0.01, which is 0.2 spikes. The typical variation is the square root of 0.2, about 0.45 spikes. That is 2.2 times the expected count, so the signal drowns. In a 50 ms bin you expect 1.0 spike, and the variation is 1.0, which is 100% of the signal. In a 100 ms bin you expect 2, and the variation is 1.41, about 71%. In a 200 ms bin you expect 4, and the variation is 2, about 50%.
relative noise = 1 ÷ √(rate × bin width) (20 per s: 10 ms 224%, 50 ms 100%, 100 ms 71%, 200 ms 50%)
A single neuron in a short bin is almost useless. A population rescues it. If 100 neurons fire independently at the same rate, adding their counts cuts the relative noise by the square root of 100, which is 10. A 10 ms bin then has about 22% noise. This is why the number of electrodes matters so much to real-time decoding, and why the lesson on linear decoders asks for many channels.
Bins also cost time. Chapter 1 gave the rule: anything that groups data adds a wait of about half the group. A decoder can only use a bin when the bin is complete, so a bin of width B adds an average wait of B divided by 2. A neuron that changes its rate at a random moment is seen on average B/2 late, and at worst B late.
Now the two costs pull in opposite directions. A short bin has low delay and high noise. A long bin has low noise and high delay. The best choice sits in between. The device below lets you see both costs on one set of spikes.
Top: 20 simulated neurons, one row each, a tick per spike. Middle: the true population rate (teal) and the estimate a causal decoder would hold (warm). Bottom: error against bin width. Drag the bin width.
Toy data, made fresh from a fixed seed so every visit matches: 20 independent neurons, mean rate 20 spikes per second, rate swinging up and down by 60% once every 0.8 s. The estimate at each moment is the last finished bin's count divided by the bin width and the neuron count. The error is the root-mean-square gap to the true rate, measured live on these spikes.
At 5 ms and 10 ms, the warm estimate chatters: most bins hold one spike or none, so the line leaps. At 100 ms and 200 ms, the line is smooth, but it trails the teal curve and flattens the peaks. Somewhere in the middle the gap is smallest. The read-out tells you where the minimum falls for these particular spikes.
For years, groups chose long bins. Cunningham and colleagues (J Neurophysiol 2011) report that "previous literature and our offline analyses agree that neural activity should be analyzed in bins of 100- to 300-ms width". Then they tested in a closed loop. Their online prosthesis simulator, where a healthy human steers a cursor driven by synthetic neural activity, "suggests that much shorter bin widths (25-50 ms) yield higher decode performance". They confirmed the result in a rhesus monkey with a closed-loop prosthesis.
The lesson is bigger than the number. An offline test replays old recordings and scores the guess against the true movement. It treats noise and delay as costs the decoder must pay. An online test puts the person in the loop. A person can correct some noise by steering. Our reading, not a claim from the paper: noise that varies fast is easy to steer around, while delay changes the loop itself. Only a closed-loop test shows which cost the person tolerates better.
A stateful decoder softens the trade. The Kalman decoder keeps a running guess of the cursor state and blends each noisy bin into it, so it needs less smoothing from the bin itself. The next chapters show how a recurrent network does the same.
When bins are too short, the cursor shakes like a nervous hand, even when the person holds still. To measure it, record the cursor speed while the person rests, and compute its standard deviation. A high value means noise. The fixes are a slightly longer bin, a decoder with state, or more channels. When bins are too long, the cursor looks smooth but the person overshoots targets. That symptom is delay, and it needs the opposite fix.
Chapter 3
Add up seven stages from electrode to display, and find out which one eats the fifteen milliseconds
A neuron fires. A moment later a pixel moves. In between lies a relay race with seven runners, and each one hands the baton to the next. The total time is the sum of every leg, including the legs where the baton sits and waits. Our job in this chapter is to write the race down, give each runner a time, and check the total against the 15 ms target.
Look at stage 7. Of all seven stages, the display is the largest on average at 60 Hz. The neural and software parts together sum to a few milliseconds. This is a useful surprise: the fastest decoder in the world cannot make a 60 Hz screen answer in 5 ms.
Take 5 ms bins, a 60 Hz display and the stage times above. Add the averages: 0.5 (acquire), plus 0.2 (features), plus 2.5 (half a bin), plus 1.2 (decode), plus 0.6 (transport), plus 0.3 (inject), plus 8.3 (half a frame). The sum is 13.6 ms. That fits inside 15 ms, but only just.
Now the worst case. Use the full wait at each stage that waits: 1.0 for the packet, 0.2, 5.0 for the bin, 1.2, 0.6, 0.3, and 16.7 for the frame. The sum is 25.0 ms. The worst case is almost double the average, and the display supplies about three quarters of the gap.
Now change one thing. Use 10 ms bins, as in the Wairagkar system. The average grows by 2.5 ms, from 13.6 to 16.1 ms, over the target. Or keep 5 ms bins and buy a 120 Hz display. The frame lasts 8.3 ms, the average display wait falls to 4.2 ms, and the average total falls to 9.5 ms. The budget is a set of trades, and the best trade is rarely in the stage you first look at.
Play with the stages below. The bar shows the average path. The thin tick shows the worst case.
Each coloured block is one stage on the average path. The dashed line is 15 ms. The thin tick is the worst case. Change the bin width, the decode time and the display, and watch which block grows.
Illustrative sums. Sourced: 1 ms packets, 30 kHz (BRAND), RNN node latency under 1.2 ms and inter-process latency under 0.6 ms (BRAND), 15 ms target (a public Neuralink description, a company statement). Assumed by us: 0.2 ms feature extraction and 0.3 ms injection. Display wait is half a frame on average and a full frame at worst, by arithmetic.
With the default setting, the read-out should show an average near 13.6 ms and a worst case near 25 ms. Raise the decode time to 10 ms and the decoder alone breaks the budget. Move to 240 Hz and the display almost vanishes. In every setting, the sum of the averages hides the tail. That is the subject of Chapter 5.
The Neuralink description says "within 15ms". Within means a ceiling. A ceiling that holds only on average is a weak promise, because half of the frames would be worse. A careful team asks: is 15 ms the average, the 99th percentile, or the strict worst case? The answer changes every design choice. We cannot tell which one the company means, so we treat the question as open and plan for the tail.
You cannot manage a number you cannot read. The BRAND team measured stage latencies with "timestamps from the system clock", read through Python's monotonic clock functions, and each node wrote its timestamp to the shared database with its output. A monotonic clock only ever counts forward. It ignores the changes that the network time service makes to the wall clock. That makes it safe for subtracting two times on the same computer.
pythonimport time # stamp the packet when it arrives, carry the stamp with the data packet = {"ch": samples, "t_in": time.monotonic_ns()} cmd = decode(bin_features) # ~1 ms cmd["t_done"] = time.monotonic_ns() latency_ms = (cmd["t_done"] - packet["t_in"]) / 1e6
The stamp must travel with the data. A separate log that you line up by hand later will drift. Two limits apply. First, clocks on different computers disagree, so a stamp from one machine cannot be subtracted from another's unless you synchronise them. The BRAND paper does not describe cross-machine synchronisation. Second, a software stamp cannot see the screen. The BRAND authors note that the older systems they compare with include hardware and display latency in their 13 to 20 ms figures, while theirs do not. When you read a latency number, always ask where the clock starts and where it stops.
A common way to include the screen is a light sensor on the display and a test pattern that flips on command. The time from command to light is the true end-to-end delay. This is standard practice, not a result from the papers we cite.
Chapter 4
Run a decoder once per bin, using only the past, and keep each step inside its deadline
A person who has lost the ability to speak tries to say a sentence. A system listens to the motor cortex and plays a voice. Every 10 milliseconds it must say a little more of the sound. It cannot wait for the end of the sentence, because the sentence has not ended. It cannot peek at what the person will try a moment later, because that moment has not happened.
This is streaming inference: a model that makes one prediction per new bin, in order, as the data arrives. Compare it with the usual way a researcher runs a model, called offline or batch inference. There, the whole recording sits in memory, and the model can look at any bin, past or future, when it scores bin number 500.
A decoder is causal when its output at time t depends only on inputs from time t and earlier. The Wairagkar paper says its system "causally decode[s] neural activity". A single acausal habit can break this rule without anyone noticing. A centred smoothing filter averages bins on both sides of a time. A normaliser that uses the whole session's mean looks at the future. A bidirectional recurrent layer reads the sequence backward. All three work well offline and cannot run live.
Looking ahead also has a direct price. If a decoder needs L future bins, it must wait L times the bin width before it can answer. With 10 ms bins, two bins of look-ahead cost 20 ms. That already exceeds our 15 ms target by itself. So a real-time decoder buys its accuracy from the past, never from the future.
Way one: the sliding window. Keep the most recent W bins in a buffer. Each step, push the newest bin in, drop the oldest, and run the whole model on the window. The Wairagkar decoder works like this. Its input is a 600 ms window: 60 bins of 10 ms, each with 512 features, so the tensor is [60, 512]. Two dense layers (512 and 128 units) embed each bin. Eight Transformer encoder blocks with 4 attention heads follow, and the output is 20 speech features per step: 18 Bark cepstral coefficients (a compact way to describe a spectrum), a pitch period and a pitch strength. A pretrained vocoder called LPCNet turns them into sound at 16 kHz. (For attention, see the lesson on the transformer.)
Way two: the recurrent state. Keep a small memory vector instead of a window. Each step, mix the new bin into the memory and read off the answer. The BRAND cursor decoder works like this: a 76-unit LSTM, then a linear layer that outputs two numbers. Its input is [1, 192], its memory is a pair of 76-number vectors (an LSTM keeps two), and its cost does not depend on how far back it remembers.
Count the work per step. In the sliding window, attention compares every bin in the window with every other. For W bins that is W times W comparisons per head per layer. Double the window and the work grows four times. At 60 bins it is 3,600 comparisons at most. The window also repeats the same bins at every step: 59 of the 60 bins are the same as last time, but the model recomputes them, because attention inside the window is not causal in time and the older bins' outputs change when a new bin joins.
In the recurrent way, each step touches only the new bin and the memory. The work is the same at every step, and it does not grow with the history. The price is that the memory has to hold everything useful in 152 numbers. And training must match the way you run, so that the network learns to use a memory that starts empty and runs for minutes.
Real hardware sets the deadline. A new bin arrives every 10 ms, so each step must finish in under 10 ms, and not on average, but every time. Wairagkar's system ran its decoder on an NVIDIA RTX A6000 graphics card inside the 10 ms limit. The BRAND paper reports that its LFADS model ran with inference times "consistently below 6 ms" and the NDT transformer "below 2 ms". With LFADS in the loop the maximum end-to-end latency rose to 16 ms, still close to the cursor's budget. Compare the three costs in the device.
Bins arrive from the left, one per 10 ms. Choose how the decoder remembers. The bar at the bottom shows its work for one step against what the toy machine can do in one bin. Drag the window length.
Illustrative toy machine that can do 4,000 comparisons per 10 ms bin. The window decoder costs W × W comparisons per step (one head, one layer); the recurrent decoder costs a fixed 200. The 60-bin window, 10 ms bins and 76-unit LSTM are from the Wairagkar and BRAND papers.
At 60 bins the window decoder uses 3,600 of the toy machine's 4,000 comparisons, 90% of the step. At 70 bins it needs 4,900 and misses the deadline. The recurrent decoder stays flat at 200 whatever you do. A real system makes the same trade with bigger numbers: eight blocks, wider heads, and a faster chip.
pythonfrom collections import deque import torch W = 60 # 60 bins x 10 ms = 600 ms window win = deque([torch.zeros(512)] * W, maxlen=W) # oldest bin falls off the left def step(bin_feats): # bin_feats: [512], one finished 10 ms bin win.append(bin_feats) x = torch.stack(list(win))[None] # [1, 60, 512] with torch.no_grad(): feats = model(x)[:, -1] # [1, 20]: only the newest step is used return feats # to the vocoder # recurrent version: carry (h, c) instead of a window h = c = torch.zeros(1, 1, 76) def step_rnn(bin_feats, h, c): # bin_feats: [1, 1, 192] y, (h, c) = lstm(bin_feats, (h, c)) return head(y), h, c # head -> [1, 1, 2]
This is our sketch, not code from the papers. Notice what the window version has to do: it recomputes all 60 bins at every step and keeps one output. The Wairagkar model pools the whole window into a single 20-number output, so our sketch, which keeps the newest row, is a simplification. The repeated work is the price of attention inside a fixed window.
The classic failure is a decoder that scores well offline and behaves badly online. The symptom: the cursor lags or drifts, although the test accuracy was high. To find the cause, run a replay test. Take a saved recording, push it through the live code one bin at a time, and compare the output with the offline model's output on the same data. They should match to rounding error. Any gap shows an acausal step, such as a centred filter, a whole-session normaliser or a wrongly initialised memory. The fix is to make that step causal, then keep the replay test in your automated checks so the gap cannot return.
Chapter 5
Measure the slow outliers instead of the average, and see why one late step in a hundred means a stutter every second
A bus line averages ten minutes between stops. You check the timetable and plan your morning. Then the bus takes forty minutes, and you miss your meeting. The average was true. It was also useless to you, because you live through the bad trips one at a time.
A real-time decoder is that bus. Chapter 3 summed the average stage times and found a total near 14 ms. But the cursor does not show averages. It shows each step as it comes, and the person sees the slow ones. Jitter is the name for this variation.
Jitter is the variation of latency from one step to the next. If every step takes exactly 1.2 ms, the jitter is zero. If most take 1.2 ms and a few take 9 ms, the jitter is large, even though the average barely moves.
A percentile describes the spread. Sort all the step times from fastest to slowest. The median, also called p50, is the time that half the steps beat. The p99 is the time that 99 of every 100 steps beat. It describes the slowest 1% of steps. The tail is that slow end of the sorted list. A deadline miss is a step that takes longer than the time before the next bin arrives.
Take a decoder with 10 ms bins. It runs 100 steps every second. Suppose its p99 is exactly 10 ms. By definition 1 step in 100 is slower than 10 ms. That is one late step every second. Suppose the miss rate is 0.1%, the p99.9. Now a miss comes once every 10 seconds. Over a one-hour session, that is 360 misses.
late steps per second = steps per second × miss rate (100 × 0.01 = 1 per second; 100 × 0.001 = 0.1 per second)
What does the person feel? When a step misses its deadline, the cursor freezes for that bin. Then the late bin and the next bin may arrive close together, and the cursor leaps. People describe this as a stutter. A stutter during a fine move, such as clicking a small button or finishing a word, can undo the whole move. So the tail sets the quality of the experience, much more than the average does.
The decoder's own arithmetic takes the same time every step. The slowness comes from everything else on the computer. Here are the usual causes, from the cheapest to fix to the hardest:
The last one is not a theory. The Wairagkar paper reports that the largest latency in its system came from the audio playback driver, and that later sessions "substantially lowered" it with software changes.
The BRAND platform is built around this problem. It runs each stage as its own Linux process. It lets the user "configure the process priority and processor affinity for each node". Priority tells the scheduler that this process wins a tie. Affinity pins the process to chosen cores. The team ran the cursor benchmarks on "the Linux kernel with a PREEMPT_RT patch", a real-time version of the kernel, which lets high-priority work interrupt almost anything else. The paper describes "optimizations to achieve low-jitter real-time performance". It also tells us what it does not show: the jitter is reported "through histograms and violin plots with medians", and the text gives no numeric percentiles. One benchmark, the speech simulator, ran on a standard kernel without the patch.
Play with a toy version of the same problem. The device runs 2,000 decoder steps with a fixed 10 ms deadline and shows how long each one took.
Top: the last 100 steps as bars. Bars above the dashed 10 ms deadline turn red. Bottom: a histogram of all 2,000 steps. Choose how busy the computer is, and switch the clean-up pauses on.
Pure simulation, not a measurement. Each step costs 1.2 ms of work (the BRAND RNN node latency bound), times a random wobble. A pinned core wobbles by about 10%, a normal machine by about 35% with a 1% chance of a 3 to 8 ms preemption, a busy one by about 50% with a 4% chance of 4 to 15 ms. Clean-up pauses add a 0.5% chance of 8 to 20 ms. Every setting uses a fixed seed. These are our illustrative values.
On the pinned core the median and the p99 sit close together, and no step misses. On the busy machine the median barely moves, but the p99 jumps past the deadline, and the strip of bars shows red spikes. The average has hidden them. Now switch on the clean-up pauses and watch the p99.9 grow a long right-hand tail.
Symptom: the cursor stutters now and then, and the average latency looks fine. Measurement: log the time of every step, then plot the histogram and read p50, p99, p99.9 and the maximum. Look at the slowest steps in time order. If they come every few seconds like a clock, a periodic task is stealing the core. If they cluster after you switch a window, the cause is graphics or power management. Fix: pin the hot process to its own core, give it a high priority, use a real-time kernel if you can, allocate all memory before the loop starts, keep logging out of the loop, and measure again.
Even after all that, some steps will be late. The system must decide what to do with them. That decision belongs to the design of the queues, and it is the subject of the next chapter.
Chapter 6
Split the system into stages that run on their own, and choose what each queue does when the next stage falls behind
Imagine a kitchen with two cooks. The first cook prepares a plate every 10 seconds. The second cook adds the sauce, and usually needs 1 second. One day the second cook is called away for a minute. Plates pile up on the pass. When the cook returns, there are six plates waiting. If the cook works through them in order, the customer at the table gets a plate that is a minute old, and the next one, and the next, until the pile is gone.
A BCI has the same kitchen. The acquisition stage makes a new bin every 10 ms. The decoder sometimes stalls (Chapter 5). The question is what happens to the bins that arrive while it stalls.
A process is a running program with its own memory. Two processes cannot trample each other's data, and the operating system schedules them separately. The BRAND platform runs every stage as its own Linux process, called a node. Several nodes joined together make a graph, and the paper says graphs are "configured using Yet Another Markup Language (YAML)". A supervisor starts each node as a separate process.
The reason, in the authors' words, is to "decouple critical, highly-optimized code like data acquisition from slower, experimental code like neural network inference". A crash in a new, untested decoder then cannot stop the recording. Each process can also get its own priority and its own processor cores (Chapter 5).
The nodes pass data through streams in a Redis database. Redis is an in-memory store with low-latency messaging. The BRAND paper calls a stream an "append-only log" that persists "even when data have already been read". So the record is free: every message the decoder sees is also saved for later study. The paper reports inter-process latency under 600 microseconds for 1,024 channels of 30 kHz data sent in 1 ms chunks.
That gives us a useful split. The hot path is the chain from acquisition to decoder to injection. It must meet the deadline every step. The cold path holds everything else: saving to disk, drawing plots, training the next model. A cold-path stall must never reach the hot path.
A queue is a waiting line between a producer and a consumer. It absorbs short bursts. But if the consumer is slower than the producer for long enough, the line grows. So we must choose a policy for what to do with the line.
Policy one: keep everything. Process the bins in order, and never drop any. This is right for a log, because you want every bin. It is wrong for a cursor, because the old bins are no longer news. The cursor would replay the past.
Policy two: newest only. When the decoder is ready, it takes the most recent bin and discards the older ones. The cursor jumps to the present, and the delay stops growing. A bin that is skipped is lost for control. A recurrent decoder needs care here: if it skips bins, its memory misses those steps. A practical fix is to run the cheap state update on every bin and skip only the expensive parts.
Suppose bins arrive every a = 10 ms, and the decoder needs s milliseconds per bin. The fraction of time it is busy is s divided by a. Call it the utilisation. Say the decoder stalls for 50 ms, so 5 bins queue up. Once it recovers, it clears the backlog while new bins keep arriving. The time T to clear the backlog n is:
T = n × s ÷ (1 − s ÷ a)
Work two cases with n = 5 and a = 10 ms. A fast decoder with s = 1.2 ms has utilisation 0.12, so T = 5 × 1.2 ÷ 0.88 = 6.8 ms. The pile is gone almost at once. A slow decoder with s = 9 ms has utilisation 0.9, so T = 5 × 9 ÷ 0.1 = 450 ms. The same 50 ms stall now costs almost half a second of lag, and the cursor shows old data throughout.
The lesson: a decoder that "keeps up on average" at 90% load is a fragile design. Each hiccup becomes a long delay. Headroom is what turns a stall into a blip. The device below lets you see both effects.
A new bin arrives every 10 ms. The line shows how old the data is when the decoder uses it. Press Stall 100 ms and watch the line. Then change the policy and the decode time, and press again.
Toy simulation in 1 ms ticks: one bin every 10 ms, a decoder that takes the decode time you choose per bin, and a stall that freezes it for 100 ms. Age = the time from a bin's arrival to the moment its output is ready. The 15 ms line is the public Neuralink target; this simulation covers only the queue stage.
With 1.5 ms decoding and every bin kept, a 100 ms stall leaves 10 bins waiting. The decoder clears them in about 18 ms, and the age line spikes then falls back. Now raise the decode time to 9 ms. The spike lasts about a second. Switch to "Newest bin only" and the spike lasts one step, whatever the decode time.
Symptom: the cursor keeps drifting for a second after the person stops, or the lag seems to grow during a session. Measurement: at the consumer, compute the age of every bin it takes, using the timestamp stamped at arrival (Chapter 3), and plot age against time. A steady slope up means the consumer is slower than the producer. A spike followed by a slow decay means a stall with too little headroom. Fix: bound the queue to one or two items, drop the oldest, keep the full record on the cold path, and give the decoder enough headroom that its utilisation stays below about half. The "about half" is our rule of thumb, not a figure from the papers.
Chapter 7
Turn two decoder numbers into pointer events the operating system accepts, without losing the slow movements
The decoder has finished. Its answer is two numbers: move right a little, move up a little. Your laptop knows nothing about this. It was built to hear from a mouse, a keyboard or a touchscreen, and it trusts them because each one speaks a standard language. The decoder is not on the list. We must teach the computer to accept it.
There are three common doors into the operating system. A BCI team may use all three.
The first door is the human interface device (HID) standard. This is the rulebook that USB and Bluetooth mice, keyboards and game pads follow to describe their events. A BCI box can pretend to be an HID mouse. The computer then treats it like any other mouse, with no special software. The cost is hardware and a fixed vocabulary.
The second door is the accessibility layer. Operating systems offer programs for people with disabilities, such as screen readers and switch controls. These programs can read the screen's structure and activate buttons. A BCI application can use the same layer to say "press this button" by meaning rather than by position.
The third door is input injection: a program creates keyboard or mouse events in software and inserts them into the system's input stream. The rest of this chapter focuses on this door, because it gives the most control. The Neuralink description lists all three together: "accessibility, HID, and input-injection layers".
On Windows, the function is SendInput. Microsoft's documentation says it "synthesizes keystrokes, mouse motions, and button clicks". You pass an array of INPUT structures, and each one is "an event to be inserted into the keyboard or mouse input stream". The events are inserted serially and are not interspersed with real user input. The function returns how many events it managed to insert. There is a catch the documentation spells out: it is subject to UIPI (user interface privilege isolation), so an application may inject input only into applications "at an equal or lesser integrity level", and when UIPI blocks it, "neither GetLastError nor the return value will indicate the failure was caused by UIPI blocking".
On Linux, the kernel offers uinput, "a kernel module that makes it possible to emulate input devices from userspace". The steps are short. Open /dev/uinput. Declare what the device can do, for instance relative motion on two axes (EV_REL with REL_X and REL_Y). Fill in a setup structure and call UI_DEV_SETUP. Call UI_DEV_CREATE, and the kernel makes the device. Then write events: each has a type, a code and a value. A SYN_REPORT event closes each batch so the system processes it. The kernel's own mouse example moves the pointer by 5 units on each axis, 50 times, with a 15 ms pause between steps.
python# Linux sketch with the python-evdev library (a third-party wrapper over uinput) from evdev import UInput, ecodes as e caps = {e.EV_REL: [e.REL_X, e.REL_Y], e.EV_KEY: [e.BTN_LEFT]} ui = UInput(caps, name="bci-pointer") # creates /dev/input/eventN def emit(dx: int, dy: int): ui.write(e.EV_REL, e.REL_X, dx) ui.write(e.EV_REL, e.REL_Y, dy) ui.syn() # SYN_REPORT: the batch is complete
Other systems (macOS, iOS, Android) have their own layers. We did not open their documentation for this lesson, so check each platform's rules. The shape stays the same: a way to create events, a permission rule, and a vocabulary of event types.
A pointer event carries whole numbers. A mouse moved "3 units" cannot move 2.6. The decoder, on the other hand, outputs smooth values. Suppose it says the cursor should move at 40 pixels per second, a slow, careful glide. With 10 ms bins, that is 0.4 pixels per step.
If the injector rounds each step to the nearest whole pixel, 0.4 becomes 0, every step, forever. The cursor does not move at all. Now try 60 pixels per second: 0.6 rounds up to 1 pixel per step, which is 100 pixels per second. A small change in the request turns a motionless cursor into one that runs 67% too fast. Slow, fine motion, which is exactly what a person needs to land on a small target, is the part that breaks.
The fix is a remainder accumulator. Keep the fractional part you could not send, and add it to the next step. The steps for 0.4 pixels per step: add 0.4 (total 0.4, send 0), add 0.4 (0.8, send 0), add 0.4 (1.2, send 1, keep 0.2), add 0.4 (0.6, send 0), add 0.4 (1.0, send 1, keep 0.0). Five steps sent 2 pixels, which is 0.4 per step. Nothing is lost.
The decoder asks for a steady speed. Each tick is one 10 ms step, and each bar is the whole pixels the injector sends. The dashed line is the distance the decoder wanted. Drag the speed, then switch the method.
Exact arithmetic with 10 ms steps (100 per second), speeds as pixels per second. Rounding is to the nearest whole pixel, halves rounding up. The method of carrying a remainder is the standard fix; no paper in this lesson specifies the injector’s arithmetic.
At 40 pixels per second the first method sends nothing, and the read-out says it travelled 0 pixels in one second against 40 wanted. Carrying the remainder delivers 40. At 60 pixels per second, rounding delivers 100. The error is worst just above each half-pixel boundary, and the cursor cannot move slowly, which is what fine control needs.
Between the decoder and the injector sit a few more simple steps. A gain converts decoder units into pixels per second. A clip keeps the cursor on the screen. A dead zone treats tiny velocities as zero, so noise does not make the cursor creep. A click may come from a decoded click state, or from a dwell rule: keep the cursor on a target for a set time and the system clicks. The operating system may also apply its own pointer acceleration to relative motion. Check this on your platform, because it can change the feel in ways your tests do not show.
The injector adds little delay. The Chapter 3 budget gave it a third of a millisecond. The risk is not speed but silence. Symptom: the cursor works on the desktop and stops over one particular window. Measurement: compare the number of events you sent with the number the call reports as inserted, and test in a window that runs with more privilege. On Windows, a call blocked by UIPI gives no error code. Fix: run the application at the right privilege level and follow the platform's accessibility rules.
Chapter 8
Model the person as a controller, derive the delay they can tolerate, and see why every millisecond lowers the speed they can safely ask for
You step into a shower in an old house. The hot tap is far from the shower head. You turn it up. Nothing changes, so you turn it more. Then the water arrives scalding, and you turn it back too far, and ten seconds later it is freezing. The tap works. The pipe is long. You are steering with old news.
The person at a BCI cursor is in the same position. They see the cursor, judge the gap to the target, and push their neural activity to close it. If the cursor shows the result late, the push works on stale information. Chapter 0 let you feel this. Now we get a number.
Real people are complicated. We start with the simplest model that still shows the effect. Call the gap between the cursor and the target the error. The person pushes the cursor to shrink it: the stronger the error they see, the stronger the push. The strength of the response is the gain, k, in units of 1 per second. A gain of 10 per second means that, if the error stays unchanged, the cursor closes 10 times the error every second.
Now add the delay. Call it τ (tau). The person sees the error as it was τ seconds ago. So at each moment, the change in error is minus k times the error from τ ago:
With no delay (τ = 0), the error shrinks smoothly toward zero and never overshoots. With delay, something else happens. The push keeps arriving after the error has already gone. That is overshoot.
Look for the edge, where the error neither grows nor decays but swings forever at a steady rate. Write the swing as a wave with angular frequency ω. Put it in the equation and match the two parts. The cosine part says ωτ = π/2. The sine part says ω = k. Put the two together and you get the edge:
k × τ = π ÷ 2 ≈ 1.57 (below: the error dies out; above: it grows)
That edge is a clean rule. Take a person who pushes with gain k = 10 per second, so they close the gap in about a tenth of a second. The largest delay they can tolerate is 1.57 divided by 10, which is 157 ms. If they try a faster gain of 20, the limit drops to 78 ms. Flip it round. For a given loop delay τ, the largest stable gain is:
kmax = π ÷ (2τ)
Plug in the numbers from Chapter 3. An average pipeline of 13.6 ms allows a gain up to 1.57 ÷ 0.0136, about 115 per second. The worst case of 25 ms allows only 63 per second. A sloppy 45 ms pipeline allows 35. A 150 ms pipeline allows about 10. So delay is not only a nuisance. It caps how fast the person may steer, and a person who steers close to the cap sees oscillation when the tail latency hits.
This is the heart of the trade. People can choose a lower gain, and then they are stable but slow. Or they can push hard and risk the wobble. With a longer delay they must choose slow. That is a plausible reason why measured performance falls as feedback gets later, and why the online tests of Cunningham and colleagues behave differently from offline ones (Chapter 2).
Top: the target jumps every two seconds and the cursor chases it. Bottom: the map of gain against delay. The curve is k × τ = π/2, and the dot is your setting. Drag the delay up and the gain up.
A textbook toy, not a model of a real person: the cursor error follows de/dt = −k · e(t − τ), simulated in 1 ms steps. Real people also have their own reaction delay, can predict, and adapt their gain. The edge k × τ = π/2 is derived above and holds exactly for this equation.
At 100 ms and a gain of 10 the product is 1.0, below 1.57. The cursor overshoots by about half the size of the jump (51% in the simulation) and then settles. Raise the gain to 20 and the product is 2.0, over the edge. The cursor swings wider on every cycle, and the chip turns red. Now drop the delay to 20 ms and push the gain to 30. The product is 0.6, so it is calm again.
Count every source of delay inside the loop: the bin wait, the compute, the transport, the display. They all add up to τ. A decoder that smooths heavily also adds delay, because smoothing is a lag. So the engineer gains stability from every millisecond saved. A good measure of a BCI, such as bits per second, reflects this indirectly. And the person is not fixed: they learn the interface and shift their strategy, which is the subject of closing the loop with ReFIT.
One more idea helps. If you know the delay, you can predict. The decoder can estimate the cursor state τ seconds into the future and draw that, which cancels part of the lag. This is how a state-space decoder such as the Kalman decoder can help, because it keeps a model of the motion. It is a standard control idea, and it is our suggestion here, not a result from the papers.
Symptom: the cursor hunts around a target, swinging past it again and again. Measurement: count how often the cursor crosses the target during one approach; more than two crossings suggests the loop is near its edge. Compare that count at different measured latencies. Fix: cut the delay, lower the gain of the velocity mapping near targets, or add prediction.
Chapter 9
Review the whole chain from electrode to cursor, with the numbers, a checklist, the core code and the sources
You can now follow one burst of spikes to a pixel and name the time it spends at each stop. This page gathers what you need to rebuild the picture from memory.
A closed-loop BCI is a relay of stages: an ADC samples at 30 kHz, hardware groups samples into 1 ms packets, software turns packets into bins of 10 ms or so, a causal decoder runs one step per bin, a queue passes the result on, and an injector hands whole-pixel events to the operating system, which shows them at its next display refresh. The total delay is a sum of working time and waiting time, and the waiting parts (packets, bins, frames) are often larger than the working parts. The tail of the delay distribution matters more than its average, because the person feels each late step. Every millisecond of loop delay also lowers the fastest stable gain, kmax = π ÷ (2τ), of the person steering.
| What | Number | Source and why it matters |
|---|---|---|
| Sampling rate | 30 kHz, 33.3 µs per sample | Wairagkar 2025 and BRAND 2024. Sets the raw data rate. |
| Packet | 1 ms, 30 samples per channel | BRAND. A packet adds half its length on average. |
| Electrodes | 256 (four 64-electrode Utah arrays) | Wairagkar. Two features each give 512 per bin. |
| Bin and window | 10 ms bins; 600 ms window of 60 bins | Wairagkar. A Transformer decoder with 8 blocks and 4 heads. |
| Speech chain | within 10 ms, signal to speech samples | Wairagkar. The audio playback driver was the largest delay. |
| Cursor decoder | 76-unit LSTM, 192 channels, under 8 ms end to end | BRAND. Per-node latency under 1.2 ms. |
| Large models in the loop | LFADS under 6 ms; NDT under 2 ms; max 16 ms with LFADS | BRAND. Big models can still fit. |
| Inter-process latency | under 600 µs for 1,024 channels at 30 kHz | BRAND. Redis streams between Linux processes. |
| Older systems | 13 to 20 ms, including hardware and display | As compared in BRAND. Ask where the clock starts and stops. |
| Bin width, offline vs online | 100 to 300 ms offline; 25 to 50 ms online | Cunningham 2011. Closed-loop tests change the answer. |
| The target | 15 ms, neural stream to device control | A public Neuralink description. A company target, not a result. |
| Display at 60 Hz | 16.7 ms per frame; 8.3 ms average wait | Arithmetic. The largest average stage in Chapter 3. |
| Late steps | 1% miss at 100 steps per second = 1 per second | Arithmetic. Why the tail sets the feel. |
| Queue recovery | T = n × s ÷ (1 − s/a) | Derived. 9 ms decode: 450 ms; 1.2 ms decode: 6.8 ms. |
| Stability edge | k × τ = π/2 | Derived for a delayed-feedback toy. 25 ms allows k up to 63 per second. |
This is a sketch of the hot path. It joins the ideas of Chapters 3 to 7. The names newest, model and inject stand for your own pieces.
pythonimport time DEADLINE_MS = 10.0 # one bin (Ch 5) GAIN, acc = 1.0, [0, 0] # integer accumulators, units of 1/100 px (Ch 7) state = model.init_state() # recurrent memory, starts empty (Ch 4) while True: b = newest() # blocks; drops older bins (Ch 6) t0 = time.monotonic_ns() age_ms = (t0 - b.t_in) / 1e6 # how stale is this bin? (Ch 3, 6) vx, vy, state = model.step(b.feats, state) # [192] -> [2], causal (Ch 4) for i, v in enumerate((vx, vy)): # v in px/s; 10 ms step = v/100 px acc[i] += round(v * GAIN) # keep the fraction (Ch 7) dx, dy = (int(a / 100) for a in acc) # whole pixels to send acc[0] -= dx * 100; acc[1] -= dy * 100 if dx or dy: inject(dx, dy) # SendInput / uinput (Ch 7) step_ms = (time.monotonic_ns() - t0) / 1e6 log.append((age_ms, step_ms)) # cold path reads p50, p99, p99.9 (Ch 5) if step_ms > DEADLINE_MS: misses += 1
The BRAND authors compare their platform with earlier Simulink-based rigs that report 13 to 20 ms, hardware included. Speech neuroprostheses push the same ideas further: the Wairagkar system decodes every 10 ms and drives a voice, and its largest delay was the audio playback driver, not the decoder. A product for daily use must also reach phones, game consoles and wheelchairs, which means many operating systems and many input layers. The engineering stays the same: count the stages, measure the tail, and never let old data reach the person.
Now press Present or Teach and explain the chain from electrode to pixel out loud, from memory: the stages, the budget, why the tail matters, and what delay does to the person. Then go back to the chase and choose a bin width again.