Skip to main content
v2026.11,986 entries · CC-BY 4.0

Kilosort: Principles, Architecture, and Practical Guide

A comprehensive laboratory guide to Kilosort, detailing GPU-accelerated template matching, motion drift registration, and spike sorting quality curation.

Written and maintained by CASRAI Editorial Board

Published

On this page

Kilosort is an open-source, GPU-accelerated spike sorting software package designed to identify, isolate, and track individual action potentials from multi-channel extracellular electrophysiology recordings in neuroscience research. Engineered specifically to meet the high data throughput of modern silicon probes, such as Neuropixels and multi-shank microelectrode arrays, Kilosort employs biophysical template matching and automated drift correction to resolve overlapping neural waveforms that traditional thresholding algorithms fail to distinguish.

Definition and Scope of Kilosort

Developed by Marius Pachitariu, Carsen Stringer, and colleagues across Janelia Research Campus and University College London, Kilosort represents the standard computational pipeline for large-scale extracellular spike sorting. Electrophysiology has expanded rapidly from recording single microwires or tetrodes to contemporary high-density silicon probes that record from hundreds to thousands of tightly spaced electrode sites simultaneously. This transition generates tens of gigabytes of raw binary voltage data per hour that cannot be curated manually.

The core objective of Kilosort is to deconvolve this extracellular voltage mixture into discrete firing rasters corresponding to individual biological neurons. The software models continuous recorded voltage as a linear sum of spatial-temporal spike waveforms generated by distinct neuronal units, corrupted by background noise. Across its iterations—from Kilosort 1 (2016) and Kilosort 2 (2019) through Kilosort 2.5, 3, and the pure Python release of Kilosort 4 (2024)—the package has evolved from basic GPU-accelerated template matching to an integrated framework capable of handling non-rigid physical tissue movement, automated graph clustering, and standardized quality metric calculation.

In modern systems neuroscience laboratories, Kilosort operates as an indispensable bridge between raw data acquisition systems (such as SpikeGLX or Open Ephys) and downstream computational analysis. By outputting structured arrays that trace spike timestamps, unit identity, waveform shapes, and spatial coordinates, it provides the primary empirical dataset for decoding neural population dynamics, sensory coding, and circuit computation.

What Is a Spike Sorting Algorithm?

A spike sorting algorithm is a computational method that detects extracellular action potentials in continuous multi-channel electrical recordings and assigns each detected event to its putative originating single neuron. When an action potential fires in neural tissue, the rapid flow of sodium and potassium ions generates a transient extracellular electric field. An extracellular microelectrode placed near the soma detects this transient voltage deflection, which typically lasts between 1.0 and 2.0 milliseconds with peak-to-peak amplitudes ranging from tens to hundreds of microvolts.

Because extracellular electrodes record aggregate electrical activity from all surrounding tissue, multiple neurons contribute to each electrode contact. Closer neurons produce larger voltage deflections, while distant cells form an unresolved background activity pattern known as multi-unit activity (MUA). The primary task of a spike sorting algorithm is to unmix this aggregate trace: separating true single-unit spikes from noise, clustering spikes with identical spatial-temporal shapes into distinct neuronal units, and resolving overlapping waveforms when neighboring cells fire synchronously.

Historically, spike sorting relied on threshold detection followed by principal component analysis (PCA) and manual cluster cutting on 2D or 3D feature plots. While suitable for recordings from 4 to 16 channels, PCA feature reduction fails on high-density probes: manual cluster cutting across hundreds of channels is subjective, prone to severe operator bias, and incapable of resolving overlapping waveforms.

Algorithmic Architecture and Mechanics of Kilosort

Kilosort departs from the traditional PCA-and-clustering framework by treating spike sorting as a generative waveform deconvolution problem. Instead of projecting detected peaks into abstract features, Kilosort models the continuous multi-channel voltage trace as a linear combination of spatial-temporal templates. The processing pipeline operates across four major phases: pre-processing, drift registration, matching pursuit, and graph clustering.

Pre-Processing: Filtering, Referencing, and Spatial Whitening

Raw binary data is first passed through a third-order Butterworth high-pass filter (cutoff frequency at 300 Hz) to remove local field potentials (LFP) and baseline fluctuations. To eliminate shared environmental noise—such as power-line interference and mechanical vibrations—Kilosort subtracts common average or median reference signals across probe channels.

