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.*.

NameDefined inWhat it is
MatchedFilter_filterFlat peak-only filter: per (data, template) pair, the largest correlation sample in each output bin of a search window.
CorrelationFilter_filterThe same spectral product, returning every complex lag.
HierarchicalFilter_hierarchicalA MatchedFilter subclass that gates pairs with a chain of coarse tiers and refines the survivors.
TimeDomainFilterBank, FilterResults, template_spectra, template_validtime_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, DevicedeviceDevice 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 _coreThe 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_resultsThe structured (index, value) peak record.
UnsupportedSize_errorsRaised 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:

LayerWhat 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
platformdevice, _vulkan, _cuda, _metal (enumeration only), _vksubgroup
modelsgatemodel (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__
applicationsbenchmark, 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.

FileRole
dispatch.cThe public C API over whichever kernel the runtime dispatch selected.
matchfilt.cThe flat batched filter: ingest rearranges and conjugates, then the D x T pair loop with the product fused into the inverse transform (design).
hmf.cThe 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.hThe 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.hThe int16 (Q15) coarse screen; its codelets are generated by src/gen_q15.py.
gate16.ccThe FP16 first gate on ARM NEON with FP16 arithmetic; stubs elsewhere.
td-inl.hThe direct (time-domain) refine: correlation at a few lags around a survivor's coarse peak.
kernel_avx1.cc, simd-avx1.hThe AVX back end: SSE4's kernels with the float paths at 8 lanes, for CPUs with AVX but not AVX2.
gauss.ccCounter-based normal draws for the gate model's simulation, identical on every ISA.
simulate.c, records.ccThe gate model's simulation: the rows' transforms (simulate.c, behind simulate.h) and the power and running-maximum kernels (records.cc).
followup.cThe 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.ccShared-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:

_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).

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.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:

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.

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.

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.

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:

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:

_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:

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:

TestWhat it pins
test_search_contracts.pySearch-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.pyThe gate model's dismissal and the simulation's draws.
test_tier_conformance.py, test_coarse_conformance.pyEvery 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.pyThe measured-choice rule and the joint trial.
test_reproducible_choices.pyTwo processes sharing a cost file choose alike.
test_argument_validation.py, test_core_boundary.pyArguments a bank, a filter or a native routine cannot run are refused.
test_edge_paths.pySeries 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.pyThe 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/:

WorkflowRuns
ci.ymlOn 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.ymlThe suite under AddressSanitizer and UndefinedBehaviorSanitizer (x86 and arm64), the suite in reverse module order, and the musllinux wheel with its full suite.
benchmark.ymlThe 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.ymlOn 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.ymlThe 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