Architecture
This page describes the library as it is: what the public API is, how the code is layered, and the models and measured choices that decide what a hierarchical call runs. Every statement names the module or function it describes, so it can be checked against the code. Where the code and this page disagree, the code is right and this page needs fixing.
Public API
The package root, python/matchedfilter/__init__.py, defines __all__ and re-exports the classes from the modules that implement them. The three filter classes keep __module__ = "matchedfilter", so their reprs and pickle paths are matchedfilter.*.
| Name | Defined in | What it is |
|---|---|---|
MatchedFilter | _filter | Flat peak-only filter: per (data, template) pair, the largest correlation sample in each output bin of a search window. |
CorrelationFilter | _filter | The same spectral product, returning every complex lag. |
HierarchicalFilter | _hierarchical | A MatchedFilter subclass that gates pairs with a chain of coarse tiers and refines the survivors. |
TimeDomainFilterBank, FilterResults, template_spectra, template_valid | time_domain (FilterResults in _results) | A bank built from time-domain FIR taps: it partitions templates by length, chooses block sizes and filters continuous series. |
taps_to_spectra | __init__ | FIR taps to frequency-domain spectra, in C. |
devices, Device | device | Device enumeration and the "cpu", "gpu", "gpu:<n>", "cuda", "auto" spellings (device.parse; "cuda" is an alias of "gpu", whatever the backend). |
backend, targets, set_target | __init__ over _core | The CPU SIMD target in use, the targets the build and CPU support, and a way to narrow them. |
get_autotune_state, clear_autotune_cache | __init__ | A snapshot of the process's chain choices and joint trials, and a reset of every workload choice (see Measured choices). |
PEAK_DTYPE | _results | The structured (index, value) peak record. |
UnsupportedSize | _errors | Raised when a device cannot run a transform length. |
include_dir | __init__ | The directory holding matchedfilter.h, for C callers. |
Outside __all__: choose_threshold (the single-tier gate, gatemodel.gate_for) and matchedfilter.search.HierarchicalSearch, a tree of filters run over input blocks with hooks (see the search design).
All filters take frequency-domain complex64 spectra, the unnormalised forward transform of each segment in natural order (set_data, set_templates), or time series through run_series and run_blocks (MatchedFilter.run_series, MatchedFilter.run_blocks). The default device is the CPU: device.parse(None) reads MF_DEVICE and otherwise returns the CPU device. The usage guide documents shapes, normalisation, windows and output lifetime.
Layers
Python modules
The package's modules form layers, and a module imports only from its own layer or the layers below it. tests/test_layers.py holds the table (LAYERS) and fails on an upward import; its allowlist (UPWARD) has been empty since 2026-10-22. From the bottom:
| Layer | What lives there (examples; LAYERS is the full list) |
|---|---|
| extension | _core, the compiled C extension, below every Python module |
| foundation | _config (environment registry), _choice (measured choices), _settings (tunable dimensions), _costfile (MF_COST_FILE), _results, _windows, _gpu_cache, _gputime, _coarse, _shared, _kernel_id, _execution_policy |
| platform | device, _vulkan, _cuda, _metal (enumeration only), _vksubgroup |
| models | gatemodel (the two-tier gate), _gatedraws (the draws a plan rests on), _costmodel (the cost model), gatechain (chain planning), _screeners (shared screeners), _signal_law, _chains, _prices, _trial |
| gpu host | _gpuhost, _gpuhier, _gpuexec |
| backends | _vkcompute, _cudacompute, _mtlcompute |
| workloads | _filter, _hierarchical, time_domain (the bank), _batches (several banks' calls as one), _layout, _calibration, search, _roofline, __init__ |
| applications | benchmark, tutorial, demo, precision |
The cost calibrations run hierarchical plans, so they live in _calibration (workloads), above the model they feed. When the package loads, _calibration binds its calibrate_costs to the public name gatechain.calibrate_costs: one function, whichever name plans, tools and tests call. gatechain also binds the cost model's names and the public names of _gatedraws under its own, so callers reach the planner's whole interface in one module; private names are reached in the module that defines them. A model is cached and stored under the calls it was measured with (blocks, rounds, seed) as well as n, templates and series group, so a calibration with other calls never hands its model to a default one.
The C engine (src/)
The CPU engine is C and C++ compiled into _core. Kernels are written once against the V_* macros of src/simd-inl.h, which bind to Google Highway; src/kernel.cc includes Highway's foreach_target.h, so one build holds a copy per SIMD target and HWY_DYNAMIC_DISPATCH picks one at run time (the SIMD layer). MF_ISA and set_target narrow the choice.
| File | Role |
|---|---|
dispatch.c | The public C API over whichever kernel the runtime dispatch selected. |
matchfilt.c | The flat batched filter: ingest rearranges and conjugates, then the D x T pair loop with the product fused into the inverse transform (design). |
hmf.c | The hierarchical engine: the tiers of a chain on survivor lists, then the refine. It takes thresholds from the caller and holds no statistical model. |
balanced-inl.h, elemfft-inl.h, product-inl.h, codelets-inl.h | The width-generic four-step transform and its codelets; codelets-inl.h is generated by src/gen.py. |
q15-inl.h, q15.h, codelets-q15-inl.h | The int16 (Q15) coarse screen; its codelets are generated by src/gen_q15.py. |
gate16.cc | The FP16 first gate on ARM NEON with FP16 arithmetic; stubs elsewhere. |
td-inl.h | The direct (time-domain) refine: correlation at a few lags around a survivor's coarse peak. |
kernel_avx1.cc, simd-avx1.h | The AVX back end: SSE4's kernels with the float paths at 8 lanes, for CPUs with AVX but not AVX2. |
gauss.cc | Counter-based normal draws for the gate model's simulation, identical on every ISA. |
simulate.c, records.cc | The gate model's simulation: the rows' transforms (simulate.c, behind simulate.h) and the power and running-maximum kernels (records.cc). |
followup.c | The single-template steps of the time-domain banks (follow-up calls), many at once: the plan and scratch pools, the block layout, the per-length kernel and the compaction of peaks (behind followup.h). |
tier0.cc, tier0_mwu.cc, tier0_pass.cc, tier0_match.cc, tier0_prep.cc | Shared-screener clustering: preparing a band's templates, pairing a band's vectors, merging groups and synthesising each group's screener. The last four reproduce NumPy's arithmetic operation for operation and are built without floating-point contraction. |
CI checks that the generated codelet headers match their generators (generated-files job in .github/workflows/ci.yml).
The extension boundary (python/matchedfilter/_core.c)
_core.c wraps the engine for Python: the plan types MF (flat), HMF (hierarchical) and Root (the root stage of search.HierarchicalSearch), and module functions. Besides the target controls (targets, set_target, backend), the gate model's inner loops are here: simulate (the one simulation, below; its kernel is src/simulate.c), records_within, chain_candidates (the threshold-split search; the Python recursion in gatechain._chain_candidates is its reference, selected by gatechain._C_SEARCH), plan_best (a chain's candidate plans priced on a cost model; reference in gatechain.plan_chain, selected by gatechain._C_PRICING), the shared-screener routines (tier0_match, tier0_pair_level, tier0_pass, tier0_mwu), gauss_fill, and the step table HMFTable (gated leaf steps, run with ap_hmf_run_series_batch_sparse; flat steps, run with ap_mf_run_series; single-template steps, run with the follow-up kernel of src/followup.c; and correlation steps, run with ap_mf_correlate_series_continuous or its real-series form, then zeroed and scaled in C; run runs a table's correlation steps, then its leaf steps, which may read what the correlation steps wrote). Buffers are checked at the boundary independently of the Python API. MF and HMF share one implementation of ingest, run and run_series (bind_set, bind_set_batch, bind_run, bind_run_series, reading a filter_view of the object); every buffer a binding takes is released on every path, which tests/test_native_buffers.py checks by reference count.
GPU kernels
GPU kernels are written in Slang (src/gpu/*.slang). They are compiled ahead of time and shipped: SPIR-V, Metal sources and PTX by one generator, tools/kernel_variants.py, into python/matchedfilter/spirv/, metal/ and ptx/, each with a manifest of the same schema: per kernel stem, its file, entry point, build facts and the facts read back from the artifact (local size, workgroup memory; for SPIR-V its descriptors and push-constant bytes) and its digest. The hosts read every kernel fact from it through _kernels and restate none; CI checks that the shipped files and manifests are exactly what the generator makes. No PTX module declares more than the 48 KB of static shared memory CUDA allows a block (such a module launches on no NVIDIA GPU, so the build does not ship it); where a kernel's staging is the reason, its 32 KB staging build (_lds32) serves that length. _kernel_dirs.shipped decides which directories a platform's wheel carries (SPIR-V everywhere, PTX off macOS, Metal on macOS). _kernel_id gives each backend's shipped programs an identity, which the stored kernel choices include in their keys, so a build with other kernels measures afresh.
The GPU host layer and backends
GPU operations are written once, above a thin per-API driver:
_gpuexec.Executorholds every operation: full and continuous correlation, the forward transform, flat peaks, follow-up items and deferred forwards. Each decision it makes uses what the driver reports about the hardware, never which API it is._gpuhier.HierOps, a base ofExecutor, is the hierarchical search: one recording per call shape runs the feed, tier 0, a second tier, the refine and the readback on the device, with no counts read back between stages._gpuhostis pure host logic shared by every backend (windows, bin shifts; the band forward ruleband_forward_wantedis the gate model's, which prices it);_gpu_cacheholds input residency and in-flight results;_sharedprovides host-visible allocations with DLPack lifetimes;_gputimecollects device time underMF_GPU_TIMING=1.- A search's scratch is one arena per device (
_gpuhost.Arena, made by_gpuroot.device_arena), leased by a search while it runs (HierarchicalSearch.run): the buffers its plans' records own and their pipelining slots' spectra and starts are sections of the arena's blocks. The search keeps its lease between runs; when another search takes the arena the lease ends, each plan and context giving back what it built on it (deferred work dropped, records on its sections released), and the new search reuses the same blocks. Every section has a serial of its own, so nothing keyed on a serial mistakes a recycled section for its previous tenant. The device reports what the arena holds: device-only scratch everywhere; buffers the host reads or writes, and host arrays, only where the host sees device memory in place (unified_memory). It reports how sections lie in blocks too: packed first fit where only the driver contract orders work (Vulkan, CUDA), a block per section where the device orders work by allocation (allocation_hazards: Metal, whose hazard tracking would order the runs of every plan with a section in one block after each other). - Each backend's
Context(_vkcompute.Context,_cudacompute.Context,_mtlcompute.Context) inheritsExecutorandInputUploadsand supplies only driver primitives: allocate, record, submit, read back. All three call their APIs throughctypeswith no compiled host code.
_filter._compute_module picks the driver from Device.backend: Metal on Apple, CUDA on NVIDIA, Vulkan otherwise. device.devices lists the CPU first, then Metal devices, CUDA devices, and Vulkan devices; a Vulkan entry for an NVIDIA GPU is skipped when CUDA lists it. Software Vulkan devices are listed but flagged, and a bare "gpu" skips them. HierarchicalFilter._MAX_TIERS limits GPU chains to two tiers and CPU chains to eight.
A hierarchical call, end to end
HierarchicalFilter(n, ndata=1, ntemplates=1, snr=5.5, fd=1e-2, chain=None, device=None, *, valid=None, max_tiers=3, search_window=None) holds its inputs. Before it runs, it settles everything that decides which pairs are refined into one immutable record, the resolved plan (_hierarchical._Resolved: chain, per-tier thresholds, the model's refine reach, per-tier band fractions, and the CPU direct refine's half-width), computed by HierarchicalFilter._resolve and dropped by every setter that changes an input (the resolved plan).
- Chain. A pinned
chain=is used as given. OtherwiseHierarchicalFilter._choose_chaincallsgatechain.choose_chainwith this device's cost model (_cost_model), caches the result per (n, snr, fd, tiers, window, profile signature, device, gate kind, direct refine) in_chains._CHAIN_CHOICE, and runs the model's best chain.MF_CHAIN_FORCEoverrides it for measurement. - Thresholds.
set_coarse_thresholdgives them explicitly (a pinned chain is then required). OtherwiseHierarchicalFilter._thresholdstakes them fromgatechain.chain_thresholdsfor the chain, the reference,snr(orset_first_stage's) andfd. Thethresholdpassed torunis the final reporting cut, separate from the gates. - Execution. On the CPU,
_execution_planapplies the resolved plan to an_core.HMFplan, which runs tier 0 on every (block, template) pair, each later tier on the previous tier's survivors, and the refine on the last tier's survivors (src/hmf.c). On a GPU the same chain runs as one recording (_gpuhier). - Refine. Survivors are refined by an n-point transform and a peak scan over each bin, or, on the CPU with real taps and one bin per pair, by the direct refine around the last tier's coarse maximum (CPU direct refine).
MF_DIRECT_REFINE=0turns the direct refine off.
config reports the chain in use and refine_rate the fraction of pairs refined over the plan's lifetime. On the CPU, tier_stats gives each tier's passes and ticks (it is None on a GPU). autotune_info says whether the plan's chain is pinned, the model's or forced, and whether a trial has locked its arm.
Several banks' calls as one
TimeDomainFilterBank.filter_series_many runs a list of bank calls as one batch (_batches._run_batch): follow-up windows, single-template calls and sparse CPU jobs each go to a path that takes many at once, and the rest run in turn. On a GPU every call is submitted before any is collected. The gated CPU calls run as compiled leaf steps (_batches._compile_steps, _core.HMFTable): each template group's blocks of one bin count are a step on the plan of the call's profile, compiled once per call shape (the calls' banks, layouts, profiles, series lengths and kinds, windows, bin sizes and thresholds) and kept by the first call's bank; a run is one C call that sets each plan's series mode, clusters the steps whose series share cache lines, runs them and returns every call's peaks in one arena, window bins merged. The other every-template CPU calls (a flat bank's, and a hierarchical bank's below its threshold) are flat steps of the same table: each template group's blocks of one bin count on the group's ungated plan (a MatchedFilter of one data row), run with ap_mf_run_series (a real series widened to complex over the samples the blocks read) and assembled in the same arena. Single-template CPU calls (template_index, a search's follow-ups) are single-template steps of the same table type: a template group's step (its block geometry, its templates' taps and bank indices, and the group's store of template spectra, _batches._single_step) is compiled once and kept by the group, or for a batch over several groups by the first call's bank; a call binds its template, series, windows, bin size and threshold and runs in the same C call, which lays its blocks out, correlates (time-domain for a narrow window, else by transforms), bins and merges in C. A template's spectrum is made from its taps when a call first needs it and kept in a slot of the group's store (256 slots at most, the least recently used given up first). CPU correlation calls (correlate_series, and correlate_series_channels for all its channels) are correlation steps of the same table type, compiled by the same compiler (_batches._cpu_correlate, _batches._compile_steps): a step is one template group's templates adjacent in the group and in the output, over the group's blocks that a window reaches, written into rows of an output, with the samples it clears (outside the windows, and inside the output's support) and, for a scaled call, each row's scale vector entry and the samples it scales. A group whose templates are not one run of the output writes through a scratch and copies its rows. The steps of a call shape (the calls' banks, layouts, series lengths and kinds, windows, supports, rows and whether scaled) are compiled once and kept by the first call's bank; a run binds the series, outputs and scale vectors and is one C call for every channel and group. TimeDomainFilterBank.correlate_and_filter_many runs a hierarchical search's middle correlations together with the leaf calls that read them. By default its correlations and the batch's every-template leaf calls are the steps of one table, run by one C call (_batches._untiled_batch; correlations off the CPU, or whose series may lie in an earlier job's output, are made first, _batches._correlate_jobs). With a positive tile_bytes, as an explicit choice, jobs on one middle bank and window layout form a cohort (the detectors of one search) that runs tiled, as a schedule of the same step table (_batches._cascade_steps, _cohort_schedule; HMFTable's ops, run by hmf_run_schedule in the same C call as the rest): per middle group the stale scratch cleared and the output's margins zeroed and scaled, then per time tile and template batch the carried collar restored, the batch's correlation steps (every detector) into a scratch slot (the middle bank's pool), the rows copied to the output, the leaf steps' slabs that are ready run as one batch of block ranges, the output written around the batch's peaks where retain_radius > 0 (spans the executor takes from those peaks), and the collar a later tile's leaves read carried to a carry slot. The leaf steps a schedule runs gather their slices' peaks and are assembled with the others. Its results equal the untiled schedule's. Tiling is not the default: on the shapes measured it did not pay (docs/host-layer-plan.md, 2026-11-28); tools/schedule_bench.py measures it on other machines.
The calls the steps do not take (GPU calls, and CPU plans the steps decline) are assembled by the same C functions (_core.assemble_peaks, sharing hmf_append_peaks and the window-bin merge with HMFTable.run). filter_series records each call it makes as the bank index of each template of its result, the blocks' starts in output order, each block's bin count where one ragged call computed several, the block length and the result (_results._PeaksJob); a filter_series_many batch's jobs are assembled in one extension call by whichever is asked first, and handed back as slices of one arena. A hierarchical GPU call with sparse peaks returns its parts (_results._CallParts: per batch of blocks its first block and its in-flight result), and the assembly reads each run's readback buffers where the device wrote them (_gpuhier._readback: views made once per record, the buffers themselves where the device reports unified memory, the page-locked copy on CUDA), adding each run's work counts to its plan's counters (MatchedFilter._gwork). Host results (dense lags and values, or _SparsePeaks) are parts of the same assembly. Where the device holds readback buffers in the search's arena (unified memory), a record's readback buffers are arena sections: the counters' words are indexed from the counts section's own offset and each view reads its section in place. The views die with the record, which the lease's end evicts after collecting every result still in flight into host arrays, so no readback outlives the lease whose bytes it names. The window-bin merge of the assembly compares peaks that are out of template-then-sample order by magnitude as numpy's absolute value of a complex64 rounds it, as the Python merge it replaced did; HMFTable.run's steps compare them by hypotf, as before (the two differ in the last place for some values).
A CPU search runs each chunk's inner correlations (of inner nodes whose children are leaves) and its leaf searches as the steps of one table, one C call (HierarchicalSearch._cpu_chunk, _batches._chunk_steps). The table is compiled the first time the chunk's shape is seen: the series length, the active channels, every leaf's windows and the spans its parent must hold, and what each inner node's slots hold (_InnerBatch.support_key, by which the correlations clear). The search keeps it (the eight most recent shapes), with the inner series and spans the hooks read and what the run leaves in the slots, so a chunk of a kept shape makes no walk and no job: it binds the root outputs and runs. A shape whose jobs do not all fit one table (a job the steps do not take) is remembered as declined and runs through the walk and correlate_and_filter_many; so does every chunk while a leaf bank's trial is open or playing.
The gate model
The gate model decides, for a chain of bands, the thresholds that meet a false-dismissal budget, and the noise pass rates that price it. It is computed from the reference profile (the expected output power per frequency bin, set_reference) and the algorithm; nothing is tabulated. The code is gatechain (chains, any number of tiers) and gatemodel (the single-tier case and the draw counts).
One simulation
The model is one simulation of stationary Gaussian noise with the reference's output spectrum (_gatedraws._simulate, which calls _core.simulate). Each draw is a block's n bins with variance p_k. The fine statistic is their n-point transform, and band b's statistic is the b-point transform of bins [0, b), normalised to unit variance per component, so the tiers and the fine stage share their noise as the filter's do. Every maximum is taken over the whole searched window, over the lags the engine visits for it (_gatedraws._engine_lags, mirroring hmf.c).
Two readers take their statistics from the same simulation:
gatechain.signal_drawsadds a signal of strengthsnrarriving at a uniformly random time (16 sub-sample phases,_NF) through the transforms' linearity, and returns each band's coarse window maximum with the fine window maximum, and where each lies. Only draws whose fine statistic reachessnrsomewhere in the block hold records. The simulation runs until it holds the detections asked for (draws whose fine window maximum reachessnr), however few of its draws a largesnrkeeps, and is extended in place for a larger request: a row's draws depend only on its row. A plan reads it in the window local to the signal (gatechain.local_window, four times the profile's autocorrelation extent), so every window of a profile plans on one set of signal draws.gatechain.noise_block_maximareads the same draws without the signal: each band's noise-only window maximum per block, from which a chain's joint pass rates follow (gatechain._reach).
gatechain.kept_draws selects the draws the fine stage keeps (fine maximum at least snr): the false-dismissal budget is a fraction of those.
The draw count is a function of fd and the per-plan tolerance only (gatemodel._nsamp_for): 2 (round(j / fd) - 1) detections, where j (gatemodel.fit_order) is the smallest order statistic whose plans exceed 1.25 fd with probability at most 5% (_TAIL_RATIO, _TAIL_SHARE). j is 47 at fd 1e-2 and 48 at 1e-3 and 1e-4: 9,398 and 95,998 detections, a median of 16,500 and 167,000 draws at snr 5.5 over the fdr_audit profiles (200/fd drew 20,000 and 200,000). The noise blocks are the simulation's first 20,000 rows (_NOISE_BLOCKS). A budget whose tail bound needs more than _MAX_DETECTIONS (1.75M, 0.7-0.9 GB of records; fd below 5.5e-5) is refused (gatemodel.gate_for, gatechain.chain_thresholds, gatechain.choose_chain).
Profiles that agree in shape and in every band's signal response share cached simulations and plans (_gatedraws._similar_get: a cosine of at least _REUSE_COS and a gate response within _REUSE_RESPONSE), because a search's banks have nearly one reference.
What follows from a reference alone is worked out once, by its _gatedraws.ProfileClass: the normalised profile and its signature (the key of the exact caches), the band offsets and usable bands, the gate features, whether the reference has a localised peak, and, for each profile the similarity store holds a result for, whether this one takes it. TimeDomainFilterBank.set_reference makes one class per reference and block size and hands it to every plan the reference reaches (a top template's leaf banks in one detector share one), and the chain choice, the thresholds and the screeners read it. Its identity is its content (a SHA-1 of the normalised profile and n). It holds no plan, bank or other class: it goes with the last plan holding it; a class made from a bare array (a direct call of choose_chain or chain_thresholds) is held in _gatedraws._CLASSES, by identity.
Chains and the budget split
gatechain.enumerate_chains lists every increasing tuple of up to max_tiers power-of-two bands from 64 to n/2 that hold some of the reference's power (usable_bands). gatechain.plan_chain gives each chain the thresholds, and on the CPU the direct refine's half-width, that meet the budget at the lowest modelled cost, and gatechain.choose_chain prices them all and returns the best with the list. The detections fall into two independent halves:
- the search half decides the plan's structure:
_chain_candidatessearches the budget's split between tiers (over the shares_SPLIT) and, where the cost model prices a direct refine (CostModel.with_direct), every half-width at which a different set of the detections falls outside the window (_halfwidths, up togatemodel.window_allowancemisses), its misses counted against the same budget; the cheapest candidate wins, and every choice among plans (choose_chain's, the block size's) ranks their searched costs; - the fit half sets the thresholds (
_fit): the search's, every tier moved by one shift, the j-th smallest over the fit half of the shift at which each detection is first dismissed (a detection the window misses is dismissed at any shift).
- A split in which a tier passes more than
_USELESS_PASS(half) of its pairs on to another tier is skipped when choosing. - Chains whose costs are within
TIE(5%,_choice.TIE) of the cheapest are tied; the tie goes to the cheaper chain on a calibration-free operation count (_flop_cost), so the choice does not flip with calibration noise (gatechain.pick_stable).
Shared screeners
On a plan of four or more templates, the first tiers may screen on one coarse vector per group of alike templates in place of each template's own. _screeners pairs a leaf bank's templates over the first band and merges the pairs into groups of up to 16, each with a screener that every member overlaps well (cluster_tier0_candidates); a group's members can be paired again at the next band (cluster_tier1_from_tier0). The compiled routines do the work (_core.tier0_match, tier0_pair_level, tier0_pass, tier0_mwu). A member keeps only part of its signal through its group's screener, its retention, and the planner prices and fits a chain with those retentions (gatechain.choose_chain), so the plan's budget holds with the screeners in place. Survivors of a screener are passed to its members.
What fd means
fd is a mean target: the expected fraction of the detections the flat filter makes at strength snr (fine maximum at least snr) that the chain dismisses, for signals at that strength in Gaussian noise with the reference's spectrum. It is not a bound for every plan, population or noise.
- A plan's dismissal counts the detections some tier dismisses and those the CPU direct refine's window misses (the fine maximum further from the last tier's coarse maximum than the half-width), together: the window's misses come out of the budget, not on top of it, and the plan runs the half-width the model counted.
- Given the search half, the fit half is independent of the plan's structure and the shift's score is continuous, so the plan's dismissal on fresh draws is the j-th smallest of M uniforms, M + 1 = round(j / fd): its mean is fd, whatever the search chose and whichever chain or block size was chosen from it, with no correction for the search. Where the window alone misses j of the fit half, the plan refines by transform instead and the tiers take the whole budget. A whole-number window cannot move with the fit, and that branch is taken on the fit half, so the search offers a window only where the branch's predictive probability (from the window's misses on the search half) is at most the share of the tail bound the fit leaves (
gatemodel.window_allowance: a window may miss at most 15-22 of the about 47 dismissals the budget allows). A single tier is the same with no search (gatemodel.gate_for). - Individual plans scatter about the mean with an sd of about fd / sqrt(j), 0.14 fd, and P(plan > 1.25 fd) is 5% by construction. On independent draws (
tools/split_bias.py: 10 profiles x 30 model seeds, 16M check detections at fd 1e-3, n = 2048 and 4096, one to three tiers, every chain's plan and the pick, with and without a direct refine) the pooled mean is 0.996-1.006 of fd and 4-6% of plans exceed 1.25 fd. The gate model's one seed gives every profile the same underlying noise, so a job's plans share one draw's luck.
Reduced-precision tiers (the Q15 screen, the FP16 gates) answer to the same budget against the flat filter; reduced-precision gates gives their error models. tools/fdr_audit.py measures a chain's dismissal against the flat filter by injection, two-sided against what the model says the plan dismisses (and pooled over the cases against the budget), and tools/gate.py runs it before every merge.
Refusals
HierarchicalFilter._choose_chain raises ValueError when no chain can be planned: a reference with no localised correlation peak (_gatedraws.ProfileClass.uncovered, every band's effective bandwidth below _BEFF_MIN), a transform size too small for any band of at least 64 at or below n/2 (n = 64), or a budget the draws cannot resolve (_uncovered_message). A pinned chain with explicit thresholds always runs, with whatever guarantee those thresholds carry.
Cost models
A chain's cost is the model's expected cost per (block, template) pair (gatechain.CostModel.chain_cost):
first_tier(b1) + sum over later tiers i of P(reach tier i) sparse(b_i, density) + P(reach refine) refine(density)
where the pass probabilities come from the noise simulation and the per-tier prices are measured on the machine the job runs on. A CostModel holds, per transform size n: dense (a first tier per pair, per band), sparse (a later tier per survivor, as a function of survivor density), refine (per refined pair, as a function of density), block (fixed work per block), screen (the Q15 screen as the first tier, where the back end has one), excess (a bounding first tier's extra passes), and on a GPU feed (the per-block change from block's feed of the band forward at each widest band and of the full forward, timed by the calibration; the model takes the one the backend's own rule takes for the chain, gatechain.band_forward_wanted on its modelled refine probability). The model ranks chains. It cannot change a single tier's gate; for a multi-tier chain it picks among budget splits that all meet the budget, so different costs can move the thresholds.
- CPU (
_calibration.calibrate_costs). Synthetic analytic noise and whitened random templates, at thresholds placed for target survivor densities (_costmodel._CAL_DENSITIES), run through the engine; costs are read from the engine's per-tier tick counters (tier_stats), not from wall-clock differences. Calls are 32 blocks of_costmodel._CAL_TEMPLATES(64) templates at the plans' own series group. Band costs are shared by every n on the same series group. The Q15 screen is priced per band, andCostModel.first_tierpicks the cheaper first tier. - GPU (
_calibration.calibrate_costs_gpu). The same construction, timed by device timestamps around each submission, each time taken relative to a fixed reference call (_calibration._ClockRef) so that clock changes cancel. A tier's cost is the difference between runs that differ in that tier. A second tier's price is the slope of device time against first-tier survivors over the calibration densities (_calibration._sparse_rows), so a per-call cost cannot be charged to the few survivors of one density point. - Other prices (
_prices.price_once): the CPU platform forward, the direct refine's per-lag and per-pair prices, and the continuous correlation's block costs (_layout). Each is timed once per process, or once per machine withMF_COST_FILE, where the first record written is the one every process uses.
Cost models are kept per process (_costmodel._COSTS) and in MF_COST_FILE when it is set (_costmodel._stored_cost_model; a record that is not a cost model is reported and recalibrated). A model another process stored first is the one used (_costfile._store_first). _calibration.price_block_sizes uses them to price a bank's layout at each candidate block size; that layout is one arm of the bank's joint trial (below).
Every reader of the file (_costfile._load_cost_file: cost models, prices, measured choices, a joint trial's lock) asks the file for its identity each time (device, inode, size and times: every write replaces the file), so that a record another process stored is seen at once, and opens and reads it only when that has changed. The parse is kept with the bytes it came from and handed out again while the file is the same or holds the same bytes (the readers read the records and never change them; a writer, under the lock, reads a parse of its own). A leaf bank reads its joint trial's lock this way when it is given its first reference, once per bank.
Measured choices
Where the library cannot predict which of a few candidates is faster on this machine, it measures them on the job's own calls. One lifecycle serves every such choice: _choice.Choice.
- Preference.
candidates[0]is the preference. It stands unless another candidate is clearly faster. - Paired rounds.
Choice.playruns every live candidate on the same call, back to back. Each timed run comes right after an untimed run of the same candidate, so every timed run is a second run (a GPU batch run second ran 20-30% faster). The order reverses every round. Candidates that would run the call identically run once and share the timing. - The rule.
_choice.paired_choicejudges rounds as ratios to the preference. A candidate wins when at least 75% of the rounds are faster than the preference by more thanTIE(5%). The preference stands at once when, for every candidate, at least 75% of the rounds are not faster by more thanTIE. Otherwise the contest takes more rounds, up to its cap, and at the cap the preference stands. No decision is made beforeMF_TRIAL_ROUNDSrounds (default 5,_choice.MINIMUM), and the cap is twice that (_choice.rounds). - Exact elimination. A candidate that can no longer reach the share of wins it needs by the cap is dropped from later rounds (
_choice.can_still_win); a test enumerates every win/loss history againstpaired_choice(tests/test_paired_cpu_trials.py). - Confirmation. With
confirm=True, a challenger the rule picks is not locked at once: it must win again in fresh rounds alone against the preference, or the preference stands. - Budget. Calls that cannot be rounds count against a budget (
Choice.tick); when it is spent, the contest ends on the rounds it has. - Lock. The winner is locked for the process and, with
MF_COST_FILE, stored aschoice|<store_key>with its medians. A lock already on file is reused without timing, and the first lock written stands: a process that finds another's lock adopts it (Choice.lock,Choice._write). Samples of an open contest are not stored. - Scope.
_choice.SCOPESdeclares each kind of choice asworkload(forgotten byclear_autotune_cache) ormachine(a hardware property that outlives it). - What a trial may cost (
Choice.afford,Choice.charge). A trial may not cost more than all the work its decision can change over the life the library knows; otherwise the preference runs for now, nothing is stored, and the contest stays open: the caller asks again at its next decision point, with what the process has measured by then. The most any candidate can save is that work (it would have to make every call of it free), so a trial that costs more could not be repaid within that life. - The stake is the best measurement the process has of that work: the preference's wall time per call (host and device time, either of which an arm could save) times the calls still to come. It is not an unconditional upper bound: a first decision can only use the trial's own waited call, which on a device with many jobs in flight reads below what production pays (1.5-1.6x on an RTX 6000); later decisions take production's own measured wall per call where it is larger. The cost is a lower bound of what the trial spends: the thread time it has spent beyond what the preference alone would have run (its preparations, every run beyond one of the preference's), plus the caller's prediction of its next step from this process's own measurements. The trial waits while the cost reaches the stake (at equality the preference runs).
- Once a trial has played a round it runs to its lock, as before the rule: a later decision point does not take back what it has begun, and a lock is never reverted.
- Without a prediction (nothing measured yet) the step is taken and measured, so a wrong prediction costs at most one step.
- Only the bank's joint trial knows a life (below). The GPU kernel slots, the single-template side, root placement, the Vulkan subgroup size, the cost calibrations and the prices know none: they pass no stake and run as before.
Two kinds of choice are first decided offline, because a real call cannot carry their candidates. The GPU coarse kernel layouts and gate ways per band are ranked on synthetic dispatches (_coarse.screen), and _coarse.shortlist keeps the fastest two; the second is then played on real batches as a kernel slot (below). The Vulkan subgroup size (_vksubgroup) is measured in subprocesses, because a size can lose the device, and decided by paired_choice over the sizes' timings of the same calls.
Joint trials
_trial decides coupled choices together, over complete configurations, with one trial per key:
- Arms are labels in the grammar of
_settings:default(every dimension at its default) or<dim>=<value>[,<dim>=<value>...]in declaration order (_settings.compose,_settings.moves).defaultis the preference. - Instances resolve an arm to a configuration (
arm_config), run it (use_arm) and lock it (lock_arm). ATimeDomainFilterBankis one (its block-size layouts and its plans' screens; its rounds run infilter_series_manythroughtime_domain._joint_round), and so is aHierarchicalFilterused on its own (its screen; rounds inrun_series). A plan inside a bank is governed by the bank's trial. - The bank's arms (
TimeDomainFilterBank._joint_arms):defaultis the bank at its smallest candidate block size;n=<size>is the next single size;n=modelis the layoutprice_block_sizesprices cheapest;q15=1andq15=0turn the Q15 screen on or off where the first band has one. Each plan runs its model chain under every arm: the gate chain is never an arm. - What a round holds for an arm is its full cost over the work its instances will do, not its timed call alone (
_trial.run_round'scost;time_domain._arm_cost): the setup the arm's lock makes a bank pay beyond the cheapest arm's, plus the timed replay times the calls each bank gets. A bank's arms differ in setup: a block size's layout and build, the model's per-bank pricing, the clustering of the plans' bands at that size and the gate law's draws there. On a cluster GPU a trial that weighed the calls alone lockedn=model, which added 50 s of setup to a PyCBC job to save 1.5 s of filtering (2026-11-28). - Setup is measured where the trial already builds it, in thread time: the default's layout at the bank's first reference (
set_reference), each candidate layout and its plans' chains as_prepare_armsbuilds them on the sampled banks (_arm_setup). A layout the trial found already built for another rank (the model pricing every batch at a size a single-size arm offers) is charged that rank's build too, since a lock on it builds it in every bank. The trial takes, per layout, the median over its sampled banks of each one's excess over its cheapest layout per template (_note_setup,_setup_estimate): a bank that paid for what the job shares (the gate law's first draws at a size) does not set it. - Calls (
time_domain._life): a search's leaf bank gets one call per chunk and channel of the run, whichHierarchicalSearch.runhands it (_life_calls) where every chunk is searched. A bank used on its own, or under awindowscallable, counts the calls it has had: the trial decides on a bank's first calls and what will follow is not known, so an arm that costs more setup must pay for itself in the calls seen, and the default (the preference) stands otherwise. - An arm that moves no setup (the Q15 screen; a plan used on its own) costs its timed calls alone, so the rule for it is the one it had. The same paired rule, tie and confirmation judge the full costs, so a job near the break-even keeps the default.
- The record keeps the parts beside the lock:
setup(seconds per template, per arm),call(seconds per call, per arm) andcalls. A bank's trial key startsbank-cost|and names the device the bank runs on as the neighbouring records do (time_domain._device_name: a GPU by ordinal and name, the CPU with its SIMD target), so banks on different devices sharing a cost file keep different locks. A lock stored under the earlierbank|key was judged on the calls alone and is not read, so a machine runs the trial once more (tools/migrate_cost_file.pyremoves those records). - The stake of a bank's trial (
time_domain._bank_stake) is the wall time per bank call times the calls each of the trial's banks in the batch still gets in the run, summed over the banks; a bank's jobs in a batch are that many of its calls (one per chunk and channel). The wall per call (time_domain._call_wall) is the larger of two measurements: one settled, waited call of the default on every job of the trial's banks in the first batch the trial meets (the batch's own call: its results are kept), and production's wall per leaf call in this process so far (time_domain._PRODUCTION: each search adds its leaf time and calls after its run, less the batches a trial took). The first search has only the first; the next search's first batch, where the trial is asked again, has both. The stake does not count the single-template follow-ups a caller runs on a bank (how many is not known when the trial decides), which a block size changes too. Each candidate layout is a step the trial must afford before_prepare_armsbuilds it, and its first round one after them. A first build at a size is predicted as the dearer of the default's measured setup over the batch's banks (the first bank's, which paid the first-time work at the default's size: gate-law draws, a calibration when one was measured) and the bank's own default setup plus the dearest cost calibration this process measured (_calibration.MEASURED); a later build of a size as the bank's own default setup (time_domain._prepare_step). A bank first sampled after an arm was dropped builds only the layouts of the live arms. Banks whose life is not known (on their own, or under awindowscallable) have no stake, and their trial runs as before. - Measured on dev2 (PyCBC job, 171,828 templates, 64 searches of 10 segments, under load from neighbouring cores), the trial is asked once a search. On the Radeon 8060S the stake is 0.04-0.06 s at the first search and up to 0.2 s at later ones, once production's own wall per call is known, against a first build predicted at 1.9-2.2 s (0.2 s when the file holds everything but the bank's record): no candidate is built in any search. On its CPU the stake is 0.19-0.77 s against 0.65-1.41 s: the first search waits, one later search whose banks get more calls affords one candidate layout on one bank (0.5-1.2 s), and every search after it waits again.
- A stored bank lock is read at the reader's life (
time_domain._bank_judge, the judge of_trial.stored_search). The record's value was judged at the life of the job that wrote it. A bank whose life is known scores the record's parts (setup,call) with its own templates and calls by the trial's own score (time_domain._bank_score, which the rounds use too) and its paired rule over that one row: an arm other than the pass's base wins only when cheaper by more than the tie. - A record without parts, or with parts of fewer than two arms, keeps its value.
- Parts that miss the pass's base or a block size the trial key offers, or that do not give a positive finite score, cannot decide. The pass then runs afresh in this process (
_trial.REOPEN; itsChoiceisfresh), and its lock replaces the record. So does a pass whose re-scored arm leads to a pass that was never run. - A bank whose life is not known reads the value, as before.
- The parts keep the trial's known bias: its sampled banks' setup estimate is 3-14x the job's real difference, toward the default. It is read as stored.
- Dropped arms (an arm that can no longer win, or the others when a challenger goes to confirmation) never run again: a bank frees their candidate layouts at once (
TimeDomainFilterBank._release_layouts), keeping the default's layout (the others are built from its templates) and any layout a live arm shares; the lock frees the rest. - Coordinate passes (
_trial.current_pass). A first pass offersdefaultand the arms that move one dimension. A pass that locks an arm other than its base opens the next pass around that arm, with each dimension it has not moved moved too (_settings.around). The search ends at a pass that keeps its base; a first pass that keepsdefaultends it. - Passes are
Choicecontests with confirmation and a budget of_trial.UNROUNDED_BUDGETcalls that could not be rounds. Each pass's lock is stored under_trial.pass_key("joint|" + key, base);_trial.winnerand_trial.stored_searchread the end of a search from the file. A pass whose trial could not be afforded is not stored.
With MF_AUTOTUNE=0 no timed choice runs on real calls (the joint trials, the GPU device trials and single-template side below, and the Vulkan subgroup size): a bank builds the model's priced layout, every plan keeps the model's chain and screen setting, and batch dimensions take their locks or defaults. Cost calibration and the offline kernel screens still run.
Tunable dimensions and the settings store
_settings.DIMS declares every dimension a trial can move, with how its values parse and print, its default and its scope:
- subject dimensions are resolved by each instance: a bank's block size
nand a plan's screenq15; - batch dimensions are read by the code they steer while a batch runs: where a GPU batch's follow-ups run (
single), and where a lone single-template call runs (side); - kernel slots
kern:<what>:<band>carry a call's default kernel and its alternative (_settings.slot): the coarse layout, the gate way and the sparse readback.
_settings.setting answers a batch dimension: the arm a running trial plays, else the lock of a device set holding the device, else the default. The GPU device trials that decide them (gpu-single, gpu-kernels; time_domain._gpu_trials) use the same paired Choice and coordinate passes (_trial.current_pass). The single-template side (single-device, time_domain._single_choice) is one paired Choice between two candidates, the default and the CPU, with confirmation.
What MF_COST_FILE holds
_costfile is the one reader and writer of the file: a writer lock on a .lock sidecar, then an atomic replace, so unlocked readers never see a partial file. Its records, by key prefix:
- cost models, keyed by n, template count, series group and gate kind on the CPU, and by n, device, gate kind and fit on a GPU, with the calls measured appended when they are not the defaults (
_calibration.calibrate_costs,calibrate_costs_gpu); - prices:
cpu-fft,corr4,corr-pfft,choice+direct-lagtapanddirect-pair(_prices,_layout); - joint-trial passes:
choice+joint+bank-costorplan(_trial.Trial), a bank's with the parts of each arm's cost; - GPU device trials and the single-template side:
choice+gpu-single,gpu-kernelsandsingle-device(time_domain); - kernel shortlists and the Vulkan subgroup size:
choice+coarse,gatewayandvk-subgroup(_coarse.shortlist,_vksubgroup).
The parts of a key are joined by | (cost models and some prices by ,); the formats belong to the code that writes them. Records of the trial format before 2026-10-21 are reported and ignored (_costfile._LEGACY_PREFIXES); tools/migrate_cost_file.py removes them.
With a shared file, every process sharing it makes the same choices and reports the same peaks; tests/test_reproducible_choices.py checks two processes, and tools/gate.py runs it repeatedly. Without one, each process measures afresh, and two processes can choose differently on timing noise; every choice still meets the budget, but pairs near a gate can be refined in one process and not in another.
A process without one also pays for the measuring. Measured on 2026-11-14 on one pycbc_inspiral_fir job of pycbc's FIR search example (11,988 templates, H1 and L1, 2,048 s, SNR 5.5, false-dismissal budget 0.001, one core): 426 billion instructions without a cost file against about 360 billion with one reused from an earlier job. The difference is the block-size trial: its preparation calibrates both profiles at the second block size (39 billion instructions, of which 28 billion are twenty simulations at n = 2048), and that arm is then played (32 of 100 trial calls; all eight banks locked the model's first choice). Nothing prepared at cost goes unplayed, so the saving is the file's alone: a workflow whose jobs share one runs the trial once.
Configuration
Every environment variable the package, the C extension and the tools read is declared once, in the registry python/matchedfilter/_config.py (VARS): its kind, default, which side reads it, its section and what it does. The sections are config (user configuration), diagnostic (output only), override (changes what runs, for measurement and tests) and tools. _config.check_environment runs at import, before _core reads anything: it raises on a malformed value and warns about a removed or unknown MF_* name. The C side reads flags with the same rule (src/env.h). Environment variables is generated from the registry by tools/gen_environment_doc.py, and tests/test_config_registry.py checks that every MF_* name the code reads is registered, that every registered name is read, and that the document is current. This page does not list the variables; the registry is the source of truth.
Execution scheduling rows (series groups per device and shape) come from python/matchedfilter/execution-policy.json through _execution_policy; they select scheduling only, never calibration or device capability.
Testing and gates
The test suite is tests/, run with pytest. Tests and benchmarks run single-threaded (OMP_NUM_THREADS=1 and the BLAS equivalents, as CI sets them). tests/conftest.py removes every MF_* variable from the environment before collection except MF_ISA and the tool paths (--keep-mf-env NAME keeps another), probes for a usable GPU (conftest.usable_gpu) so GPU tests skip cleanly without one, and adds --shard K/N, --reverse-modules and the opt-in --run-performance checks. CI also runs the suite with MF_ISA forced to SSE4, AVX, AVX2 and AVX3, so a change to the CPU kernels should be tested under those targets locally as well.
Some suites pin contracts the rest of the code relies on:
| Test | What it pins |
|---|---|
test_search_contracts.py | Search-level behaviour per engine: noise and injections, lazy template loading, the gate chain's thresholds, autotuning. |
test_fdr_calibration.py, test_fdr_engine.py, test_fdr_plans.py, test_gate_model.py, test_gate_chain.py, test_gate_draws.py | The gate model's dismissal and the simulation's draws. |
test_tier_conformance.py, test_coarse_conformance.py | Every CPU tier kind and every GPU coarse layout refines exactly the pairs above thresholds placed in gaps of the exact maxima. |
test_choice.py, test_paired_cpu_trials.py, test_joint_trials.py | The measured-choice rule and the joint trial. |
test_reproducible_choices.py | Two processes sharing a cost file choose alike. |
test_argument_validation.py, test_core_boundary.py | Arguments a bank, a filter or a native routine cannot run are refused. |
test_edge_paths.py | Series ends, separate windows in a cascade, and random banks, series and calls against the ungated answer. |
test_layers.py, test_config_registry.py, test_docs_index.py | The import layers, the environment registry, and this directory's index. |
tools/gate.py is the merge gate, one command for every check a change must pass. Its stages, in order: suite (the full suite), check and settled (tools/ladder.py --check cpu, the GPU against the CPU, fresh and after the trials have locked; these need a GPU and a production-like bank and profiles, and are skipped without them), margin (tools/gate_margin.py --loud), fdr (tools/fdr_audit.py), repro (test_reproducible_choices.py, repeated), followups (test_call_plan.py and test_followup_batch.py, repeated) and ci (tools/ci_status.py --schedules: main's and the scheduled workflows' latest runs are green). A skipped stage is reported as skipped, never as a pass.
The CI workflows are in .github/workflows/:
| Workflow | Runs |
|---|---|
ci.yml | On pushes to main and ci/** proof branches and on pull requests: the suite on Python 3.11-3.15 across the SSE4, AVX, AVX2 and widest targets (one job from the sdist), Linux arm64, the generated-codelet check, a wheel smoke test, and Metal on a macOS runner. |
nightly.yml | The suite under AddressSanitizer and UndefinedBehaviorSanitizer (x86 and arm64), the suite in reverse module order, and the musllinux wheel with its full suite. |
benchmark.yml | The benchmark on each platform, weekly, by hand and on ci/bench/** branches; the documentation site is built on every run and published from main. |
release.yml | On a published release: requires a green CI run of the commit, builds and tests every wheel and the sdist, and publishes; weekly, a rehearsal without upload. |
wheels.yml | The reusable wheel build the others call. |
The standard performance workload is tools/ladder.py, the three-level search on a real bank; the tooling map lists every tool.
Where to read next
- Using matchedfilter for the API in practice.
- The hierarchical filter, the resolved plan and reduced-precision gates for the gating contract.
- Environment variables, generated from the registry.
- The documentation index for every other page.