Kilosort then applies spatial whitening across the electrode array. Because extracellular voltage spreads through conductive tissue, electrical noise is correlated between adjacent recording sites. The algorithm computes the spatial covariance matrix across channels during quiescent windows and applies a whitening transformation. This decorrelates background noise across sites, allowing template matching to operate under standard independent Gaussian assumptions. In scientific software environments, these transformations rely on matrix factorizations detailed in NumPy linalg svd for decomposing spatial footprints and temporal basis kernels.

Drift Correction and Motion Registration

In awake, behaving animal recordings, physical brain tissue moves relative to the rigid probe shank due to heartbeat, respiration, and mechanical movement. Over several hours, neurons can drift by 10 to 50 micrometers. On probes with 15 to 20 micrometer site spacing, this displacement shifts a neuron’s waveform across distinct physical channels. Without correction, stationary sorting algorithms split single units into artificial fragments or merge distinct adjacent cells.

Kilosort tracks and corrects this motion automatically. While Kilosort 2 introduced rigid motion correction, dense recordings from multishank probes like Neuropixels 2.0 (Steinmetz et al., 2021) demonstrated that brain tissue often exhibits non-rigid deformation, where superficial and deep cortical layers shift independently. Kilosort 4 addresses this by dividing the probe into vertical depth blocks (configured via the nblocks parameter, typically set to 5 for Neuropixels). The algorithm calculates continuous displacement trajectories for each block and aligns spatial histograms across time batches to track units stably throughout the recording.

Generative Template Matching Pursuit

The central computational engine of Kilosort is template matching pursuit. Each neuronal unit is represented as a spatial-temporal template: a matrix defining expected voltage across channels and time (typically 61 samples, or ~2 ms at 30 kHz). The generative model expresses pre-processed voltage V(t) as:

V(t) = Σ (K_i * s_i)(t) + e(t)

where K_i is the spatial-temporal template of unit i, s_i(t) is a time series of spike times scaled by amplitude, the asterisk denotes convolution, and e(t) represents residual noise. Kilosort scans the recording on the GPU, detects the template with the highest projection above a threshold (Th_universal), and subtracts that waveform from the voltage trace. This iterative subtraction isolates overlapping spikes that occur simultaneously on nearby channels.

Graph-Based Clustering in Kilosort4

Kilosort 4 replaces earlier heuristic split-and-merge cycles with an unsupervised graph-based clustering algorithm. Detected candidate spikes are projected into a compact latent space of basis functions, forming a k-nearest neighbor (k-NN) affinity graph across events. Community detection algorithms group similar waveforms into cohesive single-unit clusters, improving detection sensitivity for low-amplitude units and preventing artificial splitting of burst-firing neurons.

How to Do Spike Sorting?

Executing spike sorting with Kilosort requires a structured laboratory protocol spanning raw data preparation, algorithmic configuration, GPU execution, automated quality validation, and visual curation. Adhering to a standardized pipeline ensures consistent, reproducible single-unit isolation across experimental cohorts.

The operational protocol for running Kilosort in an electrophysiology laboratory follows six sequential steps:

  1. Format Raw Binary Data and Channel Maps: Store continuous electrophysiology recordings in a flat binary format (16-bit signed integer, int16). Supply an accurate channel mapping file or probe JSON defining physical x and y coordinates, shank indices, contact pitch, and disconnected or noisy channels to exclude.
  2. Set Configuration Parameters: Configure algorithmic parameters according to probe density and experimental design. Key settings include batch_size (defaulting to 60,000 samples, or 2.0 s at 30 kHz), nblocks (set to 5 for non-rigid Neuropixels recordings, 1 for rigid linear probes, or 0 to disable drift correction on sparse arrays with contact spacing exceeding 50 micrometers), and detection thresholds (Th_universal and Th_learned, typically between 8 and 9).
  3. Run GPU Processing: Launch Kilosort via the Python API, graphical user interface (GUI), or command line. Ensure execution on an NVIDIA CUDA GPU with sufficient VRAM. The software streams binary chunks into GPU memory, applies filtering, computes drift displacement, and performs template matching. Traditional workflows developed in Signal Analysis in MATLAB can be transitioned to Python to leverage PyTorch acceleration and automated execution.
  4. Inspect Output Files: Verify that Kilosort outputs standard NumPy binary arrays in the results directory, including spike_times.npy (sample indices for every spike), spike_clusters.npy (unit ID per spike), amplitudes.npy (template scaling amplitudes), and templates.npy (waveform shapes). Persistent storage and pipeline integration follow principles described in NumPy save.
  5. Compute Automated Quality Metrics: Evaluate cluster validity using an automated framework such as SpikeInterface (Buccino et al., 2020). Calculate objective metrics including Inter-Spike-Interval (ISI) violations, amplitude cutoff, presence ratio, and signal-to-noise ratio to filter out contaminated or incomplete clusters.
  6. Conduct Visual Curation in Phy: Open the results in Phy to review borderline units. Inspect auto-correlograms for clear refractory periods, check waveform consistency across probe depth, and merge split clusters exhibiting identical spatial footprints. Label remaining units as ‘good’ (single unit), ‘mua’ (multi-unit activity), or ‘noise’ (electrical artifact).

Quality Metrics and Curation Standards

To ensure scientific rigor and empirical reproducibility, laboratories must apply quantitative thresholds to classify spike clusters. Relying solely on automated classifier outputs or subjective visual inspection introduces substantial variability. Standardized benchmarks formalized by the International Brain Laboratory (IBL) and SpikeInterface establish objective criteria for unit isolation.

The table below summarizes the four primary quality metrics used to evaluate Kilosort clusters, their biophysical rationale, and standard acceptance benchmarks:

Quality Metric Metric Category Biophysical Rationale Standard Benchmark Threshold Underlying Failure Mode
ISI Violations Contamination (False Positives) Refractory period prevents single neurons from firing within 1.5 ms Violation rate ≤ 0.10 (less than 10% estimated contamination) Distinct neurons falsely merged into one cluster
Amplitude Cutoff Completeness (False Negatives) Gaussian amplitude profile; measures missing spikes below noise floor Cutoff fraction ≤ 0.10 (fewer than 10% missed spikes) Threshold set too high or unit drifting out of range
Presence Ratio Stationarity and Stability Fraction of recording time bins containing at least one spike Presence ratio ≥ 0.90 (active across at least 90% of recording) Unit lost mid-session due to mechanical drift or injury
Isolation Distance Cluster Separation Mahalanobis distance from cluster center to nearest non-cluster spike Isolation distance ≥ 20 (high spatial distinctiveness) Poorly resolved unit blending into background noise

Systematic application of these quality metrics eliminates subjective observer bias and standardizes data curation across experimental rigs, aligning with institutional laboratory protocols outlined in Internal Quality Control in the Laboratory.

Laboratory Operations, Computing Infrastructure, and Hardware Setup

Deploying Kilosort in an active electrophysiology laboratory requires computational hardware tailored for continuous streaming I/O and high-throughput parallel processing. Inadequate computing resources bottleneck experimental workflows, delaying data turnaround and impeding large-cohort studies.

GPU Hardware and CUDA Configuration

Kilosort requires an NVIDIA graphics processing unit with dedicated CUDA cores to accelerate spatial whitening, batch correlations, and template matching. For standard 384-channel Neuropixels 1.0 probes sampled at 30 kHz, the GPU must have at least 8 GB of VRAM. For multi-shank probes such as Neuropixels 2.0 (four shanks, up to 5,120 sites), 16 GB to 24 GB of VRAM is strongly recommended to accommodate larger spatial templates and memory buffers without runtime out-of-memory errors.

Storage I/O and Data Pipeline Architecture

A single 384-channel Neuropixels probe records approximately 41.5 gigabytes of raw binary data per hour (384 channels × 30,000 samples/sec × 2 bytes/sample). Running Kilosort directly from mechanical hard drives or network shares introduces severe I/O bottlenecks where GPU cores idle while awaiting disk access. Laboratories should execute sorting on dedicated high-speed NVMe solid-state drives, moving raw traces and curated results to archival servers only after sorting completes.

Common Pitfalls and Troubleshooting in Spike Sorting

While Kilosort automates spike detection and assignment, physiological anomalies and hardware issues can introduce systematic artifacts. Operators should watch for four common failure modes during curation:

  • Drift Over-Correction on Sparse Arrays: Kilosort’s drift tracking assumes high-density contact layouts where single action potentials span multiple neighboring sites. Applying drift correction (nblocks ≥ 1) to sparse probes (site spacing exceeding 50 micrometers) leads the algorithm to misinterpret biological firing rate variations as physical motion, distorting waveforms. Set nblocks = 0 for sparse arrays.
  • Burst-Firing Waveform Broadening: Neurons firing in rapid high-frequency bursts undergo progressive sodium channel inactivation, resulting in smaller, broader waveforms for late spikes in a burst. In earlier versions, this caused Kilosort to split bursts into separate clusters. In Kilosort 4, graph clustering minimizes splitting, but operators must inspect auto-correlograms in Phy to merge burst-related sub-clusters.
  • False Merging of Synchronous Units: When two nearby neurons fire within the same millisecond, their waveforms superimpose. If amplitudes are low, matching pursuit may fit a single composite template rather than two independent events. This error appears as an elevated ISI violation rate (exceeding 0.10) with a central peak in the auto-correlogram.
  • Channel Mapping and Bad Channel Errors: Inverted site coordinates or unflagged disconnected channels corrupt the spatial whitening matrix, injecting high-frequency noise across the probe. Always verify channel maps and inspect raw traces prior to launching sorting runs.

Frequently asked questions

What is a spike sorting algorithm?

A spike sorting algorithm is a computational framework that detects extracellular action potentials in continuous multi-channel voltage recordings and assigns each spike to its originating single neuron. It separates overlapping electrical waveforms, filters background noise, and clusters spikes based on spatial-temporal shape characteristics.

How to do spike sorting?

Spike sorting is conducted through a multi-step laboratory protocol: preparing raw binary voltage data and probe channel geometry, configuring algorithmic parameters (such as drift blocks and detection thresholds), running GPU-accelerated template matching in Kilosort, computing automated quality metrics (such as ISI violations and amplitude cutoff in SpikeInterface), and visually curating borderline clusters in Phy.

What hardware and GPU are required to run Kilosort4?

Kilosort4 requires an NVIDIA GPU supporting CUDA with at least 8 GB of dedicated VRAM for standard 384-channel Neuropixels recordings, with 16 GB to 24 GB recommended for dense multi-shank probes. A fast NVMe SSD is essential to prevent disk I/O bottlenecks during continuous raw binary data streaming.

How does Kilosort handle brain tissue drift during long recordings?

Kilosort corrects for mechanical and physiological tissue movement by dividing the probe into depth blocks and tracking displacement curves over continuous time batches. It aligns spatial spike histograms to estimate vertical motion, dynamically adjusting template positions to track single neurons across tens of micrometers of drift.

What is the difference between Kilosort and Phy?

Kilosort is an automated spike sorting engine that detects spikes, matches templates, and clusters waveforms on the GPU. Phy is an interactive graphical user interface used after Kilosort finishes to inspect, curate, merge, and split clusters based on auto-correlograms, waveform shapes, and spatial probe distributions.

How are quality metrics such as ISI violations and amplitude cutoff calculated?

Inter-Spike-Interval (ISI) violations measure the fraction of spikes occurring within the biological refractory period (typically under 1.5 milliseconds), quantifying false-positive contamination. Amplitude cutoff estimates the fraction of missing spikes (false negatives) by analyzing the drop-off tail of the spike amplitude distribution relative to the noise detection threshold.

Sources

Data: Extracellular Spike Sorting Algorithm and Tool Comparison

Comparative specifications, algorithmic architectures, drift correction methods, and hardware dependencies across high-density extracellular spike sorting frameworks, compiled from published literature and official package documentation.

Period covered: 2016-2024. Coverage: Global.

Extracellular Spike Sorting Algorithm and Tool Comparison
Software PackagePrimary AlgorithmDrift Correction MechanismExecution EnvironmentGPU AccelerationChannel Scalability
Kilosort4Graph-based clustering and template matchingNon-rigid depth block displacement registrationPython (PyTorch)Required (CUDA)Thousands of channels (Neuropixels 1.0/2.0)
Kilosort1Iterative template matching pursuitNone (stationary probe assumption)MATLAB / CUDA C++Required (CUDA)Hundreds to thousands of channels
Kilosort2Continuous template drift trackingRigid probe-wide displacement trackingMATLAB / CUDA C++Required (CUDA)Thousands of channels
MountainSort4ISO-SPLIT non-parametric clusteringNone (pre-processing drift correction required)Python / C++Optional / CPU multi-threadingLow to moderate (up to 128 channels)
SpyKING CIRCUSTemplate matching with spatial sub-clusteringNone (stationary spatial neighborhoods)Python / MPIOptional / Multi-CPUModerate (up to 512 channels)

Sources

Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · full access

Ask about Kilosort: Principles, Architecture, and Practical Guide

Full access: large monthly usage, up to 10 source passages behind each answer, and MCP and API access for Claude Code, Codex and other CLIs. Cancel any time.

An AI assistant for research: funder rules, compliance, methods and publishing. It links the sources behind its answers and labels answers that come from a web search.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays open to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →